import { View, Image, Text } from "@tarojs/components";
import { useEffect, useState } from "react";
import { isSuccess } from "@/utils";
import { getVisitorMessages } from "@/service/visitor";
import { TVisitorChat } from "@/types/visitor";
import IconEditButtonBlue from "@/images/svgs/dashboard/IconEditButtonBlue.svg";

import style from "./index.module.less";
import Taro from "@tarojs/taro";
import { EContentType, TMessageBodyContent } from "@/types/bot";
import MarkDislike from "@/components/marks/MarkDislike";
import MarkLike from "@/components/marks/MarkLike";

interface IProps {
  visitorId: string;
  sessionId: string;
  showMoreButton?: boolean;
}
export default ({ visitorId, sessionId, showMoreButton = false }: IProps) => {
  const [question, setQuestion] = useState<TVisitorChat | null>(null);
  const [answer, setAnswer] = useState<TVisitorChat | null>(null);

  const fetchData = async () => {
    const response = await getVisitorMessages({
      pageSize: 2,
      visitorId,
      sessionId,
    });
    if (isSuccess(response.status)) {
      const [q, a] = response.data.data ?? [];
      if (q) {
        setQuestion(q);
      }
      if (a) {
        if (a.contentType == EContentType.AiseekQA) {
          try {
            const contentJson = JSON.parse(
              a.content as string
            ) as TMessageBodyContent;
            a.content = contentJson.answer.text;
            // 把消息详情放入统一 body 中
            a.body = { contentType: a.contentType, content: contentJson };
          } catch (e) {
            // console.error(e)
          }
        }
        setAnswer(a);
      }
    }
  };

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

  const handleClick = () => {
    Taro.navigateTo({
      url: `/pages/chat-session-messages/index?visitorId=${visitorId}&sessionId=${sessionId}`,
    });
  };

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

  const renderAnswerContent = (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 className="break-words h-max-[360px] overflow-hidden">
          <View className="break-words">{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 user-select>{link}</Text>;
            })}
          </View>
        </View>
      );
    }
    return (
      <View className="break-words h-max-[360px] overflow-hidden">
        {item.content}
      </View>
    );
  };

  return (
    <View className="w-full">
      <View className={` bg-white rounded-12 overflow-hidden`}>
        <View className="p-16 relative">
          <View className="text-14 text-dark font-medium leading-22 mb-8 font-pingfangSCMedium">
            {question?.content}
          </View>
          {!!answer?.content?.length && (
            <View
              className="p-16 text-dark text-12 leading-18 rounded-8 relative max-h-[360px] overflow-hidden"
              style={{ backgroundColor: "#F4F9FF" }}
            >
              {renderAnswerContent(answer)}
              <View className="absolute top-0 right-0 z-10">
                {answer.isDislike ? <MarkDislike /> : <></>}
                {answer.isLike ? <MarkLike /> : <></>}
              </View>
              <View className={style.editButton} onClick={handleEdit}>
                <Image src={IconEditButtonBlue} className="w-14 h-14" />
              </View>
            </View>
          )}
          <View className={style.blurMask}></View>
        </View>
        {showMoreButton && (
          <View
            className="text-primary flex-center border-top1-gray bg-white py-10"
            onClick={handleClick}
          >
            查看更多
          </View>
        )}
      </View>

      {/* <View className="text-primary flex-center" onClick={handleClick}>查看更多</View> */}
      {/* {list.map(item => {
        return <View className="px-16 bg-white">
          <View className="text-14 text-title"></View>
        </View>
      })} */}
    </View>
  );
};
