import Taro, { useEffect, useState, useReducer } from '@tarojs/taro';
import { fetchFeedbackList, FeedbackItem } from '@/api/feedback';
import usePagination from '@/hooks/usePagination';
import Actions from '@/types/Store/Actions';

const reducer = (state: FeedbackItem[], action: Actions): FeedbackItem[] => {
  switch (action.type) {
    case 'getMoreList':
      return [...action.payload, ...state];
    case 'refreshList':
      return action.payload;
    case 'addNewMessage':
      return [...state, action.payload];
    default:
      return state;
  }
};
const initState: FeedbackItem[] = [];
const useFeedbackList = (customerId: number) => {
  const [lastId, setLastId] = useState(0);
  const [pagination, setPaination] = usePagination();
  const fetchListHandle = (lastId: number) => setLastId(lastId);
  const [feedbackList, dispatch] = useReducer(reducer, initState);

  useEffect(() => {
    Taro.showLoading();
    fetchFeedbackList(
      lastId
        ? {
            pageNum: pagination.pageNum + 1,
            pageSize: pagination.pageSize,
            customerId,
            lastId,
          }
        : {
            pageNum: 1,
            pageSize: pagination.pageSize,
            customerId,
          },
    )
      .then(res => {
        console.log(res);
        if (res.data.length) {
          let list = res.data.map(item => ({
            ...item,
            replayList: item.replayList.reverse(),
          }));
          if (lastId) {
            dispatch({
              type: 'getMoreList',
              payload: list,
            });
            setPaination({ ...pagination, pageNum: pagination.pageNum + 1 });
          } else {
            dispatch({
              type: 'refreshList',
              payload: list,
            });
          }
        }
        Taro.hideLoading();
      })
      .catch(err => {
        Taro.hideLoading();
        Taro.showToast({
          title: err.msg || '请求失败',
          icon: 'none',
        });
      });
  }, [lastId]);
  const pushNewMsg = (msgData: FeedbackItem) =>
    dispatch({
      type: 'addNewMessage',
      payload: msgData,
    });

  return { list: feedbackList, fetchListHandle, pushNewMsg };
};

export default useFeedbackList;
