<template>
  <div class="app-container">
    <el-alert
      title="外呼 AI 配置说明"
      type="info"
      show-icon
      :closable="false"
      style="margin-bottom: 16px"
    >
      <template slot="default">
        <p style="margin: 0 0 6px 0;">
          本页维护外呼<strong>提示词</strong>与<strong>知识库分类</strong>；大模型由总后台「场景配置 → 外呼对话」统一分配，无需在此选择模型。
        </p>
        <p v-if="sceneInfo.models && sceneInfo.models.length" style="margin: 0; color: #606266; font-size: 13px;">
          当前分配模型：
          <el-tag
            v-for="m in sceneInfo.models"
            :key="m.modelId"
            size="mini"
            type="success"
            style="margin-right: 6px"
          >{{ m.modelName }}（{{ m.modelIdentifier }}）</el-tag>
        </p>
        <p v-else style="margin: 0; color: #e6a23c; font-size: 13px;">
          总后台尚未配置外呼场景模型，新增配置前请联系平台管理员。
        </p>
      </template>
    </el-alert>

    <el-form
      v-show="showSearch"
      ref="queryForm"
      :inline="true"
      :model="queryParams"
      label-width="88px"
    >
      <el-form-item label="配置名称" prop="name">
        <el-input
          v-model="queryParams.name"
          clearable
          placeholder="请输入配置名称"
          size="small"
          style="width: 200px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button 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="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          icon="el-icon-plus"
          plain
          size="mini"
          type="primary"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          icon="el-icon-edit"
          plain
          size="mini"
          type="success"
          @click="handleEdit()"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          icon="el-icon-delete"
          plain
          size="mini"
          type="danger"
          @click="handleDelete()"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="configList" border @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column align="center" label="配置名称" prop="name" min-width="140" show-overflow-tooltip />
      <el-table-column align="center" label="知识库分类" min-width="120">
        <template slot-scope="{ row }">
          {{ kbCatLabel(row) }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="打断方式" width="110">
        <template slot-scope="{ row }">
          {{ interruptLabel(row.interruptFlag) }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="转人工按键" prop="transferManualDigit" width="100" />
      <el-table-column
        align="center"
        class-name="small-padding fixed-width"
        label="操作"
        width="200"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document-copy"
            @click="handleCopy(scope.row)"
          >复制</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleEdit(scope.row)"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :limit.sync="queryParams.pageSize"
      :page.sync="queryParams.pageNum"
      :total="total"
      @pagination="getList"
    />

    <el-drawer
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      direction="rtl"
      size="min(760px, 96vw)"
      append-to-body
      destroy-on-close
      wrapper-closable
      custom-class="ai-model-drawer"
      @close="handleDialogClose"
    >
      <account-form
        v-if="dialogVisible"
        ref="accountForm"
        :initial-data="currentRow"
        :scene-info="sceneInfo"
        @cancel="handleDialogClose"
        @success="handleFormSuccess"
      />
    </el-drawer>
  </div>
</template>

<script>
import { list, remove } from '@/api/company/aiModel'
import { all as listKbCats } from '@/api/company/aiCall'
import { getOutboundAiScene } from '@/api/company/adminAiModel'
import Info from '@/views/company/aiModel/account/info.vue'

export default {
  name: 'AiModelConfigView',
  components: {
    AccountForm: Info
  },
  data() {
    return {
      selectedRows: [],
      loading: false,
      showSearch: true,
      total: 0,
      configList: [],
      kbCatMap: {},
      sceneInfo: {},
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined
      },
      dialogVisible: false,
      dialogTitle: '新增外呼配置',
      currentRow: {}
    }
  },
  created() {
    this.loadScene()
    this.loadKbCatMap()
    this.getList()
  },
  methods: {
    loadScene() {
      getOutboundAiScene()
        .then(res => {
          this.sceneInfo = res.data || {}
        })
        .catch(() => {
          this.sceneInfo = {}
        })
    },
    loadKbCatMap() {
      listKbCats().then(res => {
        const map = {}
        ;(res.data || []).forEach(item => {
          map[item.id] = item.cat
        })
        this.kbCatMap = map
      }).catch(() => {
        this.kbCatMap = {}
      })
    },
    kbCatLabel(row) {
      let id = row.kbCatId
      if (id == null || id === -1) {
        try {
          const json = typeof row.accountJson === 'string' ? JSON.parse(row.accountJson) : row.accountJson
          id = json && json.kbCatId
        } catch (e) {
          id = null
        }
      }
      if (id == null || id === -1 || id === '') {
        return '—'
      }
      return this.kbCatMap[id] || id
    },
    interruptLabel(flag) {
      if (flag === 1) return '关键词打断'
      if (flag === 2) return '有声音就打断'
      return '不打断'
    },
    getList() {
      this.loading = true
      list(this.queryParams)
        .then(response => {
          this.configList = response.rows || []
          this.total = response.total || 0
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    handleAdd() {
      if (!this.sceneInfo.models || !this.sceneInfo.models.length) {
        this.$message.warning('总后台尚未配置外呼场景模型，无法新增')
        return
      }
      this.dialogTitle = '新增外呼配置'
      this.currentRow = {}
      this.dialogVisible = true
    },
    handleDialogClose() {
      this.dialogVisible = false
      this.currentRow = {}
    },
    handleFormSuccess() {
      this.dialogVisible = false
      this.getList()
    },
    handleEdit(row) {
      let editRow = row
      if (!editRow) {
        if (this.selectedRows.length !== 1) {
          this.$message.warning('请选择一条要修改的数据')
          return
        }
        editRow = this.selectedRows[0]
      }
      this.dialogTitle = '编辑外呼配置'
      this.currentRow = { ...editRow }
      this.dialogVisible = true
    },
    handleSelectionChange(selection) {
      this.selectedRows = selection
    },
    handleDelete(row) {
      let ids = []
      if (row) {
        ids = [row.id]
      } else {
        if (this.selectedRows.length === 0) {
          this.$message.warning('请至少选择一条要删除的数据')
          return
        }
        ids = this.selectedRows.map(item => item.id)
      }
      this.$confirm(`此操作将永久删除${ids.length > 1 ? '这些' : '该'}配置，是否继续？`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        remove(ids.join(',')).then(response => {
          if (response.code === 200) {
            this.$message.success('删除成功')
            this.getList()
          } else {
            this.$message.error(response.msg || '删除失败')
          }
        })
      }).catch(() => {})
    },
    handleCopy(row) {
      const copiedRow = { ...row }
      delete copiedRow.id
      copiedRow.name = copiedRow.name + '-副本'
      this.dialogTitle = '复制外呼配置'
      this.currentRow = copiedRow
      this.dialogVisible = true
    }
  }
}
</script>

<style scoped>
.ai-model-drawer.el-drawer /deep/ .el-drawer__body {
  padding: 0;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.ai-model-drawer.el-drawer /deep/ .el-drawer__header {
  padding: 16px 20px;
  margin-bottom: 0;
  border-bottom: 1px solid #f0f2f5;
}

.ai-model-drawer.el-drawer /deep/ .el-drawer__header span {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}
</style>
