/**
 * 交易历史页面
 * @邠心vbe on 2024/03/29
 */
import React, { Component } from 'react';
import { View, Text, RefreshControl, FlatList, StyleSheet, Pressable, Image } from 'react-native';
import { MyRefreshProps } from '../../components/ThemesConfig';
import apiWallet from '../../api/apiWallet';
import TextView from '../../components/TextView';
import Dialog from '../../components/Dialog';
import { PageList } from '../Router';
import VbeSkeleton from '../../components/VbeSkeleton';

const IconCharge = require('../../images/wallet/ic-type-charge.png');
const IconPayment = require('../../images/wallet/ic-type-payment.png');

export default class HistoryList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      dataList: [],
      hasMore: true,
      refreshing: false,
      loadingList: ["", "", "", ""]
    };
  }

  componentDidMount() {
    setTimeout(() => {
      this.getHistoryList();
    }, 500);
  }

  onRefresh() {
    this.setState({
      refreshing: true
    })
    this.getHistoryList();
  }

  getNextPage() {
    if (this.state.dataList.length > 0 && this.state.hasMore) {
      console.log("[Wallet History]", "getNextPage");
      const last = this.state.dataList[this.state.dataList.length-1]
      this.getHistoryList(last.creditRecordPk);
    }
  }

  getHistoryList(lastPk="") {
    apiWallet.getTransactionListV2({latestPk: lastPk}).then(res => {
      if (res.data) {
        if (lastPk) {
          if (res.data.length > 0) {
            const list = this.state.dataList;
            this.setState({
              dataList: list.concat(res.data)
            });
          } else {
            this.setState({
              hasMore: false
            })
          }
        } else {
          this.setState({
            dataList: res.data,
            hasMore: true
          });
        }
      } else {
        this.setState({
          dataList: []
        });
      }
    }).catch(err => {
      toastShort(err)
    }).finally(() => {
      this.setState({
        loading: false,
        refreshing: false
      });
    });
  }

  toSummary(item) {
    if (item.refPk) {
      startPage(PageList.summary, { action: 'view', chargingPk: item.refPk });
    }
  }

  getTransTitle(item) {
    let title =  item.createTime;
    if (item.remarks) {
      title += ': ' + item.remarks;
    } else if (item.amountSymbol == 'M') {
      title += ': ' + (item.siteName || "Charging");
    } else {
      title += ': ' + $t('wallet.topUp');
    }
    return title;
  }

  listItem = ({item, index, separators}) => {
    return (
      <Pressable
        android_ripple={ripple}
        style={styles.itemView}
        onPress={() => {
          this.toSummary(item)
        }}>
        <Image
          style={styles.iconType}
          resizeMode="contain"
          source={(item.amountSymbol == 'P' || item.remarks) ? IconPayment : IconCharge}/>
        <View style={styles.itemContent}>
          <View style={ui.flex1}>
            <TextView style={styles.issueName}>{this.getTransTitle(item)}</TextView>
            <TextView style={styles.issueDesc}>{$t('wallet.labelTransactionId') + item.creditRecordPk}</TextView>
          </View>
          { item.amountSymbol == 'M'
            ? <TextView style={styles.amountDuct}>- {item.amount}</TextView>
            : <TextView style={styles.amountText}>+ {item.amount}</TextView>
          }
        </View>
      </Pressable>
    )
  }

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

  bottomView = () => {
    if (!this.state.hasMore) {
      return (<Text style={styles.noMore}>{$t('wallet.noMore')}</Text>)
    } else {
      return null
    }
  }

  render() {
    if (this.state.loading) {
      return (
        <View>
          { this.state.loadingList.map((item, index) =>
            <View style={styles.itemView} key={index}>
              <VbeSkeleton
                style={styles.iconType}
                layout={[
                  {width: 32, height: 32, borderRadius: 30, marginRight: 16}
                ]}
                animationDirection={"horizontalRight"}
              />
              <View style={styles.itemContent}>
                <VbeSkeleton
                  style={ui.flex1}
                  layout={[
                    {width: '100%', height: 15, marginTop: 4},
                    {width: '60%', height: 15, marginTop: 4}
                  ]}
                  animationDirection={"horizontalRight"}
                />
              </View>
            </View>
          )}
        </View>
      )
    } else {
      return (
        <FlatList
          style={styles.listView}
          data={this.state.dataList}
          renderItem={this.listItem}
          ItemSeparatorComponent={this.divideView}
          ListFooterComponent={this.bottomView}
          keyExtractor={item => item.creditRecordPk}
          onEndReached={() => this.getNextPage()}
          onEndReachedThreshold={0.3}
          refreshControl={
            <RefreshControl
              {...MyRefreshProps()}
              refreshing={this.state.refreshing}
              onRefresh={() => this.onRefresh()}
            />
          }
          ListEmptyComponent={<Text style={styles.noData}>{$t('wallet.noHistoryData')}</Text>}
        />
      );
    }
  }
}

const styles = StyleSheet.create({
  listView: {
    flex: 1
  },
  itemView: {
    paddingLeft: 16,
    paddingRight: 16,
    alignItems: 'center',
    flexDirection: 'row'
  },
  itemContent: {
    flex: 1,
    marginLeft: 16,
    ...$padding(16, 4),
    alignItems: 'center',
    flexDirection: 'row'
  },
  divide: {
    marginLeft: 60,
    marginRight: 16,
    borderTopWidth: 1,
    borderTopColor: '#eee',
  },
  iconType: {
    width: 32,
    height: 32
  },
  issueName: {
    color: textPrimary,
    fontSize: 12,
    paddingBottom: 2
  },
  issueDesc: {
    color: '#999',
    fontSize: 11
  },
  amountDuct: {
    color: '#FF2E00',
    fontSize: 14,
    paddingLeft: 8
  },
  amountText: {
    color: textPrimary,
    fontSize: 14,
    paddingLeft: 8
  },
  noData: {
    color: textPlacehoder,
    fontSize: 14,
    padding: 20,
    textAlign: 'center'
  },
  noMore: {
    color: textPlacehoder,
    fontSize: 14,
    padding: 16,
    textAlign: 'center'
  }
})