<template>
  <section class="space-y-6">
    <header class="space-y-2">
      <h1 class="mos-title text-2xl font-semibold">系统配置</h1>
      <p class="mos-muted text-sm">管理系统参数和缓存配置。</p>
    </header>

    <!-- 配置tabs -->
    <div class="flex gap-2 border-b border-mosquito-line pb-2">
      <button
        v-for="tab in tabs"
        :key="tab.key"
        class="px-4 py-2 text-sm font-semibold rounded-t-lg transition"
        :class="activeTab === tab.key
          ? 'bg-mosquito-accent/10 text-mosquito-brand border-b-2 border-mosquito-brand'
          : 'text-mosquito-ink/70 hover:bg-mosquito-bg'"
        @click="activeTab = tab.key"
      >
        {{ tab.label }}
      </button>
    </div>

    <!-- 系统参数 -->
    <div v-if="activeTab === 'params'" class="mos-card p-5">
      <div v-if="loading" class="py-8 text-center text-mosquito-ink/60">
        加载中...
      </div>
      <div v-else class="space-y-4">
        <div v-for="config in systemParams" :key="config.key" class="flex items-center justify-between py-3 border-b border-mosquito-line">
          <div>
            <div class="font-semibold">{{ config.label }}</div>
            <div class="text-xs text-mosquito-ink/70">{{ config.description }}</div>
          </div>
          <div class="w-64">
            <input
              v-if="config.type === 'string'"
              v-model="config.value"
              class="mos-input w-full"
            />
            <input
              v-else-if="config.type === 'number'"
              v-model.number="config.value"
              type="number"
              class="mos-input w-full"
            />
            <select
              v-else-if="config.type === 'boolean'"
              v-model="config.value"
              class="mos-input w-full"
            >
              <option :value="true">启用</option>
              <option :value="false">禁用</option>
            </select>
          </div>
        </div>
      </div>
      <div class="mt-6 flex justify-end gap-2">
        <button class="mos-btn mos-btn-secondary" @click="loadConfigs">刷新</button>
        <PermissionButton permission="system.config.manage.ALL" :hide-when-no-permission="true" @click="saveParams">
          {{ saving ? '保存中...' : '保存配置' }}
        </PermissionButton>
      </div>
    </div>

    <!-- 缓存管理 -->
    <div v-if="activeTab === 'cache'" class="mos-card p-5">
      <div class="space-y-4">
        <div class="flex items-center justify-between py-3 border-b border-mosquito-line">
          <div>
            <div class="font-semibold">活动数据缓存</div>
            <div class="text-xs text-mosquito-ink/70">缓存活动列表和统计数据</div>
          </div>
          <div class="flex gap-2">
            <PermissionButton permission="system.cache.manage.ALL" variant="secondary" :hide-when-no-permission="true" @click="clearCache('activity')">
              清除缓存
            </PermissionButton>
          </div>
        </div>
        <div class="flex items-center justify-between py-3 border-b border-mosquito-line">
          <div>
            <div class="font-semibold">用户数据缓存</div>
            <div class="text-xs text-mosquito-ink/70">缓存用户信息和权限数据</div>
          </div>
          <div class="flex gap-2">
            <PermissionButton permission="system.cache.manage.ALL" variant="secondary" :hide-when-no-permission="true" @click="clearCache('user')">
              清除缓存
            </PermissionButton>
          </div>
        </div>
        <div class="flex items-center justify-between py-3 border-b border-mosquito-line">
          <div>
            <div class="font-semibold">奖励数据缓存</div>
            <div class="text-xs text-mosquito-ink/70">缓存奖励配置和发放记录</div>
          </div>
          <div class="flex gap-2">
            <PermissionButton permission="system.cache.manage.ALL" variant="secondary" :hide-when-no-permission="true" @click="clearCache('reward')">
              清除缓存
            </PermissionButton>
          </div>
        </div>
        <div class="flex items-center justify-between py-3">
          <div>
            <div class="font-semibold">全部缓存</div>
            <div class="text-xs text-mosquito-ink/70">清除所有系统缓存</div>
          </div>
          <div class="flex gap-2">
            <PermissionButton permission="system.cache.manage.ALL" variant="danger" :hide-when-no-permission="true" @click="clearCache('all')">
              清除全部缓存
            </PermissionButton>
          </div>
        </div>
      </div>
    </div>

    <!-- API密钥 -->
    <div v-if="activeTab === 'apiKey'" class="mos-card p-5">
      <div class="flex justify-between items-center mb-4">
        <div class="font-semibold">API密钥管理</div>
        <PermissionButton permission="system.api-key.create.ALL" :hide-when-no-permission="true" @click="createApiKey">
          创建新密钥
        </PermissionButton>
      </div>
      <table class="w-full">
        <thead>
          <tr class="text-left text-xs text-mosquito-ink/70 border-b border-mosquito-line">
            <th class="pb-2">名称</th>
            <th class="pb-2">密钥</th>
            <th class="pb-2">状态</th>
            <th class="pb-2">创建时间</th>
            <th class="pb-2">操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="key in apiKeys" :key="key.id" class="border-b border-mosquito-line">
            <td class="py-3">{{ key.name }}</td>
            <td class="py-3 font-mono text-sm">{{ showKeyId === key.id ? key.key : '••••••••••••••••' }}</td>
            <td class="py-3">
              <span :class="key.status === 1 ? 'text-green-600' : 'text-red-600'">
                {{ key.status === 1 ? '启用' : '禁用' }}
              </span>
            </td>
            <td class="py-3 text-sm">{{ key.createdAt }}</td>
            <td class="py-3">
              <PermissionButton permission="system.api-key.view.ALL" variant="secondary" @click="handleToggleShowKey(key.id)">
                <span class="!py-1 !px-2 !text-xs">{{ showKeyId === key.id ? '隐藏' : '显示' }}</span>
              </PermissionButton>
              <PermissionButton :permission="key.status === 1 ? 'system.api-key.disable.ALL' : 'system.api-key.enable.ALL'" variant="secondary" @click="toggleApiKeyStatus(key.id, key.status)">
                <span class="!py-1 !px-2 !text-xs ml-2">{{ key.status === 1 ? '禁用' : '启用' }}</span>
              </PermissionButton>
              <PermissionButton permission="system.api-key.reset.ALL" variant="secondary" @click="handleResetApiKey(key.id)">
                <span class="!py-1 !px-2 !text-xs ml-2">重置</span>
              </PermissionButton>
              <PermissionButton permission="system.api-key.delete.ALL" variant="danger" @click="deleteApiKey(key.id)">
                <span class="!py-1 !px-2 !text-xs ml-2">删除</span>
              </PermissionButton>
            </td>
          </tr>
        </tbody>
      </table>
      <div v-if="!apiKeys.length" class="py-8 text-center text-mosquito-ink/60">
        暂无API密钥
      </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'

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

const activeTab = ref('params')
const showKeyId = ref<number | null>(null)
const loading = ref(false)
const saving = ref(false)
const apiKeyLoading = ref(false)

// 活动列表（用于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 tabs = [
  { key: 'params', label: '系统参数' },
  { key: 'cache', label: '缓存管理' },
  { key: 'apiKey', label: 'API密钥' }
]

interface ConfigItem {
  key: string
  label: string
  description: string
  value: string | number | boolean
  type: 'string' | 'number' | 'boolean'
}

const systemParams = ref<ConfigItem[]>([
  { key: 'reward.max.points', label: '单次奖励上限', description: '单次奖励发放的最大积分值', value: 10000, type: 'number' },
  { key: 'activity.max.count', label: '最大活动数', description: '系统允许创建的最大活动数量', value: 100, type: 'number' },
  { key: 'risk.callback.threshold', label: '回调失败阈值', description: '触发告警的回调失败率(%)', value: 5, type: 'number' },
  { key: 'approval.auto.timeout', label: '审批超时时间', description: '审批自动通过的超时时间(小时)', value: 24, type: 'number' },
  { key: 'user.invite.expire', label: '邀请链接有效期', description: '邀请链接有效天数', value: 7, type: 'number' },
  { key: 'reward.batch.size', label: '批量发放大小', description: '奖励批量发放的每批数量', value: 200, type: 'number' }
])

const apiKeys = ref<any[]>([])

// 从后端加载配置
const loadConfigs = async () => {
  loading.value = true
  try {
    const result = await systemConfigService.getConfigs()
    if (result && result.length > 0) {
      // 将后端配置合并到本地
      result.forEach((config: any) => {
        const param = systemParams.value.find(p => p.key === config.key)
        if (param) {
          if (param.type === 'number') {
            param.value = Number(config.value) || 0
          } else if (param.type === 'boolean') {
            param.value = config.value === 'true'
          } else {
            param.value = config.value
          }
        }
      })
    }
  } catch (error: any) {
    console.error('加载配置失败:', error)
    showMessage(error.message || '加载配置失败', 'error')
  } finally {
    loading.value = false
  }
}

// 保存配置到后端
const saveParams = async () => {
  saving.value = true
  try {
    for (const param of systemParams.value) {
      await systemConfigService.updateConfig(param.key, String(param.value))
    }
    showMessage('配置保存成功')
    await loadConfigs()
  } catch (error: any) {
    console.error('保存配置失败:', error)
    showMessage(error.message || '保存配置失败', 'error')
  } finally {
    saving.value = false
  }
}

const clearCache = async (type: string) => {
  if (confirm(`确定要清除${type === 'all' ? '全部' : type}缓存吗？`)) {
    try {
      await systemConfigService.clearCache(type === 'all' ? undefined : type)
      showMessage('缓存清除成功')
    } catch (error: any) {
      showMessage(error.message || '清除缓存失败', 'error')
    }
  }
}

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

  const name = prompt('请输入密钥名称:')
  if (!name) return

  // 让用户选择活动
  const activityOptions = activities.value.map((a, i) => `${i + 1}. ${a.name} (ID: ${a.id})`).join('\n')
  const activityIndexStr = prompt(`请选择绑定的活动（输入编号）：\n${activityOptions}`)
  if (!activityIndexStr) return

  const activityIndex = parseInt(activityIndexStr, 10) - 1
  if (isNaN(activityIndex) || activityIndex < 0 || activityIndex >= activities.value.length) {
    showMessage('请选择有效的活动编号', 'error')
    return
  }

  const selectedActivity = activities.value[activityIndex]

  try {
    apiKeyLoading.value = true
    const newKey = await systemConfigService.createApiKey(name, selectedActivity.id)
    showMessage(`API密钥创建成功: ${newKey}`, 'success')
    await loadApiKeys()
  } catch (error: any) {
    showMessage(error.message || '创建API密钥失败', 'error')
  } finally {
    apiKeyLoading.value = false
  }
}

const toggleShowKey = (id: number) => {
  showKeyId.value = showKeyId.value === id ? null : id
}

const deleteApiKey = async (id: number) => {
  if (confirm('确定要删除这个API密钥吗？')) {
    try {
      apiKeyLoading.value = true
      await systemConfigService.deleteApiKey(id)
      showMessage('API密钥删除成功')
      await loadApiKeys()
    } catch (error: any) {
      showMessage(error.message || '删除API密钥失败', 'error')
    } finally {
      apiKeyLoading.value = false
    }
  }
}

// 加载API密钥列表
const loadApiKeys = async () => {
  try {
    apiKeyLoading.value = true
    const keys = await systemConfigService.getApiKeys()
    apiKeys.value = keys.map((k: any) => ({
      id: k.id,
      name: k.name,
      key: k.prefix || k.apiKeyPrefix || '',
      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 {
    apiKeyLoading.value = false
  }
}

// 切换显示/隐藏密钥
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: any) => k.id === id)
    if (idx >= 0) {
      apiKeys.value[idx].key = key
    }
    showKeyId.value = id
  } catch (error: any) {
    showMessage(error.message || '获取密钥失败', 'error')
  }
}

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

// 重置API密钥
const handleResetApiKey = async (id: number) => {
  if (confirm('确定要重置这个API密钥吗？重置后旧密钥将失效。')) {
    try {
      apiKeyLoading.value = true
      const newKey = await systemConfigService.resetApiKey(id)
      showMessage(`API密钥已重置，新密钥: ${newKey}`, 'success')
      showKeyId.value = null
      await loadApiKeys()
    } catch (error: any) {
      showMessage(error.message || '重置失败', 'error')
    } finally {
      apiKeyLoading.value = false
    }
  }
}

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