<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { NCard, NButton, NForm, NFormItem, NInput, NInputNumber, NSelect, NSkeleton, NAlert, NTag, NSpace, NModal, NIcon } from 'naive-ui'
import { SettingsOutline, CloseOutline, SaveOutline } from '@vicons/ionicons5'
import { api } from '../../api/client'
import { useToast } from '../../composables/useToast'

const toast = useToast()
const loading = ref(true)
const saving = ref(false)
const config = ref<any>({})
const editJwt = ref(15)
const showEdit = ref(false)

// AI config
const aiConfig = ref<any>({})
const aiLoading = ref(true)
const aiSaving = ref(false)
const showAiEdit = ref(false)
const aiForm = ref({
  provider: 'deepseek',
  api_key: '',
  base_url: '',
  model_name: '',
  temperature: 3,
})

const providerOptions = [
  { label: 'DeepSeek', value: 'deepseek' },
  { label: 'OpenAI', value: 'openai' },
  { label: 'Claude (Anthropic)', value: 'claude' },
  { label: 'SiliconFlow', value: 'siliconflow' },
  { label: '自定义', value: 'custom' },
]

onMounted(() => {
  loadConfig()
  loadAiConfig()
})

async function loadConfig() {
  try { const { data } = await api.get('/admin/config'); config.value = data; editJwt.value = data.jwt_expire_min || 15 }
  catch (e) { toast.apiError(e, '加载配置失败') }
  finally { loading.value = false }
}

async function saveConfig() {
  saving.value = true
  try { await api.put('/admin/config', { jwt_expire_min: editJwt.value }); showEdit.value = false; toast.success('配置已更新'); await loadConfig() }
  catch (e) { toast.apiError(e, '保存失败') }
  finally { saving.value = false }
}

async function loadAiConfig() {
  aiLoading.value = true
  try {
    const { data } = await api.get('/admin/ai-config')
    aiConfig.value = data
    if (data.configured) {
      aiForm.value = {
        provider: data.provider || 'deepseek',
        api_key: '',
        base_url: data.base_url || '',
        model_name: data.model_name || '',
        temperature: data.temperature ?? 3,
      }
    }
  } catch (e) { toast.apiError(e, '加载 AI 配置失败') }
  finally { aiLoading.value = false }
}

function openAiEdit() {
  aiForm.value.api_key = ''
  showAiEdit.value = true
}

function formatTemp(t: number | null | undefined): string {
  if (t === null || t === undefined) return '-'
  return (t / 10).toFixed(1)
}

async function saveAiConfig() {
  aiSaving.value = true
  try {
    await api.put('/admin/ai-config', {
      provider: aiForm.value.provider,
      api_key: aiForm.value.api_key || undefined,
      base_url: aiForm.value.base_url || undefined,
      model_name: aiForm.value.model_name || undefined,
      temperature: aiForm.value.temperature,
    })
    showAiEdit.value = false
    toast.success('AI 配置已更新')
    await loadAiConfig()
  } catch (e) { toast.apiError(e, '保存失败') }
  finally { aiSaving.value = false }
}
</script>

<template>
  <div>
    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px">
      <h2 style="margin:0">&#x2699;&#xFE0F; 系统配置</h2>
      <NButton size="small" @click="showEdit = true" class="sky-btn"><template #icon><NIcon size="14"><SettingsOutline /></NIcon></template>编辑配置</NButton>
    </div>
    <NSkeleton v-if="loading" text :repeat="4" />
    <template v-else>
      <NCard title="基本参数" size="small" style="margin-bottom:16px">
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px">
          <div><NTag size="tiny" :bordered="false">专科</NTag><span style="margin-left:8px;font-weight:600">{{ config.specialty || 'oncology' }}</span></div>
          <div><NTag size="tiny" :bordered="false">调试模式</NTag><span style="margin-left:8px">{{ config.debug ? '开启' : '关闭' }}</span></div>
          <div><NTag size="tiny" :bordered="false">JWT 过期</NTag><span style="margin-left:8px">{{ config.jwt_expire_min || 15 }} 分钟</span></div>
        </div>
      </NCard>

      <NCard title="AI 摘要配置" size="small" style="margin-bottom:16px">
        <template #header-extra><NButton size="tiny" class="sky-btn" @click="openAiEdit" :disabled="aiLoading">编辑</NButton>
        </template>
        <NSkeleton v-if="aiLoading" text :repeat="3" />
        <template v-else-if="!aiConfig.configured">
          <NAlert type="info" :bordered="false" style="margin-bottom:0">
            <template #header>未配置</template>
            AI 摘要当前使用环境变量中的 API Key。点击编辑以通过数据库配置。
          </NAlert>
        </template>
        <div v-else style="display:grid;grid-template-columns:1fr 1fr;gap:16px">
          <div><NTag size="tiny" :bordered="false">Provider</NTag><span style="margin-left:8px;font-weight:600">{{ aiConfig.provider }}</span></div>
          <div><NTag size="tiny" :bordered="false">API Key</NTag><span style="margin-left:8px;font-family:monospace">{{ aiConfig.api_key }}</span></div>
          <div><NTag size="tiny" :bordered="false">Base URL</NTag><span style="margin-left:8px;font-size:12px">{{ aiConfig.base_url }}</span></div>
          <div><NTag size="tiny" :bordered="false">Model</NTag><span style="margin-left:8px">{{ aiConfig.model_name }}</span></div>
          <div><NTag size="tiny" :bordered="false">Temperature</NTag><span style="margin-left:8px">{{ formatTemp(aiConfig.temperature) }}</span></div>
          <div><NTag size="tiny" :bordered="false">状态</NTag><span style="margin-left:8px">{{ aiConfig.is_active ? '启用' : '停用' }}</span></div>
        </div>
      </NCard>

      <NAlert type="info" title="配置管理说明" style="margin-bottom:16px">
        <div style="font-size:13px;line-height:1.8">
          &bull; 运行参数通过 <code>config/specialties/oncology.yaml</code> 和环境变量配置<br>
          &bull; JWT 过期时间可在运行时修改，重启后恢复为配置值<br>
          &bull; AI 摘要配置优先使用数据库配置，无数据库配置时回退到环境变量
        </div>
      </NAlert>
    </template>

    <NModal v-model:show="showEdit" title="编辑配置" preset="card" style="width:450px">
      <NForm label-placement="top">
        <NFormItem label="JWT 过期时间（分钟）">
          <NInputNumber v-model:value="editJwt" :min="1" :max="1440" style="width:100%" />
        </NFormItem>
        <NSpace justify="end" style="margin-top:12px">
          <NButton class="sky-btn" @click="showEdit = false"><template #icon><NIcon size="14"><CloseOutline /></NIcon></template>取消</NButton>
          <NButton class="sky-btn" type="primary" :loading="saving" @click="saveConfig"><template #icon><NIcon size="14"><SaveOutline /></NIcon></template>保存</NButton>
        </NSpace>
      </NForm>
    </NModal>

    <NModal v-model:show="showAiEdit" title="编辑 AI 摘要配置" preset="card" style="width:500px">
      <NForm label-placement="top">
        <NFormItem label="Provider">
          <NSelect v-model:value="aiForm.provider" :options="providerOptions" />
        </NFormItem>
        <NFormItem label="API Key">
          <NInput v-model:value="aiForm.api_key" type="password" :placeholder="aiConfig.configured ? '留空不修改' : '必填'" show-password-on="click" />
        </NFormItem>
        <NFormItem label="Base URL">
          <NInput v-model:value="aiForm.base_url" placeholder="https://api.deepseek.com" />
        </NFormItem>
        <NFormItem label="Model">
          <NInput v-model:value="aiForm.model_name" placeholder="deepseek-chat" />
        </NFormItem>
        <NFormItem label="Temperature ({{ formatTemp(aiForm.temperature) }})">
          <NInputNumber v-model:value="aiForm.temperature" :min="0" :max="10" :step="1" style="width:100%" />
        </NFormItem>
        <NSpace justify="end" style="margin-top:12px">
          <NButton class="sky-btn" @click="showAiEdit = false"><template #icon><NIcon size="14"><CloseOutline /></NIcon></template>取消</NButton>
          <NButton class="sky-btn" type="primary" :loading="aiSaving" @click="saveAiConfig"><template #icon><NIcon size="14"><SaveOutline /></NIcon></template>保存</NButton>
        </NSpace>
      </NForm>
    </NModal>
  </div>
</template>
