/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2025-04-15 14:47:27
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2025-05-27 15:04:38
 * @FilePath: /pfmBackMana/src/pages/baseInfoMana/empMana/components/EmployeeList/useEmployeeList.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
// useEmployeeList.ts
import { useState, useEffect, useCallback, useRef } from 'react';
import { Employee, fetchEmployeeList, syncEmployeeList } from '../../service';
import { message } from 'antd';

export const useEmployeeList = (keywords: string, pageSize: number = 10) => {
  const [employees, setEmployees] = useState<Employee[]>([]);
  const [curPage, setCurPage] = useState<number>(1);
  const [totalPage, setTotalPage] = useState<number>(1);
  const [hasMore, setHasMore] = useState<boolean>(true);
  const [loading, setLoading] = useState<boolean>(false);
  const [error, setError] = useState<string | null>(null);
  const [syncing, setSyncing] = useState<boolean>(false); // 添加同步状态
  
  // 添加请求状态引用
  const isLoadingRef = useRef<boolean>(false);

  /**
   * 根据 page 及关键词获取数据
   * @param page 要获取的页码
   * @param isRefresh 是否重置数据（刷新或搜索时使用）
   */
  const fetchData = useCallback(
    async (page: number, isRefresh: boolean = false) => {
      // 防止重复请求 - 使用ref来检查状态
      if (isLoadingRef.current && !isRefresh) {
        return;
      }
      
      isLoadingRef.current = true;
      setLoading(true);
      setError(null);
      
      try {
        const res = await fetchEmployeeList({
          current: page,
          pageSize,
          filter: keywords,
        });

        if (res) {
          const {
            currPage: returnedPage,
            totalPage: returnedTotalPage,
            list,
          } = res;
          
          if (isRefresh) {
            setEmployees(list);
          } else {
            setEmployees((prev) => [...prev, ...list]);
          }
          
          setCurPage(returnedPage);
          setTotalPage(returnedTotalPage);
          const hasMoreData = returnedPage < returnedTotalPage;
          setHasMore(hasMoreData);
        } else {
          setError('接口返回错误');
        }
      } catch (err: any) {
        const errorMessage = err.message || '网络错误';
        setError(errorMessage);
      } finally {
        isLoadingRef.current = false;
        setLoading(false);
      }
    },
    [keywords, pageSize],
  );

  // 当关键词发生变化时，重置页码并重新请求数据
  useEffect(() => {
    setCurPage(1);
    setHasMore(true); // 重置hasMore状态
    fetchData(1, true);
  }, [keywords, fetchData]);

  // 加载更多数据
  const loadMore = useCallback(async () => {
    if (!hasMore || isLoadingRef.current) {
      return;
    }
    
    await fetchData(curPage + 1);
  }, [hasMore, curPage, fetchData]);

  // 刷新数据
  const refresh = async () => {
    setCurPage(1);
    setHasMore(true);
    await fetchData(1, true);
  };

  // 同步员工数据
  const syncEmpData = async () => {
    try {
      setSyncing(true); // 使用独立的同步状态
      const response = await syncEmployeeList();
      if (response) {
        message.success('员工数据同步成功');
        // 同步成功后刷新列表
        await refresh();
      }
    } catch (error) {
      console.error('同步员工数据失败', error);
      message.error('员工数据同步失败');
    } finally {
      setSyncing(false); // 重置同步状态
    }
  };

  return {
    employees,
    loadMore,
    refresh,
    syncEmpData,
    hasMore,
    loading,
    syncing,
    error,
    curPage,
    totalPage,
  };
};
