<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>API Key 管理</span>
          <el-button type="primary" @click="openCreateDialog">新建 API Key</el-button>
        </div>
      </template>

      <el-alert type="error" :closable="false" style="margin-bottom: 16px;">
        <template #title>
          <div>
            <p>
              此 API Key 仅可调用
              <strong>/admin-api</strong>
              专用接口（用户管理与组织管理的常规读写操作），等同于一把永久凭证，请妥善保管。
            </p>
            <p style="margin-top: 6px;">
              <strong>明文 Key 仅在创建时显示一次。</strong>丢失后只能吊销重发；不可物理删除，仅可禁用 / 启用 / 吊销，所有调用与生命周期事件均会写入操作日志。
            </p>
          </div>
        </template>
      </el-alert>

      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-input
          v-model="searchForm.keyword"
          placeholder="按名称或 Key 前缀搜索"
          clearable
          style="width: 320px;"
          @clear="fetchList"
          @keyup.enter="fetchList"
        />
        <el-select
          v-model="searchForm.status"
          placeholder="状态"
          clearable
          style="width: 160px; margin-left: 12px;"
          @change="fetchList"
        >
          <el-option label="启用" value="active" />
          <el-option label="禁用" value="disabled" />
          <el-option label="已吊销" value="revoked" />
        </el-select>
        <el-button type="primary" style="margin-left: 12px;" @click="fetchList">查询</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>

      <el-table
        :data="list"
        v-loading="loading"
        stripe
        border
        style="width: 100%; margin-top: 12px;"
        :row-class-name="rowClassName"
      >
        <el-table-column prop="name" label="名称" min-width="160" />
        <el-table-column label="Key 前缀" width="170">
          <template #default="scope">
            <code class="prefix">{{ scope.row.key_prefix }}…</code>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="110" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.is_revoked" type="danger">已吊销</el-tag>
            <el-tag v-else-if="!scope.row.is_active" type="info">已禁用</el-tag>
            <el-tag v-else type="success">启用中</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="权限范围" min-width="220">
          <template #default="scope">
            <el-tag
              v-for="s in (scope.row.scopes || '').split(',').filter(Boolean)"
              :key="s"
              size="small"
              type="info"
              style="margin-right: 4px; margin-bottom: 2px;"
            >
              {{ s }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建人" width="140">
          <template #default="scope">
            {{ scope.row.creator_mobile || `用户#${scope.row.created_by}` }}
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="170">
          <template #default="scope">{{ formatTime(scope.row.created_at) }}</template>
        </el-table-column>
        <el-table-column label="最近使用" width="180">
          <template #default="scope">
            <div v-if="scope.row.last_used_at">
              <div>{{ formatTime(scope.row.last_used_at) }}</div>
              <div v-if="scope.row.last_used_ip" class="meta-ip">{{ scope.row.last_used_ip }}</div>
            </div>
            <span v-else class="meta-empty">从未使用</span>
          </template>
        </el-table-column>
        <el-table-column prop="use_count" label="使用次数" width="100" align="center" />
        <el-table-column label="操作" width="240" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              link
              :disabled="scope.row.is_revoked"
              @click="openEditDialog(scope.row)"
            >编辑</el-button>
            <el-button
              v-if="scope.row.is_active && !scope.row.is_revoked"
              link
              type="warning"
              @click="handleDisable(scope.row)"
            >禁用</el-button>
            <el-button
              v-else-if="!scope.row.is_active && !scope.row.is_revoked"
              link
              type="success"
              @click="handleEnable(scope.row)"
            >启用</el-button>
            <el-button
              v-else
              link
              disabled
            >已吊销</el-button>
            <el-button
              type="danger"
              link
              :disabled="scope.row.is_revoked"
              @click="openRevokeDialog(scope.row)"
            >吊销</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          background
          layout="total, prev, pager, next, sizes"
          :total="total"
          v-model:current-page="page"
          v-model:page-size="pageSize"
          :page-sizes="[20, 50, 100]"
          @current-change="fetchList"
          @size-change="handleSizeChange"
        />
      </div>
    </el-card>

    <!-- 新建 / 编辑对话框 -->
    <el-dialog
      v-model="formDialogVisible"
      :title="isEdit ? '编辑 API Key' : '新建 API Key'"
      width="540px"
      :close-on-click-modal="false"
    >
      <el-form :model="form" label-width="100px" :rules="formRules" ref="formRef">
        <el-form-item label="名称" prop="name" required>
          <el-input v-model="form.name" maxlength="100" show-word-limit placeholder="例如：ops-script" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="2"
            maxlength="500"
            show-word-limit
            placeholder="备注 Key 的用途（可选）"
          />
        </el-form-item>
        <el-form-item label="权限范围">
          <el-checkbox-group v-model="form.scopeList">
            <el-checkbox value="user:read">user:read</el-checkbox>
            <el-checkbox value="user:write">user:write</el-checkbox>
            <el-checkbox value="org:read">org:read</el-checkbox>
            <el-checkbox value="org:write">org:write</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <template v-if="!isEdit">
          <el-form-item label="管理员密码" prop="admin_password" required>
            <el-input
              v-model="form.admin_password"
              type="password"
              show-password
              placeholder="请输入您的登录密码"
              autocomplete="new-password"
            />
          </el-form-item>
          <el-form-item label="短信验证码" prop="sms_code" required>
            <div style="display: flex; gap: 8px; width: 100%;">
              <el-input v-model="form.sms_code" placeholder="发送至您手机的验证码" />
              <el-button :disabled="cooldown > 0" @click="sendSmsCode" :loading="sendingSms">
                {{ cooldown > 0 ? `${cooldown}s` : '发送验证码' }}
              </el-button>
            </div>
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <el-button @click="formDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">确定</el-button>
      </template>
    </el-dialog>

    <!-- 创建后明文展示对话框（仅一次） -->
    <el-dialog
      v-model="secretDialogVisible"
      title="API Key 创建成功"
      width="640px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <el-alert type="warning" :closable="false" style="margin-bottom: 12px;">
        请立即复制并保存以下明文 Key。<strong>关闭后将无法再次查看，丢失只能吊销重发。</strong>
      </el-alert>
      <div class="secret-box">
        <div class="credential-item">
          <strong>名称：</strong>
          <span>{{ createdKey?.name }}</span>
        </div>
        <div class="credential-item">
          <strong>权限范围：</strong>
          <span>{{ createdKey?.scopes }}</span>
        </div>
        <div class="credential-item">
          <strong>API Key（永久）：</strong>
          <div class="token-text">{{ createdKey?.key_once }}</div>
        </div>
        <div style="margin-top: 12px;">
          <el-checkbox v-model="confirmedSaved">我已复制并妥善保存该 Key</el-checkbox>
        </div>
      </div>
      <template #footer>
        <el-button @click="copyKey">复制 Key</el-button>
        <el-button type="primary" :disabled="!confirmedSaved" @click="closeSecretDialog">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 吊销确认对话框 -->
    <el-dialog
      v-model="revokeDialogVisible"
      title="吊销 API Key"
      width="480px"
      :close-on-click-modal="false"
    >
      <el-alert type="error" :closable="false" style="margin-bottom: 16px;">
        吊销后该 Key 将<strong>永久作废，无法恢复</strong>。请确认操作。
      </el-alert>
      <div style="margin-bottom: 12px;">
        即将吊销：<strong>{{ revokeTarget?.name }}</strong>
        <code class="prefix" style="margin-left: 6px;">{{ revokeTarget?.key_prefix }}…</code>
      </div>
      <el-form :model="revokeForm" label-width="100px">
        <el-form-item label="管理员密码" required>
          <el-input
            v-model="revokeForm.admin_password"
            type="password"
            show-password
            placeholder="请输入您的登录密码"
            autocomplete="new-password"
          />
        </el-form-item>
        <el-form-item label="短信验证码" required>
          <div style="display: flex; gap: 8px; width: 100%;">
            <el-input v-model="revokeForm.sms_code" placeholder="发送至您手机的验证码" />
            <el-button :disabled="cooldown > 0" @click="sendSmsCode" :loading="sendingSms">
              {{ cooldown > 0 ? `${cooldown}s` : '发送验证码' }}
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="revokeDialogVisible = false">取消</el-button>
        <el-button type="danger" :loading="revoking" @click="confirmRevoke">确认吊销</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  AdminApiKey,
  AdminApiKeySecretDisplay,
  listAdminApiKeys,
  createAdminApiKey,
  updateAdminApiKey,
  disableAdminApiKey,
  enableAdminApiKey,
  revokeAdminApiKey,
  sendAdminApiKeySms,
} from '../../../api/adminApiKey'

const list = ref<AdminApiKey[]>([])
const total = ref(0)
const loading = ref(false)
const page = ref(1)
const pageSize = ref(20)

const searchForm = reactive<{ keyword: string; status: '' | 'active' | 'disabled' | 'revoked' }>({
  keyword: '',
  status: '',
})

const formDialogVisible = ref(false)
const isEdit = ref(false)
const editingId = ref<number | null>(null)
const submitting = ref(false)

interface FormState {
  name: string
  description: string
  scopeList: string[]
  admin_password: string
  sms_code: string
}

const form = reactive<FormState>({
  name: '',
  description: '',
  scopeList: ['user:read', 'user:write', 'org:read', 'org:write'],
  admin_password: '',
  sms_code: '',
})

const formRules = {
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  admin_password: [{ required: true, message: '请输入管理员密码', trigger: 'blur' }],
  sms_code: [{ required: true, message: '请输入短信验证码', trigger: 'blur' }],
}

const formRef = ref()

const secretDialogVisible = ref(false)
const createdKey = ref<AdminApiKeySecretDisplay | null>(null)
const confirmedSaved = ref(false)

const revokeDialogVisible = ref(false)
const revokeTarget = ref<AdminApiKey | null>(null)
const revokeForm = reactive({ admin_password: '', sms_code: '' })
const revoking = ref(false)

const cooldown = ref(0)
const sendingSms = ref(false)
let cooldownTimer: ReturnType<typeof setInterval> | null = null

const formatTime = (s?: string | null) => {
  if (!s) return '-'
  const d = new Date(s)
  if (Number.isNaN(d.getTime())) return s
  const pad = (n: number) => `${n}`.padStart(2, '0')
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
}

const rowClassName = ({ row }: { row: AdminApiKey }) => (row.is_revoked ? 'row-revoked' : '')

const fetchList = async () => {
  loading.value = true
  try {
    const params = {
      skip: (page.value - 1) * pageSize.value,
      limit: pageSize.value,
      keyword: searchForm.keyword || undefined,
      status: searchForm.status || undefined,
    }
    const { data } = await listAdminApiKeys(params)
    list.value = data.items
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  page.value = 1
  fetchList()
}

const resetSearch = () => {
  searchForm.keyword = ''
  searchForm.status = ''
  page.value = 1
  fetchList()
}

const resetForm = () => {
  form.name = ''
  form.description = ''
  form.scopeList = ['user:read', 'user:write', 'org:read', 'org:write']
  form.admin_password = ''
  form.sms_code = ''
}

const openCreateDialog = () => {
  isEdit.value = false
  editingId.value = null
  resetForm()
  formDialogVisible.value = true
}

const openEditDialog = (row: AdminApiKey) => {
  isEdit.value = true
  editingId.value = row.id
  form.name = row.name
  form.description = row.description || ''
  form.scopeList = (row.scopes || '').split(',').filter(Boolean)
  form.admin_password = ''
  form.sms_code = ''
  formDialogVisible.value = true
}

const startCooldown = () => {
  cooldown.value = 60
  cooldownTimer = setInterval(() => {
    cooldown.value -= 1
    if (cooldown.value <= 0 && cooldownTimer) {
      clearInterval(cooldownTimer)
      cooldownTimer = null
    }
  }, 1000)
}

const sendSmsCode = async () => {
  if (cooldown.value > 0) return
  sendingSms.value = true
  try {
    await sendAdminApiKeySms()
    ElMessage.success('验证码已发送至您的手机')
    startCooldown()
  } finally {
    sendingSms.value = false
  }
}

const handleSubmit = async () => {
  if (!form.name.trim()) {
    ElMessage.warning('请输入名称')
    return
  }
  if (form.scopeList.length === 0) {
    ElMessage.warning('至少选择一个权限范围')
    return
  }
  submitting.value = true
  try {
    if (isEdit.value && editingId.value !== null) {
      const { data } = await updateAdminApiKey(editingId.value, {
        name: form.name.trim(),
        description: form.description || undefined,
        scopes: form.scopeList.join(','),
      })
      ElMessage.success('已更新')
      formDialogVisible.value = false
      // 局部刷新该行
      const idx = list.value.findIndex((k) => k.id === data.id)
      if (idx >= 0) list.value[idx] = data
      else fetchList()
    } else {
      if (!form.admin_password) {
        ElMessage.warning('请输入管理员密码')
        return
      }
      if (!form.sms_code) {
        ElMessage.warning('请输入短信验证码')
        return
      }
      const { data } = await createAdminApiKey({
        name: form.name.trim(),
        description: form.description || undefined,
        scopes: form.scopeList.join(','),
        admin_password: form.admin_password,
        sms_code: form.sms_code,
      })
      formDialogVisible.value = false
      createdKey.value = data
      confirmedSaved.value = false
      secretDialogVisible.value = true
      fetchList()
    }
  } finally {
    submitting.value = false
  }
}

const handleDisable = async (row: AdminApiKey) => {
  try {
    await ElMessageBox.confirm(
      `确认禁用 API Key「${row.name}」吗？禁用后调用将立即失败，可随时恢复。`,
      '禁用 API Key',
      { confirmButtonText: '禁用', cancelButtonText: '取消', type: 'warning' },
    )
  } catch {
    return
  }
  const { data } = await disableAdminApiKey(row.id)
  const idx = list.value.findIndex((k) => k.id === data.id)
  if (idx >= 0) list.value[idx] = data
  ElMessage.success('已禁用')
}

const handleEnable = async (row: AdminApiKey) => {
  const { data } = await enableAdminApiKey(row.id)
  const idx = list.value.findIndex((k) => k.id === data.id)
  if (idx >= 0) list.value[idx] = data
  ElMessage.success('已启用')
}

const openRevokeDialog = (row: AdminApiKey) => {
  revokeTarget.value = row
  revokeForm.admin_password = ''
  revokeForm.sms_code = ''
  revokeDialogVisible.value = true
}

const confirmRevoke = async () => {
  if (!revokeTarget.value) return
  if (!revokeForm.admin_password || !revokeForm.sms_code) {
    ElMessage.warning('请输入管理员密码与短信验证码')
    return
  }
  revoking.value = true
  try {
    const { data } = await revokeAdminApiKey(revokeTarget.value.id, {
      admin_password: revokeForm.admin_password,
      sms_code: revokeForm.sms_code,
    })
    const idx = list.value.findIndex((k) => k.id === data.id)
    if (idx >= 0) list.value[idx] = data
    ElMessage.success('已吊销')
    revokeDialogVisible.value = false
  } finally {
    revoking.value = false
  }
}

const copyKey = async () => {
  if (!createdKey.value?.key_once) return
  try {
    await navigator.clipboard.writeText(createdKey.value.key_once)
    ElMessage.success('已复制到剪贴板')
  } catch {
    ElMessage.error('复制失败，请手动复制')
  }
}

const closeSecretDialog = () => {
  if (!confirmedSaved.value) {
    ElMessage.warning('请先勾选「我已复制并妥善保存该 Key」')
    return
  }
  secretDialogVisible.value = false
  createdKey.value = null
  confirmedSaved.value = false
}

onMounted(fetchList)
onUnmounted(() => {
  if (cooldownTimer) clearInterval(cooldownTimer)
})
</script>

<style scoped>
.app-container {
  padding: 16px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.search-bar {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
}
.prefix {
  background: #f4f4f5;
  padding: 2px 6px;
  border-radius: 3px;
  font-family: monospace;
  font-size: 12px;
}
.meta-ip {
  font-size: 12px;
  color: #909399;
  font-family: monospace;
}
.meta-empty {
  color: #c0c4cc;
}
.pagination {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}
.secret-box {
  background: #f4f4f5;
  padding: 14px;
  border-radius: 4px;
}
.credential-item {
  margin-top: 8px;
  font-family: monospace;
}
.token-text {
  color: #67c23a;
  font-weight: bold;
  word-break: break-all;
  margin-top: 6px;
  background: #fff;
  padding: 8px;
  border-radius: 4px;
  border: 1px dashed #dcdfe6;
  font-family: monospace;
}
:deep(.row-revoked) {
  opacity: 0.55;
}
</style>
