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

import IconError from '@/images/svgs/knowledge/IconError.svg'
import IconCorrect from '@/images/svgs/knowledge/IconCorrect.svg'
import FigureListItem from "@/components/list/FigureListItem";
import { useDidShow } from "@tarojs/taro";
import { useEffect, useState } from "react";
import { WelcomeCard  } from "../../AsistantMessage";
import RotateLoading from "@/components/rotate-loading";
import Taro from "@tarojs/taro";
import MessageRobotRich from "@/components/chat-message/MessageRobotRich";
import { EKnowlegeTypes } from "@/consts/enum";
import KnowledgeIcon from "@/components/KnowledgeIcon";
import EmptyData from "@/components/EmptyData";
import { DEFAULT_AGENT } from "@/config";
import type { TKnowledgeItem } from "@/types/knowledge";

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

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

export interface IProps {
  types?: EKnowlegeTypes[];
  setTotalCount: (count: number) => void;
}

const Index = ({ types, setTotalCount }: IProps) => {
  const fetcher = async ([_url, { nextId, pageSize }, [types]]) => {
    const res = await getKnowledgeList({ startId: nextId, pageSize, types });
    return res.data;
  };
  const [showAsistantGreeting, setShowAsistantGreeting] = useState(false)
  const { list, loadMore, mutate, data, pageIndex } = useLoadMoreInfinite<
    TKnowledgeItem[]
  >(createKey("getKnowledgeList", 30, [types]), fetcher);

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

  useDidShow(() => {
    mutate(undefined, { revalidate: true });
  });

  let timer:any = undefined
  useEffect(()=> {
    timer = setTimeout(()=> {
      setShowAsistantGreeting(list.length <= 0)
    }, 1000)
    return ()=> {
      clearTimeout(timer)
    }
  }, [list])

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

  const handleEdit = (item: TKnowledgeItem) => {
    if (item.parseStatus !== "parsed") {
      return;
    }
    Taro.navigateTo({
      url: `/pages/knowledge-item/index?knowledgeId=${item.knowledgeId}`,
    });
  };

  const handleDelete = async (id: string | number) => {
    Taro.showModal({
      content: "确认删除该知识？",
      async success(result) {
        if (result.confirm) {
          const response = await deleteMyKnowledge(id);
          if (isSuccess(response.status)) {
            Taro.showToast({
              title: "删除成功",
              icon: "none",
            });
            mutate();
          }
        }
      },
    });
  };

  const handleHello = async (e: any) => {
    const detail = e.detail as { type: string; id: string };
    console.log(detail);
    // 置顶与取消置顶
    if (detail.type === "delete") {
      handleDelete(detail.id);
    }
  };

  const rightRenderer = (item: TKnowledgeItem) => {
    if (item.isParsing) {
      return (
        <View className="flex items-center gap-4 self-center">
          <RotateLoading />
          <View className="text-primary text-12">解析中</View>
        </View>
      );
    }
    if(item.parseStatus === 'parsed'){
      return (
        <View className="flex items-center self-center">
          <Image src={IconCorrect} className="w-20 h-20"  />
        </View>
      );
    }
    return (
      <View className="flex items-center self-center">
        <Image src={IconError} className="w-20 h-20"  />
      </View>
    );
  };

  const renderSummary = (item: TKnowledgeItem) => {
    const createTime = item.createTime.slice(5, 16);
    if (item.enableExactAnswer) {
      return (
        <View className="flex gap-8 items-center">
          <View>{createTime}</View>
          <View>|</View>
          <View className="">
            已开启 <Text className="text-primary">{item.answerCnt}</Text>{" "}
            条精准问答
          </View>
        </View>
      );
    }
    return (
      <>
        {createTime} | {item.fileSizeStr}
      </>
    );
  };

  return (
    <View className="flex-1 h-full overflow-hidden">
    <ScrollView
      scrollY
      onScrollToLower={onScrollToLower}
      style={{
        flex: 1,
        height: "100%", // 高度自适应
      }}
    >
      {(showAsistantGreeting) && <MessageRobotRich data={DEFAULT_AGENT}><WelcomeCard /></MessageRobotRich>}
      {/* <slide-delete> 如果被嵌套太深，会无法正常执行原生小程序逻辑 */}
      <View className="flex flex-col gap-8 pb-32 mx-16">
        {list.map((item) => {
          // @ts-ignore
          return (
            <View className="rounded-12 overflow-hidden">
              <slide-delete pid={item.knowledgeId} onAction={handleHello}>
                <FigureListItem
                  className="bg-white p-16"
                  figure={() => <KnowledgeIcon data={item} />}
                  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 flex items-center">
                      {renderSummary(item)}
                    </View>
                  </View>
                </FigureListItem>
              </slide-delete>
            </View>
          );
        })}
      </View>
    </ScrollView>
    </View>
  );
};

export default Index;
