<template>
  <div class="app-container search-table-box aidex-table">
    <el-card shadow="never" class="search_card" style="margin-bottom: 12px;">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="会话ID" prop="conversationId">
          <el-input
            v-model="queryParams.conversationId"
            placeholder="请输入会话ID"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="对话ID" prop="chatId">
          <el-input
            v-model="queryParams.chatId"
            placeholder="请输入对话ID"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="daterangeCreateTime"
            style="width: 240px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card shadow="never">

      <el-table v-loading="loading" :data="conversationChatList" height="calc(100vh - 220px)" size="small">
        <el-table-column label="对话ID" align="center" prop="chatId" width="170"/>
        <el-table-column label="会话ID" align="center" prop="conversationId"width="170"/>
        <el-table-column label="智能体标识" align="center" prop="botId" width="170"/>
        <el-table-column label="用户标识" align="center" prop="userId" width="150" :show-overflow-tooltip="true"/>
        <el-table-column label="发送消息角色" align="center" prop="role" width="110"/>
        <el-table-column label="用户发送" align="left" prop="msgContent" width="220" :show-overflow-tooltip="true"/>
        <el-table-column label="智能体回复" align="left" prop="backMsgContent" width="220"  :show-overflow-tooltip="true"/>
        <el-table-column label="赞或踩" align="center" prop="evaluate" width="100">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.chat_evaluate" :value="scope.row.evaluate"/>
          </template>
        </el-table-column>
        <el-table-column label="是否被传过质料库" align="center" prop="isUpload" width="130">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.chat_is_upload" :value="scope.row.isUpload"/>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="160">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" width="120" :show-overflow-tooltip="true"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="170" fixed="right">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-document"
              @click="handleDetails(scope.row)"
              v-hasPermi="['system:conversationChat:query']"
            >详情
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-files"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:conversationChat:edit']"
            >设为知识库
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!--对话详情-->
    <el-drawer title="对话详情" :visible.sync="openDrawer" size="900px" direction="rtl">
      <div class="ai-chat-container">
        <div ref="messageContainer" class="message-list">
          <div v-if="conversationChatMsgList===undefined || conversationChatMsgList.length === 0" class="empty-message">
            <el-empty :image-size="50"/>
          </div>
          <div v-else v-for="(message, index) in conversationChatMsgList" :key="index" :class="['message-item', message.role==='assistant' ? 'ai-message' : 'user-message']">
            <!-- 消息内容 -->
            <div class="message-content">
              <div class="message-text" v-if="message.role==='user'" v-html="formatMarkdown(message.content)"/>
              <div class="message-text" v-else style=" padding: 5px 0px">
                <mavon-editor
                  v-model="message.content"
                  :subfield="false"
                  :defaultOpen="'preview'"
                  :editable="false"
                  :toolbarsFlag="false"
                  :autosize="true"
                  :toolbars="{}"
                  style="box-shadow: 0px 0px 0px 0px rgba(0, 0, 0, 0.2); min-height: 50px"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-drawer>

    <!-- 设为知识库 -->
    <el-dialog title="设为知识库文件" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" label-position="top" :model="form" :rules="rules" label-width="80px" size="small">
        <el-alert title="将对话内容转为txt文件，上传到知识库，类型是文件类型的知识库，格式为txt" type="warning" class="search_card_desc" :closable="false" show-icon/>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="对话ID" prop="chatId">
              {{form.chatId}}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="知识库" prop="knowledgeId">
              <el-select v-model="form.knowledgeId" placeholder="请选择知识库" style="width: 100%">
                <el-option
                  v-for="item in knowledgeList"
                  :key="item.dataset_id"
                  :label="item.name"
                  :value="item.dataset_id">
                  <span style="float: left">{{ item.name }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px;margin-left: 15px">
                    <dict-tag :options="dict.type.datasets_format_type" :value="item.format_type"/>
                  </span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="文件名称" prop="msgContent">
              <el-input v-model="form.msgContent" placeholder="请输入文件名称">
                <template slot="append">.txt</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入内容"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="内容" prop="backMsgContent">
              <div style="height: 300px;overflow: auto">
              <mavon-editor
                v-model="form.backMsgContent"
                ref="mdEditor"
                style="min-height: 350px"
                :subfield="false"
                :toolbars="toolbarsConfig"
              />
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listConversationChat, getConversationChat, getConversationChatMsg, setknowledgeFile} from "@/api/business/aichat/conversationChat";
import {listKnowledge} from "@/api/business/aimodel/knowledgeDocument";
import {marked} from "marked";
import DOMPurify from "dompurify";

import {mavonEditor} from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'

export default {
  name: "ConversationChat",
  dicts: ['chat_evaluate', 'chat_is_upload','datasets_format_type'],
  components: {
    mavonEditor
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 对话列表表格数据
      conversationChatList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 备注时间范围
      daterangeCreateTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        conversationId: null,
        chatId: null,
        role: null,
        evaluate: null,
        isUpload: null,
        createTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        msgContent: [
          { required: true, message: "文件名称不能为空", trigger: "blur" },
        ],
        backMsgContent: [
          { required: true, message: "内容不能为空", trigger: "blur" },
        ],
        knowledgeId: [
          { required: true, message: "知识库不能为空", trigger: "blur" },
        ],
      },

      // 对话详情
      openDrawer: false,
      // 对话详情-列表
      conversationChatMsgList: [],

      //设为知识库
      // 知识库列表
      knowledgeList: [],
      // 富文本编辑器配置
      toolbarsConfig: {
        bold: true,          // 粗体
        italic: true,        // 斜体
        header: true,        // 标题
        underline: true,     // 下划线
        quote: true,         // 引用
        ol: true,            // 有序列表
        ul: true,            // 无序列表
        link: true,          // 链接
        imagelink: true,     // 图片链接
        code: true,          // 代码块
        subfield: true,      // 双栏
        fullscreen: true,     // 全屏
        help: true           // 帮助（之前添加的）
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询对话列表列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
        this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0];
        this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1];
      }
      listConversationChat(this.queryParams).then(response => {
        this.conversationChatList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        conversationId: null,
        botId: null,
        chatId: null,
        userId: null,
        role: null,
        msgContent: null,
        backMsgContent: null,
        evaluate: null,
        isUpload: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCreateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 设为知识库 */
    handleUpdate(row) {
      this.reset();
      const id = row.id
      getConversationChat(id).then(response => {
        this.form = response.data;
        this.form.backMsgContent = "提问：\n"+this.form.msgContent + "\n\n回复：\n" + response.data.backMsgContent;
        this.open = true;
        this.getKnowledgeList();
      });
    },
    /** 设为知识库 - 查询知识库列表 */
    getKnowledgeList() {
      listKnowledge({"formatType":0}).then(response => {
        this.knowledgeList = response.data;
      });
    },
    /** 设为知识库 - 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            setknowledgeFile(this.form).then(response => {
              this.$modal.msgSuccess("设置成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    //详情
    formatMarkdown(content) {
      const html = marked(content); // 先解析 Markdown
      return DOMPurify.sanitize(html); // 再清理 HTML
    },
    handleDetails(row) {
      getConversationChatMsg(row.id).then(response => {
        this.conversationChatMsgList = response.data;
        this.openDrawer = true;
      });
    },

  }
};
</script>


<style>
.ai-chat-container {
  height: calc(100vh - 120px);
  display: flex;
  flex-direction: column;
  width: 100%;
  border-top: 1px solid #ebeef5;
}

.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 10px 15px;
}

.empty-message .el-empty{
  height: calc(100vh - 220px);
}

.message-item {
  display: flex;
  margin-bottom: 20px;
  gap: 15px;
}

.user-message {
  flex-direction: row-reverse;
}

.message-content {
  position: relative;
}

.message-text {
  padding: 2px 10px;
  border-radius: 8px;
  line-height: 1.2;
}

.user-message .message-text {
  background: #0000000a;
  color: #000000d9;
}

.ai-message .message-text {
  background: white;
  /*border: 1px solid #ebeef5;*/
}

.message-text .v-note-wrapper .v-note-panel .v-note-show .v-show-content{
  padding: 8px 10px 15px 10px;
  background-color:#fff !important
}
</style>
