import { useEffect, useReducer } from '@tarojs/taro';
import { fetchPayConfig, PayConfig, PayTypeVo } from '@/api/account';
import Actions from '@/types/Store/Actions';

enum FirstRechargeState {
  isFirstRecharge = 1,
  notFirstRecharge = 0,
}

type RechargePayState = {
  paywayList: PayTypeVo[];
  payConfigList: PayConfig[];
  isFirstRecharge: FirstRechargeState;
};

const reducer = (state: RechargePayState, action: Actions) => {
  switch (action.type) {
    case 'updateRechargeInfo':
      return action.payload;
    default:
      return state;
  }
};

const usePaywayList = (
  areaId: number,
  customerId: number,
): RechargePayState => {
  const [state, dispatch] = useReducer(reducer, {
    paywayList: [],
    payConfigList: [],
    isFirstRecharge: 0,
  });

  const fetchDate = (areaId: number, customerId: number) => {
    fetchPayConfig({
      areaId,
      customerId,
    })
      .then(res => {
        console.log(res);
        const {
          isFirstRecharge,
          listPayList,
          listRechargeConfDetail,
        } = res.data;
        dispatch({
          type: 'updateRechargeInfo',
          payload: {
            isFirstRecharge,
            payConfigList: listRechargeConfDetail,
            paywayList: listPayList,
          },
        });
      })
      .catch(console.error);
  };
  useEffect(() => {
    fetchDate(areaId, customerId);
  }, [areaId, customerId]);

  return state;
};

export default usePaywayList;
