<script setup lang="ts">
import { Info, Loader2, Upload, X } 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 EmailConfig {
  id: number
  name: string
  status: string
}

interface SmsConfig {
  id: number
  name: string
  status: string
}

interface AppData {
  id: number
  name: string
  description: string
  icon_url: string
  billing_type: string
  login_policy: string
  allow_register: boolean
  enable_login_verify: boolean
  enable_register_verify: boolean
  verify_method: string
  email_config_id: number | null
  sms_config_id: number | null
  enable_trial: boolean
  trial_balance: number
  enable_free_period: boolean
  free_period_type: string
  free_period_start: string
  free_period_end: string
  free_period_weekdays: string
  free_period_start_time: string
  free_period_end_time: string
  status: string
  deduction_cycle: string
  deduction_amount: number
}

const app = ref<AppData | null>(null)
const emailConfigs = ref<EmailConfig[]>([])
const smsConfigs = ref<SmsConfig[]>([])

const form = ref({
  name: '',
  description: '',
  icon_url: '',
  iconFile: null as File | null,
  iconPreview: '',
  billing_type: 'free',
  login_policy: 'loose',
  allow_register: true,
  enable_login_verify: false,
  enable_register_verify: false,
  verify_method: 'email',
  email_config_id: null as number | null,
  sms_config_id: null as number | null,
  enable_password_reset: false,
  password_reset_method: 'email',
  password_reset_email_id: null as number | null,
  password_reset_sms_id: null as number | null,
  enable_trial: false,
  trial_balance: 0,
  trial_days: 0,
  enable_free_period: false,
  free_period_type: 'range',
  free_period_start: '',
  free_period_end: '',
  free_period_weekdays: [] as number[],
  free_period_start_time: '',
  free_period_end_time: '',
  status: 'active',
  deduction_mode: 'auto',
  deduction_type: 'login',
  deduction_interval: 1,
  deduction_unit: 'minute',
  deduction_amount: 1,
})

function parseWeekdays(str: string): number[] {
  if (!str)
    return []
  try {
    const parsed = JSON.parse(str)
    return Array.isArray(parsed) ? parsed : []
  }
  catch {
    return []
  }
}

function weekdaysToString(arr: number[]): string {
  return JSON.stringify(arr)
}

function getIconUrl(url: string): string {
  if (!url)
    return ''
  if (url.startsWith('http'))
    return url
  return `${API_BASE.replace('/api/v1', '')}${url}`
}

function handleIconUpload(event: Event) {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  if (file) {
    form.value.iconFile = file
    form.value.iconPreview = URL.createObjectURL(file)
  }
}

function clearIcon() {
  form.value.iconFile = null
  form.value.iconPreview = ''
  form.value.icon_url = ''
}

async function fetchEmailConfigs() {
  try {
    const token = localStorage.getItem('token')
    const response = await fetch(`${API_BASE}/dev/email-configs`, {
      headers: {
        Authorization: `Bearer ${token}`,
      },
    })
    const data = await response.json()
    if (data.code === 200) {
      emailConfigs.value = data.data?.email_configs?.filter((c: EmailConfig) => c.status === 'active') || []
    }
  }
  catch (error) {
    console.error('获取邮箱配置失败:', error)
  }
}

async function fetchSmsConfigs() {
  try {
    const token = localStorage.getItem('token')
    const response = await fetch(`${API_BASE}/dev/sms-configs`, {
      headers: {
        Authorization: `Bearer ${token}`,
      },
    })
    const data = await response.json()
    if (data.code === 200) {
      smsConfigs.value = data.data?.sms_configs?.filter((c: SmsConfig) => c.status === 'active') || []
    }
  }
  catch (error) {
    console.error('获取短信配置失败:', error)
  }
}

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 = {
        name: appData.name || '',
        description: appData.description || '',
        icon_url: appData.icon_url || '',
        iconFile: null,
        iconPreview: getIconUrl(appData.icon_url),
        billing_type: appData.billing_type || 'free',
        login_policy: appData.login_policy || 'loose',
        allow_register: appData.allow_register ?? true,
        enable_login_verify: appData.enable_login_verify || false,
        enable_register_verify: appData.enable_register_verify || false,
        verify_method: appData.verify_method || 'email',
        email_config_id: appData.email_config_id || null,
        sms_config_id: appData.sms_config_id || null,
        enable_password_reset: appData.enable_password_reset || false,
        password_reset_method: appData.password_reset_method || 'email',
        password_reset_email_id: appData.password_reset_email_id || null,
        password_reset_sms_id: appData.password_reset_sms_id || null,
        enable_trial: appData.enable_trial || false,
        trial_balance: appData.trial_balance || 0,
        trial_days: appData.trial_days || 0,
        enable_free_period: appData.enable_free_period || false,
        free_period_type: appData.free_period_type || 'range',
        free_period_start: appData.free_period_start || '',
        free_period_end: appData.free_period_end || '',
        free_period_weekdays: parseWeekdays(appData.free_period_weekdays),
        free_period_start_time: appData.free_period_start_time || '',
        free_period_end_time: appData.free_period_end_time || '',
        status: appData.status || 'active',
        deduction_mode: appData.deduction_mode || 'auto',
        deduction_type: appData.deduction_type || 'login',
        deduction_interval: appData.deduction_interval || 1,
        deduction_unit: appData.deduction_unit || 'minute',
        deduction_amount: appData.deduction_amount || 1,
      }
    }
  }
  catch (error) {
    console.error('获取应用详情失败:', error)
    toast.error('获取应用详情失败')
  }
  finally {
    loading.value = false
  }
}

async function handleSave() {
  saving.value = true
  try {
    const token = localStorage.getItem('token')
    const formDataToSend = new FormData()
    formDataToSend.append('name', form.value.name)
    formDataToSend.append('description', form.value.description)
    formDataToSend.append('billing_type', form.value.billing_type)
    formDataToSend.append('login_policy', form.value.login_policy)
    formDataToSend.append('allow_register', form.value.allow_register.toString())
    formDataToSend.append('enable_login_verify', form.value.enable_login_verify.toString())
    formDataToSend.append('enable_register_verify', form.value.enable_register_verify.toString())
    formDataToSend.append('verify_method', form.value.verify_method)
    if (form.value.email_config_id) {
      formDataToSend.append('email_config_id', form.value.email_config_id.toString())
    }
    if (form.value.sms_config_id) {
      formDataToSend.append('sms_config_id', form.value.sms_config_id.toString())
    }
    formDataToSend.append('enable_trial', form.value.enable_trial.toString())
    formDataToSend.append('trial_balance', form.value.trial_balance.toString())
    formDataToSend.append('trial_days', form.value.trial_days.toString())
    formDataToSend.append('enable_free_period', form.value.enable_free_period.toString())
    formDataToSend.append('free_period_type', form.value.free_period_type)
    formDataToSend.append('free_period_start', form.value.free_period_start)
    formDataToSend.append('free_period_end', form.value.free_period_end)
    formDataToSend.append('free_period_weekdays', weekdaysToString(form.value.free_period_weekdays))
    formDataToSend.append('free_period_start_time', form.value.free_period_start_time)
    formDataToSend.append('free_period_end_time', form.value.free_period_end_time)
    formDataToSend.append('status', form.value.status)
    formDataToSend.append('deduction_mode', form.value.deduction_mode)
    formDataToSend.append('deduction_type', form.value.deduction_type)
    formDataToSend.append('deduction_interval', form.value.deduction_interval.toString())
    formDataToSend.append('deduction_unit', form.value.deduction_unit)
    formDataToSend.append('deduction_amount', form.value.deduction_amount.toString())

    if (form.value.iconFile) {
      formDataToSend.append('icon', form.value.iconFile)
    }

    const response = await fetch(`${API_BASE}/dev/applications/${route.params.id}`, {
      method: 'PUT',
      headers: {
        Authorization: `Bearer ${token}`,
      },
      body: formDataToSend,
    })
    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()
  fetchEmailConfigs()
  fetchSmsConfigs()
})

function toggleWeekday(index: number) {
  const idx = form.value.free_period_weekdays.indexOf(index)
  if (idx === -1) {
    form.value.free_period_weekdays.push(index)
    form.value.free_period_weekdays.sort()
  }
  else {
    form.value.free_period_weekdays.splice(idx, 1)
  }
}
</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 for="name">
              应用名称
            </UiLabel>
            <UiInput id="name" v-model="form.name" placeholder="请输入应用名称" />
          </div>

          <div class="space-y-2">
            <UiLabel>运营状态</UiLabel>
            <UiRadioGroup v-model="form.status" 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.status === 'active' ? 'border-primary bg-primary/5' : 'hover:bg-accent'"
                @click="form.status = 'active'"
              >
                <UiRadioGroupItem value="active" 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.status === 'maintenance' ? 'border-primary bg-primary/5' : 'hover:bg-accent'"
                @click="form.status = 'maintenance'"
              >
                <UiRadioGroupItem value="maintenance" 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.status === 'stopped' ? 'border-primary bg-primary/5' : 'hover:bg-accent'"
                @click="form.status = 'stopped'"
              >
                <UiRadioGroupItem value="stopped" class="mt-0.5" />
                <div>
                  <p class="font-medium">
                    停止
                  </p>
                  <p class="text-sm text-muted-foreground">
                    应用已停止
                  </p>
                </div>
              </div>
            </UiRadioGroup>
          </div>

          <div class="space-y-2">
            <UiLabel>应用图标</UiLabel>
            <div class="flex items-center gap-4">
              <div v-if="form.iconPreview" class="relative group">
                <img
                  :src="form.iconPreview"
                  alt="应用图标"
                  class="w-16 h-16 rounded-lg object-cover border"
                >
                <UiButton
                  variant="destructive"
                  size="icon"
                  class="absolute -top-1.5 -right-1.5 h-5 w-5 rounded-full opacity-0 group-hover:opacity-100 transition-opacity"
                  @click="clearIcon"
                >
                  <X class="h-3 w-3" />
                </UiButton>
              </div>
              <label
                for="appIcon"
                class="flex items-center justify-center h-16 px-4 border-2 border-dashed rounded-lg cursor-pointer hover:bg-accent/50 transition-colors"
              >
                <Upload class="w-4 h-4 mr-2 text-muted-foreground" />
                <span class="text-sm text-muted-foreground">{{ form.iconPreview ? '更换图标' : '上传图标' }}</span>
                <input
                  id="appIcon"
                  type="file"
                  accept="image/*"
                  class="hidden"
                  @change="handleIconUpload"
                >
              </label>
            </div>
            <p class="text-xs text-muted-foreground">
              支持 JPG、PNG、GIF 格式，建议尺寸 512x512
            </p>
          </div>

          <div class="space-y-2">
            <UiLabel for="description">
              应用描述
            </UiLabel>
            <UiTextarea id="description" v-model="form.description" placeholder="请输入应用描述" rows="3" />
          </div>
        </UiCardContent>
      </UiCard>

      <UiCard>
        <UiCardHeader>
          <UiCardTitle>运营模式</UiCardTitle>
          <UiCardDescription>选择应用的计费方式</UiCardDescription>
        </UiCardHeader>
        <UiCardContent>
          <UiRadioGroup v-model="form.billing_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.billing_type === 'free' ? 'border-primary bg-primary/5' : 'hover:bg-accent'"
              @click="form.billing_type = 'free'"
            >
              <UiRadioGroupItem value="free" 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.billing_type === 'subscription' ? 'border-primary bg-primary/5' : 'hover:bg-accent'"
              @click="form.billing_type = 'subscription'"
            >
              <UiRadioGroupItem value="subscription" 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.billing_type === 'balance' ? 'border-primary bg-primary/5' : 'hover:bg-accent'"
              @click="form.billing_type = 'balance'"
            >
              <UiRadioGroupItem value="balance" 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.billing_type === 'balance'" class="space-y-4 pt-4 border-t mt-4">
            <div class="space-y-2">
              <UiLabel>扣费方式</UiLabel>
              <UiRadioGroup v-model="form.deduction_mode" 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.deduction_mode === 'auto' ? 'border-primary bg-primary/5' : 'hover:bg-accent'"
                  @click="form.deduction_mode = 'auto'"
                >
                  <UiRadioGroupItem value="auto" 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.deduction_mode === 'manual' ? 'border-primary bg-primary/5' : 'hover:bg-accent'"
                  @click="form.deduction_mode = 'manual'"
                >
                  <UiRadioGroupItem value="manual" class="mt-0.5" />
                  <div>
                    <p class="font-medium">
                      手动扣费
                    </p>
                    <p class="text-sm text-muted-foreground">
                      通过 API 自行控制扣费
                    </p>
                  </div>
                </div>
              </UiRadioGroup>
            </div>

            <div v-if="form.deduction_mode === 'auto'" class="space-y-4 pt-4 border-t">
              <div class="space-y-2">
                <UiLabel>自动扣费类型</UiLabel>
                <UiRadioGroup v-model="form.deduction_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.deduction_type === 'login' ? 'border-primary bg-primary/5' : 'hover:bg-accent'"
                    @click="form.deduction_type = 'login'"
                  >
                    <UiRadioGroupItem value="login" 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.deduction_type === 'timer' ? 'border-primary bg-primary/5' : 'hover:bg-accent'"
                    @click="form.deduction_type = 'timer'"
                  >
                    <UiRadioGroupItem value="timer" 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.deduction_type === 'timer'" class="space-y-2">
                <UiLabel>扣费间隔</UiLabel>
                <div class="flex items-center gap-3">
                  <span class="text-sm text-muted-foreground">每</span>
                  <UiNumberField
                    v-model="form.deduction_interval"
                    :min="1"
                    :max="9999"
                    :step="1"
                    class="w-24"
                  >
                    <UiNumberFieldContent>
                      <UiNumberFieldDecrement />
                      <UiNumberFieldInput />
                      <UiNumberFieldIncrement />
                    </UiNumberFieldContent>
                  </UiNumberField>
                  <UiSelect v-model="form.deduction_unit">
                    <UiSelectTrigger class="w-24">
                      <UiSelectValue placeholder="单位" />
                    </UiSelectTrigger>
                    <UiSelectContent>
                      <UiSelectItem value="minute">
                        分钟
                      </UiSelectItem>
                      <UiSelectItem value="hour">
                        小时
                      </UiSelectItem>
                      <UiSelectItem value="day">
                        天
                      </UiSelectItem>
                    </UiSelectContent>
                  </UiSelect>
                  <span class="text-sm text-muted-foreground">扣费一次</span>
                </div>
              </div>

              <div class="space-y-2">
                <UiLabel>每次扣费金额</UiLabel>
                <UiNumberField
                  v-model="form.deduction_amount"
                  :min="0.01"
                  :max="10000"
                  :step="0.01"
                  class="max-w-xs"
                >
                  <UiNumberFieldContent>
                    <UiNumberFieldDecrement />
                    <UiNumberFieldInput />
                    <UiNumberFieldIncrement />
                  </UiNumberFieldContent>
                </UiNumberField>
                <p class="text-xs text-muted-foreground">
                  每次扣费时扣除的余额数量
                </p>
              </div>
            </div>

            <div v-else class="p-4 rounded-lg bg-muted/50 border">
              <div class="flex items-start gap-3">
                <Info class="size-5 text-blue-500 mt-0.5" />
                <div class="space-y-2">
                  <p class="font-medium text-sm">
                    手动扣费说明
                  </p>
                  <p class="text-xs text-muted-foreground">
                    选择手动扣费后，系统不会自动扣除用户余额。您需要通过 API 接口自行控制扣费时机和金额。
                  </p>
                  <div class="mt-2 p-2 rounded bg-background border text-xs font-mono">
                    POST /api/v1/dev/applications/:id/deduct
                  </div>
                </div>
              </div>
            </div>
          </div>
        </UiCardContent>
      </UiCard>

      <UiCard v-if="form.billing_type === 'subscription'">
        <UiCardHeader>
          <UiCardTitle>登录策略</UiCardTitle>
          <UiCardDescription>设置用户登录验证策略</UiCardDescription>
        </UiCardHeader>
        <UiCardContent>
          <UiRadioGroup v-model="form.login_policy" 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.login_policy === 'loose' ? 'border-primary bg-primary/5' : 'hover:bg-accent'"
              @click="form.login_policy = 'loose'"
            >
              <UiRadioGroupItem value="loose" 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.login_policy === 'strict' ? 'border-primary bg-primary/5' : 'hover:bg-accent'"
              @click="form.login_policy = 'strict'"
            >
              <UiRadioGroupItem value="strict" class="mt-0.5" />
              <div>
                <p class="font-medium">
                  严格模式
                </p>
                <p class="text-sm text-muted-foreground">
                  用户到期后无法登录，必须续费
                </p>
              </div>
            </div>
          </UiRadioGroup>
        </UiCardContent>
      </UiCard>

      <UiCard>
        <UiCardHeader>
          <UiCardTitle>注册设置</UiCardTitle>
          <UiCardDescription>配置用户注册权限</UiCardDescription>
        </UiCardHeader>
        <UiCardContent class="space-y-4">
          <div class="flex items-center justify-between">
            <div>
              <p class="font-medium">
                允许注册
              </p>
              <p class="text-sm text-muted-foreground">
                是否允许新用户注册账号
              </p>
            </div>
            <UiSwitch v-model="form.allow_register" />
          </div>
        </UiCardContent>
      </UiCard>

      <UiCard>
        <UiCardHeader>
          <UiCardTitle>验证设置</UiCardTitle>
          <UiCardDescription>配置登录和注册的验证方式</UiCardDescription>
        </UiCardHeader>
        <UiCardContent class="space-y-4">
          <div class="flex items-center justify-between">
            <div>
              <p class="font-medium">
                登录验证
              </p>
              <p class="text-sm text-muted-foreground">
                用户登录时需要进行验证
              </p>
            </div>
            <UiSwitch v-model="form.enable_login_verify" />
          </div>

          <div class="flex items-center justify-between">
            <div>
              <p class="font-medium">
                注册验证
              </p>
              <p class="text-sm text-muted-foreground">
                用户注册时需要进行验证
              </p>
            </div>
            <UiSwitch v-model="form.enable_register_verify" />
          </div>

          <div v-if="form.enable_login_verify || form.enable_register_verify" class="space-y-4 pt-4 border-t">
            <div class="space-y-2">
              <UiLabel>验证方式</UiLabel>
              <UiRadioGroup v-model="form.verify_method" 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.verify_method === 'email' ? 'border-primary bg-primary/5' : 'hover:bg-accent'"
                  @click="form.verify_method = 'email'"
                >
                  <UiRadioGroupItem value="email" 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.verify_method === 'sms' ? 'border-primary bg-primary/5' : 'hover:bg-accent'"
                  @click="form.verify_method = 'sms'"
                >
                  <UiRadioGroupItem value="sms" 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.verify_method === 'email'" class="space-y-2 pt-4 border-t">
              <UiLabel>邮箱配置</UiLabel>
              <UiSelect v-model="form.email_config_id" @update:model-value="(val: number | null) => form.email_config_id = val">
                <UiSelectTrigger>
                  <UiSelectValue placeholder="请选择邮箱配置" />
                </UiSelectTrigger>
                <UiSelectContent>
                  <UiSelectItem v-for="config in emailConfigs" :key="config.id" :value="config.id">
                    {{ config.name }}
                  </UiSelectItem>
                </UiSelectContent>
              </UiSelect>
              <p class="text-xs text-muted-foreground">
                选择用于发送验证码的邮箱配置
              </p>
              <div v-if="emailConfigs.length === 0" class="p-3 rounded-lg bg-yellow-50 dark:bg-yellow-950/20 border border-yellow-200 dark:border-yellow-900">
                <p class="text-sm text-yellow-800 dark:text-yellow-200">
                  暂无可用的邮箱配置，请先在「系统设置 - 邮箱配置」中添加并启用邮箱配置
                </p>
              </div>
            </div>

            <div v-if="form.verify_method === 'sms'" class="space-y-2 pt-4 border-t">
              <UiLabel>短信配置</UiLabel>
              <UiSelect v-model="form.sms_config_id" @update:model-value="(val: number | null) => form.sms_config_id = val">
                <UiSelectTrigger>
                  <UiSelectValue placeholder="请选择短信配置" />
                </UiSelectTrigger>
                <UiSelectContent>
                  <UiSelectItem v-for="config in smsConfigs" :key="config.id" :value="config.id">
                    {{ config.name }}
                  </UiSelectItem>
                </UiSelectContent>
              </UiSelect>
              <p class="text-xs text-muted-foreground">
                选择用于发送验证码的短信配置
              </p>
              <div v-if="smsConfigs.length === 0" class="p-3 rounded-lg bg-yellow-50 dark:bg-yellow-950/20 border border-yellow-200 dark:border-yellow-900">
                <p class="text-sm text-yellow-800 dark:text-yellow-200">
                  暂无可用的短信配置，请先在「系统设置 - 短信配置」中添加并启用短信配置
                </p>
              </div>
            </div>
          </div>

          <div class="pt-4 border-t">
            <div class="flex items-center justify-between">
              <div>
                <p class="font-medium">
                  密码重置
                </p>
                <p class="text-sm text-muted-foreground">
                  用户忘记密码时通过邮箱或短信重置
                </p>
              </div>
              <UiSwitch v-model="form.enable_password_reset" />
            </div>

            <div v-if="form.enable_password_reset" class="space-y-4 pt-4">
              <div class="space-y-2">
                <UiLabel>验证方式</UiLabel>
                <UiRadioGroup v-model="form.password_reset_method" 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.password_reset_method === 'email' ? 'border-primary bg-primary/5' : 'hover:bg-accent'"
                    @click="form.password_reset_method = 'email'"
                  >
                    <UiRadioGroupItem value="email" 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.password_reset_method === 'sms' ? 'border-primary bg-primary/5' : 'hover:bg-accent'"
                    @click="form.password_reset_method = 'sms'"
                  >
                    <UiRadioGroupItem value="sms" 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.password_reset_method === 'email'" class="space-y-2 pt-4 border-t">
                <UiLabel>邮箱配置</UiLabel>
                <UiSelect v-model="form.password_reset_email_id" @update:model-value="(val: number | null) => form.password_reset_email_id = val">
                  <UiSelectTrigger>
                    <UiSelectValue placeholder="请选择邮箱配置" />
                  </UiSelectTrigger>
                  <UiSelectContent>
                    <UiSelectItem v-for="config in emailConfigs" :key="config.id" :value="config.id">
                      {{ config.name }}
                    </UiSelectItem>
                  </UiSelectContent>
                </UiSelect>
                <p class="text-xs text-muted-foreground">
                  选择用于发送密码重置邮件的邮箱配置
                </p>
                <div v-if="emailConfigs.length === 0" class="p-3 rounded-lg bg-yellow-50 dark:bg-yellow-950/20 border border-yellow-200 dark:border-yellow-900">
                  <p class="text-sm text-yellow-800 dark:text-yellow-200">
                    暂无可用的邮箱配置，请先在「系统设置 - 邮箱配置」中添加并启用邮箱配置
                  </p>
                </div>
              </div>

              <div v-if="form.password_reset_method === 'sms'" class="space-y-2 pt-4 border-t">
                <UiLabel>短信配置</UiLabel>
                <UiSelect v-model="form.password_reset_sms_id" @update:model-value="(val: number | null) => form.password_reset_sms_id = val">
                  <UiSelectTrigger>
                    <UiSelectValue placeholder="请选择短信配置" />
                  </UiSelectTrigger>
                  <UiSelectContent>
                    <UiSelectItem v-for="config in smsConfigs" :key="config.id" :value="config.id">
                      {{ config.name }}
                    </UiSelectItem>
                  </UiSelectContent>
                </UiSelect>
                <p class="text-xs text-muted-foreground">
                  选择用于发送密码重置短信的短信配置
                </p>
                <div v-if="smsConfigs.length === 0" class="p-3 rounded-lg bg-yellow-50 dark:bg-yellow-950/20 border border-yellow-200 dark:border-yellow-900">
                  <p class="text-sm text-yellow-800 dark:text-yellow-200">
                    暂无可用的短信配置，请先在「系统设置 - 短信配置」中添加并启用短信配置
                  </p>
                </div>
              </div>
            </div>
          </div>
        </UiCardContent>
      </UiCard>

      <UiCard v-if="form.billing_type !== 'free'">
        <UiCardHeader>
          <UiCardTitle>试用功能</UiCardTitle>
          <UiCardDescription>为新用户提供试用体验</UiCardDescription>
        </UiCardHeader>
        <UiCardContent class="space-y-4">
          <div class="flex items-center justify-between">
            <div>
              <p class="font-medium">
                启用试用
              </p>
              <p class="text-sm text-muted-foreground">
                新用户注册后自动获得试用资格
              </p>
            </div>
            <UiSwitch v-model="form.enable_trial" />
          </div>

          <div v-if="form.enable_trial" class="space-y-2 pt-4 border-t">
            <template v-if="form.billing_type === 'balance'">
              <UiLabel>试用余额</UiLabel>
              <UiNumberField
                v-model="form.trial_balance"
                :min="0"
                :step="0.01"
                class="max-w-xs"
              >
                <UiNumberFieldContent>
                  <UiNumberFieldDecrement />
                  <UiNumberFieldInput />
                  <UiNumberFieldIncrement />
                </UiNumberFieldContent>
              </UiNumberField>
              <p class="text-xs text-muted-foreground">
                新用户注册后自动获得的余额数量
              </p>
            </template>

            <template v-else-if="form.billing_type === 'subscription'">
              <UiLabel>试用天数</UiLabel>
              <UiNumberField
                v-model="form.trial_days"
                :min="1"
                :max="365"
                :step="1"
                class="max-w-xs"
              >
                <UiNumberFieldContent>
                  <UiNumberFieldDecrement />
                  <UiNumberFieldInput />
                  <UiNumberFieldIncrement />
                </UiNumberFieldContent>
              </UiNumberField>
              <p class="text-xs text-muted-foreground">
                新用户注册后自动获得的试用天数
              </p>
            </template>
          </div>
        </UiCardContent>
      </UiCard>

      <UiCard>
        <UiCardHeader>
          <UiCardTitle>免费时段</UiCardTitle>
          <UiCardDescription>在指定时间段内所有用户免费使用</UiCardDescription>
        </UiCardHeader>
        <UiCardContent class="space-y-4">
          <div class="flex items-center justify-between">
            <div>
              <p class="font-medium">
                启用免费时段
              </p>
              <p class="text-sm text-muted-foreground">
                在设定的时间段内，所有用户可免费使用
              </p>
            </div>
            <UiSwitch v-model="form.enable_free_period" />
          </div>

          <div v-if="form.enable_free_period" class="space-y-4 pt-4 border-t">
            <div class="space-y-2">
              <UiLabel>免费时段类型</UiLabel>
              <UiRadioGroup v-model="form.free_period_type" class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div
                  class="flex items-start gap-3 p-3 rounded-lg border cursor-pointer transition-colors"
                  :class="form.free_period_type === 'range' ? 'border-primary bg-primary/5' : 'hover:bg-accent'"
                  @click="form.free_period_type = 'range'"
                >
                  <UiRadioGroupItem value="range" class="mt-0.5" />
                  <div>
                    <p class="font-medium text-sm">
                      日期范围
                    </p>
                    <p class="text-xs text-muted-foreground">
                      指定开始和结束日期
                    </p>
                  </div>
                </div>

                <div
                  class="flex items-start gap-3 p-3 rounded-lg border cursor-pointer transition-colors"
                  :class="form.free_period_type === 'weekly' ? 'border-primary bg-primary/5' : 'hover:bg-accent'"
                  @click="form.free_period_type = 'weekly'"
                >
                  <UiRadioGroupItem value="weekly" class="mt-0.5" />
                  <div>
                    <p class="font-medium text-sm">
                      每周重复
                    </p>
                    <p class="text-xs text-muted-foreground">
                      每周指定日期和时间
                    </p>
                  </div>
                </div>
              </UiRadioGroup>
            </div>

            <div v-if="form.free_period_type === 'range'" class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div class="space-y-2">
                <UiLabel>开始时间</UiLabel>
                <UiInput v-model="form.free_period_start" type="datetime-local" />
              </div>
              <div class="space-y-2">
                <UiLabel>结束时间</UiLabel>
                <UiInput v-model="form.free_period_end" type="datetime-local" />
              </div>
            </div>

            <div v-if="form.free_period_type === 'weekly'" class="space-y-4">
              <div class="space-y-2">
                <UiLabel>选择日期</UiLabel>
                <div class="flex flex-wrap gap-2">
                  <UiButton
                    v-for="(day, index) in ['日', '一', '二', '三', '四', '五', '六']"
                    :key="index"
                    :variant="form.free_period_weekdays.includes(index) ? 'default' : 'outline'"
                    size="sm"
                    @click="toggleWeekday(index)"
                  >
                    周{{ day }}
                  </UiButton>
                </div>
              </div>

              <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div class="space-y-2">
                  <UiLabel>开始时间</UiLabel>
                  <UiInput v-model="form.free_period_start_time" type="time" />
                </div>
                <div class="space-y-2">
                  <UiLabel>结束时间</UiLabel>
                  <UiInput v-model="form.free_period_end_time" type="time" />
                </div>
              </div>
            </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>
