import { View, Image, Text } from "@tarojs/components";
import Taro, { useReachBottom, useRouter } from "@tarojs/taro";
import NavBarNormal from "@/components/NavBarNormal/index";
import PageCustom from "@/components/page-custom/index";
import { useEffect, useState } from "react";
import { isSuccess } from "@/utils";
import { getVisitorInfo } from "@/service/visitor";
import VisitorSummary from "./components/VisitorSummary";
import EmptyData, { EmptyDataSubInfo } from "@/components/EmptyData";
import { getVisitorMessages } from "@/service/visitor";
import { TVisitorAgent, TVisitorChat } from "@/types/visitor";
import { createKey, useLoadMoreInfinite } from "@/utils/loadMoreInfinite";
import IconEditButtonBlue from "@/images/svgs/dashboard/IconEditButtonBlue.svg";
import MarkDislike from "@/components/marks/MarkDislike";
import MarkLike from "@/components/marks/MarkLike";
import style from "./index.module.less";
import { EContentType, TMessage } from "@/types/bot";

export default () => {
  const router = useRouter();
  const { visitorId, sessionId } = router.params;
  if (!visitorId || !sessionId) {
    return <View>...</View>;
  }

  const [visitor, setVisitor] = useState<TVisitorAgent>();


  const fetchData = async () => {
    if (visitorId) {
      const response = await getVisitorInfo(visitorId);
      if (isSuccess(response.status)) {
        setVisitor(response.data);
      }
    }
  };

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

  const { list, loadMore } = useLoadMoreInfinite<TVisitorChat[]>(
    createKey(`api/v1/my/visitor/sessions${visitorId}`, 10, [sessionId]),
    fetcher,
    );
  
  // const parsedList = list.map((item: TMessage) => {
  //     if(item.contentType == EContentType.AiseekQA){
  //       try{
  //         const contentJson = JSON.parse(item.content as string)
  //         item.content = contentJson.answer.text
  //         // 把消息详情放入统一 body 中
  //         item.body = {...item, content: contentJson,}
  //       }catch(e){
  //         // console.error(e)
  //       }
  //     }
  //     return item
  //   })
    const qaList: { user?: TVisitorChat; assistant?: TVisitorChat|null }[] = [];
    for (let i = 0; i < list.length; i++) {
      const item: { user?: TVisitorChat; assistant?: TVisitorChat|null } = {};
      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);
          
        }else{
          item.assistant = null
          qaList.push(item);
          // continue; // 如果下一个不是 assistant，则跳过当前 user
        }
        i++; // 跳过下一个元素，因为它已经被配对了
      }
    }
    

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

  useReachBottom(() => {
    loadMore();
  });

  useEffect(()=> {
    fetchData()
  }, [visitorId])

  const renderAsistentContent = (item: TVisitorChat|null) => {
    if(item === null){
      return <View>
        无响应
      </View>
    }
    if(item.contentType === EContentType.AiseekQA){
      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>
      );
    }
    return <View>{item.content}</View>
  }

  const renderContent = (item: TVisitorChat|null) => {

    return (
      <View
        className="p-16 text-title rounded-8 relative"
        style={{ backgroundColor: "#F4F9FF" }}
      >
        <View>{renderAsistentContent(item)}</View>
        <View className="absolute top-0 right-0 z-10">
          {item?.isDislike ? <MarkDislike/>:<></>}
          {item?.isLike ? <MarkLike />:<></>}
        </View>
        {!!item && <View className={style.editButton} onClick={()=> handleEdit(item)}>
          <Image src={IconEditButtonBlue} className="w-14 h-14" />
        </View>}
      </View>
    );
  };
  
  return (
    <PageCustom>
      <NavBarNormal backText="对话记录" scrollFadeIn></NavBarNormal>
      {visitor ? <VisitorSummary data={visitor} /> : <></>}
      <View className="flex-1 overflow-hidden w-full mb-100">
        <View className="flex flex-col gap-16 px-16 w-full">
        {qaList.length <= 0 && (
            <EmptyData type="chat">
              <EmptyDataSubInfo>
                <View>当前暂无用户访问记录</View>
                <View>你的智能体正在等待首次互动</View>
              </EmptyDataSubInfo>
            </EmptyData>
          )}

          {qaList.map((item) => {
            return (
              <View className={` bg-white rounded-12 overflow-hidden`}>
                <View className="text-14 text-title mb-8 pt-16 px-16 font-pingfangSCMedium leading-22">{item.user?.content}</View>
                <View className="px-16 pb-16">{renderContent(item.assistant)}</View>
              </View>
            )
          })}
        </View>
      </View>
    </PageCustom>
  );
};
