import {
  FetchWasherStatus,
  WashingMachineDevice,
  fetchDeviceListByStatus,
  AppointOrderStatus,
} from '@/api/washingMachine';
import Taro, { useEffect, useState, useCallback } from '@tarojs/taro';
import { useSelector, useDispatch } from '@tarojs/redux';
import { Customer } from '@/types/Customer/Customer';
import { updateWasherOrderDetail } from '@/store/rootReducers/washer';

const initList: WashingMachineDevice[] = [];

const useWasherList = (
  state: FetchWasherStatus,
): [WashingMachineDevice[], (state: FetchWasherStatus) => void] => {
  const dispatch = useDispatch();
  const userInfo = useSelector(
    (state: { userinfo: Customer }) => state.userinfo,
  );
  const [list, setList] = useState(initList);
  const fetchHandle = useCallback(
    (state: FetchWasherStatus) => {
      Taro.showLoading();
      return fetchDeviceListByStatus({
        customerId: userInfo.customerId,
        status: state,
        campusId: userInfo.areaId,
      })
        .then(res => {
          Taro.hideLoading();
          console.log(res.data);
          const { deviceList, appointOrder } = res.data;
          setList(deviceList);
          if (appointOrder) {
            dispatch(
              updateWasherOrderDetail({
                ...appointOrder,
                money: appointOrder.money / 100,
                status: AppointOrderStatus.appointing,
              }),
            );
          } else {
            dispatch(
              updateWasherOrderDetail({
                bluetoothMode: 0,
                deviceCode: '',
                deviceName: '',
                endDate: '',
                money: 0,
                orderCode: '',
                position: '',
                services: [],
                startDate: '',
                status: AppointOrderStatus.appointing,
              }),
            );
          }
        })
        .catch(err => {
          Taro.hideLoading();
          Taro.showToast({
            title: err.msg || '网络异常',
            icon: 'none',
          });
        });
    },
    [fetchDeviceListByStatus, userInfo.customerId, userInfo.areaId],
  );
  useEffect(() => {
    fetchHandle(state);
  }, [state]);
  return [list, fetchHandle];
};

export default useWasherList;
