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


import { EKnowlegeTypes } from "@/consts/enum";
import KnowledgeIcon from "@/components/KnowledgeIcon";
import EmptyData from "@/components/empty-data";


import type { TKnowledgeItem } from "@/types/knowledge";

import {
  getKnowledgeList,
} from "@/service/knowledge";

import { useLoadMoreInfinite, createKey } from "@/utils/loadMoreInfinite";

export interface IProps {
  types?: EKnowlegeTypes[],
}

const Index = ({types}: IProps) => {
  
  const [scrollTop, setScrollTop] = useState(9999)

  const fetcher = async ([_url, {nextId, pageSize}, [types]]) => {
    const res = await getKnowledgeList({ startId: nextId, pageSize, types });
    return res.data;
  };
  const { list, loadMore } = useLoadMoreInfinite<TKnowledgeItem[]>( createKey('getKnowledgeList', 2, [types]), fetcher,);

  const onScrollToUpper = async () => {
    console.log('toUpper')
    loadMore()
  }


  useEffect(() => {
    loadMore();
  }, []);

  

  const handleEdit = (item: TKnowledgeItem)=> {
    if(item.parseStatus !== 'parsed'){
      return ;
    }
    Taro.navigateTo({
      url: `/pages/knowledge-item/index?knowledgeId=${item.knowledgeId}`
    })
  }
  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;
