<template>
  <ConfigPageBase
    section="system"
    title="系统级配置"
    description="运行参数、日志策略、安全策略（对齐 SystemConfig）"
    :defaults="DEFAULT_SYSTEM">
    <template #default="{ payload, update }">
      <el-form label-width="160px" :model="payload">
        <el-form-item label="调度循环 (Hz)">
          <el-input-number :model-value="payload.dispatchLoopHz" :min="1" :max="200" @update:model-value="(v: number | undefined) => update({ ...payload, dispatchLoopHz: v ?? 0 })" />
        </el-form-item>
        <el-divider content-position="left">日志策略</el-divider>
        <el-form-item label="日志级别">
          <el-select :model-value="payload.log.level" @update:model-value="(v: any) => update({ ...payload, log: { ...payload.log, level: v } })">
            <el-option v-for="lv in ['trace','debug','info','warn','error']" :key="lv" :label="lv" :value="lv" />
          </el-select>
        </el-form-item>
        <el-form-item label="日志保留 (天)">
          <el-input-number :model-value="payload.log.rollDays" :min="1" :max="365" @update:model-value="(v: number | undefined) => update({ ...payload, log: { ...payload.log, rollDays: v ?? 0 } })" />
        </el-form-item>
        <el-form-item label="单文件上限 (MB)">
          <el-input-number :model-value="payload.log.maxSizeMB" :min="1" :max="4096" @update:model-value="(v: number | undefined) => update({ ...payload, log: { ...payload.log, maxSizeMB: v ?? 0 } })" />
        </el-form-item>
        <el-divider content-position="left">安全策略</el-divider>
        <el-form-item label="JWT 过期 (分钟)">
          <el-input-number :model-value="payload.security.jwtExpireMin" :min="5" :max="43200" @update:model-value="(v: number | undefined) => update({ ...payload, security: { ...payload.security, jwtExpireMin: v ?? 0 } })" />
        </el-form-item>
        <el-form-item label="启用 Swagger">
          <el-switch :model-value="payload.security.enableSwagger" @update:model-value="(v: string | number | boolean) => update({ ...payload, security: { ...payload.security, enableSwagger: Boolean(v) } })" />
        </el-form-item>
        <el-form-item label="CORS 白名单">
          <el-input
            type="textarea"
            :rows="3"
            :model-value="payload.security.corsWhitelist.join('\n')"
            @update:model-value="(v: string) => update({ ...payload, security: { ...payload.security, corsWhitelist: v.split(/\s+/).filter(Boolean) } })" />
        </el-form-item>
        <el-divider content-position="left">界面主题配色</el-divider>
        <el-form-item label="主题取色盘">
          <ThemeCustomizer />
        </el-form-item>
      </el-form>
    </template>
  </ConfigPageBase>

  <el-card class="ai-service-card" shadow="never">
    <template #header>
      <span>AI 服务（地图编辑器「AI 生图」依赖）</span>
      <el-tag v-if="aiCfg.configured" type="success" size="small" effect="dark" class="ml-8">已配置</el-tag>
      <el-tag v-else type="warning" size="small" effect="dark" class="ml-8">未配置</el-tag>
    </template>
    <el-form label-width="140px" size="default">
      <el-form-item label="Endpoint">
        <el-input v-model="aiCfg.endpoint" placeholder="https://api.openai.com/v1/chat/completions" />
      </el-form-item>
      <el-form-item label="API Key">
        <el-input v-model="aiCfg.apiKey" type="password" show-password placeholder="sk-..." />
      </el-form-item>
      <el-form-item label="模型">
        <el-input v-model="aiCfg.model" placeholder="gpt-4o-mini" />
      </el-form-item>
      <el-form-item label="System Prompt">
        <el-input v-model="aiCfg.systemPrompt" type="textarea" :rows="4" />
      </el-form-item>
      <el-form-item label="Temperature">
        <el-input-number v-model="aiCfg.temperature" :min="0" :max="2" :step="0.1" />
      </el-form-item>
      <el-form-item label="Max Tokens">
        <el-input-number v-model="aiCfg.maxTokens" :min="64" :max="32000" :step="64" />
      </el-form-item>
      <el-form-item label="超时 (秒)">
        <el-input-number v-model="aiCfg.timeoutSec" :min="5" :max="600" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :loading="aiSaving" @click="onSaveAi">保存 AI 配置</el-button>
        <el-button :loading="aiTesting" @click="onTestAi">测试连通</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script setup lang="ts">
import ConfigPageBase from '@/components/ConfigPageBase.vue'
import ThemeCustomizer from '@/components/ThemeCustomizer.vue'
import { DEFAULT_SYSTEM } from '@/mock/data/configs'
import { onMounted, reactive, ref } from 'vue'
import { aiConfigApi, mapEditApi, type AiConfig } from '@/api/mapEdit'
import { ElMessage } from 'element-plus'

const aiCfg = reactive<AiConfig>({
  endpoint: 'https://api.openai.com/v1/chat/completions',
  apiKey: '',
  model: 'gpt-4o-mini',
  systemPrompt: '你是一个 AGV 路网设计师。',
  temperature: 0.4,
  maxTokens: 4096,
  timeoutSec: 60,
  configured: false
})

const aiSaving = ref(false)
const aiTesting = ref(false)

onMounted(async () => {
  try {
    const r = await aiConfigApi.get()
    Object.assign(aiCfg, r)
  } catch (err) {
    ElMessage.warning(`无法读取 AI 配置：${(err as Error).message}`)
  }
})

async function onSaveAi() {
  try {
    aiSaving.value = true
    await aiConfigApi.save({ ...aiCfg })
    ElMessage.success('AI 配置已保存')
    aiCfg.configured = !!aiCfg.apiKey
  } catch (err) {
    ElMessage.error(`保存失败：${(err as Error).message}`)
  } finally {
    aiSaving.value = false
  }
}

async function onTestAi() {
  try {
    aiTesting.value = true
    const r = await mapEditApi.aiMapGenerate({
      prompt: '测试连通：仅返回 "ok"，不要生成任何站点或路径。',
      mode: 'sites',
      bounds: [0, 0, 0, 0]
    })
    ElMessage.success(`AI 服务连通正常：返回工具调用 ${r.usedTools} 次`)
  } catch (err) {
    ElMessage.error(`连通失败：${(err as Error).message}`)
  } finally {
    aiTesting.value = false
  }
}
</script>

<style scoped>
.ai-service-card { margin: 12px 0; }
.ml-8 { margin-left: 8px; }
</style>
