<template>
  <div class="artificial-words-page">
    <el-card>
      <div slot="header" class="card-header">
        <span>转人工关键词配置</span>
        <el-button type="primary" size="small" @click="handleAdd">
          <i class="el-icon-plus"></i>新增关键词
        </el-button>
      </div>

      <el-alert
        title="无感转人工说明"
        description="配置触发转人工的关键词。当客户消息包含这些关键词时，系统会以'为您安排专属顾问'等真人化话术完成转接，不暴露机器人身份。建议避免使用'转人工'、'找客服'等暴露身份的词，龙虾引擎会通过语义分析自动检测客户意图。"
        type="info"
        show-icon
        :closable="false"
        style="margin-bottom: 20px"
      />

      <el-form :model="queryParams" ref="queryForm" :inline="true" size="small">
        <el-form-item label="类型" prop="type">
          <el-select v-model="queryParams.type" placeholder="请选择类型" clearable>
            <el-option label="报错类型" :value="1" />
            <el-option label="关键词类型" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="0" />
            <el-option label="禁用" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="tableData" v-loading="loading" border>
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="type" label="类型" width="100" align="center">
          <template slot-scope="{ row }">
            <el-tag :type="row.type === 2 ? 'warning' : 'info'">
              {{ row.type === 2 ? '关键词' : '报错' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="content" label="关键词文本" min-width="200" show-overflow-tooltip>
          <template slot-scope="{ row }">
            <span>{{ row.content }}</span>
            <el-tag v-if="isIdentityRevealing(row.content)" type="danger" size="mini" style="margin-left: 8px">
              可能暴露身份
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80" align="center">
          <template slot-scope="{ row }">
            <el-tag :type="row.status === 0 ? 'success' : 'danger'">
              {{ row.status === 0 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="80" align="center" />
        <el-table-column prop="createTime" label="创建时间" width="160" align="center" />
        <el-table-column label="操作" width="180" fixed="right">
          <template slot-scope="{ row }">
            <el-button type="primary" size="mini" @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" size="mini" @click="handleDelete(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-card>

    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="550px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio :label="1">报错类型</el-radio>
            <el-radio :label="2">关键词类型</el-radio>
          </el-radio-group>
          <div class="form-tip">关键词类型：客户消息包含指定词时触发转人工；报错类型：AI回复报错时触发转人工</div>
        </el-form-item>
        <el-form-item label="关键词" prop="content">
          <el-input v-model="form.content" placeholder="请输入触发转人工的关键词" />
          <div v-if="form.content && isIdentityRevealing(form.content)" class="identity-warning">
            <i class="el-icon-warning"></i>
            此关键词可能暴露机器人身份，建议使用更隐晦的触发词
          </div>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio :label="0">启用</el-radio>
            <el-radio :label="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" :max="999" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listArtificialWords, getArtificialWords, addArtificialWords, updateArtificialWords, delArtificialWords } from '@/api/fastGpt/fastgptChatArtificialWords'

const IDENTITY_REVEALING_KEYWORDS = [
  '转人工', '人工客服', '找客服', '真人', '不要机器人',
  '换个真人', '不是真人', '机器人', 'AI客服', '智能客服',
  '人工服务', '客服人员', '活人', '真人客服'
]

export default {
  name: 'ArtificialWords',
  data() {
    return {
      loading: false,
      submitting: false,
      tableData: [],
      total: 0,
      dialogVisible: false,
      dialogTitle: '',
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: null,
        status: null
      },
      form: {
        id: null,
        type: 2,
        content: '',
        status: 0,
        sort: 0
      },
      rules: {
        type: [{ required: true, message: '请选择类型', trigger: 'change' }],
        content: [{ required: true, message: '请输入关键词', trigger: 'blur' }],
        sort: [{ required: true, message: '请输入排序', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    isIdentityRevealing(content) {
      if (!content) return false
      return IDENTITY_REVEALING_KEYWORDS.some(kw => content.includes(kw))
    },
    async getList() {
      this.loading = true
      try {
        const res = await listArtificialWords(this.queryParams)
        this.tableData = res.rows || []
        this.total = res.total || 0
      } catch (e) {
        this.$message.error('获取列表失败')
      } finally {
        this.loading = false
      }
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.queryParams = { pageNum: 1, pageSize: 10, type: null, status: null }
      this.getList()
    },
    handleAdd() {
      this.dialogTitle = '新增转人工关键词'
      this.form = { id: null, type: 2, content: '', status: 0, sort: 0 }
      this.dialogVisible = true
      this.$nextTick(() => { this.$refs.formRef && this.$refs.formRef.resetFields() })
    },
    async handleEdit(row) {
      this.dialogTitle = '编辑转人工关键词'
      try {
        const res = await getArtificialWords(row.id)
        this.form = { ...res.data }
        this.dialogVisible = true
      } catch (e) {
        this.form = { ...row }
        this.dialogVisible = true
      }
    },
    async handleSubmit() {
      try {
        await this.$refs.formRef.validate()
        this.submitting = true
        let res
        if (this.form.id) {
          res = await updateArtificialWords(this.form)
        } else {
          res = await addArtificialWords(this.form)
        }
        if (res.identityWarning) {
          this.$message({ type: 'warning', message: res.identityWarning, duration: 8000 })
        } else {
          this.$message.success(this.form.id ? '修改成功' : '新增成功')
        }
        this.dialogVisible = false
        this.getList()
      } catch (e) {
        if (e !== false) this.$message.error('操作失败')
      } finally {
        this.submitting = false
      }
    },
    async handleDelete(row) {
      try {
        await this.$confirm('确定要删除该关键词吗？', '提示', { type: 'warning' })
        await delArtificialWords(row.id)
        this.$message.success('删除成功')
        this.getList()
      } catch (e) {
        if (e !== 'cancel') this.$message.error('删除失败')
      }
    }
  }
}
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
}
.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  line-height: 1.4;
}
.identity-warning {
  color: #e6a23c;
  font-size: 12px;
  margin-top: 4px;
  line-height: 1.4;
}
.identity-warning i {
  margin-right: 4px;
}
</style>
