import { useEffect } from '@tarojs/taro';
import { fetchAllOrder } from '@/api/order';
import { AllOrderItem } from '@/types/Order/Order';
import { useSelector, useDispatch } from '@tarojs/redux';
import { OrderStoreState } from './store';
import {
  appendConsumeOrders,
  updateConsumeOrders,
  updateConsumeLastId,
} from './actions';

const useConsumeOrders = (
  customerId: number,
  pageSize: number,
): [AllOrderItem[], () => Promise<any>, () => Promise<any>] => {
  const state = useSelector(
    (state: { OrderList: OrderStoreState }) => state.OrderList.consume,
  );
  const dispatch = useDispatch();

  const fetchData = (customerId: number, pageSize: number) =>
    fetchAllOrder({
      customerId,
      lastOrderId: state.lastOrderId,
      pageSize,
    })
      .then(res => {
        state.lastOrderId
          ? dispatch(appendConsumeOrders(res.data))
          : dispatch(updateConsumeOrders(res.data));
        return res.data;
      })
      .catch(err => {
        console.log(err);
      });
  const fetchMore = () => {
    return fetchData(customerId, pageSize);
  };
  const resetOrders = () => {
    dispatch(updateConsumeLastId(0));
    return fetchData(customerId, pageSize);
  };

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

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

export default useConsumeOrders;
