<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="会话标题" prop="conversationTile">
          <el-input
            v-model="queryParams.conversationTile"
            placeholder="请输入会话标题"
            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="conversationList" height="calc(100vh - 220px)" size="small">
        <el-table-column label="记录ID" align="center" prop="id" width="200"/>
        <el-table-column label="智能体标识" align="center" prop="botId" width="200"/>
        <el-table-column label="会话ID" align="center" prop="conversationId" width="200"/>
        <el-table-column label="会话标题" align="left" prop="conversationTile" :show-overflow-tooltip="true"/>
        <el-table-column label="创建时间" align="center" prop="createTime" width="150">
          <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="200" :show-overflow-tooltip="true"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:conversation:edit']"
            >备注
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-chat-line-square"
              @click="dialogueDetails(scope.row)"
              v-hasPermi="['system:conversation:remove']"
            >对话详情
            </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-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="智能体标识" prop="botId">
          {{ form.botId }}
        </el-form-item>
        <el-form-item label="会话ID" prop="conversationId">
          {{ form.conversationId }}
        </el-form-item>
        <el-form-item label="会话标题" prop="conversationTile">
          {{ form.conversationTile }}
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </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>

    <!--对话详情-->
    <el-drawer title="对话详情" :visible.sync="openDrawer" size="900px" direction="rtl">
      <div class="ai-chat-container">
        <div ref="messageContainer" class="message-list">
          <div v-if="conversationChatList===undefined || conversationChatList.length === 0" class="empty-message">
            <el-empty :image-size="50"/>
          </div>
          <div v-else v-for="(message, index) in conversationChatList" :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>

  </div>
</template>

<script>
import {listConversation, getConversation, updateConversation, getConversationChatList} from "@/api/business/aichat/conversation";
import {marked} from "marked";
import DOMPurify from "dompurify";

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

export default {
  name: "Conversation",
  components: {
    mavonEditor
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 会话列表表格数据
      conversationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 备注时间范围
      daterangeCreateTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        conversationId: null,
        conversationTile: null,
        createTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},

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


    };
  },
  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];
      }
      listConversation(this.queryParams).then(response => {
        this.conversationList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        botId: null,
        conversationId: null,
        conversationTile: 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
      getConversation(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "设置备注";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateConversation(this.form).then(response => {
              this.$modal.msgSuccess("设置成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    /** 对话详情 - 窗口*/
    dialogueDetails(row) {
      getConversationChatList(row.id).then(response => {
        this.conversationChatList = response.data;
        this.openDrawer = true;
      });
    },
    formatMarkdown(content) {
      const html = marked(content); // 先解析 Markdown
      return DOMPurify.sanitize(html); // 再清理 HTML
    },

  }
};
</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>
