<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="问题分类" prop="categoryType">
        <el-select v-model="queryParams.categoryType" placeholder="请选择问题分类" clearable style="width: 180px">
          <el-option
            v-for="dict in robot_faq_category"
            :key="dict.value"
            :label="dict.label"
            :value="String(dict.value)"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="标准问题" prop="question">
        <el-input
          v-model="queryParams.question"
          placeholder="请输入标准问题关键字"
          clearable
          style="width: 220px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="启用状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择启用状态" clearable style="width: 160px">
          <el-option label="启用" value="1" />
          <el-option label="停用" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['base:faq:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['base:faq:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['base:faq:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['base:faq:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="faqList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="问题分类" align="center" prop="categoryType" width="120">
        <template #default="scope">
          <dict-tag :options="robot_faq_category" :value="scope.row.categoryType != null ? String(scope.row.categoryType) : ''" />
        </template>
      </el-table-column>
      <el-table-column label="标准问题" align="left" prop="question" min-width="220" show-overflow-tooltip />
      <el-table-column label="相似问" align="center" width="90">
        <template #default="scope">
          <el-tag type="info">{{ getSimilarCount(scope.row) }} 条</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="答案摘要" align="left" prop="answer" min-width="260" show-overflow-tooltip>
        <template #default="scope">
          <span>{{ formatAnswerSummary(scope.row.answer) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="启用状态" align="center" prop="status" width="100">
        <template #default="scope">
          <el-tag v-if="String(scope.row.status) === '1'" type="success">启用</el-tag>
          <el-tag v-else-if="String(scope.row.status) === '0'" type="info">停用</el-tag>
          <el-tag v-else type="info">-</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="160">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="240" fixed="right" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            v-if="String(scope.row.status) !== '1'"
            link
            type="primary"
            icon="CircleCheck"
            @click="handleStatusChange(scope.row, '1')"
            v-hasPermi="['base:faq:edit']"
          >启用</el-button>
          <el-button
            v-if="String(scope.row.status) === '1'"
            link
            type="warning"
            icon="CircleClose"
            @click="handleStatusChange(scope.row, '0')"
            v-hasPermi="['base:faq:edit']"
          >停用</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['base:faq:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['base:faq:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改问答对话框 -->
    <el-dialog :title="title" v-model="open" width="760px" append-to-body>
      <el-form ref="faqRef" :model="form" :rules="rules" label-width="110px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="问题分类" prop="categoryType">
              <el-select v-model="form.categoryType" placeholder="请选择问题分类" style="width: 100%">
                <el-option
                  v-for="dict in robot_faq_category"
                  :key="dict.value"
                  :label="dict.label"
                  :value="String(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="标准问题" prop="question">
              <el-input
                v-model="form.question"
                maxlength="500"
                show-word-limit
                placeholder="请输入标准问题"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="相似问" prop="similarQuestionsText">
              <el-input
                v-model="similarQuestionsText"
                type="textarea"
                :rows="5"
                maxlength="2000"
                show-word-limit
                placeholder="请输入相似问，一行一个。例如：&#10;你是谁？&#10;你能做什么？&#10;介绍一下你自己"
              />
              <div class="form-tip">一行一个相似问，保存时会自动转换为相似问列表。</div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="答案内容" prop="answer">
              <el-input
                v-model="form.answer"
                type="textarea"
                :rows="6"
                maxlength="2000"
                show-word-limit
                placeholder="请输入答案内容"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="启用状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio label="1">启用</el-radio>
                <el-radio label="0">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                :rows="3"
                maxlength="500"
                show-word-limit
                placeholder="请输入备注"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Faq">
import { listFaq, getFaq, delFaq, addFaq, updateFaq } from "@/api/base/faq"

const { proxy } = getCurrentInstance()
const { robot_faq_category } = useDict('robot_faq_category')

const faqList = ref([])
const similarQuestionsText = ref("")
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    categoryType: undefined,
    question: undefined,
    status: undefined,
  },
  rules: {
    categoryType: [
      { required: true, message: "请选择问题分类", trigger: "change" }
    ],
    question: [
      { required: true, message: "标准问题不能为空", trigger: "blur" }
    ],
    answer: [
      { required: true, message: "答案内容不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "请选择启用状态", trigger: "change" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询问答库列表 */
function getList() {
  loading.value = true
  listFaq(queryParams.value).then(response => {
    faqList.value = response.rows || []
    total.value = response.total || 0
  }).catch(() => {
    faqList.value = []
    total.value = 0
  }).finally(() => {
    loading.value = false
  })
}

/** 取消按钮 */
function cancel() {
  open.value = false
  reset()
}

/** 表单重置 */
function reset() {
  form.value = {
    id: null,
    categoryType: null,
    question: null,
    answer: null,
    sortNo: 0,
    status: "1",
    remark: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null
  }
  similarQuestionsText.value = ""
  proxy.resetForm("faqRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "新增问答"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value[0]
  getFaq(_id).then(response => {
    const data = response.data || {}
    form.value = {
      ...data,
      categoryType: data.categoryType != null ? String(data.categoryType) : null,
      status: data.status != null ? String(data.status) : "1",
      sortNo: data.sortNo != null ? Number(data.sortNo) : 0
    }
    const similarList = data.robotOpsFaqSimilarList || data.similarQuestions || []
    if (Array.isArray(similarList)) {
      similarQuestionsText.value = similarList
        .map(item => typeof item === "string" ? item : item.similarQuestion)
        .filter(Boolean)
        .join("\n")
    } else {
      similarQuestionsText.value = ""
    }
    open.value = true
    title.value = "修改问答"
  }).catch(() => {
    proxy.$modal.msgError("获取问答详情失败")
  })
}

/** 将相似问多行文本转换为子表列表 */
function buildSimilarQuestionList() {
  const uniqueList = Array.from(new Set(
    similarQuestionsText.value
      .split("\n")
      .map(item => item.trim())
      .filter(Boolean)
  ))
  return uniqueList.map((text, index) => ({
    similarQuestion: text,
    sortNo: index + 1
  }))
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["faqRef"].validate(valid => {
    if (valid) {
      const similarList = buildSimilarQuestionList()
      form.value.sortNo = form.value.sortNo != null ? Number(form.value.sortNo) : 0
      form.value.robotOpsFaqSimilarList = similarList
      form.value.similarQuestions = similarList.map(item => item.similarQuestion)
      if (form.value.id != null) {
        updateFaq(form.value).then(() => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        }).catch(() => {
          proxy.$modal.msgError("修改失败")
        })
      } else {
        addFaq(form.value).then(() => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        }).catch(() => {
          proxy.$modal.msgError("新增失败")
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm("确认删除选中的问答数据吗？删除后不可恢复。").then(function() {
    return delFaq(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 启用/停用问答 */
function handleStatusChange(row, status) {
  const actionText = status === "1" ? "启用" : "停用"
  proxy.$modal.confirm('确认' + actionText + '问答“' + row.question + '”吗？').then(() => {
    return getFaq(row.id)
  }).then(response => {
    const data = response.data || {}
    return updateFaq({
      ...data,
      status,
      categoryType: data.categoryType != null ? String(data.categoryType) : data.categoryType,
      robotOpsFaqSimilarList: data.robotOpsFaqSimilarList || []
    })
  }).then(() => {
    proxy.$modal.msgSuccess(actionText + "成功")
    getList()
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('base/faq/export', {
    ...queryParams.value
  }, `问答库_${new Date().getTime()}.xlsx`)
}

/** 获取相似问数量 */
function getSimilarCount(row) {
  if (row.similarCount !== undefined && row.similarCount !== null) {
    return row.similarCount
  }
  if (Array.isArray(row.robotOpsFaqSimilarList)) {
    return row.robotOpsFaqSimilarList.length
  }
  return 0
}

/** 格式化答案摘要 */
function formatAnswerSummary(answer) {
  if (!answer) return "-"
  return answer.length > 80 ? answer.slice(0, 80) + "..." : answer
}

getList()
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.form-tip {
  margin-top: 6px;
  font-size: 12px;
  line-height: 1.5;
  color: #909399;
}
:deep(.el-table .cell) {
  line-height: 22px;
}
</style>

