import { fetchCreditDeposites, fetchOperationMode } from '@/api/account';
import { useEffect, useReducer } from '@tarojs/taro';
import Actions from '@/types/Store/Actions';

type CreditDepositsState = {
  amount: number; // 金额

  areaId: number; // 区域id

  operateId: number; // 运营商id

  showType: string; //展示类型 1授信额度 2保证金
};

const reducer = (state: CreditDepositsState, action: Actions) => {
  switch (action.type) {
    case 'updateCreditInfo':
      return action.payload;
    default:
      return state;
  }
};
const initState = {
  amount: 0,
  areaId: 0,
  operateId: 0,
  showType: '',
};

const useCreditDeposits = (areaId: number): CreditDepositsState => {
  const [state, dispatch] = useReducer(reducer, initState);

  useEffect(() => {
    fetchOperationMode({
      areaId: areaId,
    }).then(res => {
      if (res.data.mode === '1' || res.data.mode === '2') {
        fetchCreditDeposites({
          areaId: areaId,
        }).then(res => {
          if (res.data) {
            dispatch({ type: 'updateCreditInfo', payload: res.data });
          }
        });
      }
    });
  }, [areaId]);

  return state;
};

export default useCreditDeposits;
