import { ComponentClass } from 'react';
import Taro, { Component, Config, useState, useEffect } from '@tarojs/taro';
import { View, Text, ScrollView } from '@tarojs/components';
import { connect, useSelector, useDispatch, useStore } from '@tarojs/redux';

import OrderItem from '../components/OrderItem/OrderItem';

import './OrderList.scss';

import {
  fetchAllOrder,
  RechargeOrderItem,
  fetchRechargeOrders,
} from '../../../api/order';
import { Customer } from '@/types/Customer/Customer';
import { shareHandle } from '@/common/shareMethod';
import RechargeItem from '../components/RechargeItem/RechargeItem';
import Order, { AllOrderItem } from '@/types/Order/Order';
import {
  selectOrder,
  updateConsumeOrders,
  updateRechargeOrders,
  appendConsumeOrders,
  appendRechargeOrders,
} from './actions';
import { ConsumeOrderInfo, RechargeOrderInfo, OrderStoreState } from './store';

type PageStateProps = {
  userinfo: Customer;
  consume: ConsumeOrderInfo;
  recharge: RechargeOrderInfo;
};
type PageDispatchProps = {
  selectOrder: (entity: Order) => void;
  updateConsumeOrders: (entity: AllOrderItem[]) => void;
  appendConsumeOrders: (entity: AllOrderItem[]) => void;
  updateRechargeOrders: (entity: RechargeOrderItem[]) => void;
  appendRechargeOrders: (entity: RechargeOrderItem[]) => void;
};
type PageOwnProps = {};

type PageProps = PageStateProps & PageDispatchProps & PageOwnProps;

type PageState = {
  needRefresh: boolean;
  orderType: number; // 0 消费,1 充值
  consumeScrollTop: number;
  rechargeScrollTop: number;
};

interface OrderList {
  props: PageProps;
  state: PageState;
}
@connect(
  (state: { userinfo: Customer; OrderList: OrderStoreState }) => ({
    userinfo: state.userinfo,
    consume: state.OrderList.consume,
    recharge: state.OrderList.recharge,
  }),
  dispatch => ({
    selectOrder(data: Order) {
      dispatch(selectOrder(data));
    },
    updateConsumeOrders(data: AllOrderItem[]) {
      dispatch(updateConsumeOrders(data));
    },
    appendConsumeOrders(data: AllOrderItem[]) {
      dispatch(appendConsumeOrders(data));
    },
    updateRechargeOrders(data: RechargeOrderItem[]) {
      dispatch(updateRechargeOrders(data));
    },
    appendRechargeOrders(data: RechargeOrderItem[]) {
      dispatch(appendRechargeOrders(data));
    },
  }),
)
class OrderList extends Component {
  config: Config = {
    navigationBarTitleText: '订单',
    enablePullDownRefresh: true,
  };
  onShareAppMessage = shareHandle;

  constructor(props: PageProps) {
    super(props);
    this.state = {
      needRefresh: false,
      orderType: 0,
      consumeScrollTop: 0,
      rechargeScrollTop: 0,
    };
  }

  componentWillMount() {
    this.fetchConsumeOrders();
    this.fetchRechargeOrders();
  }
  componentDidShow() {
    const { needRefresh } = this.state;

    if (needRefresh) {
      this.fetchConsumeOrders();
    }
  }

  onPullDownRefresh() {
    const { orderType } = this.state;
    Taro.showLoading({
      title: '',
      mask: true,
    });

    if (orderType) {
      this.fetchRechargeOrders().then(() => {
        Taro.stopPullDownRefresh();
        Taro.hideLoading();
      });
    } else {
      this.fetchConsumeOrders().then(() => {
        Taro.stopPullDownRefresh();
        Taro.hideLoading();
      });
    }
  }
  onReachBottom() {
    const { orderType } = this.state;
    Taro.showLoading({
      title: '',
      mask: true,
    });
    if (orderType) {
      this.appendRechargeOrders().then(() => {
        Taro.stopPullDownRefresh();
        Taro.hideLoading();
      });
    } else {
      this.appendConsumeOrders().then(() => {
        Taro.stopPullDownRefresh();
        Taro.hideLoading();
      });
    }
  }
  onPageScroll(e) {
    const { orderType } = this.state;
    if (orderType) {
      this.setState({
        rechargeScrollTop: e.scrollTop,
      });
    } else {
      this.setState({
        consumeScrollTop: e.scrollTop,
      });
    }
  }

  fetchConsumeOrders() {
    const {
      userinfo: { customerId },
      updateConsumeOrders,
    } = this.props;
    return fetchAllOrder({
      customerId,
      pageSize: 10,
    })
      .then(res => {
        updateConsumeOrders(res.data);
      })
      .catch(err => {
        Taro.showToast({
          title: err.msg || '请求失败',
          icon: 'none',
        });
      });
  }
  appendConsumeOrders() {
    const {
      userinfo: { customerId },
      consume: { lastOrderId },
      appendConsumeOrders,
    } = this.props;
    return fetchAllOrder({
      customerId,
      lastOrderId,
      pageSize: 10,
    })
      .then(res => {
        appendConsumeOrders(res.data);
      })
      .catch(err => {
        Taro.showToast({
          title: err.msg || '请求失败',
          icon: 'none',
        });
      });
  }

  fetchRechargeOrders() {
    const {
      userinfo: { customerId },
      updateRechargeOrders,
    } = this.props;
    return fetchRechargeOrders({
      customerId,
      pageSize: 10,
    })
      .then(res => {
        updateRechargeOrders(res.data);
      })
      .catch(err => {
        Taro.showToast({
          title: err.msg || '请求失败',
          icon: 'none',
        });
      });
  }
  appendRechargeOrders() {
    const {
      userinfo: { customerId },
      recharge: { lastOrderId },
      appendRechargeOrders,
    } = this.props;
    return fetchRechargeOrders({
      customerId,
      lastOrderId,
      pageSize: 10,
    })
      .then(res => {
        appendRechargeOrders(res.data);
      })
      .catch(err => {
        Taro.showToast({
          title: err.msg || '请求失败',
          icon: 'none',
        });
      });
  }

  goPayPage = (data: Order) => {
    const { selectOrder } = this.props;
    // dispatch(selectOrder(data));
    // setNeedRefresh(true);
    selectOrder(data);
    this.setState({
      needRefresh: true,
    });
    Taro.navigateTo({
      url: `/pages/Order/OrderPay/OrderPay?id=${data.id}`,
    });
  };
  goDetail = (data: Order) => {
    const { selectOrder } = this.props;
    // dispatch(selectOrder(data));
    // setNeedRefresh(false);
    selectOrder(data);
    this.setState({
      needRefresh: false,
    });
    Taro.navigateTo({
      url: '/pages/Order/OrderDetail/OrderDetail',
    });
  };
  setOrderType(type: number) {
    this.setState(
      {
        orderType: type,
      },
      () => {
        const { orderType, consumeScrollTop, rechargeScrollTop } = this.state;
        if (orderType) {
          Taro.pageScrollTo({
            scrollTop: rechargeScrollTop,
            duration: 0,
          });
        } else {
          Taro.pageScrollTo({
            scrollTop: consumeScrollTop,
            duration: 0,
          });
        }
      },
    );
  }

  render() {
    const { orderType } = this.state;
    const {
      consume: { consumeOrders },
      recharge: { rechargeOrders },
    } = this.props;

    return (
      <View className='OrderList'>
        <View className='Tab'>
          <Text
            className={`Tab-item ${orderType === 0 ? 'active' : ''}`}
            onClick={() => this.setOrderType(0)}>
            消费
          </Text>
          <Text
            className={`Tab-item ${orderType === 1 ? 'active' : ''}`}
            onClick={() => this.setOrderType(1)}>
            充值
          </Text>
        </View>
        {orderType === 0 ? (
          <View className='OrderList-Wrap'>
            {consumeOrders.map((allItem, index) => (
              <View key={allItem.groupName} className='OrderList-Group'>
                <View className='OrderList-GroupTitle'>
                  <View className='OrderList-GroupName'>
                    {allItem.groupName}
                  </View>
                  {index === 0 && <Text>只保留最近三个月消费订单数据</Text>}
                </View>
                {allItem.data.map(order => (
                  <OrderItem
                    key={order.id}
                    data={order}
                    onGoDetail={this.goDetail}
                    onPayHandle={this.goPayPage}
                  />
                ))}
              </View>
            ))}
          </View>
        ) : (
          <View className='OrderList-Wrap'>
            {rechargeOrders.map(reChargeItem => (
              <View key={reChargeItem.groupName} className='OrderList-Group'>
                <View className='OrderList-GroupTitle'>
                  <View className='OrderList-GroupName'>
                    {reChargeItem.groupName}
                  </View>
                  {/* {index === 0 && <Text>只保留最近三个月充值订单数据</Text>} */}
                </View>
                {reChargeItem.data.map(order => (
                  <RechargeItem key={order.id} data={order} />
                ))}
              </View>
            ))}
          </View>
        )}
      </View>
    );
  }
}

export default OrderList;
