<template>
  <div class="dialog-item dialog-anwser" :class="anwser_klass">
    <BtnSelectItem v-if="select_btn_visible" @change="handleSelectChange" />

    <div class="dialog-main answer-main">
      <div class="dialog-icon answer-icon">
        <!-- 根据智能体显示图标 -->
        <!-- <img :src="answer.client_custom_icon" /> -->

        <!-- 2024-12-26：薛娜提出，使用设计稿的图标 -->
        <!-- 需求详情查看 https://note.youdao.com/ynoteshare/index.html?id=d781d48a6d64bab8451026fe65342a7f&type=note&_time=1735176727116 6.1 -->
        <img :src="chat_agent_icon" />
      </div>

      <div class="dialog-content answer-content">
        <div>
          <DialogContent
            :content="answer_html"
            :is_loading="is_content_loading"
            :max_width="content_max_width"
            :show_think="show_think"
          >
            <DialogActions
              v-if="answer_status === 2"
              class="answer-actions-btns"
              :action_list="answer_action_list"
              @copy="handleAnswerCopy"
              @share="handleAnswerShare"
              @retry="handleAnswerRetry"
              @edit="handleAnswerEdit"
            />
          </DialogContent>

          <!-- <BtnStopChat v-if="answer_status === 1" @stop="handleStopChat" /> -->

          <!-- 对话已经结束，并且有引用数据 -->
          <template v-if="has_refference && answer_status === 2">
            <RefferenceFileBlocks
              class="refference-files-blocks-container"
              :doc_aggs="full_refference.doc_aggs"
              :chunks="full_refference.chunks"
              :total="full_refference.total"
            />
          </template>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
/**
 * 智能体的回答内容，可能需要包括下面一些功能
 *
 * 4. 回答反馈：分享、点赞、复制
 */
import { computed, onMounted } from 'vue';

import { Message } from '../../3rd-libs/arco-vue-libs';

import BtnSelectItem from './BtnSelectItem.vue';

import DialogActions from './DialogActions.vue';
import BtnStopChat from './BtnStopChat.vue';
import DialogContent from '../conversation-content/DialogContent.vue';

import formatAnwserString from '../conversation-dialog/format-anwser-string';
// import { formatFileDownloadStr } from '../conversation-dialog/format-dialog-answer-custom-markdown-str';
// import { getIconIntelligent } from '../common/icon-map';
// import { formatStaticAssetsUrl } from '../../utils/utils';

import applyRefferencePopover4DownloadFile from '../answer-refference/apply-refference-popover-4-download-file';
import applyRefferencePopover4RefFlag from '../answer-refference/apply-refference-popover-4-ref-flag';
// import applyRefferencePopover4FileName from '../answer-refference/apply-refference-popover-4-filename';
import { applyCodeHighLight } from '../conversation-dialog/format-code-string';

import RefferenceFileBlocks from '../answer-refference/RefferenceFileBlocks.vue';

import copyText from '../../3rd-libs/clipboard';

import chat_agent_icon from '../../assets/chat/chat-agent-icon.png';

const props = defineProps({
  /**
   * 是否显示选择按钮
   * 仿照kimi，当用户选择分享时，选择按钮会展示
   */
  show_select: true,

  /**
   * 答案内容数据
   */
  answer: Object,

  /**
   * 对话区域的宽度
   */
  width: Number,

  answer_action_list: Array
});

const emit = defineEmits(['stop', 'retry', 'select', 'edit']);

const select_btn_visible = computed(() => {
  return props.show_select === true;
});

/**
 * 当前对话的状态
 * 0 加载中
 * 1 正在对话
 * 2 已结束
 */
const answer_status = computed(() => {
  const answer = props.answer;

  return answer.client_custom_chat_status;
});

/**
 * 内容是否正在加载中
 */
const is_content_loading = computed(() => {
  return answer_status.value === 0;
});

/**
 * 内容区域的最大宽度
 * 内容区域的宽度，根据父容器的宽度，减去此组件内非内容区域元素（icon等）的宽度，以及横向的的margin/padding
 * 最终得出内容区域的最大宽度
 */
const content_max_width = computed(() => {
  return props.width - 40 - 40 - 20;
});

const system_message = computed(() => {
  const answer = props.answer;

  return answer.client_custom_running_msg || '';
});

/**
 * 智能体回答的内容的html字符串
 * 是markdown格式
 * 需要使用markdown解析器进行解析
 */
const answer_html = computed(() => {
  const answer = props.answer;
  const str = answer.content;

  /**
   * 第一步处理位于：../conversation-dialogformat-dialog-answer-from-websocket_receive_message.js
   * 此处将websocket的答案数据进行第二步处理
   * 使用markdown解析器进行解析，并处理一部分字符串
   * 最终生成html字符串
   */
  let answer_string = formatAnwserString(str);

  // 第二步处理已经结束，html字符串已经生成
  // 接下来进行最后一步：附加内容的字符串拼接
  // 由于SQL和代码不能通过markdown解析，所以此处进行字符串的拼接
  // 在markdown转换结束后，添加拼接字符串
  // answer.client_custom_attached_html_before_render 的生成过程位于 ../conversation-dialogformat-dialog-answer-from-websocket_receive_message.js
  if (answer.client_custom_attached_html_before_render) {
    answer_string = answer_string + answer.client_custom_attached_html_before_render;
  }

  // // 第二步处理已经结束，html字符串已经生成
  // // 接下来进行最后一步：附加内容的字符串拼接
  // // 由于SQL和代码不能通过markdown解析，所以此处进行字符串的拼接
  // // 在markdown转换结束后，添加拼接字符串
  // // 拼接python代码
  // if (answer.client_custom_linked_code) {
  //   answer_string = answer_string + answer.client_custom_linked_code;
  // }
  // // 拼接SQL代码
  // if (answer.client_custom_linked_sql) {
  //   answer_string = answer_string + answer.client_custom_linked_sql;
  // }
  // // 拼接生成的图片
  // if (answer.client_custom_linked_image) {
  //   const img_url = formatStaticAssetsUrl(answer.client_custom_linked_image);
  //   answer_string = answer_string + `<img src="${img_url}" />`;
  // }
  // // 拼接文件的下载链接
  // if (answer.client_custom_linked_download_files) {
  //   const file_name = answer.client_custom_linked_download_files.file_name;
  //   const file_url = answer.client_custom_linked_download_files.file_url;
  //   const download_file_str = formatFileDownloadStr(file_name, file_url);
  //   answer_string = answer_string + download_file_str;
  // }

  /**
   * 系统消息展示
   * 如果有系统消息，则展示系统消息
   * 如果没有系统消息，则不用展示
   */
  const loader_str = `<div class="answer-system-message-content-container">${system_message.value} <span class="answer-system-message-content-loader"></span></div>`;

  /**
   * 所有步骤已经走完
   * 返回最终的html字符串
   * 此字符串就是要渲染到界面上的html字符串
   */
  if (system_message.value) {
    return `${answer_string}${loader_str}`;
  } else {
    return answer_string;
  }
});

/**
 * 智能体回答区域容器的class值
 * 通过唯一ID生成，可以保证界面中每一个答案都有一个唯一的容器类名
 * 为后续其他处理（引用效果、代码美化）做准备：后续处理可以通过此class定位相关子元素
 */
const anwser_klass = computed(() => {
  const answer = props.answer;

  return `klass-${answer.client_custom_unique_id}-answer-content`;
});

/**
 * 完整引用数据
 */
const full_refference = computed(() => {
  if (!props.answer) {
    return null;
  }

  const answer = props.answer;

  if (!answer.client_custom_linked_refference_full_content) {
    return null;
  }

  if (Object.keys(answer.client_custom_linked_refference_full_content).length === 0) {
    return null;
  } else {
    for (let key in answer.client_custom_linked_refference_full_content) {
      if (answer.client_custom_linked_refference_full_content[key].length === -0) {
        return null;
      }
    }
  }

  return answer.client_custom_linked_refference_full_content;
});

/**
 * 是否显示引用效果
 */
const has_refference = computed(() => {
  if (!full_refference.value) {
    return false;
  }

  return true;
});
/**
 * 是否展示思考过程
 * */
const show_think = computed(() => {
  return true;
});

const handleSelectChange = () => {
  emit('select');
};

/**
 * 停止答案的生成
 */
const handleStopChat = () => {
  emit('stop');
};

/**
 * copy
 */
const handleAnswerCopy = () => {
  copyText(answer_html.value);
  Message.success('已复制');
};

/**
 * 分享答案
 */
const handleAnswerShare = () => {};

/**
 * 重新生成答案
 */
const handleAnswerRetry = () => {
  emit('retry');
};
/**
 * 编辑文本
 * */
const handleAnswerEdit = () => {
  emit('edit');
};

onMounted(() => {
  const container_klass = anwser_klass.value;
  const answer = props.answer;

  const full_refference = answer.client_custom_linked_refference_full_content;
  const download_files = answer.client_custom_linked_download_files;
  const download_file_list = answer.client_custom_linked_download_files_List || [];

  /**
   * 文档引用效果
   */
  applyRefferencePopover4RefFlag(container_klass, full_refference);
  // applyRefferencePopover4FileName(container_klass, full_refference);

  if (download_files) {
    applyRefferencePopover4DownloadFile(container_klass, [download_files, ...download_file_list]);
  }

  /**
   * 处理代码样式: 美化代码的展示
   */
  applyCodeHighLight(container_klass);
});
</script>

<style src="./dialog-item-common.css" />
<style lang="css" scoped>
.dialog-anwser {
  color: var(--color-text-1);

  display: flex;
  justify-content: space-between;
}

.answer-main {
}
.answer-content {
  display: flex;
  justify-content: flex-start;
}

.answer-icon {
  margin-right: 22px;
}
.answer-icon img {
  width: 100%;
  transform: scale(1.6);
}

.answer-actions-btns {
  margin-top: 5px;
}

.refference-files-blocks-container {
  margin-top: 26px;
}

.dialog-content.answer-content .dialog-chat-answer-content {
  padding-right: 45px;
}
</style>

<style>
.answer-system-message-content-container {
  display: flex;
  align-items: center;
}

.answer-system-message-content-loader {
  display: inline-block;

  margin-left: 14px;

  width: 6px;
  height: 6px;
  border-radius: 50%;
  background-color: #165dff;
  box-shadow: 10px 0 #165dff, -10px 0 #165dff;
  position: relative;
  animation: flash 0.8s ease-out infinite alternate;
}

@keyframes flash {
  0% {
    background-color: #fff2;
    box-shadow: 10px 0 #fff2, -10px 0 #165dff;
  }
  50% {
    background-color: #165dff;
    box-shadow: 10px 0 #fff2, -10px 0 #fff2;
  }
  100% {
    background-color: #fff2;
    box-shadow: 10px 0 #165dff, -10px 0 #fff2;
  }
}
</style>
