import { useEffect, useReducer } from '@tarojs/taro';
import { fetchRechargeOrders, RechargeOrderItem } from '@/api/order';
import Actions from '@/types/Store/Actions';

const reducer = (state: RechargeOrderItem[], action: Actions) => {
  switch (action.type) {
    case 'updateRechargeOrders':
      return action.payload;

    default:
      return state;
  }
};
const useRechargeOrders = (
  customerId: number,
  lastOrderId: number,
  pageSize: number,
): RechargeOrderItem[] => {
  const [state, dispatch] = useReducer(reducer, []);
  const fetchData = (
    customerId: number,
    lastOrderId: number,
    pageSize: number,
  ) =>
    fetchRechargeOrders({
      customerId,
      lastOrderId,
      pageSize,
    })
      .then(res => {
        dispatch({ type: 'updateRechargeOrders', payload: res.data });
        return res.data;
      })
      .catch(err => {
        console.log(err);
      });

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

  return state;
};

export default useRechargeOrders;
