import Taro, { useEffect, useState, useReducer } from '@tarojs/taro';
import {
  getAppointmentRecords,
  AppointmentRecordsResponse,
} from '@/api/shower';
import Actions from '@/types/Store/Actions';

const reducer = (state: AppointmentRecordsResponse[], action: Actions) => {
  switch (action.type) {
    case 'getRecordList':
      return action.payload;
    case 'appendRecordList':
      return [...state, ...action.payload];
    default:
      return state;
  }
};

const useAppointRecordsList = (
  userId: number,
): [AppointmentRecordsResponse[], () => void, () => void] => {
  const [pageNum, setPageNum] = useState(1);
  const [list, dispatch] = useReducer(reducer, []);

  const fetchList = (pageNum: number) => {
    return getAppointmentRecords({
      userId,
      pageSize: 10,
      pageNum,
    });
  };

  const fetchMoreList = () => {
    Taro.showLoading({
      title: '',
      mask: true,
    });
    fetchList(pageNum + 1)
      .then(res => {
        Taro.hideLoading();
        console.log(res);
        let list = res.data.list;
        if (list.length) {
          setPageNum(pageNum + 1);
          dispatch({ type: 'appendRecordList', payload: res.data.list });
        }
      })
      .catch(err => {
        console.log(err);
        Taro.showToast({
          title: err.msg || '网络错误',
          icon: 'none',
        });
      });
  };

  const fetchNewList = () => {
    Taro.showLoading();
    fetchList(1)
      .then(res => {
        Taro.hideLoading();
        console.log(res);
        dispatch({ type: 'getRecordList', payload: res.data.list });
      })
      .catch(err => {
        console.log(err);
        Taro.showToast({
          title: err.msg || '网络错误',
          icon: 'none',
        });
      });
  };

  useEffect(() => {
    fetchNewList();
  }, [userId]);

  return [list, fetchNewList, fetchMoreList];
};

export default useAppointRecordsList;
