import { ScrollView, View, Image } from "@tarojs/components";
import MessageRobotRich from "@/components/chat-message/MessageRobotRich";
import MessageRich from "@/components/chat-message/MessageRich";

import FigureList from "@/components/list/FigureList";
import FigureListItem from "@/components/list/FigureListItem";
import EmptyData, {EmptyDataTitle, EmptyDataSubInfo} from "@/components/EmptyData";

import { useEffect, useRef, useState } from "react";
import Taro, { useDidShow } from "@tarojs/taro";

import { useUserStore } from "@/store/userStore";
import KnowledgeIcon from "@/components/KnowledgeIcon";
import {
  isParsedFail,
  isParsedSuccess,
  isParsing,
} from "../../../knowledgeUtils";
import { getEntKnowledgeStream } from "@/service/knowledge";

import type { TKnowledgeStreamResponseData } from "@/types/knowledge";
import { DEFAULT_AGENT } from "@/config";
import { useLoadMoreInfinite, createKey } from "@/utils/loadMoreInfinite";

export interface IProps {
  entId: string | number;
  assistantOnly?: boolean;
  setTotalCount: (count: number) => void;
}

const Index = ({ entId, assistantOnly, setTotalCount }: IProps) => {
  const [scrollTop, setScrollTop] = useState(9999);
  const { whoami } = useUserStore();

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

  const getFilterList = (list: TKnowledgeStreamResponseData[]) => {
    if (!assistantOnly) return list;
    return list.filter((item) => {
      return item.role === "assistant";
    });
  };

  const reversedList = getFilterList(list).reverse();

  const onScrollToUpper = async () => {
    console.log("toUpper");
    loadMore();
  };
  useDidShow(() => {
    mutate(undefined, { revalidate: true });
  });
  useEffect(() => {
    if (pageIndex === 1) {
      setScrollTop((prev) => prev + 1);
    }
  }, [pageIndex]);

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

  return (
    <View className="flex-1 h-full overflow-hidden">
      <ScrollView
        scrollY
        onScrollToUpper={onScrollToUpper}
        scrollTop={scrollTop}
        style={{
          flex: 1,
          height: "100%", // 高度自适应
        }}
      >
        <View className="flex flex-col gap-20 pb-32 mx-16">
          {reversedList.length <= 0 ? (
            <EmptyData type={"search"}>
              <EmptyDataTitle>暂无数据</EmptyDataTitle>
                <EmptyDataSubInfo>
                  <View>可登录电报端管理企业知识库</View>
                  <View>也可以开启个人知识库同步到企业知识库</View>
                </EmptyDataSubInfo>
            </EmptyData>
          ) : (
            <></>
          )}
          {reversedList.map((group) => {
            // 渲染自己发送的消息
            if (group.role === "user") {
              return group.knowledgeList.map((item) => {
                return (
                  <MessageRich
                    data={{
                      avatar: whoami?.avatarUrl ?? "",
                      name: whoami?.nickName ?? "",
                    }}
                  >
                    <View className="flex items-center gap-12">
                      <KnowledgeIcon data={item} />
                      <View className="flex flex-col flex-1 gap-2">
                        <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>
                    </View>
                  </MessageRich>
                );
              });
            }
            // 渲染机器人小蓝本助手的消息
            return (
              <MessageRobotRich
                data={{ ...DEFAULT_AGENT, fileLen: group.knowledgeList.length }}
                analyzeStatus={group.isParsing ? "doing" : "done"}
                content={group.content}
              >
                <FigureList>
                  {group.knowledgeList.map((item, index) => {
                    return (
                      <FigureListItem
                        figure={() => {
                          return <KnowledgeIcon data={item} />;
                        }}
                        underline={index + 1 < group.knowledgeList.length}
                        arrow={isParsedSuccess(item)}
                        onClick={() =>
                          Taro.navigateTo({
                            url: `/pages/knowledge-item/index?knowledgeId=${item.knowledgeId}&entId=${entId}`,
                          })
                        }
                      >
                        <View className="flex flex-col flex-1 gap-2 w-full">
                          <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>
              </MessageRobotRich>
            );
          })}
        </View>
      </ScrollView>
    </View>
  );
};

export default Index;
