import { ScrollView, View,Text } 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 { useContext, 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 {
  deleteMyKnowledgeStream,
  getMyKnowledgeStream,
} from "@/service/knowledge";

import { useLoadMoreInfinite, createKey } from "@/utils/loadMoreInfinite";
import { DEFAULT_AGENT } from "@/config";
import { isSuccess } from "@/utils";
import LoginMutationContext from "@/pages/knowledge/LoginMutationContext";


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

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

  const [scrollTop, setScrollTop] = useState(9999)

  const { isMutate, setLoginShow } = useContext(LoginMutationContext)
  const [showAsistantGreeting, setShowAsistantGreeting] = useState(false)


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


  const { list, loadMore, pageIndex, mutate ,data, error  } = 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}`
    })
  }

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

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

    }
  }, [pageIndex])

  useDidShow(()=> {
    mutate();
  })

  useEffect(()=> {
    mutate();
  }, [isMutate])
  useEffect(()=> {
    if(error?.code === 401){
      setLoginShow(true)
    }

  }, [error])

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

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

  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 px-16">
        {/* 欢迎语 */}
        {(showAsistantGreeting) && <MessageRobotRich data={DEFAULT_AGENT}><WelcomeCard /></MessageRobotRich>}

        {reversedList.map((group) => {
          // 渲染自己发送的消息
          if (group.role === "user") {
            return <View onLongPress={()=> handleLongPress(group.streamId)}>
            {group.knowledgeList.map((item) => {
              return (
                <MessageRich data={{
                  avatar: whoami?.avatarUrl ?? '',
                  name: whoami?.nickName ?? ''
                }}>
                  <View className="flex items-start gap-12">
                    <View className="w-36 h-36 overflow-hidden pt-4"><KnowledgeIcon data={item} /></View>
                    <View className="flex flex-col flex-1 gap-2 truncate">
                      <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>
              );
            })}
            </View>
          }
          // 渲染机器人小蓝本助手的消息
          return (<View onLongPress={()=> handleLongPress(group.streamId)}>
            <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 <View className="w-36 h-36 overflow-hidden pt-4"><KnowledgeIcon data={item}/></View>
                      }}
                      underline={index + 1 < group.knowledgeList.length}
                      arrow={item.parseStatus === 'parsed'}
                      onClick={()=> handleEdit(item)}
                    >
                      <View className="flex flex-col flex-1 gap-2 truncate">
                        <View className="text-14 leading-22 max-w-full min-w-0 inline-block truncate">{item.title}</View>
                        <View className="flex items-center text-12 leading-20 text-gray-4">
                          <View className="flex items-center gap-8">
                            <View>{item.createTime}</View> <View>|</View> { item.parseStatus === 'parsed' ? <View><Text className="text-primary">{`${item.answerCnt}`}</Text> 条问答</View> :  item.fileSizeStr}
                          </View>
                        </View>
                      </View>
                    </FigureListItem>
                  );
                })}
              </FigureList>
            </MessageRobotRich>
            </View>
          );
        })}
      </View>
    </ScrollView>
    </View>
  );
};

export default Index;
