import Taro, { useCallback, useEffect } from '@tarojs/taro';
import {
  fetchWasherDeviceInfo,
  FetchWasherDeviceInfoRes,
} from '@/api/washingMachine';
import { useSelector, useDispatch } from '@tarojs/redux';
import { Customer } from '@/types/Customer/Customer';
import { updateWasherDeviceInfo } from '@/store/rootReducers/washer';

const initState: FetchWasherDeviceInfoRes = {
  bluetoothMode: 0,
  deviceCode: '',
  deviceName: '',
  enabledAppoint: false,
  optionalPrograms: [],
  paymentWaysInner: [],
  paymentWaysOuter: [],
  position: '',
  requiredPrograms: [],
};

const useWasherDevice = (
  deviceCode: string,
  goNextPage?: () => void,
): FetchWasherDeviceInfoRes => {
  const userInfo = useSelector(
    (state: { userinfo: Customer }) => state.userinfo,
  );
  const data = useSelector(
    (state: { washer: FetchWasherDeviceInfoRes }) => state.washer,
  );
  const dispatch = useDispatch();
  const fetchHandle = useCallback(
    (deviceCode: string) => {
      if (deviceCode) {
        Taro.showLoading();
        fetchWasherDeviceInfo({
          customerId: userInfo.customerId,
          deviceCode: deviceCode,
        })
          .then(res => {
            Taro.hideLoading();
            console.log(res);
            dispatch(updateWasherDeviceInfo(res.data));
            goNextPage && goNextPage();
          })
          .catch(err => {
            Taro.hideLoading();
            Taro.showToast({
              title: err.msg || '网络异常',
              icon: 'none',
            });
          });
      }
    },
    [fetchWasherDeviceInfo, userInfo.customerId, deviceCode],
  );
  useEffect(() => {
    console.log('orderDetail', deviceCode);

    if (deviceCode) {
      fetchHandle(deviceCode);
    } else {
      updateWasherDeviceInfo(initState);
    }
  }, [deviceCode]);

  return data;
};

export default useWasherDevice;
