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

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

import './OrderList.scss';

import { fetchAllOrder, RechargeOrderItem } from '../../../api/order';
import { Customer } from '@/types/Customer/Customer';
import { shareHandle } from '@/common/shareMethod';
import RechargeItem from '../components/RechargeItem/RechargeItem';
import useRechargeOrders from './useRechargeOrders';
import useConsumeOrders from './useConsumeOrders';
import Order, { AllOrderItem } from '@/types/Order/Order';
import { selectOrder, updateConsumeOrders } from './actions';

type PageStateProps = {
  userinfo: Customer;
};
type PageDispatchProps = {
  selectOrder: (entity: Order) => void;
  updateConsumeOrders: (entity: AllOrderItem[]) => void;
};
type PageOwnProps = {};

type PageProps = PageStateProps & PageDispatchProps & PageOwnProps;

type PageState = {
  needRefresh: boolean;
};

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

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

  // componentWillMount() {
  //   this.getAllOrderHandle();
  // }
  componentDidShow() {
    const { needRefresh } = this.state;
    const {
      userinfo: { customerId },
      updateConsumeOrders,
    } = this.props;
    if (needRefresh) {
      fetchAllOrder({
        customerId,
        pageSize: 10,
      })
        .then(res => {
          updateConsumeOrders(res.data);
        })
        .catch(err => {
          Taro.showToast({
            title: err.msg || '请求失败',
            icon: 'none',
          });
        });
      // this.getAllOrderHandle();
    }
  }

  // const onPullDownRefresh = () => {
  //   console.log('in onPullDownRefresh');
  //   this.getAllOrderHandle().then(() => {
  //     Taro.stopPullDownRefresh();
  //   });
  // };
  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',
    });
  };

  render() {
    const {
      userinfo: { customerId },
    } = this.props;
    const [orderType, setOrderType] = useState(0); // 0 消费,1 充值
    const [
      consumeOrders,
      fetchMoreConsumeOrders,
      resetConsumeOrders,
    ] = useConsumeOrders(customerId, 10);
    // const [consumeScrollTop, setConsumeScrollTop] = useState(0);
    // const scrollHandle = e => {
    //   console.log(e);
    // };
    const onConsumeScrollToLower = () => {
      Taro.showLoading({
        title: '',
        mask: true,
      });
      fetchMoreConsumeOrders()
        .then(() => {
          Taro.hideLoading();
        })
        .catch(err => {
          Taro.hideLoading();
          Taro.showToast({
            title: err.msg || '请求失败',
            icon: 'none',
          });
        });
    };

    const [
      rechargeOrders,
      fetchMoreRechargeOrders,
      resetRechargeOrders,
    ] = useRechargeOrders(customerId, 10);
    const onRechargeScrollToLower = () => {
      Taro.showLoading({
        title: '',
        mask: true,
      });
      fetchMoreRechargeOrders()
        .then(() => {
          Taro.hideLoading();
        })
        .catch(err => {
          Taro.hideLoading();
          Taro.showToast({
            title: err.msg || '请求失败',
            icon: 'none',
          });
        });
    };

    return (
      <View className='OrderList'>
        <View className='Tab'>
          <Text
            className={`Tab-item ${orderType === 0 ? 'active' : ''}`}
            onClick={() => setOrderType(0)}>
            消费
          </Text>
          <Text
            className={`Tab-item ${orderType === 1 ? 'active' : ''}`}
            onClick={() => setOrderType(1)}>
            充值
          </Text>
        </View>
        {orderType === 0 ? (
          <ScrollView
            className='OrderList-Content'
            scrollY
            onScrollToUpper={() => resetConsumeOrders()}
            onScrollToLower={onConsumeScrollToLower}
            upperThreshold={-100}
            lowerThreshold={70}
            scrollWithAnimation
            scrollTop={0}>
            {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>
            ))}
          </ScrollView>
        ) : (
          <ScrollView
            className='OrderList-Content'
            scrollY
            onScrollToUpper={() => resetRechargeOrders()}
            onScrollToLower={onRechargeScrollToLower}
            upperThreshold={-100}
            lowerThreshold={70}
            scrollWithAnimation
            scrollTop={0}>
            {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>
            ))}
          </ScrollView>
        )}
      </View>
    );
  }
}

export default OrderList;
