<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">连接测试</el-button>
          </div>
        </div>
        <el-descriptions :column="2" border size="default" class="config-descriptions">
          <el-descriptions-item label="服务地址">{{ configData.baseUrl || '-' }}</el-descriptions-item>
          <el-descriptions-item label="验签接口路径">{{ configData.verifyPath || '-' }}</el-descriptions-item>
          <el-descriptions-item label="超时时间">{{ configData.timeout }} 秒</el-descriptions-item>
          <el-descriptions-item label="失败重试次数">{{ configData.retryCount }} 次</el-descriptions-item>
          <el-descriptions-item label="鉴权方式">
            <el-tag size="small" :type="authTypeTag(configData.authType)">
              {{ authTypeLabel(configData.authType) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="应用 ID（Token 模式）">
            {{ configData.authType === 'token' ? configData.appId || '-' : '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="API 密钥（Token 模式）">
            {{ configData.authType === 'token' ? maskSecret(configData.apiKey) : '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="客户端证书（Cert 模式）">
            {{ configData.authType === 'cert' ? maskSecret(configData.clientCert, true) : '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="客户端私钥（Cert 模式）">
            {{ configData.authType === 'cert' ? '****' : '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="CA 证书（可选）">
            {{ configData.caCert ? maskSecret(configData.caCert, true) : '-' }}
          </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="140px">
          <el-divider content-position="left">基础连接</el-divider>
          <el-form-item label="服务地址" prop="baseUrl">
            <el-input v-model="editForm.baseUrl" placeholder="https://sign.example.com" />
          </el-form-item>
          <el-form-item label="验签接口路径" prop="verifyPath">
            <el-input v-model="editForm.verifyPath" placeholder="/api/v1/verify" />
          </el-form-item>
          <el-form-item label="超时时间(秒)" prop="timeout">
            <el-input-number
              v-model="editForm.timeout"
              :min="1"
              :max="60"
              controls-position="right"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="失败重试次数" prop="retryCount">
            <el-input-number
              v-model="editForm.retryCount"
              :min="0"
              :max="5"
              controls-position="right"
              style="width: 100%"
            />
          </el-form-item>

          <el-divider content-position="left">鉴权设置</el-divider>
          <el-form-item label="鉴权方式" prop="authType">
            <el-radio-group v-model="editForm.authType">
              <el-radio value="none">无鉴权</el-radio>
              <el-radio value="token">Token / API Key</el-radio>
              <el-radio value="cert">客户端证书</el-radio>
            </el-radio-group>
          </el-form-item>

          <template v-if="editForm.authType === 'token'">
            <el-form-item label="应用ID" prop="appId">
              <el-input v-model="editForm.appId" placeholder="请输入 AppId" />
            </el-form-item>
            <el-form-item label="API密钥" prop="apiKey">
              <el-input
                v-model="editForm.apiKey"
                placeholder="请输入密钥"
                show-password
                type="password"
              />
            </el-form-item>
          </template>

          <template v-if="editForm.authType === 'cert'">
            <el-form-item label="客户端证书" prop="clientCert">
              <el-input
                v-model="editForm.clientCert"
                type="textarea"
                :rows="4"
                placeholder="粘贴 PEM 格式证书"
              />
            </el-form-item>
            <el-form-item label="客户端私钥" prop="clientKey">
              <el-input
                v-model="editForm.clientKey"
                type="textarea"
                :rows="4"
                placeholder="粘贴 PEM 格式私钥（加密存储）"
                show-password
              />
            </el-form-item>
          </template>

          <el-form-item label="CA证书(可选)" prop="caCert">
            <el-input
              v-model="editForm.caCert"
              type="textarea"
              :rows="3"
              placeholder="用于校验服务器证书，可选"
            />
          </el-form-item>

          <el-divider content-position="left">状态</el-divider>
          <el-form-item label="启用">
            <el-switch
              v-model="editForm.enable"
              :active-value="1"
              :inactive-value="2"
              inline-prompt
            />
          </el-form-item>

          <!-- 编辑弹窗内可放置测试按钮（可选） -->
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <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-alert
          v-if="testDialog.result"
          :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>延迟：{{ testDialog.result.latency }}ms</div>
              <div>服务响应正常</div>
            </div>
            <div v-else>{{ testDialog.result.message }}</div>
          </template>
        </el-alert>
        <div v-else style="color: #909399; text-align: center; padding: 20px 0">
          点击下方按钮测试与签名验签服务器的连通性
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="testDialog.visible = false">关闭</el-button>
          <el-button type="primary" :loading="testDialog.loading" @click="executeTest">
            开始测试
          </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: 'SignVerifyConfig' })

// 当前配置数据
const configData = reactive({
  baseUrl: '',
  verifyPath: '/api/v1/verify',
  timeout: 10,
  retryCount: 2,
  authType: 'token',
  appId: '',
  apiKey: '',
  clientCert: '',
  clientKey: '',
  caCert: '',
  enable: 1
})

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

const authTypeLabel = (type) => {
  const map = { none: '无鉴权', token: 'Token / API Key', cert: '客户端证书' }
  return map[type] || type
}

const authTypeTag = (type) => {
  const map = { none: 'info', token: 'primary', cert: 'warning' }
  return map[type] || 'info'
}

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

const editForm = reactive({
  baseUrl: '',
  verifyPath: '/api/v1/verify',
  timeout: 10,
  retryCount: 2,
  authType: 'token',
  appId: '',
  apiKey: '',
  clientCert: '',
  clientKey: '',
  caCert: '',
  enable: 1
})

const editRules = {
  baseUrl: [{ required: true, message: '请输入服务地址', trigger: 'blur' }],
  verifyPath: [{ required: true, message: '请输入验签接口路径', trigger: 'blur' }],
  timeout: [{ required: true, message: '请输入超时时间', trigger: 'blur' }],
  retryCount: [{ required: true, message: '请选择重试次数', trigger: 'blur' }],
  authType: [{ required: true, message: '请选择鉴权方式', trigger: 'change' }],
  appId: [{ required: true, message: '请输入应用ID', trigger: 'blur' }],
  apiKey: [{ required: true, message: '请输入API密钥', trigger: 'blur' }],
  clientCert: [{ required: true, message: '请输入客户端证书', trigger: 'blur' }],
  clientKey: [{ 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,
  loading: false,
  result: null
})

const openTestDialog = () => {
  testDialog.visible = true
  testDialog.result = null
}

const executeTest = async () => {
  testDialog.loading = true
  testDialog.result = null
  try {
    // 要替换为真实测试接口，可使用当前配置
    await new Promise(resolve => setTimeout(resolve, 1000))
    const mockSuccess = true // 可改为随机模拟失败
    testDialog.result = {
      success: mockSuccess,
      latency: mockSuccess ? Math.floor(Math.random() * 200 + 50) : null,
      message: mockSuccess ? '' : '连接失败，请检查服务地址及鉴权信息'
    }
    if (mockSuccess) {
      ElMessage.success('连接测试成功')
    } else {
      ElMessage.error('连接测试失败')
    }
  } finally {
    testDialog.loading = false
  }
}

// 加载模拟配置
onMounted(() => {
  Object.assign(configData, {
    baseUrl: 'https://sign.example.com',
    verifyPath: '/api/v1/verify',
    timeout: 10,
    retryCount: 2,
    authType: 'token',
    appId: 'myapp',
    apiKey: 'sk-xxxxxxxxxxxx',
    clientCert: '',
    clientKey: '',
    caCert: '',
    enable: 1
  })
})
</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;
}
</style>