<template>
  <div class="app-container outbound-config-form">
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="120px"
      class="account-form"
    >
      <el-form-item label="配置名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入外呼配置名称" />
      </el-form-item>

      <el-divider content-position="left">提示词与知识库</el-divider>

      <el-form-item label="大模型提示词" prop="accountJson.llmTips">
        <el-input
          v-model="form.accountJson.llmTips"
          type="textarea"
          :rows="12"
          placeholder="请输入外呼对话主提示词"
        />
      </el-form-item>

      <el-form-item label="FAQ上下文" prop="accountJson.faqContext">
        <el-input
          v-model="form.accountJson.faqContext"
          type="textarea"
          :rows="12"
          placeholder="请输入 FAQ 上下文"
        />
      </el-form-item>

      <el-form-item label="知识库分类" prop="accountJson.kbCatId">
        <el-select
          v-model="form.accountJson.kbCatId"
          placeholder="请选择知识库分类（可选）"
          style="width: 100%"
          clearable
          filterable
        >
          <el-option
            v-for="item in kbCatOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="开场白" prop="accountJson.openingRemarks">
        <el-input
          v-model="form.accountJson.openingRemarks"
          type="textarea"
          :rows="3"
          placeholder="请输入开场白"
        />
      </el-form-item>

      <el-form-item label="转人工提示词" prop="accountJson.transferToAgentTips">
        <el-input
          v-model="form.accountJson.transferToAgentTips"
          type="textarea"
          :rows="3"
          placeholder="请输入转人工提示词"
        />
      </el-form-item>

      <el-form-item label="挂机提示" prop="accountJson.hangupTips">
        <el-input
          v-model="form.accountJson.hangupTips"
          type="textarea"
          :rows="3"
          placeholder="请输入挂机提示"
        />
      </el-form-item>

      <el-form-item label="客户不说话提示" prop="accountJson.customerNoVoiceTips">
        <el-input
          v-model="form.accountJson.customerNoVoiceTips"
          type="textarea"
          :rows="3"
          placeholder="请输入客户不说话时的提示"
        />
      </el-form-item>

      <el-form-item label="客户意向提示词" prop="intentionTips">
        <el-input
          v-model="form.intentionTips"
          type="textarea"
          :rows="5"
          placeholder="请输入客户意向分析提示词"
        />
      </el-form-item>

      <el-divider content-position="left">通话行为</el-divider>

      <el-form-item label="打断开关" prop="interruptFlag">
        <el-select v-model="form.interruptFlag" placeholder="请选择打断方式" style="width: 100%">
          <el-option label="不打断" :value="0" />
          <el-option label="关键词打断" :value="1" />
          <el-option label="有声音就打断" :value="2" />
        </el-select>
      </el-form-item>

      <el-form-item
        v-if="form.interruptFlag === 1"
        label="打断关键词"
        prop="interruptKeywords"
      >
        <el-input
          v-model="form.interruptKeywords"
          type="textarea"
          :rows="4"
          placeholder="请输入打断关键词"
        />
      </el-form-item>

      <el-form-item
        v-if="form.interruptFlag === 1"
        label="忽略打断关键词"
        prop="interruptIgnoreKeywords"
      >
        <el-input
          v-model="form.interruptIgnoreKeywords"
          type="textarea"
          :rows="4"
          placeholder="请输入忽略打断关键词"
        />
      </el-form-item>

      <el-form-item label="转人工数字按键" prop="transferManualDigit">
        <el-input
          v-model="form.transferManualDigit"
          placeholder="例如: 1"
          maxlength="1"
          @input="handleTransferManualDigitInput"
        />
      </el-form-item>
    </el-form>

    <div class="dialog-footer">
      <el-button @click="handleCancel">取 消</el-button>
      <el-button type="primary" :loading="submitting" @click="handleSubmit">确 定</el-button>
    </div>
  </div>
</template>

<script>
import { add, update } from '@/api/company/aiModel'
import { all } from '@/api/company/aiCall'

const DEFAULT_IGNORE_KEYWORDS = '呃 哦 哦哦 嗯 嗯嗯 嗯好的 好的 对 对对 是的 明白 啊 这样啊 是这样啊这样的 您好 你好'

export default {
  name: 'OutboundAiConfigForm',
  props: {
    initialData: {
      type: Object,
      default: () => ({})
    },
    sceneInfo: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      submitting: false,
      kbCatOptions: [],
      form: {
        id: undefined,
        name: '',
        interruptFlag: 0,
        interruptKeywords: '',
        interruptIgnoreKeywords: DEFAULT_IGNORE_KEYWORDS,
        transferManualDigit: '',
        intentionTips: '',
        accountJson: {
          llmTips: '',
          faqContext: '',
          kbCatId: undefined,
          openingRemarks: '',
          transferToAgentTips: '',
          hangupTips: '',
          customerNoVoiceTips: ''
        }
      },
      rules: {
        name: [{ required: true, message: '请输入配置名称', trigger: 'blur' }],
        'accountJson.llmTips': [{ required: true, message: '请输入大模型提示词', trigger: 'blur' }],
        'accountJson.faqContext': [{ required: true, message: '请输入 FAQ 上下文', trigger: 'blur' }],
        'accountJson.openingRemarks': [{ required: true, message: '请输入开场白', trigger: 'blur' }],
        'accountJson.transferToAgentTips': [{ required: true, message: '请输入转人工提示词', trigger: 'blur' }],
        'accountJson.hangupTips': [{ required: true, message: '请输入挂机提示', trigger: 'blur' }],
        'accountJson.customerNoVoiceTips': [{ required: true, message: '请输入客户不说话提示', trigger: 'blur' }],
        interruptFlag: [{ required: true, message: '请选择打断方式', trigger: 'change' }],
        transferManualDigit: [{ pattern: /^[0-9]?$/, message: '请输入单个数字 0-9', trigger: 'blur' }]
      }
    }
  },
  watch: {
    initialData: {
      handler(val) {
        if (val && Object.keys(val).length > 0) {
          this.initFormData(val)
        }
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    this.loadKbCatOptions()
  },
  methods: {
    initFormData(data) {
      this.form.id = data.id
      this.form.name = data.name || ''
      this.form.interruptFlag = data.interruptFlag != null ? data.interruptFlag : 0
      this.form.interruptKeywords = data.interruptKeywords || ''
      this.form.interruptIgnoreKeywords = data.interruptIgnoreKeywords || DEFAULT_IGNORE_KEYWORDS
      this.form.transferManualDigit = data.transferManualDigit || ''
      this.form.intentionTips = data.intentionTips || ''

      let parsed = {}
      try {
        parsed = data.accountJson
          ? (typeof data.accountJson === 'string' ? JSON.parse(data.accountJson) : data.accountJson)
          : {}
      } catch (e) {
        parsed = {}
      }

      const kbCatId = parsed.kbCatId != null && parsed.kbCatId !== -1
        ? parsed.kbCatId
        : (data.kbCatId != null && data.kbCatId !== -1 ? data.kbCatId : undefined)

      this.form.accountJson = {
        llmTips: parsed.llmTips || '',
        faqContext: parsed.faqContext || '',
        kbCatId,
        openingRemarks: parsed.openingRemarks || '',
        transferToAgentTips: parsed.transferToAgentTips || '',
        hangupTips: parsed.hangupTips || '',
        customerNoVoiceTips: parsed.customerNoVoiceTips || ''
      }
    },
    handleTransferManualDigitInput(value) {
      let val = value.replace(/[^0-9]/g, '')
      if (val.length > 1) val = val.substring(0, 1)
      this.$set(this.form, 'transferManualDigit', val)
    },
    async loadKbCatOptions() {
      try {
        const response = await all()
        const list = response?.data ?? []
        this.kbCatOptions = Array.isArray(list)
          ? list.map(item => ({ label: item.cat, value: item.id }))
          : []
      } catch (error) {
        this.kbCatOptions = []
      }
    },
    handleCancel() {
      this.$emit('cancel')
    },
    handleSubmit() {
      this.$refs.form.validate(async valid => {
        if (!valid) return
        if (!this.sceneInfo.models || !this.sceneInfo.models.length) {
          this.$message.warning('总后台尚未配置外呼场景模型，无法保存')
          return
        }
        this.submitting = true
        try {
          const accountJson = { ...this.form.accountJson }
          const submitData = {
            id: this.form.id,
            name: this.form.name,
            interruptFlag: this.form.interruptFlag,
            interruptKeywords: this.form.interruptKeywords || '',
            interruptIgnoreKeywords: this.form.interruptIgnoreKeywords || '',
            transferManualDigit: this.form.transferManualDigit || '',
            intentionTips: this.form.intentionTips || '',
            kbCatId: accountJson.kbCatId != null ? accountJson.kbCatId : -1,
            accountJson: JSON.stringify(accountJson)
          }
          const response = submitData.id ? await update(submitData) : await add(submitData)
          if (response.code === 200) {
            this.$message.success('保存成功')
            this.$emit('success', response)
          } else {
            this.$message.error(response.msg || '保存失败')
          }
        } catch (error) {
          this.$message.error(error.msg || error.message || '保存失败')
        } finally {
          this.submitting = false
        }
      })
    }
  }
}
</script>

<style scoped>
.outbound-config-form {
  padding: 16px 20px 72px;
  overflow-y: auto;
  flex: 1;
}

.dialog-footer {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 12px 20px;
  background: #fff;
  border-top: 1px solid #f0f2f5;
  text-align: right;
  z-index: 1;
}
</style>
