import { useEffect, useReducer } from '@tarojs/taro';
import { fetchPayOrder, fetchOrderDetailAndPay } from '@/api/order';
import { PaymentAndActiveInfo, CustomerBeanAccountVo } from '@/api/baseClass';
import Order from '@/types/Order/Order';
import Actions from '@/types/Store/Actions';
import { useDispatch } from '@tarojs/redux';
import { updateOrderState } from '@/store/rootReducers/orderState';

type PayOrderData = {
  accountList: CustomerBeanAccountVo[];
  orderInfo: Order;
  payInfos: {
    paymentAndActiveInfos: PaymentAndActiveInfo[];
    paymentConfId: number;
  };
};
const initPayOrderData = {
  accountList: [],
  orderInfo: {
    actualMoney: 0,
    areaId: 0,
    areaName: '',
    consumeType: '',
    createAt: '',
    customerCellphone: '',
    customerId: 0,
    customerName: '',
    deductionBean: 0,
    deductionMoney: 0,
    equipmentNum: '',
    equipmentPosition: '',
    id: 0,
    operateId: 0,
    operateName: '',
    operationMode: '',
    orderName: '',
    orderNumber: '',
    orderState: '',
    outTradeNo: '',
    payType: '',
    payableMoney: 0,
    serviceId: 0,
    serviceName: '',
    thirdDiscountMoney: 0,
    thirdTradeNumber: '',
    updateDate: '',
  },
  payInfos: {
    paymentAndActiveInfos: [],
    paymentConfId: 0,
  },
};
const reducer = (state: PayOrderData, action: Actions) => {
  switch (action.type) {
    case 'updateOrderData':
      return {
        ...state,
        ...action.payload,
      };
    default:
      return state;
  }
};

const useWaitPayOrderState = (customerId: number): PayOrderData => {
  const [state, dispatch] = useReducer(reducer, initPayOrderData);
  const dispatchAction = useDispatch();

  useEffect(() => {
    fetchPayOrder({
      customerId: customerId,
    })
      .then(res => {
        if (res.data.length) {
          dispatchAction(updateOrderState(true));

          fetchOrderDetailAndPay({ id: res.data[0].id })
            .then(({ accounts, orderInfo, payInfos }) => {
              dispatch({
                type: 'updateOrderData',
                payload: {
                  accountList: accounts,
                  orderInfo: orderInfo,
                  payInfos: payInfos,
                },
              });
            })
            .catch(err => {
              console.log(err);
            });
        }
      })
      .catch(err => {
        console.log(err);
      });
  }, [customerId]);

  return state;
};

export default useWaitPayOrderState;
