import { useSelector, useDispatch } from '@tarojs/redux';
import { getShowerController, ShowerUseType } from '@/api/shower';
import { updateShowerControlConfig } from '@/store/rootReducers/shower';
import { Customer } from '@/types/Customer/Customer';
import Taro, { useEffect, useState } from '@tarojs/taro';

const useShowerController = () => {
  const [method, setState] = useState('');
  const dispatch = useDispatch();
  const userinfo = useSelector(
    (state: { userinfo: Customer }) => state.userinfo,
  );

  useEffect(() => {
    if (method) {
      Taro.showLoading();
      getShowerController({
        campusId: userinfo.areaId,
        customerId: userinfo.customerId,
      })
        .then(res => {
          let data = res.data;
          dispatch(updateShowerControlConfig(res.data));
          let type =
            data.useType === ShowerUseType.mix
              ? data.defaultType
              : data.useType;
          let url = '';
          if (type === ShowerUseType.bluetooth) {
            url = '/pages/Shower/Shower';
          } else {
            url = '/pages/Shower/ShowerAppointment';
          }
          Taro.hideLoading();
          console.log(url);

          if (method === 'redirectTo') {
            Taro.redirectTo({ url: url });
          } else {
            Taro.navigateTo({ url: url });
          }
        })
        .catch(err => {
          Taro.hideLoading();
          console.log('getShowerController err:', err);
          Taro.showToast({
            title: err.msg || '网络错误',
            icon: 'none',
          });
        });
    }
  }, [method]);

  return setState;
};

export default useShowerController;
