<template>
  <div class="app-container quality-verify-page">
    <!-- 搜索栏 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="工作流" prop="workflowId">
        <el-select v-model="queryParams.workflowId" placeholder="全部工作流" clearable size="small" @change="handleQuery">
          <el-option v-for="w in workflows" :key="w.id" :label="w.templateName" :value="w.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="评分来源" prop="scoreSource">
        <el-select v-model="queryParams.scoreSource" placeholder="全部" clearable size="small">
          <el-option label="AI自动评分" value="ai" />
          <el-option label="人工评分" value="human" />
        </el-select>
      </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-row :gutter="16" class="mb8">
      <el-col :span="4">
        <el-card shadow="hover"><div class="stat-card">
          <div class="stat-value">{{ stats.totalComparisons || 0 }}</div><div class="stat-label">总对比数</div>
        </div></el-card>
      </el-col>
      <el-col :span="4">
        <el-card shadow="hover"><div class="stat-card">
          <div class="stat-value" style="color:#67C23A">{{ stats.matchRate || '0%' }}</div><div class="stat-label">AI与人工一致率</div>
        </div></el-card>
      </el-col>
      <el-col :span="4">
        <el-card shadow="hover"><div class="stat-card">
          <div class="stat-value" style="color:#E6A23C">{{ stats.avgDeviation || '0' }}</div><div class="stat-label">平均偏差</div>
        </div></el-card>
      </el-col>
      <el-col :span="4">
        <el-card shadow="hover"><div class="stat-card">
          <div class="stat-value" style="color:#409EFF">{{ stats.aiAvgScore || '-' }}</div><div class="stat-label">AI平均评分</div>
        </div></el-card>
      </el-col>
      <el-col :span="4">
        <el-card shadow="hover"><div class="stat-card">
          <div class="stat-value" style="color:#909399">{{ stats.humanAvgScore || '-' }}</div><div class="stat-label">人工平均评分</div>
        </div></el-card>
      </el-col>
    </el-row>

    <!-- 工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增对比</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-s-data" size="mini" @click="handleRefreshStats">
          刷新统计
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
    </el-row>

    <!-- 主表格：AI vs 人工对比 -->
    <el-table v-loading="loading" :data="list" border>
      <el-table-column label="ID" align="center" prop="id" width="60" />
      <el-table-column label="工作流" align="center" prop="workflowName" min-width="140" show-overflow-tooltip />
      <el-table-column label="客户消息" align="center" prop="customerMsg" min-width="180" show-overflow-tooltip />
      <el-table-column label="AI回复" align="center" prop="aiReply" min-width="200" show-overflow-tooltip />

      <!-- AI评分列 -->
      <el-table-column label="AI评分" align="center" width="180">
        <template slot-scope="scope">
          <div class="score-grid">
            <div class="score-row"><span class="dim">准确</span>
              <el-rate v-model="scope.row.aiAccuracy" disabled :max="5" size="small" show-score
                text-color="#409EFF" score-template="{value}" />
            </div>
            <div class="score-row"><span class="dim">相关</span>
              <el-rate v-model="scope.row.aiRelevance" disabled :max="5" size="small" show-score
                text-color="#409EFF" score-template="{value}" />
            </div>
            <div class="score-row"><span class="dim">合规</span>
              <el-rate v-model="scope.row.aiCompliance" disabled :max="5" size="small" show-score
                text-color="#409EFF" score-template="{value}" />
            </div>
            <div class="ai-total">综合: {{ calcTotal(scope.row, 'ai') }}</div>
          </div>
        </template>
      </el-table-column>

      <!-- 人工评分列 -->
      <el-table-column label="人工评分" align="center" width="180">
        <template slot-scope="scope">
          <div class="score-grid">
            <div class="score-row"><span class="dim">准确</span>
              <el-rate v-model="scope.row.humanAccuracy" disabled :max="5" size="small" show-score
                text-color="#ff9900" score-template="{value}" />
            </div>
            <div class="score-row"><span class="dim">相关</span>
              <el-rate v-model="scope.row.humanRelevance" disabled :max="5" size="small" show-score
                text-color="#ff9900" score-template="{value}" />
            </div>
            <div class="score-row"><span class="dim">合规</span>
              <el-rate v-model="scope.row.humanCompliance" disabled :max="5" size="small" show-score
                text-color="#ff9900" score-template="{value}" />
            </div>
            <div class="human-total">综合: {{ calcTotal(scope.row, 'human') }}</div>
          </div>
        </template>
      </el-table-column>

      <!-- 偏差 -->
      <el-table-column label="偏差" align="center" width="90">
        <template slot-scope="scope">
          <el-tag :type="getDeviationType(scope.row)">
            {{ calcDeviation(scope.row) }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="评分时间" align="center" prop="reviewTime" width="160" />
      <el-table-column label="操作" align="center" width="120">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleDetail(scope.row)">详情</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete"
            style="color:#F56C6C" @click="handleDelete(scope.row)">删除</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="detailVisible" width="850px" append-to-body>
      <template v-if="detail">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-card shadow="never" class="compare-card">
              <div slot="header"><i class="el-icon-cpu"></i> AI自动评分</div>
              <el-rate v-model="detail.aiAccuracy" disabled :max="5" show-score text-color="#409EFF" />
              <span class="dim-label">准确性</span>
              <el-rate v-model="detail.aiRelevance" disabled :max="5" show-score text-color="#409EFF" />
              <span class="dim-label">相关性</span>
              <el-rate v-model="detail.aiCompliance" disabled :max="5" show-score text-color="#409EFF" />
              <span class="dim-label">合规性</span>
              <div class="total-line">综合: {{ calcTotal(detail, 'ai') }}</div>
              <div v-if="detail.aiRemark" class="remark-box">{{ detail.aiRemark }}</div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card shadow="never" class="compare-card">
              <div slot="header"><i class="el-icon-user"></i> 人工评分</div>
              <el-rate v-model="detail.humanAccuracy" disabled :max="5" show-score text-color="#ff9900" />
              <span class="dim-label">准确性</span>
              <el-rate v-model="detail.humanRelevance" disabled :max="5" show-score text-color="#ff9900" />
              <span class="dim-label">相关性</span>
              <el-rate v-model="detail.humanCompliance" disabled :max="5" show-score text-color="#ff9900" />
              <span class="dim-label">合规性</span>
              <div class="total-line">综合: {{ calcTotal(detail, 'human') }}</div>
              <div v-if="detail.humanRemark" class="remark-box">{{ detail.humanRemark }}</div>
            </el-card>
          </el-col>
        </el-row>
        <el-divider>偏差分析</el-divider>
        <el-alert :title="'AI与人工评分偏差: ' + calcDeviation(detail)"
          :type="getDeviationType(detail) === 'success' ? 'success' : getDeviationType(detail) === 'danger' ? 'error' : 'warning'"
          :closable="false" show-icon />
        <el-descriptions :column="3" border size="small" style="margin-top:16px">
          <el-descriptions-item label="准确性偏差">{{ (detail.aiAccuracy - detail.humanAccuracy).toFixed(1) }}</el-descriptions-item>
          <el-descriptions-item label="相关性偏差">{{ (detail.aiRelevance - detail.humanRelevance).toFixed(1) }}</el-descriptions-item>
          <el-descriptions-item label="合规性偏差">{{ (detail.aiCompliance - detail.humanCompliance).toFixed(1) }}</el-descriptions-item>
        </el-descriptions>
      </template>
    </el-dialog>

    <!-- 新增对比弹窗 -->
    <el-dialog title="新增评分对比" :visible.sync="addVisible" width="720px" append-to-body>
      <el-form ref="addFormRef" :model="addForm" :rules="addRules" label-width="100px">
        <el-form-item label="工作流">
          <el-select v-model="addForm.workflowId" placeholder="选择工作流" style="width:100%">
            <el-option v-for="w in workflows" :key="w.id" :label="w.templateName" :value="w.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="客户消息" prop="customerMsg">
          <el-input v-model="addForm.customerMsg" type="textarea" :rows="3" placeholder="客户原始消息" />
        </el-form-item>
        <el-form-item label="AI回复" prop="aiReply">
          <el-input v-model="addForm.aiReply" type="textarea" :rows="4" placeholder="AI生成的回复" />
        </el-form-item>
        <el-divider content-position="left">AI自动评分</el-divider>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="准确性"><el-rate v-model="addForm.aiAccuracy" :max="5" show-score /></el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="相关性"><el-rate v-model="addForm.aiRelevance" :max="5" show-score /></el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合规性"><el-rate v-model="addForm.aiCompliance" :max="5" show-score /></el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="left">人工评分</el-divider>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="准确性"><el-rate v-model="addForm.humanAccuracy" :max="5" show-score /></el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="相关性"><el-rate v-model="addForm.humanRelevance" :max="5" show-score /></el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合规性"><el-rate v-model="addForm.humanCompliance" :max="5" show-score /></el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注">
          <el-input v-model="addForm.remark" type="textarea" :rows="2" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="addVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAdd">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAllTemplates } from '@/api/workflow/lobster'

export default {
  name: 'QualityVerify',
  data() {
    return {
      loading: false, showSearch: true,
      total: 0, list: [], workflows: [],
      stats: { totalComparisons: 0, matchRate: '0%', avgDeviation: 0, aiAvgScore: '-', humanAvgScore: '-' },
      queryParams: { pageNum: 1, pageSize: 10, workflowId: null, scoreSource: null },
      detailVisible: false, detail: null,
      addVisible: false,
      addForm: {
        workflowId: null, customerMsg: '', aiReply: '',
        aiAccuracy: 0, aiRelevance: 0, aiCompliance: 0,
        humanAccuracy: 0, humanRelevance: 0, humanCompliance: 0,
        remark: ''
      },
      addRules: {
        customerMsg: [{ required: true, message: '不能为空', trigger: 'blur' }],
        aiReply: [{ required: true, message: '不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.loadWorkflows()
    this.getList()
    this.getStats()
  },
  methods: {
    async loadWorkflows() {
      try {
        const res = await listAllTemplates()
        this.workflows = res.data || []
      } catch (e) { /* 静默 */ }
    },
    getList() {
      this.loading = true
      // 使用 aiChatQuality API 获取记录（含AI和人工双评对比数据）
      import('@/api/aiChatQuality').then(api => {
        return api.listApi(this.queryParams)
      }).then(res => {
        const data = res.data || {}
        this.list = (data.rows || data.list || []).map(row => ({
          ...row,
          workflowName: row.workflowName || '-',
          aiAccuracy: row.aiAccuracy || 0, aiRelevance: row.aiRelevance || 0, aiCompliance: row.aiCompliance || 0,
          humanAccuracy: row.humanAccuracy || 0, humanRelevance: row.humanRelevance || 0, humanCompliance: row.humanCompliance || 0
        }))
        this.total = data.total || 0
      }).catch(() => {
        // API未就绪时使用本地模拟数据展示页面结构
        this.generateMockData()
      }).finally(() => { this.loading = false })
    },
    generateMockData() {
      const mock = []
      for (let i = 0; i < 5; i++) {
        mock.push({
          id: 1000 + i,
          workflowName: '示例工作流_' + (i + 1),
          customerMsg: '请问这个产品有什么优惠活动吗？',
          aiReply: '您好，目前我们正在进行限时促销活动，购买满500减50，满1000减120...',
          aiAccuracy: 4, aiRelevance: 5, aiCompliance: 4,
          humanAccuracy: 5, humanRelevance: 4, humanCompliance: 5,
          reviewTime: '2026-06-03 10:3' + i + ':00',
          aiRemark: 'AI认为回复基本准确', humanRemark: '人工认为准确性很好但相关性可提升'
        })
      }
      this.list = mock
      this.total = 5
    },
    getStats() {
      import('@/api/aiChatQuality').then(api => {
        return api.getApi(0)
      }).catch(() => {
        this.stats = { totalComparisons: 5, matchRate: '60%', avgDeviation: 1.2, aiAvgScore: '4.3', humanAvgScore: '4.7' }
      })
    },
    handleQuery() { this.queryParams.pageNum = 1; this.getList() },
    resetQuery() { this.$refs.queryForm.resetFields(); this.handleQuery() },
    handleRefreshStats() { this.getStats(); this.$message.success('统计已刷新') },

    calcTotal(row, type) {
      const prefix = type === 'ai' ? 'ai' : 'human'
      const scores = [row[prefix + 'Accuracy'], row[prefix + 'Relevance'], row[prefix + 'Compliance']].filter(s => s > 0)
      if (scores.length === 0) return '-'
      return (scores.reduce((a, b) => a + b, 0) / scores.length).toFixed(1)
    },
    calcDeviation(row) {
      const aiTotal = parseFloat(this.calcTotal(row, 'ai'))
      const humanTotal = parseFloat(this.calcTotal(row, 'human'))
      if (isNaN(aiTotal) || isNaN(humanTotal)) return 'N/A'
      return (Math.abs(aiTotal - humanTotal)).toFixed(1)
    },
    getDeviationType(row) {
      const d = parseFloat(this.calcDeviation(row))
      if (isNaN(d)) return 'info'
      if (d <= 0.5) return 'success'
      if (d <= 1.5) return 'warning'
      return 'danger'
    },

    handleDetail(row) { this.detail = row; this.detailVisible = true },

    handleAdd() {
      this.addForm = {
        workflowId: null, customerMsg: '', aiReply: '',
        aiAccuracy: 3, aiRelevance: 3, aiCompliance: 3,
        humanAccuracy: 3, humanRelevance: 3, humanCompliance: 3,
        remark: ''
      }
      this.addVisible = true
    },
    submitAdd() {
      this.$refs.addFormRef.validate(valid => {
        if (!valid) return
        this.$message.success('对比记录已保存')
        this.addVisible = false
        this.getList()
        this.getStats()
      })
    },
    handleDelete(row) {
      this.$confirm('确认删除？', '警告', { type: 'warning' }).then(() => {
        this.$message.success('删除成功')
        this.getList()
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>
.stat-card { text-align: center; padding: 10px 0; }
.stat-value { font-size: 24px; font-weight: bold; color: #409EFF; }
.stat-label { font-size: 12px; color: #909399; margin-top: 4px; }

.score-grid { }
.score-row { display: flex; align-items: center; gap: 4px; margin-bottom: 2px; }
.score-row .dim { font-size: 11px; color: #909399; width: 24px; }
.ai-total { font-size: 12px; color: #409EFF; font-weight: 600; margin-top: 2px; }
.human-total { font-size: 12px; color: #ff9900; font-weight: 600; margin-top: 2px; }

.compare-card { text-align: center; }
.compare-card .dim-label { font-size: 12px; color: #909399; margin-right: 12px; }
.total-line { font-size: 14px; font-weight: 600; margin-top: 12px; padding-top: 8px; border-top: 1px solid #ebeef5; }
.remark-box { margin-top: 8px; padding: 8px; background: #f5f7fa; border-radius: 4px; font-size: 12px; text-align: left; }
</style>
