import { ScrollView, View,Image } from "@tarojs/components";
import MessageRobotRich from "@/components/chat-message/MessageRobotRich";
import MessageRich from "@/components/chat-message/MessageRich";
import { WelcomeCard  } from "../../AsistantMessage";
import KnowledgeIcon from '@/components/KnowledgeIcon'


import FigureList from "@/components/list/FigureList";
import FigureListItem from "@/components/list/FigureListItem";

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

import { useUserStore } from "@/store/userStore";

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

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

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

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

interface IProps {
  assistantOnly?: boolean;
}

const Index = ({assistantOnly}: IProps) => {

  const [scrollTop, setScrollTop] = useState(9999)
  // const [list, setList] = useState<TKnowledgeStreamResponseData[]>([]);

  const fetcher = async ([_url, {nextId, pageSize}]) => {
      const res = await getMyKnowledgeStream({startId: nextId, pageSize });
      return res.data;
  };

  
  const { list, loadMore, pageIndex } = useLoadMoreInfinite<TKnowledgeStreamResponseData[]>(
    createKey('getMyKnowledgeStream', 10),
    fetcher,
  );

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

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

  
  const {whoami} = useUserStore();
  
  
  const onScrollToUpper = async () => {
    console.log("toUpper");
    loadMore();
  };

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

  useEffect(()=> {
    if(pageIndex === 1){
      setTimeout(()=> {
        setScrollTop( prev => prev + 1); // 重置滚动位置
      }, 300)
      
    }
  }, [pageIndex])

  console.log(reversedList, 'reversedList');
  

  return (
    <ScrollView
      scrollY
      onScrollToUpper={onScrollToUpper}
      scrollTop={scrollTop}
      style={{
        flex: 1,
        height: "100%", // 高度自适应
      }}
    >
      <View className="flex flex-col gap-20 pb-80">
        {/* 欢迎语 */}
        {(reversedList.length <= 0) && <MessageRobotRich data={DEFAULT_AGENT}><WelcomeCard /></MessageRobotRich>}

        {/* 添加小蓝本助手成功 */}
        {/* <MessageRobotRich data={avatarData}>
          <AddSuccessfulTips />
        </MessageRobotRich> */}

        {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">
                    <View className="w-36 h-36 overflow-hidden"><KnowledgeIcon data={item} /></View>
                    <View className="flex flex-col flex-1 gap-2">
                      <View className="text-14 leading-22">{item.title}</View>
                      <View className="text-12 leading-20 text-gray-45">
                        {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={item.parseStatus === 'parsed'}
                      onClick={()=> handleEdit(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.fileSizeStr}
                        </View>
                      </View>
                    </FigureListItem>
                  );
                })}
              </FigureList>
            </MessageRobotRich>
          );
        })}
      </View>
    </ScrollView>
  );
};

export default Index;
