import { View, Image, Text } from "@tarojs/components";
import Taro, { 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 { getVisitorMessagesByMsgId } from "@/service/visitor";
import { TVisitorAgent, TVisitorChat } from "@/types/visitor";
import { EContentType, TMessageBodyContent } from "@/types/bot";

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

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

  const fetchVisitor = async ()=> {
    const response = await getVisitorInfo(visitorId);
      if (isSuccess(response.status)) {
        setVisitor(response.data);
      }
  }
  const fetchData = async () => {
    const response = await getVisitorMessagesByMsgId({
      visitorId,
      msgId,
      size: 10,
    });
    if (isSuccess(response.status)) {
      const data = response.data.map((item)=> {
        
        if(item.contentType == EContentType.AiseekQA){
          try{
            const contentJson = JSON.parse(item.content as string) as TMessageBodyContent
            item.content = contentJson.answer.text
            // 把消息详情放入统一 body 中
            item.body = {contentType: item.contentType, content: contentJson,}
          }catch(e){
            // console.error(e)
          }
        }
        return item
      })
      // 提取提问与回答，返回的原数据数组回答排在了提问前面，还需要过虑掉没有回答的提问
      const result:TVisitorChat[] = []
      for(let i=0; i< data.length;){
        console.log(data[i])
        if(data[i] && data[i].role === 'assistant'){
          if(data[i+1] && data[i+1].role === 'user'){
            result.push(data[i+1])
            result.push(data[i])
            i+=2
            continue
          }
        }
        i++;
      }
      setList(result)
    }
  };


  const renderAsistentContent = (item: TVisitorChat) => {
    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>
  }

  
  useEffect(() => {
    fetchVisitor();
    fetchData();
  }, []);


  

  const renderContent = (item: TVisitorChat) => {
    if (item.role === "user") {
      return <View className="text-14 text-title mb-8">{item?.content}</View>;
    }

    return (
      <View
        className="p-16 text-title rounded-8 relative"
        style={{ backgroundColor: "#F4F9FF" }}
      >
        <View>{renderAsistentContent(item)}</View>
      </View>
    );
  };

  return (
    <PageCustom>
      <NavBarNormal 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">
          {list.map((item) => {
            return (
              <View className={` bg-white rounded-12 overflow-hidden`}>
                <View className="p-16">{renderContent(item)}</View>
              </View>
            );
          })}
        </View>
      </View>
    </PageCustom>
  );
};
