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

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

import './OrderList.scss';

import {
  toggleOrderState,
  updatePayOrderList,
  updateAllOrderList,
  UpdateOrderParams,
} from './actions';
import { StoreState } from './store';
import { fetchAllOrder, fetchPayOrder } from '../../../api/order';
import Order, { AllOrderItem } from '../../../types/Order/Order';
import { Customer } from '@/types/Customer/Customer';
import { shareHandle } from '@/common/shareMethod';

type PageStateProps = {
  orderList: StoreState;
  userinfo: Customer;
};
type PageDispatchProps = {
  toggleOrderState: (state: String) => void;
  updatePayOrder: (entity: UpdateOrderParams<Order>) => void;
  updateAllOrder: (entity: UpdateOrderParams<AllOrderItem>) => void;
};

type PageOwnProps = {};

type PageProps = PageStateProps & PageDispatchProps & PageOwnProps;

type PageState = {
  needRefresh: boolean;
};

interface OrderList {
  props: PageProps;
  state: PageState;
}

@connect(
  ({ OrderList, userinfo }) => ({
    orderList: OrderList,
    userinfo,
  }),
  dispatch => ({
    toggleOrderState(state: String) {
      dispatch(toggleOrderState(state));
    },
    updatePayOrder(data) {
      dispatch(updatePayOrderList(data));
    },
    updateAllOrder(data) {
      dispatch(updateAllOrderList(data));
    },
  }),
)
class OrderList extends Component {
  config: Config = {
    navigationBarTitleText: '订单',
    enablePullDownRefresh: true,
  };
  constructor(props: PageProps) {
    super(props);
    this.state = {
      needRefresh: false,
    };
  }
  onShareAppMessage = shareHandle;

  componentWillMount() {
    this.getPayOrderHandle();
    this.getAllOrderHandle();
  }
  componentDidShow() {
    const { needRefresh } = this.state;
    if (needRefresh) {
      this.getPayOrderHandle();
      this.getAllOrderHandle();
    }
  }

  onPullDownRefresh() {
    console.log('in onPullDownRefresh');
    const {
      orderList: { orderState },
    } = this.props;
    if (orderState === '1') {
      this.getPayOrderHandle().then(() => {
        Taro.stopPullDownRefresh();
      });
    } else {
      this.getAllOrderHandle().then(() => {
        Taro.stopPullDownRefresh();
      });
    }
  }

  getPayOrderHandle(lastOrderId?: number) {
    const { userinfo, updatePayOrder } = this.props;
    return fetchPayOrder(
      lastOrderId
        ? {
            customerId: userinfo.customerId,
            pageSize: 10,
            lastOrderId,
          }
        : {
            customerId: userinfo.customerId,
            pageSize: 10,
          },
    )
      .then(res => {
        console.log(res);
        updatePayOrder({ list: res.data, lastOrderId: lastOrderId });
      })
      .catch(console.error);
  }

  getAllOrderHandle(lastOrderId?: number) {
    const {
      userinfo: { customerId },
      updateAllOrder,
    } = this.props;
    return fetchAllOrder(
      lastOrderId
        ? {
            customerId: customerId,
            pageSize: 10,
            lastOrderId,
          }
        : {
            customerId: customerId,
            pageSize: 10,
          },
    )
      .then(res => {
        console.log(res);
        updateAllOrder({ list: res.data, lastOrderId: lastOrderId });
      })
      .catch(console.error);
  }

  goPayPage(data) {
    this.setState({
      needRefresh: true,
    });
    this.$preload({ id: data.id });
    Taro.navigateTo({
      url: '/pages/Order/OrderPay/OrderPay',
    });
  }
  goDetail(data) {
    this.setState({
      needRefresh: false,
    });
    this.$preload(data);
    Taro.navigateTo({
      url: '/pages/Order/OrderDetail/OrderDetail',
    });
  }

  toggleStateHandle(type: string) {
    const {
      toggleOrderState,
      orderList: { payList, allList },
    } = this.props;
    if (type === '1' && payList.length === 0) {
      this.getPayOrderHandle();
    }
    if (type === 'all' && allList.length === 0) {
      this.getAllOrderHandle();
    }
    toggleOrderState(type);
  }

  refreshList() {
    console.log('in refreshList');
    // Taro.startPullDownRefresh({
    //   success: this.onPullDownRefresh,
    // });
  }
  fetchMoreList() {
    const {
      orderList: { orderState, payList, allList },
    } = this.props;
    console.log('in moreList ' + orderState);
    if (orderState === '1') {
      this.getPayOrderHandle(payList[payList.length - 1].id);
    } else {
      const itemIdx = allList.length - 1;
      const orderIdx = allList[itemIdx].data.length - 1;
      console.log(itemIdx, orderIdx);

      this.getAllOrderHandle(allList[itemIdx].data[orderIdx].id);
    }
  }

  render() {
    const {
      orderList: { orderState, payList, allList },
    } = this.props;

    return (
      <View className='OrderList'>
        <View className='Tab'>
          <Text
            className={`Tab-item ${orderState === '1' ? 'active' : ''}`}
            onClick={() => this.toggleStateHandle('1')}>
            待付款
          </Text>
          <Text
            className={`Tab-item ${orderState === 'all' ? 'active' : ''}`}
            onClick={() => this.toggleStateHandle('all')}>
            全部
          </Text>
        </View>
        <ScrollView
          className='OrderList-Content'
          scrollY
          onScrollToUpper={this.refreshList}
          onScrollToLower={this.fetchMoreList}
          upperThreshold={-100}
          lowerThreshold={70}
          scrollWithAnimation
          scrollTop={0}>
          {orderState === '1'
            ? payList.map(order => (
                <OrderItem
                  key={order.id}
                  data={order}
                  onGoDetail={this.goDetail}
                  onPayHandle={this.goPayPage}
                />
              ))
            : allList.map((allItem, index) => (
                <View key={index} 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>
      </View>
    );
  }
}

export default OrderList as ComponentClass<PageOwnProps>;
