/**
 * 多钱包页面
 * @邠心vbe on 2025/01/17
 */
import React, { Component } from 'react';
import { FlatList, StyleSheet } from 'react-native';
import { View, Text } from 'react-native';
import PagerView from 'react-native-pager-view';
import apiCharge from '../../api/apiCharge';
import apiWallets from '../../api/apiWallets';
import { ElevationObject } from '../../components/Button';
import VbeSkeleton from '../../components/VbeSkeleton';
import ViewHistory from './ViewHistory';
import ViewWallet from './ViewWallet';

export default class Wallets extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      wallets: [],
      active: 0,
      history: {},
      historyList: [],
      loadingList: false
    };
  }

  componentDidMount() {
    setTimeout(() => {
      this.getWalletsInfo();
    }, 500);
    this.props.navigation.addListener('focus', () => {
      if (!this.state.loading) {
        this.refresh();
      }
    });
  }

  refresh() {
    this.setState({
      history: {},
      historyList: [],
      loadingList: true
    }, () => {
      this.getWalletsInfo(true);
    })
  }

  getWalletsInfo(refresh) {
    apiWallets.getWalletsInfo().then(res => {
      if (res.data) {
        this.setState({
          wallets: res.data
        })
        if (refresh) {
          let wallet = this.state.wallets[this.state.active];
          if (wallet && wallet.walletTypeCode) {
            setTimeout(() => {
              this.getTransactionInfo(wallet.walletTypeCode);
            }, 300);
          }
        }
      }
    }).catch(err => {
      toastShort(err)
    }).finally(() => {
      this.setState({
        loading: false
      })
    })
  }

  getTransactionInfo(code) {
    if (this.state.history[code]) {
      this.setState({
        loadingList: false,
        historyList: this.state.history[code]
      })
      return;
    }
    apiWallets.getTransactionList({
      walletTypeCode: code
    }).then(res => {
      if (res.data) {
        this.state.history[code] = res.data;
        this.setState({
          historyList: res.data
        })
      } else {
        this.setState({
          historyList: []
        })
      }
    }).catch(err => {
      this.setState({
        historyList: []
      })
    }).finally(() => {
      this.setState({
        loadingList: false
      })
    })
  }

  changeCard(e) {
    //console.log("changeCard", e.nativeEvent.position);
    this.setState({
      active: e.nativeEvent.position
    }, () => {
      let wallet = this.state.wallets[this.state.active];
      if (wallet && wallet.walletTypeCode) {
        this.setState({
          loadingList: true
        });
        setTimeout(() => {
          this.getTransactionInfo(wallet.walletTypeCode);
        }, 300);
      }
    })
  }

  setDefault(index) {
    const code = this.state.wallets[index]?.walletTypeCode;
    if (code) {
      Dialog.showProgressDialog();
      apiCharge.setDefaultPaymentType({
        defaultPaymentMethod: code
      }).then(res => {
        toastShort("success");
        this.getWalletsInfo();
      }).catch(err => {
        toastShort(err)
      }).finally(() => {
        Dialog.dismissLoading();
      })
    }
  }

  divideView = (props) => {
    return (<View style={styles.divideView}></View>)
  }

  render() {
    if (this.state.loading) {
      return (
        <VbeSkeleton
          style={[ui.flex1, $padding(16)]}
          layout={[
            {width: "100%", height: 240, borderRadius: 16},
            {width: "100%", height: $vh(100) - 330, borderRadius: 16, marginTop: 24},
          ]}
          animationDirection={"horizontalRight"}
        />
      )
    }
    return (
      <View style={styles.container}>
        <PagerView
          style={styles.pagerView}
          initialPage={this.state.active}
          onPageSelected={e => this.changeCard(e)}>
          { this.state.wallets.map((item, index) => (
            <ViewWallet
              key={index}
              wallet={item}
              setDefault={() => this.setDefault(index)}/>
          ))}
        </PagerView>
        <View style={styles.indicatorView}>
          { this.state.wallets.map((item, index) => (
            <MaterialCommunityIcons
              key={index}
              style={$margin(2)}
              name={this.state.active == index ? "checkbox-blank-circle" : "checkbox-blank-circle-outline"}
              size={10}/>
          ))}
        </View>
        <View style={styles.listView}>
          { this.state.loadingList
          ? <VbeSkeleton
            style={[ui.flex1, $padding(16)]}
            layout={[
              {width: "100%", height: 14, borderRadius: 16},
              {width: "100%", height: 14, borderRadius: 16, marginTop: 12},
              {width: "60%", height: 14, borderRadius: 16, marginTop: 12},
              {width: "100%", height: 14, borderRadius: 16, marginTop: 24},
              {width: "100%", height: 14, borderRadius: 16, marginTop: 12},
              {width: "60%", height: 14, borderRadius: 16, marginTop: 12}
            ]}/>
          : <FlatList
              data={this.state.historyList}
              renderItem={ViewHistory}
              ItemSeparatorComponent={this.divideView}
              keyExtractor={item => item.refPk}
              ListEmptyComponent={<Text style={styles.noData}>No Data</Text>}/>
          }
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: pageBackground
  },
  pagerView: {
    height: 240
  },
  indicatorView: {
    padding: 8,
    alignItems: 'center',
    flexDirection: 'row',
    justifyContent: 'center',
  },
  listView: {
    flex: 1,
    overflow: 'hidden',
    ...$margin(8, 16, 16),
    ...ElevationObject(2),
    borderRadius: 16,
    backgroundColor: colorLight
  },
  noData: {
    color: textPlacehoder,
    fontSize: 14,
    padding: 20,
    textAlign: 'center'
  },
  divideView: {
    height: 1,
    opacity: 0.5,
    marginLeft: 16,
    marginRight: 16,
    backgroundColor: '#e8e8e8'
  }
})