import Taro, { useEffect, useState, useCallback } from '@tarojs/taro';
import {
  fetchBalanceState,
  switchBalanceState,
  BalanceState,
} from '@/api/customer';

const useBalanceState = (
  customerId: number,
): [boolean, (state: boolean) => void] => {
  const [state, setState] = useState(false);

  const getBoolValue = (e: BalanceState): boolean =>
    e === BalanceState.open ? true : false;

  useEffect(() => {
    fetchBalanceState({
      customerId,
    })
      .then(res => {
        setState(getBoolValue(res.data));
      })
      .catch(err => {
        console.log(err);
      });
  }, []);

  const switchBalanceStateHandle = (state: BalanceState) => {
    Taro.showLoading();
    return switchBalanceState({
      customerId,
      isEnabled: state,
    })
      .then(res => {
        Taro.hideLoading();
        console.log(res);
        setState(getBoolValue(state));
        Taro.showToast({
          title: '修改成功',
        });
      })
      .catch(err => {
        Taro.hideLoading();
        console.log(err);
        Taro.showToast({
          title: err.msg || '修改失败',
          icon: 'none',
        });
      });
  };

  const setStateHandle = useCallback(
    (state: boolean) => {
      setState(state);
      if (state) {
        Taro.showModal({
          title: '提示',
          content: '您将切换使用预充值模式,消费时请保证账号又余额',
        }).then(res => {
          if (res.confirm) {
            switchBalanceStateHandle(BalanceState.open).catch(() => {
              setState(false);
            });
          } else {
            setState(false);
          }
        });
      } else {
        Taro.showModal({
          title: '提示',
          content: '关闭后将切换至订单单笔支付模式',
        }).then(res => {
          if (res.confirm) {
            switchBalanceStateHandle(BalanceState.close).catch(() => {
              setState(true);
            });
          } else {
            setState(true);
          }
        });
      }
    },
    [customerId],
  );

  return [state, setStateHandle];
};

export default useBalanceState;
