import { ScrollView, View, Image } from "@tarojs/components";

import FigureList from "@/components/list/FigureList";
import FigureListItem from "@/components/list/FigureListItem";
import { useDidShow } from "@tarojs/taro";
import { useEffect, useState } from "react";
import EmptyData, {EmptyDataTitle, EmptyDataSubInfo} from "@/components/EmptyData";
import RotateLoading from "@/components/rotate-loading";
import Taro from "@tarojs/taro";
import IconError from '@/images/svgs/knowledge/IconError.svg'
import IconCorrect from '@/images/svgs/knowledge/IconCorrect.svg'

import KnowledgeIcon from "@/components/KnowledgeIcon";
import { getEntKnowledgeList } from "@/service/knowledge";
import type { TKnowledgeItem } from "@/types/knowledge";
import {
  isParsedFail,
  isParsedSuccess,
  isParsing
} from '../../../knowledgeUtils'

import { useLoadMoreInfinite, createKey } from "@/utils/loadMoreInfinite";
export interface Iprops {
  entId: string | number;
  setTotalCount: (count: number) => void;
}
const Index = ({ entId, setTotalCount }: Iprops) => {
  const fetcher = async ([_url, { nextId, pageSize }, [entId]]) => {
    const res = await getEntKnowledgeList({ startId: nextId, pageSize, entId });
    return res.data;
  };
  const { list, loadMore, pageIndex, mutate, data } = useLoadMoreInfinite<
    TKnowledgeItem[]
  >(createKey(`getEntKnowledgeList ${entId}`, 30, [entId]), fetcher);

  const onScrollToLower = async () => {
    console.log("toLower");
    loadMore();
  };
  useDidShow(() => {
    mutate(undefined, { revalidate: true });
  });

  useEffect(() => {
    if (data && pageIndex === 1) {
      setTotalCount(data?.[0].totalCount || 0);
    }
  }, [data, pageIndex]);




  const handleEdit = (item: TKnowledgeItem) => {
    if (item.parseStatus === "parse_fail") {
      return;
    }
    Taro.navigateTo({
      url: `/pages/knowledge-item/index?knowledgeId=${item.knowledgeId}&entId=${entId}`,
    });
  };
  const rightRenderer = (item: TKnowledgeItem) => {
    if (isParsing(item)) {
      return (
        <View className="flex items-center gap-4 self-center">
          <RotateLoading />
          <View className="text-primary text-12">解析中</View>
        </View>
      );
    }
    if(isParsedSuccess(item)){
      return (
        <View className="flex items-center self-center">
          <Image src={IconCorrect} className="w-20 h-20"  />
        </View>
      );
    }
    if(isParsedFail(item)){
      return (
        <View className="flex items-center self-center">
          <Image src={IconError} className="w-20 h-20"  />
        </View>
      );
    }
    return <></>
  };

  return (
    <View className="flex-1 h-full overflow-hidden">
    <ScrollView
      scrollY
      onScrollToLower={onScrollToLower}
      style={{
        flex: 1,
        height: "100%", // 高度自适应
      }}
    >
      {list.length <= 0 ? (
        <EmptyData type={"search"}>
          <View className="text-center text-14 leading-28 text-gray-4 mb-44 w-full">
            <EmptyDataTitle>暂无数据</EmptyDataTitle>
            <EmptyDataSubInfo>
              <View>可登录电报端管理企业知识库</View>
              <View>也可以开启个人知识库同步到企业知识库</View>
            </EmptyDataSubInfo>
          </View>
        </EmptyData>
      ) : (
        <></>
      )}
      <FigureList className="mx-16 pb-32">
        {list.map((item) => {
          return (
            <FigureListItem
              figure={() => <KnowledgeIcon data={item} />}
              underline
              onClick={() => handleEdit(item)}
              rightRenderer={() => rightRenderer(item)}
            >
              <View className="flex flex-col flex-1 gap-2 w-full truncate">
                <View className="text-14 leading-22 truncate">{item.title}</View>
                <View className="text-12 leading-20 text-gray-4">
                  {item.createTime} | {item.fileSizeStr}
                </View>
              </View>
            </FigureListItem>
          );
        })}
      </FigureList>
    </ScrollView>
    </View>
  );
};

export default Index;
