<template>
  <popup
    v-model="showDialog"
    :title="popupTitle"
    width="560px"
    :align-center="false"
    :close-on-click-modal="false"
    :confirmLoading="isLoading"
    @confirm="handleSubmit"
  >
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="150px" v-loading="isLoading">
      <el-form-item label="网关" prop="gateway">
        <el-select
          v-model="formData.gateway"
          placeholder="请选择网关"
          :disabled="mode === 'edit'"
          @change="handleGatewayChange"
        >
          <el-option
            v-for="item in gatewayOptions"
            :key="item.gateway"
            :label="item.gateway_name"
            :value="item.gateway"
          />
        </el-select>
      </el-form-item>
      <el-alert v-if="currentGatewayGuide" class="mb-4" type="info" show-icon :closable="false">
        <div class="text-sm flex items-center">
          {{ currentGatewayGuide.label }}：
          <el-link :href="currentGatewayGuide.url" target="_blank" type="primary">
            {{ currentGatewayGuide.text }}
          </el-link>
        </div>
        <div class="mt-0.5 text-base text-info leading-normal">
          点击链接查看官方参数说明，保存前请确认所有必填项已填写。
        </div>
      </el-alert>
      <template v-for="field in currentFields" :key="field.key">
        <el-form-item
          :label="formatFieldLabel(field.key)"
          :prop="`config_data.${field.key}`"
          :rules="[
            { required: field.required, message: '请输入' + formatFieldLabel(field.key), trigger: ['blur', 'change'] }
          ]"
        >
          <el-input
            v-model="formData.config_data[field.key]"
            :placeholder="formatFieldPlaceholder(field.key)"
            clearable
          />
        </el-form-item>
      </template>
    </el-form>
  </popup>
</template>

<script setup lang="ts" name="MessageConfigEdit">
import type { FormInstance } from 'element-plus'
import { configDetail, configSave, configGateways } from '@/api/message/config'

// 定义组件事件
const emit = defineEmits<{
  (event: 'success'): void
}>()

// 表单引用
const formRef = ref<FormInstance>()
// 模式：add=新增，edit=编辑
const mode = ref<'add' | 'edit'>('add')
// 加载状态
const isLoading = ref(false)
// 是否显示弹窗
const showDialog = ref(false)
// 网关选项列表
const gatewayOptions = ref<any[]>([])
// 表单数据
const formData = reactive<Record<string, any>>({
  gateway: '',
  config_data: {}
})
// 表单验证规则
const formRules = reactive({
  gateway: [{ required: true, message: '请选择网关', trigger: ['blur', 'change'] }]
})
// 弹窗标题
const popupTitle = computed(() => (mode.value === 'edit' ? '编辑配置' : '新增配置'))
// 字段标签映射
const FIELD_LABELS: Record<string, { zh: string; en: string }> = {
  access_key_id: { zh: 'Access Key ID', en: 'Access Key ID' },
  access_key_secret: { zh: 'Access Key Secret', en: 'Access Key Secret' },
  sign_name: { zh: '短信签名', en: 'Signature' },
  sdk_app_id: { zh: 'SDK App ID', en: 'SDK App ID' },
  secret_id: { zh: 'Secret ID', en: 'Secret ID' },
  secret_key: { zh: 'Secret Key', en: 'Secret Key' },
  endpoint: { zh: '接入地址', en: 'Endpoint' },
  app_key: { zh: '应用 Key', en: 'App Key' },
  app_secret: { zh: '应用 Secret', en: 'App Secret' },
  from: { zh: '通道号', en: 'Channel/From' },
  callback: { zh: '回调地址', en: 'Callback URL' },
  access_key: { zh: 'Access Key', en: 'Access Key' },
  api_key: { zh: 'API Key', en: 'API Key' },
  signature: { zh: '短信签名', en: 'Signature' },
  app_id: { zh: '应用 ID', en: 'App ID' },
  sms_user: { zh: '短信用户', en: 'SMS User' },
  sms_key: { zh: '短信密钥', en: 'SMS Key' },
  ak: { zh: 'Access Key', en: 'Access Key' },
  sk: { zh: 'Secret Key', en: 'Secret Key' },
  invoke_id: { zh: '模板 ID', en: 'Invoke ID' },
  domain: { zh: '服务域名', en: 'Domain' }
}
// 网关配置指引
const GATEWAY_GUIDES: Record<string, { label: string; text: string; url: string }> = {
  aliyun: {
    label: '阿里云短信 / Alibaba Cloud SMS',
    text: '配置文档 / Docs',
    url: 'https://help.aliyun.com/zh/sms/user-guide/create-signatures?spm=a2c4g.11186623.help-menu-44282.d_3_3_0.4a8628fcismUDk&scm=20140722.H_108073._.OR_help-T_cn~zh-V_1'
  },
  qcloud: {
    label: '腾讯云短信 / Tencent Cloud SMS',
    text: '配置文档 / Docs',
    url: 'https://cloud.tencent.com/document/product/382/37745'
  },
  huawei: {
    label: '华为云短信 / Huawei Cloud SMS',
    text: '配置文档 / Docs',
    url: 'https://support.huaweicloud.com/intl/zh-cn/api-msgsms/sms_05_0000.html'
  },
  qiniu: {
    label: '七牛云短信 / Qiniu SMS',
    text: '配置文档 / Docs',
    url: 'https://developer.qiniu.com/sms/5897/sms-api-overview'
  },
  yunpian: {
    label: '云片短信 / Yunpian SMS',
    text: '配置文档 / Docs',
    url: 'https://www.yunpian.com/official/document/sms/zh_CN/domestic_list'
  },
  submail: {
    label: 'Submail 短信 / Submail SMS',
    text: '配置文档 / Docs',
    url: 'https://www.mysubmail.com/documents/3zc9c3'
  },
  juhe: {
    label: '聚合数据短信 / Juhe SMS',
    text: '配置文档 / Docs',
    url: 'https://www.juhe.cn/docs/api/id/54'
  },
  sendcloud: {
    label: 'SendCloud 短信 / SendCloud SMS',
    text: '配置文档 / Docs',
    url: 'https://www.sendcloud.net/doc/sms/'
  },
  baidu: {
    label: '百度云短信 / Baidu SMS',
    text: '配置文档 / Docs',
    url: 'https://cloud.baidu.com/doc/SMS/index.html'
  }
}
// 网关映射
const gatewayMap = computed(() => {
  const map: Record<string, any> = {}
  gatewayOptions.value.forEach((item) => {
    map[item.gateway] = item
  })
  return map
})
// 当前字段列表
const currentFields = computed(() => {
  const gatewayInfo = gatewayMap.value[formData.gateway]
  if (!gatewayInfo) return []
  const required = (gatewayInfo.required_fields || []).map((key: string) => ({ key, required: true }))
  const optional = (gatewayInfo.optional_fields || []).map((key: string) => ({ key, required: false }))
  return [...required, ...optional]
})
// 当前网关指引
const currentGatewayGuide = computed(() => (formData.gateway ? GATEWAY_GUIDES[formData.gateway] : null))

// 处理网关选择变化
const handleGatewayChange = () => {
  currentFields.value.forEach((field) => {
    formData.config_data[field.key] = ''
    setTimeout(() => {
      formRef.value?.clearValidate(`config_data.${field.key}`)
    }, 0)
  })
}
// 格式化字段标签
const formatFieldLabel = (key: string) => {
  const label = FIELD_LABELS[key]
  if (!label) return key
  return label.zh
}
// 格式化字段占位符
const formatFieldPlaceholder = (key: string) => {
  const label = FIELD_LABELS[key]
  if (!label) return '请输入 / Enter'
  return `请输入 ${label.zh} / Enter ${label.en}`
}
// 打开弹窗
const open = (type: 'add' | 'edit' = 'add') => {
  getGateways()
  mode.value = type
  showDialog.value = true
}
// 设置表单数据
const setFormData = async (gateway?: string) => {
  isLoading.value = true
  resetForm()
  if (gateway) {
    const data = await configDetail({ gateway })
    Object.keys(formData).forEach((key: string) => {
      if (data[key] != undefined) formData[key] = data[key]
    })
  }
  isLoading.value = false
}
// 获取网关列表
const getGateways = async () => {
  gatewayOptions.value = (await configGateways()) || []
}
// 重置表单
const resetForm = () => {
  formData.gateway = ''
  formData.config_data = {}
  formRef.value?.resetFields()
}
// 提交表单
const handleSubmit = () => {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      isLoading.value = true
      configSave({
        gateway: formData.gateway,
        config_data: formData.config_data
      })
        .then(() => {
          isLoading.value = false
          showDialog.value = false
          ElMessage.success('操作成功')
          emit('success')
        })
        .catch(() => {
          isLoading.value = false
        })
    }
  })
}

defineExpose({
  open,
  setFormData
})
</script>
