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 = () => {
    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;
