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

import FigureList from "@/components/list/FigureList";
import FigureListItem from "@/components/list/FigureListItem";
import { useEffect } from "react";
import WemetaRadio from "@/components/WemetaRadio/index";

import IconFIleLink from "@/components/icon/IconFileLink"


import { useKnowledge } from "./knowledge";
import type { TKnowledgeItem } from "@/types/knowledge";
import { EKnowlegeTypes } from "@/consts/enum";
export interface IProps {
  multi?: boolean; // 是否多选
  types?: EKnowlegeTypes[]; // 列表类型
  entId?: string|number;// 企业id
  onChange: (value: TKnowledgeItem[]) => void 
}
const Index = ({ types, multi,  entId, onChange }: IProps) => {
  const {
    list,
    scrollTop,
    checkedValue,
    loadMore,
    initLoad,
    setCheckedValue,
  } = useKnowledge({ types: types, entId });

  const onScrollToLower = async () => {
    loadMore();
  };

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

  const handleClick = (item: TKnowledgeItem) => {
    let results:TKnowledgeItem[] = [];
    // 单选
    if(!multi){
      const found = checkedValue.find( _item => _item.knowledgeId === item.knowledgeId)
      if(found){
        setCheckedValue(results)
        onChange(results)
        return;
      }  
      results = [item]
      setCheckedValue(results)
      onChange(results)
      return;
    }

    // 多选
    const found = checkedValue.find( _item => _item.knowledgeId === item.knowledgeId)
    if(found){
      results = checkedValue.filter(_item => _item.knowledgeId != item.knowledgeId)
      setCheckedValue(results)
      onChange(results)
      return;
    }
    results = [...checkedValue, item]
    setCheckedValue(results)
    onChange(results)
  };
  const rightRenderer = (item: TKnowledgeItem) => {
    
    return (
      <View className="flex items-center">
        <WemetaRadio
          checkbox
          checked={!!checkedValue.find(_item =>  _item.knowledgeId === item.knowledgeId)}
        ></WemetaRadio>
      </View>
    );
  };

  return (
    <ScrollView
      scrollY
      onScrollToLower={onScrollToLower}
      scrollTop={scrollTop}
      style={{
        flex: 1,
        height: "100%", // 高度自适应
      }}
    >
      <FigureList>
      
        {list.map((item) => {
          return (
            <FigureListItem
              figure={()=> <IconFIleLink />}
              underline
              onClick={() => handleClick(item)}
              rightRenderer={() => rightRenderer(item)}
            >
              <View className="flex flex-col flex-1 gap-2 w-full overflow-hidden">
                <View className="text-14 leading-22 truncate">{item.title}</View>
                <View className="text-12 leading-20 text-gray-45">
                
                  {item.createTime} | {item.fileSizeStr}
                </View>
              </View>
            </FigureListItem>
          );
        })}
      </FigureList>
    </ScrollView>
  );
};

export default Index;
