<template>
  <div>
    <warning-bar title="注：配置短信服务器信息，用于发送手机验证码等短信通知。" />
    <div class="gva-table-box">
      <!-- 当前生效配置卡片 -->
      <div class="config-card">
        <div class="card-header">
          <span class="card-title">当前生效配置</span>
          <div class="card-actions">
            <el-button type="primary" @click="openEditDialog">编辑配置</el-button>
            <el-button type="success" @click="openTestDialog('saved')">测试发送</el-button>
            <el-button @click="refreshClient">刷新客户端</el-button>
          </div>
        </div>
        <el-descriptions :column="2" border size="default" class="config-descriptions">
          <el-descriptions-item label="厂商">腾讯云</el-descriptions-item>
          <el-descriptions-item label="Endpoint">{{ configData.endpoint || '-' }}</el-descriptions-item>
          <el-descriptions-item label="Secret ID">{{ maskSecret(configData.secretId) }}</el-descriptions-item>
          <el-descriptions-item label="Secret Key">{{ maskSecret(configData.secretKey, true) }}</el-descriptions-item>
          <el-descriptions-item label="SDK App ID">{{ configData.sdkAppId || '-' }}</el-descriptions-item>
          <el-descriptions-item label="签名名称">{{ configData.signName || '-' }}</el-descriptions-item>
          <el-descriptions-item label="模板 ID">{{ configData.templateCode || '-' }}</el-descriptions-item>
          <el-descriptions-item label="Region">{{ configData.region || '-' }}</el-descriptions-item>
          <el-descriptions-item label="验证码长度">{{ configData.codeLength || 6 }} 位</el-descriptions-item>
          <el-descriptions-item label="验证码有效期">{{ configData.codeExpire || 5 }} 分钟</el-descriptions-item>
          <el-descriptions-item label="重发间隔">{{ configData.resendInterval || 60 }} 秒</el-descriptions-item>
          <el-descriptions-item label="每日上限">{{ configData.dailyLimit || 10 }} 条/号</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="configData.enable === 1 ? 'success' : 'danger'" effect="dark">
              {{ configData.enable === 1 ? '正常' : '未启用' }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </div>

    <!-- 编辑配置弹窗 -->
    <el-dialog
      v-model="editDialog.visible"
      title="编辑短信配置"
      width="600px"
      :close-on-click-modal="false"
      @closed="resetEditForm"
    >
      <div style="padding: 0 12px; max-height: 60vh; overflow-y: auto">
        <el-form ref="editFormRef" :model="editForm" :rules="editRules" label-width="120px">
          <el-divider content-position="left">腾讯云 API 密钥</el-divider>
          <el-form-item label="Secret ID" prop="secretId">
            <el-input v-model="editForm.secretId" placeholder="请输入 Secret ID" />
          </el-form-item>
          <el-form-item label="Secret Key" prop="secretKey">
            <el-input
              v-model="editForm.secretKey"
              placeholder="请输入 Secret Key"
              show-password
              type="password"
            />
          </el-form-item>
          <el-form-item label="Region" prop="region">
            <el-select v-model="editForm.region" style="width: 200px">
              <el-option label="ap-guangzhou" value="ap-guangzhou" />
              <el-option label="ap-shanghai" value="ap-shanghai" />
              <el-option label="ap-beijing" value="ap-beijing" />
            </el-select>
          </el-form-item>
          <el-form-item label="Endpoint" prop="endpoint">
            <el-input v-model="editForm.endpoint" placeholder="sms.tencentcloudapi.com" />
          </el-form-item>

          <el-divider content-position="left">短信应用配置</el-divider>
          <el-form-item label="SDK App ID" prop="sdkAppId">
            <el-input v-model="editForm.sdkAppId" placeholder="请输入 SDK App ID" />
          </el-form-item>
          <el-form-item label="签名名称" prop="signName">
            <el-input v-model="editForm.signName" placeholder="请输入签名名称" />
          </el-form-item>
          <el-form-item label="模板 ID" prop="templateCode">
            <el-input v-model="editForm.templateCode" placeholder="请输入模板 ID" />
          </el-form-item>

          <el-divider content-position="left">发送策略</el-divider>
          <el-form-item label="验证码长度" prop="codeLength">
            <div style="display: flex; align-items: center">
              <el-input-number
                v-model="editForm.codeLength"
                :min="4"
                :max="8"
                controls-position="right"
                style="width: 120px"
              />
              <span style="margin-left: 8px; color: #909399; white-space: nowrap">位</span>
            </div>
          </el-form-item>
          <el-form-item label="验证码有效期" prop="codeExpire">
            <div style="display: flex; align-items: center">
              <el-input-number
                v-model="editForm.codeExpire"
                :min="1"
                :max="30"
                controls-position="right"
                style="width: 120px"
              />
              <span style="margin-left: 8px; color: #909399; white-space: nowrap">分钟</span>
            </div>
          </el-form-item>
          <el-form-item label="重发间隔" prop="resendInterval">
            <div style="display: flex; align-items: center">
              <el-input-number
                v-model="editForm.resendInterval"
                :min="10"
                :max="300"
                controls-position="right"
                style="width: 120px"
              />
              <span style="margin-left: 8px; color: #909399; white-space: nowrap">秒</span>
            </div>
          </el-form-item>
          <el-form-item label="每日上限" prop="dailyLimit">
            <div style="display: flex; align-items: center">
              <el-input-number
                v-model="editForm.dailyLimit"
                :min="1"
                :max="100"
                controls-position="right"
                style="width: 120px"
              />
              <span style="margin-left: 8px; color: #909399; white-space: nowrap">条/号</span>
            </div>
          </el-form-item>

          <el-form-item label="启用">
            <el-switch v-model="editForm.enable" :active-value="1" :inactive-value="2" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="testFromEdit">测试发送</el-button>
          <el-button @click="editDialog.visible = false">取 消</el-button>
          <el-button type="primary" :loading="saving" @click="saveEditConfig">保 存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 测试发送弹窗 -->
    <el-dialog v-model="testDialog.visible" title="测试短信发送" width="450px" :close-on-click-modal="false">
      <div style="padding: 0 12px">
        <el-form :model="testDialog" label-width="100px">
          <el-form-item label="测试手机号" prop="phone">
            <el-input v-model="testDialog.phone" placeholder="请输入手机号" />
          </el-form-item>
        </el-form>
        <div v-if="testDialog.result" class="test-result">
          <el-alert :type="testDialog.result.success ? 'success' : 'error'" :closable="false" show-icon>
            <template #title>
              {{ testDialog.result.success ? '发送成功' : '发送失败' }}
            </template>
            <template #default>
              <div v-if="testDialog.result.success">
                <div>RequestId: {{ testDialog.result.requestId }}</div>
                <div>耗时: {{ testDialog.result.latency }}ms</div>
              </div>
              <div v-else>{{ testDialog.result.message }}</div>
            </template>
          </el-alert>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="testDialog.visible = false">关闭</el-button>
          <el-button type="primary" :loading="testDialog.loading" @click="executeTestSend">发送测试</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import WarningBar from '@/components/warningBar/warningBar.vue'

defineOptions({ name: 'SmsConfig' })

// 当前配置数据
const configData = reactive({
  enable: 1,
  secretId: '',
  secretKey: '',
  region: 'ap-guangzhou',
  endpoint: 'sms.tencentcloudapi.com',
  sdkAppId: '',
  signName: '',
  templateCode: '',
  codeLength: 6,
  codeExpire: 5,
  resendInterval: 60,
  dailyLimit: 10
})

// 脱敏显示
const maskSecret = (val, full = false) => {
  if (!val) return '-'
  if (full) return '****'
  return val.length > 8 ? val.slice(0, 4) + '****' + val.slice(-4) : '****'
}

// 编辑弹窗
const editDialog = reactive({ visible: false })
const editFormRef = ref(null)
const saving = ref(false)

const editForm = reactive({
  secretId: '',
  secretKey: '',
  region: 'ap-guangzhou',
  endpoint: 'sms.tencentcloudapi.com',
  sdkAppId: '',
  signName: '',
  templateCode: '',
  codeLength: 6,
  codeExpire: 5,
  resendInterval: 60,
  dailyLimit: 10,
  enable: 1
})

const editRules = {
  secretId: [{ required: true, message: '请输入 Secret ID', trigger: 'blur' }],
  secretKey: [{ required: true, message: '请输入 Secret Key', trigger: 'blur' }],
  region: [{ required: true, message: '请选择 Region', trigger: 'change' }],
  endpoint: [{ required: true, message: '请输入 Endpoint', trigger: 'blur' }],
  sdkAppId: [{ required: true, message: '请输入 SDK App ID', trigger: 'blur' }],
  signName: [{ required: true, message: '请输入签名名称', trigger: 'blur' }],
  templateCode: [{ required: true, message: '请输入模板 ID', trigger: 'blur' }],
  codeLength: [{ required: true, message: '请输入验证码长度', trigger: 'blur' }],
  codeExpire: [{ required: true, message: '请输入验证码有效期', trigger: 'blur' }],
  resendInterval: [{ required: true, message: '请输入重发间隔', trigger: 'blur' }],
  dailyLimit: [{ required: true, message: '请输入每日上限', trigger: 'blur' }]
}

const openEditDialog = () => {
  Object.assign(editForm, { ...configData })
  editDialog.visible = true
}

const resetEditForm = () => {
  editFormRef.value?.resetFields()
}

const saveEditConfig = async () => {
  const valid = await editFormRef.value.validate().catch(() => false)
  if (!valid) return
  saving.value = true
  try {
    // 替换为真实接口调用
    await new Promise(resolve => setTimeout(resolve, 600))
    Object.assign(configData, { ...editForm })
    ElMessage.success('短信配置已保存')
    editDialog.visible = false
  } finally {
    saving.value = false
  }
}

// 测试发送逻辑
const testDialog = reactive({
  visible: false,
  phone: '',
  loading: false,
  source: 'saved',
  result: null
})

const openTestDialog = (source = 'saved') => {
  testDialog.visible = true
  testDialog.source = source
  testDialog.phone = ''
  testDialog.result = null
}

const testFromEdit = () => {
  testDialog.visible = true
  testDialog.source = 'edit'
  testDialog.phone = ''
  testDialog.result = null
}

const executeTestSend = async () => {
  if (!/^1[3-9]\d{9}$/.test(testDialog.phone)) {
    ElMessage.error('请输入正确的手机号')
    return
  }
  testDialog.loading = true
  testDialog.result = null
  try {
    const payload = testDialog.source === 'edit' ? { ...editForm } : { ...configData }
    // 替换为真实接口调用
    await new Promise(resolve => setTimeout(resolve, 1200))
    const mockSuccess = Math.random() > 0.2
    testDialog.result = {
      success: mockSuccess,
      requestId: mockSuccess ? 'a1b2c3d4-' + Math.random().toString(36).substring(2, 10) : null,
      latency: mockSuccess ? Math.floor(Math.random() * 500 + 50) : null,
      message: mockSuccess ? '' : '短信服务暂时不可用，请稍后重试'
    }
    if (mockSuccess) {
      ElMessage.success('测试短信发送成功')
    } else {
      ElMessage.error('测试短信发送失败')
    }
  } catch {
    testDialog.result = { success: false, message: '请求异常' }
  } finally {
    testDialog.loading = false
  }
}

// 刷新客户端
const refreshClient = () => {
  // 调用后端刷新客户端接口
  ElMessage.success('客户端配置已刷新')
}

// 加载模拟配置
onMounted(() => {
  Object.assign(configData, {
    enable: 1,
    secretId: 'AKID1234SDhu',
    secretKey: 'sk-xxxxxxxxxxxx',
    region: 'ap-guangzhou',
    endpoint: 'sms.tencentcloudapi.com',
    sdkAppId: '1400537746',
    signName: '御码网控',
    templateCode: '1011710',
    codeLength: 6,
    codeExpire: 5,
    resendInterval: 60,
    dailyLimit: 10
  })
})
</script>

<style lang="scss" scoped>
.config-card {
  margin-bottom: 16px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}
.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}
.card-actions {
  display: flex;
  gap: 10px;
}
.config-descriptions {
  background-color: #fff;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}
.test-result {
  margin-top: 16px;
}
</style>