<template>
  <section class="space-y-6">
    <header class="flex flex-wrap items-center justify-between gap-4">
      <div>
        <h1 class="mos-title text-2xl font-semibold">API Key 管理</h1>
        <p class="mos-muted mt-2 text-sm">管理API访问密钥，包括创建、启用、禁用、重置和删除操作。</p>
      </div>
      <PermissionButton permission="system.api-key.create.ALL" @click="showCreateModal = true">
        创建 API Key
      </PermissionButton>
    </header>

    <div class="mos-card p-4">
      <div class="overflow-x-auto">
        <table class="w-full">
          <thead>
            <tr class="border-b border-mosquito-line text-left text-sm text-mosquito-ink/70">
              <th class="pb-3 font-medium">名称</th>
              <th class="pb-3 font-medium">Key前缀</th>
              <th class="pb-3 font-medium">绑定IP</th>
              <th class="pb-3 font-medium">权限</th>
              <th class="pb-3 font-medium">状态</th>
              <th class="pb-3 font-medium">创建时间</th>
              <th class="pb-3 font-medium">操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="key in apiKeys" :key="key.id" class="border-b border-mosquito-line/50">
              <td class="py-3 text-sm font-medium text-mosquito-ink">{{ key.name }}</td>
              <td class="py-3 text-sm text-mosquito-ink font-mono">
                <button
                  type="button"
                  class="hover:text-blue-600 underline"
                  @click="handleToggleShowKey(key.id)"
                  :title="showKeyId === key.id ? '点击隐藏' : '点击查看'"
                >
                  {{ showKeyId === key.id ? key.key : '••••••••••••' }}
                </button>
              </td>
              <td class="py-3 text-sm text-mosquito-ink">{{ key.ipWhitelist || '未限制' }}</td>
              <td class="py-3 text-sm text-mosquito-ink">{{ key.permissions }}</td>
              <td class="py-3">
                <span
                  :class="key.status === 1 ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-700'"
                  class="rounded-full px-2 py-1 text-xs font-semibold"
                >
                  {{ key.status === 1 ? '启用' : '禁用' }}
                </span>
              </td>
              <td class="py-3 text-sm text-mosquito-ink">{{ key.createdAt }}</td>
              <td class="py-3">
                <div class="flex gap-2">
                  <PermissionButton
                    v-if="key.status === 1 ? hasPermission('system.api-key.disable.ALL') : hasPermission('system.api-key.enable.ALL')"
                    tag="button"
                    :as-button="false"
                    class="text-sm"
                    :class="key.status === 1 ? 'text-amber-600 hover:underline' : 'text-green-600 hover:underline'"
                    :permission="key.status === 1 ? 'system.api-key.disable.ALL' : 'system.api-key.enable.ALL'"
                    @click="toggleKey(key)"
                  >
                    {{ key.status === 1 ? '禁用' : '启用' }}
                  </PermissionButton>
                  <PermissionButton
                    v-if="hasPermission('system.api-key.reset.ALL')"
                    tag="button"
                    :as-button="false"
                    class="text-sm text-blue-600 hover:underline"
                    permission="system.api-key.reset.ALL"
                    @click="resetKey(key)"
                  >
                    重置
                  </PermissionButton>
                  <PermissionButton
                    v-if="hasPermission('system.api-key.delete.ALL')"
                    tag="button"
                    :as-button="false"
                    class="text-sm text-rose-600 hover:underline"
                    permission="system.api-key.delete.ALL"
                    @click="deleteKey(key)"
                  >
                    删除
                  </PermissionButton>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <div v-if="!apiKeys.length" class="py-8 text-center text-mosquito-ink/60">
        暂无API Key
      </div>
    </div>

    <!-- 创建弹窗 -->
    <div v-if="showCreateModal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
      <div class="mos-card p-6 w-full max-w-md">
        <h3 class="text-lg font-semibold mb-4">创建 API Key</h3>
        <form @submit.prevent="createKey" class="space-y-4">
          <div>
            <label class="block text-sm font-medium text-mosquito-ink mb-1">名称</label>
            <input v-model="newKey.name" class="mos-input w-full" placeholder="请输入名称" required />
          </div>
          <div>
            <label class="block text-sm font-medium text-mosquito-ink mb-1">绑定活动（可选）</label>
            <select v-model="newKey.activityId" class="mos-input w-full">
              <option :value="undefined">不绑定活动</option>
              <option v-for="activity in activities" :key="activity.id" :value="activity.id">
                {{ activity.name }}
              </option>
            </select>
          </div>
          <div class="flex gap-3">
            <button type="submit" class="mos-btn mos-btn-primary flex-1">创建</button>
            <button type="button" class="mos-btn mos-btn-secondary flex-1" @click="showCreateModal = false">取消</button>
          </div>
        </form>
      </div>
    </div>

    <!-- 重置确认弹窗 -->
    <div v-if="showResetModal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
      <div class="mos-card p-6 w-full max-w-md">
        <h3 class="text-lg font-semibold mb-4">重置 API Key</h3>
        <p class="text-sm text-mosquito-ink mb-4">确定要重置 "{{ selectedKey?.name }}" 吗？重置后旧Key将立即失效。</p>
        <div class="flex gap-3">
          <button class="mos-btn mos-btn-primary flex-1" @click="confirmReset">确认重置</button>
          <button class="mos-btn mos-btn-secondary flex-1" @click="showResetModal = false">取消</button>
        </div>
      </div>
    </div>
  </section>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { systemConfigService } from '@/services/systemConfig'
import activityService from '@/services/activity'
import PermissionButton from '@/components/PermissionButton.vue'
import { usePermission } from '@/composables/usePermission'

const { hasPermission } = usePermission()

const showMessage = (msg: string, type: 'success' | 'error' = 'success') => {
  if (type === 'error') {
    alert(msg)
  } else {
    console.log(msg)
  }
}

interface ApiKey {
  id: number
  name: string
  key: string
  ipWhitelist?: string
  permissions: string
  enabled: boolean
  createdAt: string
  status: number
}

const showCreateModal = ref(false)
const showResetModal = ref(false)
const selectedKey = ref<ApiKey | null>(null)
const loading = ref(false)

const newKey = ref({
  name: '',
  activityId: undefined as number | undefined,
  permissions: 'read'
})

// 活动列表（用于API Key绑定）
const activities = ref<{ id: number; name: string }[]>([])

const loadActivities = async () => {
  try {
    const list = await activityService.getActivities({ size: 100 })
    activities.value = list.map((a: any) => ({ id: a.id, name: a.name || `活动 #${a.id}` }))
  } catch (error) {
    console.error('加载活动列表失败:', error)
  }
}

const apiKeys = ref<ApiKey[]>([])
const showKeyId = ref<number | null>(null)

// 加载API密钥列表
const loadApiKeys = async () => {
  try {
    loading.value = true
    const keys = await systemConfigService.getApiKeys()
    apiKeys.value = keys.map((k: any) => ({
      id: k.id,
      name: k.name,
      key: k.prefix || k.apiKeyPrefix || '',
      ipWhitelist: k.ipWhitelist,
      permissions: k.permissions || 'read',
      enabled: k.enabled !== false,
      status: k.enabled !== false ? 1 : 0,
      createdAt: k.createdAt || k.createdTime || new Date().toISOString().split('T')[0]
    }))
  } catch (error: any) {
    console.error('加载API密钥列表失败:', error)
    showMessage(error.message || '加载API密钥列表失败', 'error')
  } finally {
    loading.value = false
  }
}

const toggleKey = async (key: ApiKey) => {
  try {
    loading.value = true
    if (key.status === 1) {
      await systemConfigService.disableApiKey(key.id)
      showMessage('API密钥已禁用')
    } else {
      await systemConfigService.enableApiKey(key.id)
      showMessage('API密钥已启用')
    }
    await loadApiKeys()
  } catch (error: any) {
    showMessage(error.message || '操作失败', 'error')
  } finally {
    loading.value = false
  }
}

const resetKey = (key: ApiKey) => {
  selectedKey.value = key
  showResetModal.value = true
}

const confirmReset = async () => {
  if (selectedKey.value) {
    try {
      loading.value = true
      const newKeyValue = await systemConfigService.resetApiKey(selectedKey.value.id)
      showMessage(`API密钥已重置，新密钥: ${newKeyValue}`, 'success')
      showKeyId.value = null
      await loadApiKeys()
    } catch (error: any) {
      showMessage(error.message || '重置失败', 'error')
    } finally {
      loading.value = false
    }
  }
  showResetModal.value = false
}

const deleteKey = async (key: ApiKey) => {
  if (confirm(`确定删除API Key "${key.name}"吗？`)) {
    try {
      loading.value = true
      await systemConfigService.deleteApiKey(key.id)
      showMessage('API密钥删除成功')
      await loadApiKeys()
    } catch (error: any) {
      showMessage(error.message || '删除API密钥失败', 'error')
    } finally {
      loading.value = false
    }
  }
}

const createKey = async () => {
  // 先加载活动列表
  if (activities.value.length === 0) {
    await loadActivities()
  }

  try {
    loading.value = true
    const result = await systemConfigService.createApiKey(newKey.value.name, newKey.value.activityId)
    // 显示审批结果提示，不展示明文key
    showMessage(`${result.message} (审批记录ID: ${result.recordId})`, 'success')
    await loadApiKeys()
  } catch (error: any) {
    showMessage(error.message || '创建API密钥失败', 'error')
  } finally {
    loading.value = false
    showCreateModal.value = false
    newKey.value = { name: '', activityId: undefined, permissions: 'read' }
  }
}

// 切换显示/隐藏密钥
const handleToggleShowKey = async (id: number) => {
  if (showKeyId.value === id) {
    showKeyId.value = null
    return
  }
  try {
    const key = await systemConfigService.revealApiKey(id)
    const idx = apiKeys.value.findIndex((k: ApiKey) => k.id === id)
    if (idx >= 0) {
      apiKeys.value[idx].key = key
    }
    showKeyId.value = id
  } catch (error: any) {
    showMessage(error.message || '获取密钥失败', 'error')
  }
}

onMounted(() => {
  loadApiKeys()
})
</script>
