import { useEffect, useReducer } from '@tarojs/taro';
import { fetchAllOrder } from '@/api/order';
import Actions from '@/types/Store/Actions';
import { AllOrderItem } from '@/types/Order/Order';

const reducer = (state: AllOrderItem[], action: Actions) => {
  switch (action.type) {
    case 'updateConsumeOrders':
      return action.payload;
    case 'appendConsumeOrders':
      return [...state, ...action.payload];
    default:
      return state;
  }
};
const useConsumeOrders = (
  customerId: number,
  lastOrderId: number,
  pageSize: number,
): AllOrderItem[] => {
  const [state, dispatch] = useReducer(reducer, []);
  const fetchData = (
    customerId: number,
    lastOrderId: number,
    pageSize: number,
  ) =>
    fetchAllOrder({
      customerId,
      lastOrderId,
      pageSize,
    })
      .then(res => {
        lastOrderId
          ? dispatch({ type: 'appendConsumeOrders', payload: res.data })
          : dispatch({ type: 'updateConsumeOrders', payload: res.data });
        return res.data;
      })
      .catch(err => {
        console.log(err);
      });

  useEffect(() => {
    console.log('in fetch');

    fetchData(customerId, lastOrderId, pageSize);
  }, [customerId, lastOrderId, pageSize]);

  return state;
};

export default useConsumeOrders;
