<template>
  <div>
    <warning-bar title="注：配置动态口令认证系统接口，用于验证用户的动态令牌（OTP）码。" />
    <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.authPath || '-' }}</el-descriptions-item>
          <el-descriptions-item label="绑定接口路径">{{ configData.syncPath || '-' }}</el-descriptions-item>
          <el-descriptions-item label="应用标识">{{ configData.appId || '-' }}</el-descriptions-item>
          <el-descriptions-item label="共享密钥">{{ maskSecret(configData.sharedSecret) }}</el-descriptions-item>
          <el-descriptions-item label="超时时间">{{ configData.timeout }} 秒</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="160px">
          <el-form-item label="服务地址" prop="baseUrl">
            <el-input v-model="editForm.baseUrl" placeholder="https://otp.example.com" />
          </el-form-item>
          <el-form-item label="认证接口路径" prop="authPath">
            <el-input v-model="editForm.authPath" placeholder="/api/validate" />
          </el-form-item>
          <el-form-item label="绑定接口路径(可选)" prop="syncPath">
            <el-input v-model="editForm.syncPath" placeholder="/api/bind" />
          </el-form-item>
          <el-form-item label="应用标识" prop="appId">
            <el-input v-model="editForm.appId" placeholder="iam" />
          </el-form-item>
          <el-form-item label="共享密钥" prop="sharedSecret">
            <el-input
              v-model="editForm.sharedSecret"
              placeholder="用于签名请求"
              show-password
              type="password"
            />
          </el-form-item>
          <el-form-item label="超时时间(秒)" prop="timeout">
            <el-input-number
              v-model="editForm.timeout"
              :min="1"
              :max="30"
              controls-position="right"
              style="width: 100%"
            />
          </el-form-item>
          <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="OTP 验证测试" width="450px" :close-on-click-modal="false">
      <div style="padding: 0 12px">
        <el-form :model="testDialog" label-width="100px">
          <el-form-item label="令牌标识">
            <el-input v-model="testDialog.tokenId" placeholder="输入用户的令牌序列号或标识" />
          </el-form-item>
          <el-form-item label="动态口令">
            <el-input v-model="testDialog.code" placeholder="6位动态口令" maxlength="6" />
          </el-form-item>
        </el-form>
        <div v-if="testDialog.resultVisible" class="test-result">
          <el-alert
            :type="testDialog.result ? 'success' : 'error'"
            :closable="false"
            show-icon
          >
            <template #title>
              {{ testDialog.result ? '验证成功，动态口令正确' : '验证失败，请检查令牌或口令' }}
            </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="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: 'OtpConfig' })

// 当前配置数据
const configData = reactive({
  baseUrl: '',
  authPath: '/api/validate',
  syncPath: '',
  appId: '',
  sharedSecret: '',
  timeout: 5,
  enable: 1
})

const maskSecret = (val) => {
  if (!val) 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({
  baseUrl: '',
  authPath: '/api/validate',
  syncPath: '',
  appId: '',
  sharedSecret: '',
  timeout: 5,
  enable: 1
})

const editRules = {
  baseUrl: [{ required: true, message: '请输入服务地址', trigger: 'blur' }],
  authPath: [{ required: true, message: '请输入认证接口路径', trigger: 'blur' }],
  appId: [{ required: true, message: '请输入应用标识', trigger: 'blur' }],
  sharedSecret: [{ required: true, message: '请输入共享密钥', trigger: 'blur' }],
  timeout: [{ 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,
  tokenId: '',
  code: '',
  loading: false,
  resultVisible: false,
  result: false
})

const openTestDialog = () => {
  testDialog.visible = true
  testDialog.tokenId = ''
  testDialog.code = ''
  testDialog.resultVisible = false
  testDialog.result = false
}

const executeTest = async () => {
  if (!testDialog.tokenId || !testDialog.code) {
    ElMessage.warning('请输入令牌标识和动态口令')
    return
  }
  testDialog.loading = true
  testDialog.resultVisible = false
  try {
    await new Promise(resolve => setTimeout(resolve, 800))
    // 模拟随机结果
    const success = Math.random() > 0.5
    testDialog.resultVisible = true
    testDialog.result = success
    if (success) {
      ElMessage.success('验证成功')
    } else {
      ElMessage.error('验证失败')
    }
  } finally {
    testDialog.loading = false
  }
}

// 加载模拟配置
onMounted(() => {
  Object.assign(configData, {
    baseUrl: 'https://otp.example.com',
    authPath: '/api/validate',
    syncPath: '/api/bind',
    appId: 'iam',
    sharedSecret: 'shared-secret-123',
    timeout: 5,
    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;
}
.test-result {
  margin-top: 16px;
}
</style>