import { useState, useCallback } from "react";
import { isSuccess } from "@/utils";
import type { TKnowledgeItem } from "@/types/knowledge";
import {
  getEntKnowledgeList,
  getKnowledgeList,
} from "@/service/knowledge";
import { EKnowlegeTypes } from "@/consts/enum";

export interface UseKnowledgeHook {
  scrollTop: number;
  totalCount: number;
  list: TKnowledgeItem[];
  isLoading: boolean;
  startId?: string;
  checkedValue: TKnowledgeItem[],
  listTypes?: EKnowlegeTypes[];
  loadMore: (force?: boolean) => Promise<void>;
  initLoad: () => Promise<void>;
  setListTypes: (types: EKnowlegeTypes[]) => void;
  setCheckedValue: React.Dispatch<React.SetStateAction<TKnowledgeItem[]>>;
}

export function useKnowledge({entId, types = []}: {entId?: string|number, types?: EKnowlegeTypes[]}): UseKnowledgeHook {
  const req = entId ? getEntKnowledgeList : getKnowledgeList
  const [scrollTop, setScrollTop] = useState(9999);
  const [totalCount, setTotalCount] = useState(10000);
  const [list, setList] = useState<TKnowledgeItem[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [startId, setStartId] = useState<string | undefined>(undefined);
  const [listTypes, setListTypesState] = useState<EKnowlegeTypes[]>(types);
  const [checkedValue, setCheckedValue] = useState<TKnowledgeItem[]>([]);

  const loadMore = useCallback(async (force?: boolean) => {
    if (!force && (list.length >= totalCount || isLoading)) {
      return;
    }
    setIsLoading(true);
    try {
      const params = entId ? ({
        startId,
        pageSize: 10,
        types: listTypes,
        entId: entId,
      }) : ({
        startId,
        pageSize: 10,
        types: listTypes,
      })
      const response = await req(params);
      const result = isSuccess(response.status);
      if (result) {
        // 提取所有 TKnowledgeItem
        const newData = [...list, ...response.data.data ?? []];
        setList(newData);
        setStartId(response.data.nextId);
        setTotalCount(response.data.totalCount ?? 0);
      }
    } finally {
      setIsLoading(false);
      setScrollTop((prev) => prev + 1);
    }
  }, [list, totalCount, isLoading, startId]);

  const initLoad = useCallback(async () => {
    setList([]);
    setStartId(undefined);
    setTotalCount(9999);
    setIsLoading(false);
    // eslint-disable-next-line no-console
    console.log("initLoad");
    await loadMore();
  }, [loadMore]);

  const setListTypes = useCallback((types: EKnowlegeTypes[]) => {
    setListTypesState(types);
  }, []);

  return {
    scrollTop,
    totalCount,
    list,
    isLoading,
    startId,
    listTypes,
    checkedValue,
    loadMore,
    initLoad,
    setListTypes,
    setCheckedValue,
  };
}
