import { Customer } from '@/types/Customer/Customer';
import { useSelector } from '@tarojs/redux';
import {
  fetchPositionList,
  Position,
  addUsedPosition,
  delUsedPosition,
} from '@/api/washingMachine';
import Taro, { useCallback, useState, useEffect } from '@tarojs/taro';

const initList: Position[] = [];
const usePositionList = (
  positionName: string,
): {
  list: Position[];
  usedList: Position[];
  fetchList: (positionName: string) => void;
  addPositionHandle: (id: string) => void;
  delPositionHandle: (id: string) => void;
} => {
  const userInfo = useSelector(
    (state: { userinfo: Customer }) => state.userinfo,
  );
  const [list, setList] = useState(initList);
  const [usedList, setUsedList] = useState(initList);

  const fetchHandle = useCallback(
    positionName => {
      Taro.showLoading();
      return fetchPositionList({
        campusId: userInfo.areaId,
        customerId: userInfo.customerId,
        name: positionName,
      })
        .then(res => {
          Taro.hideLoading();
          console.log(res.data);
          const { positions, usedPositions } = res.data;
          setList(positions);
          setUsedList(usedPositions);
        })
        .catch(err => {
          Taro.hideLoading();
          console.log(err);
          Taro.showToast({
            title: err.msg || '请求失败',
            icon: 'none',
          });
        });
    },
    [positionName],
  );
  const addPositionHandle = useCallback(
    (id: string) => {
      addUsedPosition({
        positionId: id,
        customerId: userInfo.customerId,
      })
        .then(res => {
          console.log(res);
          fetchHandle('');
        })
        .catch(err => {
          console.log(err);
          Taro.showToast({
            title: err.msg || '网络错误',
            icon: 'none',
          });
        });
    },
    [addUsedPosition],
  );
  const delPositionHandle = useCallback(
    (id: string) => {
      delUsedPosition({
        positionId: id,
        customerId: userInfo.customerId,
      })
        .then(res => {
          console.log(res);
          fetchHandle('');
        })
        .catch(err => {
          console.log(err);
          Taro.showToast({
            title: err.msg || '网络错误',
            icon: 'none',
          });
        });
    },
    [addUsedPosition],
  );

  useEffect(() => {
    fetchHandle(positionName);
  }, [positionName, userInfo.customerId]);

  return {
    list,
    usedList,
    fetchList: fetchHandle,
    addPositionHandle,
    delPositionHandle,
  };
};

export default usePositionList;
