/**
 * 知识库
 */

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

import PageCustom from "@/components/page-custom/index";
import NavBarNormal from "@/components/NavBarNormal/index";
import IconA from "@/components/icon/IconA";
import IconQ from "@/components/icon/IconQ";
import { useEffect, useState } from "react";
import CardEditable from "@/components/card/card-editable/index";
import Taro, { useRouter, useDidShow } from "@tarojs/taro";
import {
  deleteVisitorDislikeAnswer,
  getVisitorDislikeMessages,
} from "@/service/visitor";
import { TVisitorChat } from "@/types/visitor";

import { useModalStore } from "@/store/modalStore";
import { isSuccess } from "@/utils";
import { useLoadMoreInfinite, createKey } from "@/utils/loadMoreInfinite";
import EmptyData from "@/components/EmptyData";
import { EContentType } from "@/types/bot";

export default function Index() {
  const router = useRouter();
  const { showModal } = useModalStore((state) => state.actions);
  const { agentId } = router.params as { agentId: string };
  const [scrollTop, setScrollTop] = useState(0);

  const fetcher = async ([_url, { nextId, pageSize }]) => {
    const res = await getVisitorDislikeMessages({
      agentId,
      startId: nextId,
      pageSize,
    });
    return res.data;
  };
  const { list, loadMore, setSize, pages, pageIndex, mutate } =
    useLoadMoreInfinite<TVisitorChat[]>(
      createKey(`getVisitorDislikeMessages${agentId}`),
      fetcher
    );
  const qaList: { user?: TVisitorChat; assistant?: TVisitorChat }[] = [];

  // 从数组中提取问答对
  // 暂定奇数行是用户的提问，偶数行是助手的回答
  // 其中有些只有用户提问，但由于错误或网络问题导致没有助手回答需要跳过
  for (let i = 0; i < list.length; i++) {
    const item: { user?: TVisitorChat; assistant?: TVisitorChat } = {};
    if (list[i].role === "user") {
      item.user = list[i];
      if (list[i + 1]?.role === "assistant") {
        item.assistant = list[i + 1];
        if(item.assistant.contentType == EContentType.AiseekQA){
          try{
            const contentJson = JSON.parse(item.assistant.content as string)
            item.assistant.content = contentJson.answer.text
            // 把消息详情放入统一 body 中
            item.assistant.body = {...item.assistant, content: contentJson, contentType: item.assistant.contentType}
          }catch(e){
            // console.error(e)
          }
        }
        qaList.push(item);
        i++; // 跳过下一个元素，因为它已经被配对了
      }else{
        continue; // 如果下一个不是 assistant，则跳过当前 user
      }
    }
  }

  // console.log(qaList);

  // const dislikeList = list.filter((_item) => _item.role === 'assistant');

  const handleEdit = (item: TVisitorChat) => {
    Taro.navigateTo({
      url: `/pages/message-editor/index?msgId=${item.msgId}&visitorId=${item.visitorId}&agentId=${item.agentId}`,
    });
  };

  // 删除问答项
  const handleDeleteItem = async (item: TVisitorChat) => {
    showModal({
      content: "确定删除该问答项吗？",
      onConfirm: async () => {
        const { status } = await deleteVisitorDislikeAnswer({
          visitorId: item.visitorId,
          msgId: item.msgId,
        });
        if (isSuccess(status)) {
          Taro.showToast({ title: "删除成功", icon: "success" });
          // if (newPages[newPages.length - 1]?.length === 0) {
          //   setSize(size - 1)
          // }
          // 1. 乐观更新：立即移除数据
          mutate((currentPages) => {
            if (currentPages === undefined) return currentPages;
            // 创建全新的 pages 数组（深拷贝）
            const newPages = currentPages.map((page, index) => {
              // 如果不是目标页，直接返回原引用（避免不必要的重渲染）
              if (index !== pageIndex - 1) return page;

              // 创建目标页的新副本
              return {
                ...page, // 复制其他属性
                data: page.data.filter((_item) => _item.msgId !== item.msgId),
              };
            });

            return newPages;
          }, false); // 不重新验证
        }
      },
    });
  };
  const handleView = async (item: TVisitorChat) => {
    Taro.navigateTo({
      url: `/pages/chat-messages/index?visitorId=${item.visitorId}&msgId=${item.msgId}`,
    });
  };

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

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

  const createCardOptions = (item: TVisitorChat) => {
    return [
      <View className="flex-1 w-full h-full py-12 flex-center" onClick={() => handleDeleteItem(item)}>删除</View>,
      <View className="flex-1 w-full h-full py-12 flex-center" onClick={() => handleView(item)}>查看对话</View>,
      <View className="flex-1 w-full h-full py-12 flex-center" onClick={() => handleEdit(item)}>编辑</View>,
    ];
  };

  const renderContent = (item:TVisitorChat)=> {
    if(item.contentType === EContentType.TextPlain){
      return item.content
    }
    if(item.contentType === EContentType.AiseekQA){
      try{
        const body = item.body
        const payload = body?.content?.answer?.payload;
        const links = payload?.links ?? [];
        const pics = payload?.pics ?? [];
        return (
          <View>
            <View>{item.content}</View>
            <View className="pb-12">
              {pics.map((pic: string) => {
                return (
                  <View>
                    <Image src={pic} mode="widthFix" className="w-full"></Image>
                  </View>
                );
              })}
            </View>
            <View className="pb-12">
              {links.map((link: string) => {
                return <Text>{link}</Text>;
              })}
            </View>
          </View>
        );
      }catch(e){}
      return <View>解析出错...</View>;
    }
    return <></>
  }

  return (
    <PageCustom fullPage>
      <NavBarNormal scrollFadeIn backText="待处理差评"></NavBarNormal>
      <View className="w-full flex flex-col overflow-hidden h-full pt-2">
        <View className="rounded-container-header"></View>
        {/* <View className="text-14 font-medium leading-22 px-16 pb-16">
          问答列表共
          <Text className="text-primary"> 10 </Text>条
        </View> */}
        <ScrollView
          scrollY
          onScrollEnd={onScrollEnd}
          scrollTop={scrollTop}
          style={{
            flex: 1,
            height: "100%", // 高度自适应
          }}
        >
          <View className="pb-80">
            {qaList.length <= 0 ? (
              <View className="pt-24">
                <EmptyData type="search" text="待处理差评"></EmptyData>
              </View>
            ) : (
              <></>
            )}
            {qaList.map((item) => {
              if (!item.assistant) {
                return <></>;
              }
              return (
                <View className="flex flex-col gap-16 px-16 mb-16">
                  <CardEditable buttons={createCardOptions(item.assistant)}>
                    <View className="flex items-start mb-8 gap-8">
                      <View className="flex-center h-28">
                        <IconQ />
                      </View>
                      <View className="flex-1 font-medium text-14 leading-28">
                        {item.user?.content}
                      </View>
                    </View>

                    <View className="flex items-start gap-8">
                      <View className="flex-center  h-28">
                        <IconA />
                      </View>
                      <View className="flex-1 text-12 leading-20 text-gray-4 truncate">
                        <View className="truncate">
                          {renderContent(item.assistant)}
                        </View>

                        {!!item.assistant?.correctionLinks?.length && (
                          <View className="pb-12">
                            {item.assistant.correctionLinks.map((link) => {
                              return (
                                <View>
                                  查看链接 <Text>{link}</Text>
                                </View>
                              );
                            })}
                          </View>
                        )}
                        {!!item?.assistant.correctionPics?.length && (
                          <View className="pb-12">
                            {item.assistant.correctionPics.map((pic) => {
                              return (
                                <View>
                                  <Image
                                    src={pic}
                                    mode="widthFix"
                                    className="w-full"
                                  ></Image>
                                </View>
                              );
                            })}
                          </View>
                        )}
                      </View>
                    </View>
                  </CardEditable>
                </View>
              );
            })}
            {/* {dislikeList.map((item) => {
              return (
                <View className="flex flex-col gap-16 px-16 mb-16">
                  <CardEditable buttons={createCardOptions(item)}>
                    <View className="flex items-start mb-8 gap-8">
                      <View className="flex-center h-28">
                        <IconQ />
                      </View>
                      <View className="flex-1 font-medium text-14 leading-28">
                        {item.content}
                      </View>
                    </View>

                    <View className="flex items-start gap-8">
                      <View className="flex-center  h-28">
                        <IconA />
                      </View>
                      <View className="flex-1 text-12 leading-20 text-gray-4 truncate">
                        <View className="truncate">
                          {item.correctionAnswer}
                        </View>

                        {!!item.correctionLinks?.length && (
                          <View className="pb-12">
                            {item.correctionLinks.map((link) => {
                              return (
                                <View>
                                  查看链接 <Text>{link}</Text>
                                </View>
                              );
                            })}
                          </View>
                        )}
                        {!!item.correctionPics?.length && (
                          <View className="pb-12">
                            {item.correctionPics.map((pic) => {
                              return (
                                <View>
                                  <Image
                                    src={pic}
                                    mode="widthFix"
                                    className="w-full"
                                  ></Image>
                                </View>
                              );
                            })}
                          </View>
                        )}
                      </View>
                    </View>
                  </CardEditable>
                </View>
              );
            })} */}
          </View>
        </ScrollView>
      </View>
    </PageCustom>
  );
}
