<template>
  <div class="knowledge-base">
    <el-card>
      <div slot="header" class="card-header">
        <span>独立知识库管理</span>
        <div>
          <el-button type="success" @click="handleSync" :disabled="!selectedRows.length">
            <i class="el-icon-refresh"></i>同步到FastGPT
          </el-button>
          <el-button type="primary" @click="handleAdd">
            <i class="el-icon-plus"></i>新增知识
          </el-button>
        </div>
      </div>

      <el-alert
        title="独立知识库说明"
        description="独立知识库专门存储客户提出的问题及对应解答、AI与客户的聊天精华内容。通过与FastGPT双库协同校验，确保话术精准度。"
        type="info"
        show-icon
        :closable="false"
        style="margin-bottom: 20px"
      />

      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="关键词">
          <el-input v-model="searchForm.keyword" placeholder="请输入关键词" clearable />
        </el-form-item>
        <el-form-item label="行业类型">
          <el-select v-model="searchForm.industryType" placeholder="请选择" clearable style="width: 150px">
            <el-option label="旅游" value="travel" />
            <el-option label="教育" value="education" />
            <el-option label="医疗" value="medical" />
            <el-option label="装修" value="decoration" />
            <el-option label="医美" value="medical_beauty" />
            <el-option label="零售" value="retail" />
            <el-option label="通用" value="general" />
          </el-select>
        </el-form-item>
        <el-form-item label="审核状态">
          <el-select v-model="searchForm.auditStatus" placeholder="请选择" clearable style="width: 150px">
            <el-option label="待审核" :value="0" />
            <el-option label="已通过" :value="1" />
            <el-option label="已驳回" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <i class="el-icon-search"></i>查询
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="tableData" v-loading="loading" border @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="title" label="知识标题" min-width="180" show-overflow-tooltip />
        <el-table-column prop="question" label="问题" min-width="200" show-overflow-tooltip />
        <el-table-column prop="industryType" label="行业类型" width="100">
          <template slot-scope="{ row }">
            {{ getIndustryText(row.industryType) }}
          </template>
        </el-table-column>
        <el-table-column prop="source" label="来源" width="120">
          <template slot-scope="{ row }">
            <el-tag :type="getSourceType(row.source)">
              {{ getSourceText(row.source) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="auditStatus" label="审核状态" width="100" align="center">
          <template slot-scope="{ row }">
            <el-tag :type="getAuditStatusType(row.auditStatus)">
              {{ getAuditStatusText(row.auditStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="useCount" label="使用次数" width="100" align="center" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="250" fixed="right">
          <template slot-scope="{ row }">
            <el-button type="primary" size="mini" @click="handleView(row)">查看</el-button>
            <el-button type="primary" size="mini" @click="handleEdit(row)">编辑</el-button>
            <el-button v-if="row.auditStatus === 0" type="success" size="mini" @click="handleAudit(row)">审核</el-button>
            <el-button type="danger" size="mini" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          :current-page="page.current"
          :page-size="page.size"
          :total="page.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="700px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="知识标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入知识标题" />
        </el-form-item>
        <el-form-item label="问题" prop="question">
          <el-input v-model="form.question" type="textarea" :rows="4" placeholder="请输入问题" />
        </el-form-item>
        <el-form-item label="答案" prop="answer">
          <el-input v-model="form.answer" type="textarea" :rows="8" placeholder="请输入答案/解答" />
        </el-form-item>
        <el-form-item label="行业类型" prop="industryType">
          <el-select v-model="form.industryType" placeholder="请选择行业类型" style="width: 100%">
            <el-option label="旅游" value="travel" />
            <el-option label="教育" value="education" />
            <el-option label="医疗" value="medical" />
            <el-option label="装修" value="decoration" />
            <el-option label="医美" value="medical_beauty" />
            <el-option label="零售" value="retail" />
            <el-option label="通用" value="general" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog title="知识详情" :visible.sync="viewDialogVisible" width="700px">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="知识标题">{{ currentItem.title }}</el-descriptions-item>
        <el-descriptions-item label="问题">{{ currentItem.question }}</el-descriptions-item>
        <el-descriptions-item label="答案">{{ currentItem.answer }}</el-descriptions-item>
        <el-descriptions-item label="行业类型">{{ getIndustryText(currentItem.industryType) }}</el-descriptions-item>
        <el-descriptions-item label="来源">{{ getSourceText(currentItem.source) }}</el-descriptions-item>
        <el-descriptions-item label="审核状态">{{ getAuditStatusText(currentItem.auditStatus) }}</el-descriptions-item>
        <el-descriptions-item label="使用次数">{{ currentItem.useCount }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ currentItem.createTime }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog title="审核知识" :visible.sync="auditDialogVisible" width="500px">
      <el-form :model="auditForm" label-width="100px">
        <el-form-item label="审核结果">
          <el-radio-group v-model="auditForm.auditStatus">
            <el-radio :label="1">通过</el-radio>
            <el-radio :label="2">驳回</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核意见">
          <el-input v-model="auditForm.comment" type="textarea" :rows="4" placeholder="请输入审核意见" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="auditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAuditSubmit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { knowledgeApi } from '@/api/company/knowledge'

export default {
  name: 'KnowledgeBase',
  data() {
    return {
      loading: false,
      tableData: [],
      selectedRows: [],
      searchForm: {
        keyword: '',
        industryType: '',
        auditStatus: null
      },
      page: {
        current: 1,
        size: 10,
        total: 0
      },
      dialogVisible: false,
      dialogTitle: '',
      form: {
        id: null,
        title: '',
        question: '',
        answer: '',
        industryType: 'general'
      },
      rules: {
        title: [{ required: true, message: '请输入知识标题', trigger: 'blur' }],
        question: [{ required: true, message: '请输入问题', trigger: 'blur' }],
        answer: [{ required: true, message: '请输入答案', trigger: 'blur' }]
      },
      viewDialogVisible: false,
      currentItem: {},
      auditDialogVisible: false,
      auditForm: {
        id: null,
        auditStatus: 1,
        comment: ''
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    async getList() {
      this.loading = true
      try {
        const res = await knowledgeApi.getList({
          keyword: this.searchForm.keyword,
          industryType: this.searchForm.industryType,
          auditStatus: this.searchForm.auditStatus
        })
        this.tableData = res.data || []
        this.page.total = this.tableData.length
      } catch (error) {
        this.$message.error('获取列表失败')
      } finally {
        this.loading = false
      }
    },
    handleSearch() {
      this.page.current = 1
      this.getList()
    },
    handleReset() {
      this.searchForm = {
        keyword: '',
        industryType: '',
        auditStatus: null
      }
      this.handleSearch()
    },
    handleSizeChange(size) {
      this.page.size = size
      this.getList()
    },
    handleCurrentChange(current) {
      this.page.current = current
      this.getList()
    },
    handleSelectionChange(rows) {
      this.selectedRows = rows
    },
    handleAdd() {
      this.dialogTitle = '新增知识'
      this.form = {
        id: null,
        title: '',
        question: '',
        answer: '',
        industryType: 'general'
      }
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.formRef && this.$refs.formRef.resetFields()
      })
    },
    handleEdit(row) {
      this.dialogTitle = '编辑知识'
      this.form = {
        id: row.id,
        title: row.title,
        question: row.question,
        answer: row.answer,
        industryType: row.industryType
      }
      this.dialogVisible = true
    },
    handleView(row) {
      this.currentItem = row
      this.viewDialogVisible = true
    },
    handleAudit(row) {
      this.auditForm = {
        id: row.id,
        auditStatus: 1,
        comment: ''
      }
      this.auditDialogVisible = true
    },
    async handleAuditSubmit() {
      try {
        await knowledgeApi.audit(this.auditForm.id, this.auditForm.auditStatus, this.auditForm.comment)
        this.$message.success('审核成功')
        this.auditDialogVisible = false
        this.getList()
      } catch (error) {
        this.$message.error('审核失败')
      }
    },
    async handleSubmit() {
      try {
        await this.$refs.formRef.validate()
        if (this.form.id) {
          await knowledgeApi.update(this.form.id, this.form)
          this.$message.success('修改成功')
        } else {
          await knowledgeApi.create(this.form)
          this.$message.success('新增成功')
        }
        this.dialogVisible = false
        this.getList()
      } catch (error) {
        if (error !== false) {
          this.$message.error('操作失败')
        }
      }
    },
    async handleDelete(row) {
      try {
        await this.$confirm('确定要删除该知识吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        await knowledgeApi.delete(row.id)
        this.$message.success('删除成功')
        this.getList()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败')
        }
      }
    },
    async handleSync() {
      try {
        await this.$confirm('确定要同步选中的知识到FastGPT吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        for (const row of this.selectedRows) {
          await knowledgeApi.syncToFastGpt(row.id)
        }
        this.$message.success('同步成功')
        this.getList()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('同步失败')
        }
      }
    },
    getIndustryText(type) {
      const map = {
        travel: '旅游',
        education: '教育',
        medical: '医疗',
        decoration: '装修',
        medical_beauty: '医美',
        retail: '零售',
        general: '通用'
      }
      return map[type] || type
    },
    getSourceText(source) {
      const map = {
        manual: '手动录入',
        chat: '聊天记录',
        ai: 'AI生成'
      }
      return map[source] || source
    },
    getSourceType(source) {
      const map = {
        manual: 'info',
        chat: 'primary',
        ai: 'warning'
      }
      return map[source] || 'info'
    },
    getAuditStatusText(status) {
      const map = {
        0: '待审核',
        1: '已通过',
        2: '已驳回'
      }
      return map[status] || '未知'
    },
    getAuditStatusType(status) {
      const map = {
        0: 'warning',
        1: 'success',
        2: 'danger'
      }
      return map[status] || 'info'
    }
  }
}
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.search-form {
  margin-bottom: 20px;
}
.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>
