<template>
  <div class="app-container">
    <el-card shadow="never" class="mb16 filter-card">
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px" size="small">
      <el-form-item label="租户名称" prop="companyName">
        <el-input
          v-model="queryParams.companyName"
          placeholder="请输入租户名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户名称" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="会话状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择会话状态" clearable size="small">
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <inline-tenant-selector @change="handleQuery" />
      <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-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['admin:aiChatQuality:list']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border size="small" style="width:100%" v-loading="loading" :data="sessionList">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="租户名称" align="center" prop="companyName" />
      <el-table-column label="用户名称" align="center" prop="userName" />
      <el-table-column label="会话ID" align="center" prop="sessionId" />
      <el-table-column label="开始时间" align="center" prop="startTime" />
      <el-table-column label="消息数量" align="center" prop="messageCount" />
      <el-table-column label="会话状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status == 'active'" type="success">进行中</el-tag>
          <el-tag v-else type="info">已结束</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-search"
            plain
            @click="handleView(scope.row)"
          >查看消息</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            plain
            @click="handleQuality(scope.row)"
            v-hasPermi="['admin:aiChatQuality:addQuality']"
          >质检</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-dialog title="会话消息详情" :visible.sync="viewOpen" width="800px" append-to-body>
      <div class="chat-messages">
        <div v-for="msg in messageList" :key="msg.id" :class="['message-item', msg.role]">
          <span class="message-role">{{ msg.role === 'user' ? '用户' : 'AI' }}</span>
          <span class="message-content">{{ msg.content }}</span>
          <span class="message-time">{{ msg.sendTime }}</span>
        </div>
      </div>
    </el-dialog>

    <!-- 质检弹窗 -->
    <el-dialog title="AI聊天质检" :visible.sync="qualityOpen" width="600px" append-to-body>
      <el-form ref="qualityForm" :model="qualityForm" :rules="qualityRules" label-width="100px">
        <el-form-item label="质检结果" prop="qualityResult">
          <el-select v-model="qualityForm.qualityResult" placeholder="请选择质检结果">
            <el-option label="合格" value="合格" />
            <el-option label="不合格" value="不合格" />
            <el-option label="待审核" value="待审核" />
          </el-select>
        </el-form-item>
        <el-form-item label="风险等级" prop="riskLevel">
          <el-select v-model="qualityForm.riskLevel" placeholder="请选择风险等级">
            <el-option label="低" value="低" />
            <el-option label="中" value="中" />
            <el-option label="高" value="高" />
          </el-select>
        </el-form-item>
        <el-form-item label="问题类型" prop="problemType">
          <el-input v-model="qualityForm.problemType" placeholder="请输入问题类型" />
        </el-form-item>
        <el-form-item label="质检备注" prop="remark">
          <el-textarea v-model="qualityForm.remark" placeholder="请输入质检备注" :rows="3" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitQualityForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listChatSessions, getSessionMessages, addQualityRecord, exportChatSessions } from '@/api/admin/aiChatQuality'

import InlineTenantSelector from "@/components/InlineTenantSelector"

export default {
  name: 'AiChatQualityAdmin',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 会话列表
      sessionList: [],
      // 消息列表
      messageList: [],
      // 状态选项
      statusOptions: [
        { value: 'active', label: '进行中' },
        { value: 'ended', label: '已结束' }
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        companyName: null,
        userName: null,
        status: null
      },
      // 查看弹窗
      viewOpen: false,
      // 质检弹窗
      qualityOpen: false,
      qualityForm: {
        sessionId: null,
        qualityResult: '',
        riskLevel: '',
        problemType: '',
        remark: ''
      },
      qualityRules: {
        qualityResult: [{ required: true, message: '请选择质检结果', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true
      listChatSessions(this.queryParams).then(response => {
        this.sessionList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 查看消息 */
    handleView(row) {
      getSessionMessages(row.sessionId).then(response => {
        this.messageList = response.data
        this.viewOpen = true
      })
    },
    /** 质检 */
    handleQuality(row) {
      this.qualityForm = {
        sessionId: row.sessionId,
        qualityResult: '',
        riskLevel: '',
        problemType: '',
        remark: ''
      }
      this.qualityOpen = true
    },
    /** 提交质检 */
    submitQualityForm() {
      this.$refs['qualityForm'].validate(valid => {
        if (valid) {
          addQualityRecord(this.qualityForm).then(response => {
            this.$message.success('质检成功')
            this.qualityOpen = false
            this.getList()
          })
        }
      })
    },
    /** 导出按钒操作 */
    handleExport() {
      this.exportLoading = true
      exportChatSessions(this.queryParams).then(response => {
        this.download(response.msg)
        this.exportLoading = false
      }).catch(() => { this.exportLoading = false })
    }
  }
}
</script>

<style scoped>
.chat-messages {
  max-height: 400px;
  overflow-y: auto;
}
.message-item {
  margin-bottom: 15px;
  padding: 10px;
  border-radius: 8px;
}
.message-item.user {
  background-color: #e8f5e9;
}
.message-item.assistant {
  background-color: #e3f2fd;
}
.message-role {
  font-weight: bold;
  margin-right: 10px;
}
.message-content {
  margin-right: 10px;
}
.message-time {
  font-size: 12px;
  color: #999;
}
.mb16 { margin-bottom: 16px; }
.filter-card { padding-bottom: 0; }
</style>