<script setup lang="ts">
import { Loader2, RefreshCw } from 'lucide-vue-next'
import { onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'
import { toast } from 'vue-sonner'

import { BasicPage } from '@/components/global-layout'

const route = useRoute()

const API_BASE = 'http://localhost:8080/api/v1'

const loading = ref(false)
const saving = ref(false)

interface AppData {
  id: number
  encrypt_type: string
  encrypt_key: string
  bind_type: string
  max_devices: number
  change_limit: number
  change_interval: number
  change_exceed_action: string
  change_deduct_amount: number
  multi_open_mode: string
  max_instances: number
  heartbeat_interval: number
  heartbeat_timeout: number
  max_attempts: number
  lock_duration: number
}

const app = ref<AppData | null>(null)

const form = ref({
  encrypt_type: 'none',
  encrypt_key: '',
  bind_type: 'none',
  max_devices: 1,
  change_limit: 3,
  change_interval: 7,
  change_exceed_action: 'deny',
  change_deduct_amount: 1,
  multi_open_mode: 'forbidden',
  max_instances: 1,
  heartbeat_interval: 60,
  heartbeat_timeout: 300,
  max_attempts: 5,
  lock_duration: 30,
})

async function fetchApp() {
  loading.value = true
  try {
    const token = localStorage.getItem('token')
    const appId = route.params.id
    const response = await fetch(`${API_BASE}/dev/applications/${appId}`, {
      headers: {
        Authorization: `Bearer ${token}`,
      },
    })
    const data = await response.json()
    if (data.code === 200) {
      const appData = data.data.application || data.data
      app.value = appData
      form.value = {
        encrypt_type: appData.encrypt_type || 'none',
        encrypt_key: appData.encrypt_key || '',
        bind_type: appData.bind_type || 'none',
        max_devices: appData.max_devices || 1,
        change_limit: appData.change_limit || 3,
        change_interval: appData.change_interval || 7,
        change_exceed_action: appData.change_exceed_action || 'deny',
        change_deduct_amount: appData.change_deduct_amount || 1,
        multi_open_mode: appData.multi_open_mode || 'forbidden',
        max_instances: appData.max_instances || 1,
        heartbeat_interval: appData.heartbeat_interval || 60,
        heartbeat_timeout: appData.heartbeat_timeout || 300,
        max_attempts: appData.max_attempts || 5,
        lock_duration: appData.lock_duration || 30,
      }
    }
  }
  catch (error) {
    console.error('获取应用详情失败:', error)
    toast.error('获取应用详情失败')
  }
  finally {
    loading.value = false
  }
}

function generateEncryptKey() {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  let result = ''
  for (let i = 0; i < 32; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  form.value.encrypt_key = result
}

async function handleSave() {
  saving.value = true
  try {
    const token = localStorage.getItem('token')
    const response = await fetch(`${API_BASE}/dev/applications/${route.params.id}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`,
      },
      body: JSON.stringify(form.value),
    })
    const data = await response.json()
    if (data.code === 200) {
      toast.success('保存成功')
      fetchApp()
    }
    else {
      toast.error(data.message || '保存失败')
    }
  }
  catch (error) {
    console.error('保存失败:', error)
    toast.error('保存失败')
  }
  finally {
    saving.value = false
  }
}

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

<template>
  <BasicPage
    title="安全设置"
    description="配置应用的安全相关设置，包括加密方式和登录策略"
    :breadcrumbs="[
      { title: '应用管理', href: '/admin/applications' },
      { title: '安全设置' },
    ]"
    sticky
  >
    <div v-if="loading" class="flex items-center justify-center py-12">
      <Loader2 class="size-8 animate-spin text-muted-foreground" />
    </div>

    <div v-else class="space-y-6">
      <UiCard>
        <UiCardHeader>
          <UiCardTitle>加密设置</UiCardTitle>
          <UiCardDescription>配置数据传输加密方式</UiCardDescription>
        </UiCardHeader>
        <UiCardContent class="space-y-4">
          <div class="space-y-2">
            <UiLabel>加密方式</UiLabel>
            <UiRadioGroup v-model="form.encrypt_type" class="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div
                class="flex items-start gap-3 p-4 rounded-lg border cursor-pointer transition-colors"
                :class="form.encrypt_type === 'none' ? 'border-primary bg-primary/5' : 'hover:bg-accent'"
                @click="form.encrypt_type = 'none'"
              >
                <UiRadioGroupItem value="none" class="mt-0.5" />
                <div>
                  <p class="font-medium">
                    不加密
                  </p>
                  <p class="text-sm text-muted-foreground">
                    数据明文传输
                  </p>
                </div>
              </div>

              <div
                class="flex items-start gap-3 p-4 rounded-lg border cursor-pointer transition-colors"
                :class="form.encrypt_type === 'aes' ? 'border-primary bg-primary/5' : 'hover:bg-accent'"
                @click="form.encrypt_type = 'aes'"
              >
                <UiRadioGroupItem value="aes" class="mt-0.5" />
                <div>
                  <p class="font-medium">
                    AES 加密
                  </p>
                  <p class="text-sm text-muted-foreground">
                    对称加密，速度快
                  </p>
                </div>
              </div>

              <div
                class="flex items-start gap-3 p-4 rounded-lg border cursor-pointer transition-colors"
                :class="form.encrypt_type === 'rsa' ? 'border-primary bg-primary/5' : 'hover:bg-accent'"
                @click="form.encrypt_type = 'rsa'"
              >
                <UiRadioGroupItem value="rsa" class="mt-0.5" />
                <div>
                  <p class="font-medium">
                    RSA 加密
                  </p>
                  <p class="text-sm text-muted-foreground">
                    非对称加密，更安全
                  </p>
                </div>
              </div>
            </UiRadioGroup>
          </div>

          <div v-if="form.encrypt_type !== 'none'" class="space-y-2 pt-4 border-t">
            <div class="flex items-center justify-between">
              <UiLabel for="encrypt_key">
                加密密钥
              </UiLabel>
              <UiButton variant="outline" size="sm" @click="generateEncryptKey">
                <RefreshCw class="mr-2 h-4 w-4" />
                自动生成
              </UiButton>
            </div>
            <UiInput id="encrypt_key" v-model="form.encrypt_key" placeholder="请输入加密密钥" />
            <p class="text-xs text-muted-foreground">
              请妥善保管密钥，丢失后无法恢复
            </p>
          </div>
        </UiCardContent>
      </UiCard>

      <UiCard>
        <UiCardHeader>
          <UiCardTitle>绑定策略</UiCardTitle>
          <UiCardDescription>配置应用的绑定策略</UiCardDescription>
        </UiCardHeader>
        <UiCardContent class="space-y-4">
          <div class="space-y-2">
            <UiLabel>绑定模式</UiLabel>
            <UiRadioGroup v-model="form.bind_type" class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div
                class="flex items-start gap-3 p-4 rounded-lg border cursor-pointer transition-colors"
                :class="form.bind_type === 'none' ? 'border-primary bg-primary/5' : 'hover:bg-accent'"
                @click="form.bind_type = 'none'"
              >
                <UiRadioGroupItem value="none" class="mt-0.5" />
                <div>
                  <p class="font-medium">
                    不绑定
                  </p>
                  <p class="text-sm text-muted-foreground">
                    不限制设备或IP
                  </p>
                </div>
              </div>

              <div
                class="flex items-start gap-3 p-4 rounded-lg border cursor-pointer transition-colors"
                :class="form.bind_type === 'device' ? 'border-primary bg-primary/5' : 'hover:bg-accent'"
                @click="form.bind_type = 'device'"
              >
                <UiRadioGroupItem value="device" class="mt-0.5" />
                <div>
                  <p class="font-medium">
                    绑定设备
                  </p>
                  <p class="text-sm text-muted-foreground">
                    绑定用户设备硬件信息
                  </p>
                </div>
              </div>

              <div
                class="flex items-start gap-3 p-4 rounded-lg border cursor-pointer transition-colors"
                :class="form.bind_type === 'ip' ? 'border-primary bg-primary/5' : 'hover:bg-accent'"
                @click="form.bind_type = 'ip'"
              >
                <UiRadioGroupItem value="ip" class="mt-0.5" />
                <div>
                  <p class="font-medium">
                    绑定IP
                  </p>
                  <p class="text-sm text-muted-foreground">
                    绑定用户IP地址
                  </p>
                </div>
              </div>

              <div
                class="flex items-start gap-3 p-4 rounded-lg border cursor-pointer transition-colors"
                :class="form.bind_type === 'mixed' ? 'border-primary bg-primary/5' : 'hover:bg-accent'"
                @click="form.bind_type = 'mixed'"
              >
                <UiRadioGroupItem value="mixed" class="mt-0.5" />
                <div>
                  <p class="font-medium">
                    混合绑定
                  </p>
                  <p class="text-sm text-muted-foreground">
                    同时绑定设备和IP
                  </p>
                </div>
              </div>
            </UiRadioGroup>
          </div>

          <div v-if="form.bind_type !== 'none'" class="space-y-4 pt-4 border-t">
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div class="space-y-2">
                <UiLabel for="max_devices">
                  最大设备数
                </UiLabel>
                <UiInput id="max_devices" v-model.number="form.max_devices" type="number" min="0" />
                <p class="text-xs text-muted-foreground">
                  用户最多可绑定的设备数量
                </p>
              </div>
              <div class="space-y-2">
                <UiLabel for="change_limit">
                  更换次数限制
                </UiLabel>
                <UiInput id="change_limit" v-model.number="form.change_limit" type="number" min="0" />
                <p class="text-xs text-muted-foreground">
                  允许更换绑定的次数
                </p>
              </div>
              <div class="space-y-2">
                <UiLabel for="change_interval">
                  更换间隔（天）
                </UiLabel>
                <UiInput id="change_interval" v-model.number="form.change_interval" type="number" min="0" />
                <p class="text-xs text-muted-foreground">
                  两次更换之间的最小间隔
                </p>
              </div>
            </div>

            <div class="space-y-3 pt-4 border-t">
              <UiLabel>超出更换次数处理</UiLabel>
              <UiRadioGroup v-model="form.change_exceed_action" class="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div
                  class="flex items-start gap-3 p-4 rounded-lg border cursor-pointer transition-colors"
                  :class="form.change_exceed_action === 'deny' ? 'border-primary bg-primary/5' : 'hover:bg-accent'"
                  @click="form.change_exceed_action = 'deny'"
                >
                  <UiRadioGroupItem value="deny" class="mt-0.5" />
                  <div>
                    <p class="font-medium">
                      拒绝更换
                    </p>
                    <p class="text-sm text-muted-foreground">
                      超出次数后禁止更换绑定
                    </p>
                  </div>
                </div>

                <div
                  class="flex items-start gap-3 p-4 rounded-lg border cursor-pointer transition-colors"
                  :class="form.change_exceed_action === 'deduct_time' ? 'border-primary bg-primary/5' : 'hover:bg-accent'"
                  @click="form.change_exceed_action = 'deduct_time'"
                >
                  <UiRadioGroupItem value="deduct_time" class="mt-0.5" />
                  <div>
                    <p class="font-medium">
                      扣除时长
                    </p>
                    <p class="text-sm text-muted-foreground">
                      超出次数后扣除使用时长
                    </p>
                  </div>
                </div>

                <div
                  class="flex items-start gap-3 p-4 rounded-lg border cursor-pointer transition-colors"
                  :class="form.change_exceed_action === 'deduct_points' ? 'border-primary bg-primary/5' : 'hover:bg-accent'"
                  @click="form.change_exceed_action = 'deduct_points'"
                >
                  <UiRadioGroupItem value="deduct_points" class="mt-0.5" />
                  <div>
                    <p class="font-medium">
                      扣除点数
                    </p>
                    <p class="text-sm text-muted-foreground">
                      超出次数后扣除点数
                    </p>
                  </div>
                </div>
              </UiRadioGroup>

              <div v-if="form.change_exceed_action !== 'deny'" class="space-y-2 pt-2">
                <UiLabel for="change_deduct_amount">
                  {{ form.change_exceed_action === 'deduct_time' ? '扣除时长（天）' : '扣除点数' }}
                </UiLabel>
                <UiInput
                  id="change_deduct_amount"
                  v-model.number="form.change_deduct_amount"
                  type="number"
                  min="1"
                  class="max-w-xs"
                />
                <p class="text-xs text-muted-foreground">
                  {{ form.change_exceed_action === 'deduct_time' ? '每次超出更换将扣除的时长' : '每次超出更换将扣除的点数' }}
                </p>
              </div>
            </div>
          </div>
        </UiCardContent>
      </UiCard>

      <UiCard>
        <UiCardHeader>
          <UiCardTitle>多开控制</UiCardTitle>
          <UiCardDescription>配置应用的多开限制</UiCardDescription>
        </UiCardHeader>
        <UiCardContent class="space-y-4">
          <div class="space-y-2">
            <UiLabel>多开模式</UiLabel>
            <UiRadioGroup v-model="form.multi_open_mode" class="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div
                class="flex items-start gap-3 p-4 rounded-lg border cursor-pointer transition-colors"
                :class="form.multi_open_mode === 'forbidden' ? 'border-primary bg-primary/5' : 'hover:bg-accent'"
                @click="form.multi_open_mode = 'forbidden'"
              >
                <UiRadioGroupItem value="forbidden" class="mt-0.5" />
                <div>
                  <p class="font-medium">
                    禁止多开
                  </p>
                  <p class="text-sm text-muted-foreground">
                    只允许运行一个实例
                  </p>
                </div>
              </div>

              <div
                class="flex items-start gap-3 p-4 rounded-lg border cursor-pointer transition-colors"
                :class="form.multi_open_mode === 'limited' ? 'border-primary bg-primary/5' : 'hover:bg-accent'"
                @click="form.multi_open_mode = 'limited'"
              >
                <UiRadioGroupItem value="limited" class="mt-0.5" />
                <div>
                  <p class="font-medium">
                    有限多开
                  </p>
                  <p class="text-sm text-muted-foreground">
                    限制同时运行的实例数
                  </p>
                </div>
              </div>

              <div
                class="flex items-start gap-3 p-4 rounded-lg border cursor-pointer transition-colors"
                :class="form.multi_open_mode === 'unlimited' ? 'border-primary bg-primary/5' : 'hover:bg-accent'"
                @click="form.multi_open_mode = 'unlimited'"
              >
                <UiRadioGroupItem value="unlimited" class="mt-0.5" />
                <div>
                  <p class="font-medium">
                    无限多开
                  </p>
                  <p class="text-sm text-muted-foreground">
                    不限制实例数量
                  </p>
                </div>
              </div>
            </UiRadioGroup>
          </div>

          <div v-if="form.multi_open_mode === 'limited'" class="space-y-2 pt-4 border-t">
            <UiLabel for="max_instances">
              最大实例数
            </UiLabel>
            <UiInput id="max_instances" v-model.number="form.max_instances" type="number" min="1" class="max-w-xs" />
            <p class="text-xs text-muted-foreground">
              同一账号最多可同时运行的实例数量
            </p>
          </div>

          <div v-if="form.multi_open_mode === 'unlimited'" class="p-4 rounded-lg bg-muted mt-4">
            <p class="text-sm text-muted-foreground">
              允许多开模式将不限制应用实例数量，请谨慎使用此选项。
            </p>
          </div>

          <div v-if="form.multi_open_mode === 'forbidden'" class="p-4 rounded-lg bg-muted mt-4">
            <p class="text-sm text-muted-foreground">
              禁止多开模式将只允许应用运行一个实例，尝试启动第二个实例将被阻止。
            </p>
          </div>
        </UiCardContent>
      </UiCard>

      <UiCard>
        <UiCardHeader>
          <UiCardTitle>心跳设置</UiCardTitle>
          <UiCardDescription>配置客户端心跳检测参数</UiCardDescription>
        </UiCardHeader>
        <UiCardContent>
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div class="space-y-2">
              <UiLabel for="heartbeat_interval">
                心跳间隔（秒）
              </UiLabel>
              <UiInput id="heartbeat_interval" v-model.number="form.heartbeat_interval" type="number" min="10" max="300" />
              <p class="text-xs text-muted-foreground">
                客户端发送心跳的间隔时间
              </p>
            </div>
            <div class="space-y-2">
              <UiLabel for="heartbeat_timeout">
                心跳超时（秒）
              </UiLabel>
              <UiInput id="heartbeat_timeout" v-model.number="form.heartbeat_timeout" type="number" min="30" max="600" />
              <p class="text-xs text-muted-foreground">
                超过此时间未收到心跳则判定离线
              </p>
            </div>
          </div>
        </UiCardContent>
      </UiCard>

      <UiCard>
        <UiCardHeader>
          <UiCardTitle>安全防护</UiCardTitle>
          <UiCardDescription>配置登录安全策略</UiCardDescription>
        </UiCardHeader>
        <UiCardContent>
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div class="space-y-2">
              <UiLabel for="max_attempts">
                最大尝试次数
              </UiLabel>
              <UiInput id="max_attempts" v-model.number="form.max_attempts" type="number" min="1" max="10" />
              <p class="text-xs text-muted-foreground">
                连续登录失败超过此次数将锁定
              </p>
            </div>
            <div class="space-y-2">
              <UiLabel for="lock_duration">
                锁定时长（分钟）
              </UiLabel>
              <UiInput id="lock_duration" v-model.number="form.lock_duration" type="number" min="1" max="1440" />
              <p class="text-xs text-muted-foreground">
                账号被锁定后的解锁时间
              </p>
            </div>
          </div>
        </UiCardContent>
      </UiCard>

      <div class="flex justify-end">
        <UiButton :disabled="saving" @click="handleSave">
          <Loader2 v-if="saving" class="mr-2 h-4 w-4 animate-spin" />
          保存设置
        </UiButton>
      </div>
    </div>
  </BasicPage>
</template>
