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 from "@/components/empty-data";
import RotateLoading from "@/components/rotate-loading";
import Taro from "@tarojs/taro";

import KnowledgeIcon from "@/components/KnowledgeIcon";
import {
  getEntKnowledgeList,
} from "@/service/knowledge";
import type { TKnowledgeItem } from "@/types/knowledge";

import { useLoadMoreInfinite, createKey } from "@/utils/loadMoreInfinite";
export interface Iprops {
  entId: string|number
}
const Index = ({entId}:Iprops) => {
  
  
  const [scrollTop, setScrollTop] = useState(9999)

  const fetcher = async ([_url, {nextId, pageSize},  [entId]]) => {
    const res = await getEntKnowledgeList({ startId: nextId, pageSize, entId });
    return res.data;
  };
  const { list, loadMore, pageIndex } = useLoadMoreInfinite<TKnowledgeItem[]>(createKey(`getEntKnowledgeList ${entId}`, 10, [entId]),
    fetcher);

  const onScrollToUpper = async () => {
    console.log('toUpper')
    loadMore()
  }
  useDidShow(()=> {
    loadMore()
  })
  useEffect(() => {
    if(pageIndex === 1){
      setScrollTop(prev => prev + 1)
    }
  }, [pageIndex]);
  

  const handleEdit = (item: TKnowledgeItem)=> {
    if(item.parseStatus !== 'parsed'){
      return ;
    }
    Taro.navigateTo({
      url: `/pages/knowledge-item/index?knowledgeId=${item.knowledgeId}&entId=${entId}`
    })
  }
  const rightRenderer = (item: TKnowledgeItem) => {
    if(item.parseStatus !== 'parsed'){
      return <></>
    }
    return (
      <View className="flex items-center gap-4">
        <RotateLoading />
        <View className="text-primary text-12">解析中</View>
      </View>
    );
  };

  return (
    <ScrollView
      scrollY
      onScrollToUpper={onScrollToUpper}
      scrollTop={scrollTop}
      style={{
        flex: 1,
        height: "100%", // 高度自适应
      }}
    >
      {list.length<=0 ? <View className="pt-46"><EmptyData type={'plane'}/></View> : <></>}
      <FigureList>
      {list.map(item => {
        return <FigureListItem
            figure={()=> <KnowledgeIcon data={item}/>}
            underline
            arrow={item.parseStatus === 'parsed'}
            onClick={()=> handleEdit(item)}
            rightRenderer={()=> rightRenderer(item)}
          >
            <View className="flex flex-col flex-1 gap-2 w-full">
              <View className="text-14 leading-22">{item.title}</View>
              <View className="text-12 leading-20 text-gray-45">
              {item.createTime} | {item.fileSize}
              </View>
            </View>
          </FigureListItem>
      })}
      </FigureList>
    </ScrollView>
  );
};

export default Index;
