<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never">
      <div slot="header">
        <span>CID配置</span>
      </div>
      <el-form ref="form" :model="form" label-width="220px">
        <el-card shadow="never" class="section-card">
          <div slot="header"><span>手机号配置</span></div>
          <el-form-item label="是否开启手机号配置" prop="enablePhoneConfig">
            <el-switch v-model="form.enablePhoneConfig"></el-switch>
          </el-form-item>
          <template v-if="form.enablePhoneConfig">
            <el-form-item label="生成条数" prop="generateCount">
              <el-input-number v-model="form.generateCount" :min="1" :step="1" :precision="0" placeholder="请输入生成条数"></el-input-number>
            </el-form-item>
            <el-form-item label="开始位置" prop="startIndex">
              <el-input-number v-model="form.startIndex" :min="1" :step="1" :precision="0" placeholder="例如: 1"></el-input-number>
              <span class="tip-text">（从第几位开始生成）</span>
            </el-form-item>
            <el-form-item label="结束位置" prop="endIndex">
              <el-input-number v-model="form.endIndex" :min="1" :step="1" :precision="0" placeholder="例如: 11"></el-input-number>
              <span class="tip-text">（到第几位结束）</span>
            </el-form-item>
          </template>
          <el-form-item label="是否开手机号拨打次数限制" prop="enablePhoneLimitConfig">
            <el-switch v-model="form.enablePhoneLimitConfig"></el-switch>
          </el-form-item>
          <template v-if="form.enablePhoneLimitConfig">
            <el-form-item label="拨打次数限制" prop="numberCalls">
              <el-input-number v-model="form.numberCalls" :min="1" :step="1" :precision="0" placeholder="例如: 1"></el-input-number>
            </el-form-item>
          </template>
        </el-card>

        <el-card shadow="never" class="section-card">
          <div slot="header"><span>DeepSeekChat配置</span></div>
          <el-form-item label="DeepSeekChat模型并发数" prop="concurrency">
            <el-input v-model="form.concurrency" placeholder="请输入DeepSeekChat模型并发数"></el-input>
          </el-form-item>
          <el-form-item label="DeepSeekChat服务地址" prop="serverAddress">
            <el-input v-model="form.serverAddress" placeholder="请输入DeepSeekChat服务地址"></el-input>
          </el-form-item>
          <el-form-item label="DeepSeekChat_apiKey" prop="apiKey">
            <el-input v-model="form.apiKey" placeholder="请输入DeepSeekChat_apiKey"></el-input>
          </el-form-item>
          <el-form-item label="DeepSeekChat模型名称" prop="modelName">
            <el-input v-model="form.modelName" placeholder="请输入DeepSeekChat模型名称"></el-input>
          </el-form-item>
        </el-card>

        <el-card shadow="never" class="section-card">
          <div slot="header"><span>外呼网关配置</span></div>
          <el-form-item label="是否限制外呼网关" prop="enableGateWayLimit">
            <el-switch v-model="form.enableGateWayLimit"></el-switch>
          </el-form-item>
          <el-form-item label="系统可见外呼网关" prop="showGatewayIds" v-if="!!form.enableGateWayLimit">
            <el-select v-model="form.showGatewayIds" multiple filterable placeholder="请选择系统可见外呼网关">
              <el-option
                v-for="item in gatewayList"
                :key="item.id"
                :label="item.gwDesc"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-card>

      </el-form>
      <div style="text-align: center; margin-top: 20px; padding-bottom: 20px;">
        <el-button type="primary" size="medium" @click="submitForm" :loading="submitLoading">保存配置</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getConfigByKey, updateConfigByKey, getGatewayList } from '@/api/system/config'

export default {
  name: 'AdminCidConfig',
  data() {
    return {
      loading: false,
      submitLoading: false,
      configId: null,
      configKey: 'cId.config',
      gatewayList: [],
      form: {
        enablePhoneConfig: false,
        enablePhoneLimitConfig: false,
        generateCount: 1,
        startIndex: 1,
        endIndex: 11,
        numberCalls: 1,
        concurrency: '',
        serverAddress: '',
        apiKey: '',
        modelName: '',
        enableGateWayLimit: false,
        showGatewayIds: []
      }
    }
  },
  created() {
    this.loadConfig()
  },
  methods: {
    loadConfig() {
      this.loading = true
      getConfigByKey(this.configKey).then(response => {
        if (response.data) {
          this.configId = response.data.configId
          try {
            const parsed = JSON.parse(response.data.configValue)
            this.form = { ...this.form, ...parsed }
          } catch (e) {
            // 使用默认值
          }
        } else {
          this.configId = null
        }
        // 加载网关列表
        if (this.form.enableGateWayLimit) {
          this.loadGatewayList()
        }
      }).finally(() => {
        this.loading = false
      })
    },
    loadGatewayList() {
      getGatewayList().then(res => {
        this.gatewayList = res.data || []
      })
    },
    submitForm() {
      // 验证手机号配置
      if (this.form.enablePhoneConfig) {
        if (!this.form.generateCount || this.form.generateCount < 1) {
          this.msgError('生成条数不能为空且不能小于1')
          return false
        }
        if (!this.form.startIndex || this.form.startIndex < 1 || this.form.startIndex > 11) {
          this.msgError('开始位置不能为空，且必须在1到11之间')
          return false
        }
        if (!this.form.endIndex || this.form.endIndex < 1 || this.form.endIndex > 11) {
          this.msgError('结束位置不能为空，且必须在1到11之间')
          return false
        }
        if (this.form.startIndex > this.form.endIndex) {
          this.msgError('开始位置不能大于结束位置')
          return false
        }
        if (this.form.startIndex === this.form.endIndex) {
          this.msgError('开始位置不能等于结束位置')
          return false
        }
        let num = this.form.endIndex - this.form.startIndex
        if (num < 4) {
          this.msgError('开始和结束位置不能小于4位')
          return false
        }
      }
      // 验证拨打次数限制
      if (this.form.enablePhoneLimitConfig) {
        if (this.form.numberCalls == null || this.form.numberCalls === 0) {
          this.msgError('限制次数不能为空或者大于0！')
          return false
        }
        if (this.form.numberCalls > 100000) {
          this.msgError('限制次数不能超过10万次！')
          return false
        }
      }
      this.submitLoading = true
      const param = {
        configId: this.configId,
        configKey: this.configKey,
        configValue: JSON.stringify(this.form)
      }
      updateConfigByKey(param).then(response => {
        if (response.code === 200) {
          this.msgSuccess('修改成功')
        }
      }).finally(() => {
        this.submitLoading = false
      })
    }
  },
  watch: {
    'form.enableGateWayLimit'(val) {
      if (val && this.gatewayList.length === 0) {
        this.loadGatewayList()
      }
    }
  }
}
</script>

<style scoped>
.section-card {
  margin-bottom: 20px;
}
.tip-text {
  color: #909399;
  font-size: 12px;
  margin-left: 8px;
}

</style>
