<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form
      v-show="showSearch"
      ref="queryForm"
      :inline="true"
      :model="queryParams"
      label-width="100px"
    >
      <el-form-item label="大模型底座" prop="llmAccountId">
        <el-select
          v-model="queryParams.llmAccountId"
          clearable
          placeholder="全部"
          size="small"
          style="width: 200px"
        >
          <el-option label="全部" value="" />
          <el-option
            v-for="item in llmAccountList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="被叫号码" prop="callee">
        <el-input
          v-model="queryParams.callee"
          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
          v-hasPermi="['inboundCallManage:add']"
          icon="el-icon-plus"
          plain
          size="mini"
          type="success"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          icon="el-icon-edit"
          plain
          size="mini"
          type="primary"
          :disabled="single"
          @click="handleEdit()"
        >修改</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          icon="el-icon-delete"
          plain
          size="mini"
          type="danger"
          :disabled="multiple"
          @click="handleDelete()"
        >删除</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
    </el-row>

    <!-- 数据表格 -->
    <el-table
      v-loading="loading"
      :data="inboundList"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column align="center" label="名称" prop="inboundAlias" />
      <el-table-column align="center" label="大模型底座" prop="llmAccountName" />
      <el-table-column align="center" label="音色" prop="voiceName" />
      <el-table-column align="center" label="被叫号码" prop="callee" />
      <el-table-column align="center" label="服务类型" prop="serviceType" width="200">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.serviceType === 'ai'" type="primary">AI</el-tag>
          <el-tag v-else-if="scope.row.serviceType === 'acd'" type="success">技能组</el-tag>
          <el-tag v-else-if="scope.row.serviceType === 'ivr'" type="info">IVR</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        class-name="small-padding fixed-width"
        label="操作"
        width="180"
      >
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['inboundCallManage:edit']"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleEdit(scope.row)"
          >修改</el-button>
          <el-button
          v-hasPermi="['inboundCallManage:delete']"
            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-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="650px"
      append-to-body
      @close="handleDialogClose"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="120px"
      >
        <!-- 名称 -->
        <el-form-item label="名称" prop="inboundAlias">
          <el-input
            v-model="form.inboundAlias"
            placeholder="请输入名称"
            style="width: 400px;"
          />
        </el-form-item>

        <!-- 被叫号码 -->
        <el-form-item label="被叫号码" prop="callee">
          <el-input
            v-model="form.callee"
            placeholder="请输入被叫号码"
            style="width: 400px;"
          />
        </el-form-item>

        <!-- 服务类型 -->
        <el-form-item label="服务类型" prop="serviceType">
          <el-select
            v-model="form.serviceType"
            placeholder="请选择服务类型"
            style="width: 400px;"
            @change="handleServiceTypeChange"
          >
            <el-option label="AI" value="ai" />
            <el-option label="技能组" value="acd" />
            <el-option label="IVR" value="ivr" />
          </el-select>
        </el-form-item>

        <!-- 大模型底座 (AI可见) -->
        <el-form-item v-if="form.serviceType === 'ai'" label="大模型底座" prop="llmAccountId">
          <el-select
            v-model="form.llmAccountId"
            placeholder="请选择大模型底座"
            style="width: 400px;"
          >
            <el-option
              v-for="item in llmAccountList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <!-- ASR提供商 (AI可见) -->
        <el-form-item v-if="form.serviceType === 'ai'" label="ASR提供商" prop="asrProvider">
          <el-select
            v-model="form.asrProvider"
            placeholder="请选择ASR提供商"
            style="width: 400px;"
          >
            <el-option
              v-for="(value, key) in asrProviderList"
              :key="key"
              :label="value"
              :value="key"
            />
          </el-select>
        </el-form-item>

        <!-- 音色来源 (AI可见) -->
        <el-form-item v-if="form.serviceType === 'ai'" label="音色来源" prop="voiceSource">
          <el-select
            v-model="form.voiceSource"
            placeholder="请选择音色来源"
            style="width: 400px;"
            @change="handleVoiceSourceChange"
          >
            <el-option
              v-for="(value, key) in voiceSourceList"
              :key="key"
              :label="value"
              :value="key"
            />
          </el-select>
        </el-form-item>

        <!-- 音色 (AI可见) -->
        <el-form-item v-if="form.serviceType === 'ai'" label="音色" prop="voiceCode">
          <el-select
            v-model="form.voiceCode"
            placeholder="请选择音色"
            style="width: 400px;"
          >
            <el-option
              v-for="item in voiceList"
              :key="item.voiceCode"
              :label="item.voiceName"
              :value="item.voiceCode"
            />
          </el-select>
        </el-form-item>

        <!-- AI转接类型 (AI可见) -->
        <el-form-item v-if="form.serviceType === 'ai'" label="AI转接类型" prop="aiTransferType">
          <el-select
            v-model="form.aiTransferType"
            placeholder="请选择AI转接类型"
            style="width: 400px;"
            @change="handleAiTransferTypeChange"
          >
            <el-option label="技能组" value="acd" />
            <el-option label="分机号" value="extension" />
            <el-option label="网关" value="gateway" />
          </el-select>
        </el-form-item>

        <!-- IVR下拉 (IVR可见) -->
        <el-form-item v-if="form.serviceType === 'ivr'" label="IVR" prop="ivrId">
          <el-select
            v-model="form.ivrId"
            placeholder="请选择IVR"
            style="width: 400px;"
          >
            <el-option
              v-for="item in ivrList"
              :key="item.id"
              :label="item.ivrNodeName"
              :value="String(item.id)"
            />
          </el-select>
        </el-form-item>

        <!-- 业务组 (ACD/AI+ACD可见) -->
        <el-form-item v-if="showBizGroup" label="业务组" prop="aiTransferGroupId">
          <el-select
            v-model="form.aiTransferGroupId"
            placeholder="请选择业务组"
            style="width: 400px;"
          >
            <el-option
              v-for="item in bizGroupList"
              :key="item.groupId"
              :label="item.bizGroupName"
              :value="String(item.groupId)"
            />
          </el-select>
        </el-form-item>

        <!-- 网关 (AI+Gateway可见) -->
        <el-form-item v-if="showGateway" label="网关" prop="aiTransferGatewayId">
          <el-select
            v-model="form.aiTransferGatewayId"
            placeholder="请选择网关"
            style="width: 400px;"
          >
            <el-option
              v-for="item in gatewayList"
              :key="item.id"
              :label="item.gwDesc"
              :value="String(item.id)"
            />
          </el-select>
        </el-form-item>

        <!-- 网关目标号码 (AI+Gateway可见) -->
        <el-form-item v-if="showGateway" label="网关目标号码" prop="aiTransferGatewayDestNumber">
          <el-input
            v-model="form.aiTransferGatewayDestNumber"
            placeholder="请输入网关目标号码"
            style="width: 400px;"
          />
        </el-form-item>

        <!-- 分机号 (AI+Extension可见) -->
        <el-form-item v-if="showExtension" label="分机号" prop="aiTransferExtNumber">
          <el-input
            v-model="form.aiTransferExtNumber"
            placeholder="请输入分机号"
            style="width: 400px;"
          />
        </el-form-item>

        <!-- 服务评价 -->
        <el-form-item label="服务评价" prop="satisfSurveyIvrId">
          <el-select
            v-model="form.satisfSurveyIvrId"
            placeholder="请选择服务评价IVR"
            clearable
            style="width: 400px;"
          >
            <el-option
              v-for="item in ivrList"
              :key="item.id"
              :label="item.ivrNodeName"
              :value="String(item.id)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="呼入场景" prop="fsSceneType">
          <el-select
            v-model="form.fsSceneType"
            placeholder="请选择呼入场景"
            clearable
            style="width: 400px;"
          >
            <el-option
              v-for="item in sceneList"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="parseInt(item.dictValue)"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="线路回调地址" prop="callBackUrl">
         <el-input
            v-model="form.callBackUrl"
            placeholder="请输入线路回调地址"
            style="width: 400px;"
          />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listInboundLlm,
  addInboundLlm,
  updateInboundLlm,
  delInboundLlm,
  listLlmAccount,
  listAsrProvider,
  listVoiceSource,
  listVoiceBySource,
  listBizGroup,
  listGateway,
  listIvr
} from '@/api/company/inboundCallManage'

export default {
  name: 'InboundCallManage',
  data() {
    return {
      // 遮罩层
      loading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      inboundList: [],
      // 选中的数据
      selectedRows: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        llmAccountId: undefined,
        callee: undefined
      },
      // 大模型账户列表
      llmAccountList: [],
      // ASR提供商列表
      asrProviderList: {},
      // 音色来源列表
      voiceSourceList: {},
      // 音色列表
      voiceList: [],
      // 业务组列表
      bizGroupList: [],
      // 网关列表
      gatewayList: [],
      // IVR列表
      ivrList: [],
      // 弹窗控制
      dialogVisible: false,
      dialogTitle: '新增呼入大模型配置',
      // 表单数据
      form: {
        id: undefined,
        inboundAlias: undefined,
        callee: undefined,
        serviceType: 'ai',
        llmAccountId: undefined,
        asrProvider: undefined,
        voiceSource: undefined,
        voiceCode: undefined,
        aiTransferType: 'acd',
        aiTransferGroupId: undefined,
        aiTransferGatewayId: undefined,
        aiTransferGatewayDestNumber: undefined,
        aiTransferExtNumber: undefined,
        ivrId: undefined,
        satisfSurveyIvrId: undefined,
        fsSceneType:null,
        callBackUrl:null
      },
      // 表单校验规则
      rules: {
        inboundAlias: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        callee: [
          { required: true, message: '请输入被叫号码', trigger: 'blur' }
        ],
        serviceType: [
          { required: true, message: '请选择服务类型', trigger: 'change' }
        ],
        fsSceneType: [
          { required: true, message: '请选择呼入场景', trigger: 'change' }
        ],
        callBackUrl: [
          { required: true, message: '请输入线路回调地址', trigger: 'blur' }
        ],
      },
      //场景下拉
      sceneList:[]
    }
  },
  computed: {
    // 是否显示业务组选择
    showBizGroup() {
      return this.form.serviceType === 'acd' ||
             (this.form.serviceType === 'ai' && this.form.aiTransferType === 'acd')
    },
    // 是否显示网关选择
    showGateway() {
      return this.form.serviceType === 'ai' && this.form.aiTransferType === 'gateway'
    },
    // 是否显示分机号输入
    showExtension() {
      return this.form.serviceType === 'ai' && this.form.aiTransferType === 'extension'
    }
  },
  created() {
    this.getList()
    this.loadDropdownData()
    this.getDicts("task_scene_type").then((response) => {
        this.sceneList = response.data;
    });
  },
  methods: {
    /** 加载下拉数据 */
    loadDropdownData() {
      // 大模型账户
      listLlmAccount().then(response => {
        this.llmAccountList = response.data || []
      })
      // ASR提供商
      listAsrProvider().then(response => {
        this.asrProviderList = response.data || {}
      })
      // 音色来源
      listVoiceSource().then(response => {
        this.voiceSourceList = response.data || {}
      })
      // 业务组
      listBizGroup().then(response => {
        this.bizGroupList = response.data || []
      })
      // 网关
      listGateway().then(response => {
        this.gatewayList = response.data || []
      })
      // IVR
      listIvr().then(response => {
        this.ivrList = response.data || []
      })
    },
    /** 查询列表 */
    getList() {
      this.loading = true
      listInboundLlm(this.queryParams).then(response => {
        this.inboundList = response.rows || []
        this.total = response.total || 0
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    /** 服务类型改变 */
    handleServiceTypeChange() {
      // 清空关联字段
      this.form.llmAccountId = undefined
      this.form.asrProvider = undefined
      this.form.voiceSource = undefined
      this.form.voiceCode = undefined
      this.form.aiTransferType = 'acd'
      this.form.ivrId = undefined
      this.voiceList = []
    },
    /** 音色来源改变 */
    handleVoiceSourceChange(val) {
      this.form.voiceCode = undefined
      if (val) {
        listVoiceBySource(val).then(response => {
          this.voiceList = response.data || []
        })
      } else {
        this.voiceList = []
      }
    },
    /** AI转接类型改变 */
    handleAiTransferTypeChange() {
      this.form.aiTransferGroupId = undefined
      this.form.aiTransferGatewayId = undefined
      this.form.aiTransferGatewayDestNumber = undefined
      this.form.aiTransferExtNumber = undefined
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 表格多选选中事件 */
    handleSelectionChange(selection) {
      this.selectedRows = selection
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.dialogTitle = '新增呼入大模型配置'
      this.dialogVisible = true
    },
    /** 修改按钮操作 */
    handleEdit(row) {
      this.reset()
      let editRow = row
      if (!editRow) {
        if (this.selectedRows.length !== 1) {
          this.$message.warning('请选择一条要修改的数据')
          return
        }
        editRow = this.selectedRows[0]
      }
      this.dialogTitle = '修改呼入大模型配置'
      this.form = { ...editRow }
      // 如果有音色来源，加载音色列表
      if (this.form.voiceSource) {
        listVoiceBySource(this.form.voiceSource).then(response => {
          this.voiceList = response.data || []
        })
      }
      this.dialogVisible = true
    },
    /** 删除按钮操作 */
    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(() => {
        delInboundLlm(ids.join(',')).then(response => {
          if (response.code === 200) {
            this.$message.success('删除成功')
            this.getList()
          } else {
            this.$message.error(response.msg || '删除失败')
          }
        })
      }).catch(() => {})
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        inboundAlias: undefined,
        callee: undefined,
        serviceType: 'ai',
        llmAccountId: undefined,
        asrProvider: undefined,
        voiceSource: undefined,
        voiceCode: undefined,
        aiTransferType: 'acd',
        aiTransferGroupId: undefined,
        aiTransferGatewayId: undefined,
        aiTransferGatewayDestNumber: undefined,
        aiTransferExtNumber: undefined,
        ivrId: undefined,
        satisfSurveyIvrId: undefined
      }
      this.voiceList = []
      this.resetForm('form')
    },
    /** 弹窗关闭时清理 */
    handleDialogClose() {
      this.reset()
    },
    /** 提交表单 */
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          // 处理转接数据
          const submitData = { ...this.form }
          if (submitData.serviceType === 'ai') {
            if (submitData.aiTransferType === 'acd') {
              submitData.aiTransferData = submitData.aiTransferGroupId
            } else if (submitData.aiTransferType === 'extension') {
              submitData.aiTransferData = submitData.aiTransferExtNumber
            } else if (submitData.aiTransferType === 'gateway') {
              submitData.aiTransferData = JSON.stringify({
                gatewayId: submitData.aiTransferGatewayId,
                destNumber: submitData.aiTransferGatewayDestNumber
              })
            }
          } else if (submitData.serviceType === 'acd') {
            submitData.aiTransferData = submitData.aiTransferGroupId
          }

          if (submitData.id) {
            updateInboundLlm(submitData).then(response => {
              if (response.code === 200) {
                this.$message.success('修改成功')
                this.dialogVisible = false
                this.getList()
              } else {
                this.$message.error(response.msg || '修改失败')
              }
            })
          } else {
            addInboundLlm(submitData).then(response => {
              if (response.code === 200) {
                this.$message.success('新增成功')
                this.dialogVisible = false
                this.getList()
              } else {
                this.$message.error(response.msg || '新增失败')
              }
            })
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}
</style>
