import { useEffect, useReducer } from '@tarojs/taro';
import { fetchRechargeOrders, RechargeOrderItem } from '@/api/order';
import { useSelector, useDispatch } from '@tarojs/redux';
import { OrderStoreState } from './store';
import {
  updateRechargeLastId,
  appendRechargeOrders,
  updateRechargeOrders,
} from './actions';

const useRechargeOrders = (
  customerId: number,
  pageSize: number,
): [RechargeOrderItem[], () => Promise<any>, () => Promise<any>] => {
  const state = useSelector(
    (state: { OrderList: OrderStoreState }) => state.OrderList.recharge,
  );
  const dispatch = useDispatch();
  const fetchData = (customerId: number, pageSize: number) =>
    fetchRechargeOrders({
      customerId,
      lastOrderId: state.lastOrderId,
      pageSize,
    })
      .then(res => {
        state.lastOrderId
          ? dispatch(appendRechargeOrders(res.data))
          : dispatch(updateRechargeOrders(res.data));
        return res.data;
      })
      .catch(err => {
        console.log(err);
      });
  const fetchMore = () => {
    let arr = state.rechargeOrders;
    const itemIdx = arr.length - 1;
    if (itemIdx >= 0) {
      const orderIdx = arr[itemIdx].data.length - 1;
      if (orderIdx >= 0) {
        dispatch(updateRechargeLastId(arr[itemIdx].data[orderIdx].id));
        return fetchData(customerId, pageSize);
      }
    }
    dispatch(updateRechargeLastId(0));
    return fetchData(customerId, pageSize);
  };
  const resetOrders = () => {
    dispatch(updateRechargeLastId(0));
    return fetchData(customerId, pageSize);
  };

  useEffect(() => {
    fetchData(customerId, pageSize);
  }, [customerId, pageSize]);

  return [state.rechargeOrders, fetchMore, resetOrders];
};

export default useRechargeOrders;
