/**
 * 积分历史列表页面
 * @邠心vbe on 2024/05/07
 */
import React, { Component } from 'react';
import { View, Text, RefreshControl, FlatList, StyleSheet } from 'react-native';
import { MyRefreshProps } from '../../components/ThemesConfig';
import TextView from '../../components/TextView';
import Dialog from '../../components/Dialog';
import apiVoucher from '../../api/apiVoucher';
import VbeSkeleton from '../../components/VbeSkeleton';

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

  componentDidMount() {
    this.getHistoryList();
  }

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

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

  getHistoryList(lastPk="") {
    apiVoucher.getPointsHistory(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
      });
    });
  }

  listItem = ({item, index, separators}) => {
    return (
      <View style={styles.itemView}>
        <MaterialCommunityIcons
          style={styles.iconType}
          name={item.action == "Increase" ? "ev-station" : "ticket-percent-outline"}
          size={20}
          color={textPrimary}/>
        <View style={styles.itemContent}>
          <View style={ui.flex1}>
            <TextView style={styles.issueName}>{item.remarks}</TextView>
            <TextView style={styles.issueDesc}>{(item.siteName ?? item.voucherName) + ", " + (item.chargeBoxId ? item.chargeBoxId + ", " : "") + item.refId}</TextView>
          </View>
          { item.action == "Increase"
            ? <TextView style={styles.amountText}>+ {item.points}</TextView>
            : <TextView style={styles.amountDuct}>- {item.points}</TextView>
          }
        </View>
      </View>
    )
  }

  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 style={styles.listView}>
          { this.state.loadingList.map((item, index) =>
            <View style={styles.loadingView} key={index}>
              <VbeSkeleton
                style={styles.iconDefault}
                layout={[
                  {width: 30, height: 30, borderRadius: 30}
                ]}
                animationDirection={"horizontalRight"}
              />
              <VbeSkeleton
                style={ui.flex1}
                layout={[
                  {width: '60%', height: 18},
                  {width: '80%', height: 12, marginTop: 8}
                ]}
                animationDirection={"horizontalRight"}
              />
            </View>
          )}
        </View>
      )
    } else {
      return (
        <FlatList
          style={styles.listView}
          data={this.state.dataList}
          renderItem={this.listItem}
          ItemSeparatorComponent={this.divideView}
          ListFooterComponent={this.bottomView}
          keyExtractor={item => item.pointsHistoryId}
          onEndReached={() => this.getNextPage()}
          onEndReachedThreshold={0.3}
          refreshControl={
            <RefreshControl
              {...MyRefreshProps()}
              refreshing={this.state.refreshing}
              onRefresh={() => this.onRefresh()}
            />
          }
          ListEmptyComponent={<Text style={styles.noData}>{$t('points.noData')}</Text>}
        />
      );
    }
  }
}

const styles = StyleSheet.create({
  listView: {
    flex: 1
  },
  itemView: {
    paddingLeft: 16,
    paddingRight: 16,
    alignItems: 'center',
    flexDirection: 'row'
  },
  loadingView: {
    padding: 16,
    alignItems: 'center',
    flexDirection: 'row'
  },
  itemContent: {
    flex: 1,
    marginLeft: 8,
    ...$padding(16, 4),
    alignItems: 'center',
    flexDirection: 'row'
  },
  divide: {
    marginLeft: 52,
    marginRight: 16,
    borderTopWidth: 1,
    borderTopColor: '#eee',
  },
  iconType: {
    width: 28,
    height: 28,
    textAlign: 'center',
    lineHeight: 27,
    borderWidth: 1,
    borderRadius: 30,
    borderColor: textPrimary
  },
  iconDefault: {
    width: 28,
    height: 28,
    marginRight: 16
  },
  issueName: {
    color: textPrimary,
    fontSize: 12,
    paddingBottom: 2
  },
  issueDesc: {
    color: '#999',
    fontSize: 8
  },
  amountDuct: {
    color: '#FF2E00',
    fontSize: 12,
    paddingLeft: 8
  },
  amountText: {
    color: colorAccent,
    fontSize: 12,
    paddingLeft: 8
  },
  noData: {
    color: textPlacehoder,
    fontSize: 8,
    padding: 20,
    textAlign: 'center'
  },
  noMore: {
    color: textPlacehoder,
    fontSize: 10,
    padding: 16,
    textAlign: 'center'
  }
})