<template>
  <div class="panel">
    <div class="toolbar">
      <div class="filters">
        <el-button type="primary" :loading="saving" @click="save">保存设置</el-button>
        <el-button @click="load">刷新</el-button>
      </div>
    </div>

    <el-form label-width="190px" class="settings-form">
      <div class="section-title">AI 默认参数</div>
      <el-form-item label="默认 AI 服务商">
        <el-select v-model="form.default_ai_provider_id" clearable placeholder="请选择" style="width: 360px" @change="selectDefaultModel">
          <el-option v-for="provider in enabledProviders" :key="provider.id" :label="provider.name" :value="provider.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="默认 AI 模型">
        <el-select v-model="form.default_ai_model_id" clearable placeholder="请选择" style="width: 360px">
          <el-option v-for="model in providerModels" :key="model.id" :label="model.display_name || model.name" :value="model.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="默认温度">
        <el-input-number v-model="form.default_ai_temperature" :min="0" :max="2" :step="0.1" />
      </el-form-item>

      <div class="section-title">文件保存路径</div>
      <el-alert type="info" show-icon :closable="false" title="路径保存为相对路径，并解析到后端 backend/data 目录下。" />
      <el-form-item label="自动化文件根路径">
        <el-input v-model="form.automation_file_root" placeholder="automation" />
      </el-form-item>
      <el-form-item label="已识别界面截图路径">
        <el-input v-model="form.automation_screen_path" placeholder="automation/screens" />
      </el-form-item>
      <el-form-item label="错误截图路径">
        <el-input v-model="form.automation_error_path" placeholder="automation/errors" />
      </el-form-item>
      <el-form-item label="临时截图路径">
        <el-input v-model="form.automation_runtime_path" placeholder="automation/runtime" />
      </el-form-item>

      <div class="section-title">自动化操作页</div>
      <el-form-item label="默认自动截屏">
        <el-switch v-model="form.automation_auto_screenshot_enabled" active-text="开启" inactive-text="关闭" />
      </el-form-item>
      <el-form-item label="自动截屏间隔秒数">
        <el-input-number v-model="form.automation_auto_screenshot_interval" :min="1" :max="3600" />
      </el-form-item>

      <div class="section-title">远程执行</div>
      <el-alert type="warning" show-icon :closable="false" title="远程执行和任务查询会校验此 Token。支持 X-Automation-Token、Bearer Token 或 automation_token 查询参数；请只在可信局域网或 VPN 内开放后端端口。" />
      <el-form-item label="远程执行 Token">
        <el-input v-model="form.automation_remote_token" show-password placeholder="用于 iOS 快捷指令和前端自动化请求" />
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { computed, onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { api, setAutomationToken } from '../api'

const providers = ref([])
const models = ref([])
const saving = ref(false)
const form = reactive({
  default_ai_provider_id: null,
  default_ai_model_id: null,
  default_ai_temperature: 0.1,
  automation_file_root: 'automation',
  automation_screen_path: 'automation/screens',
  automation_error_path: 'automation/errors',
  automation_runtime_path: 'automation/runtime',
  automation_auto_screenshot_enabled: false,
  automation_auto_screenshot_interval: 30,
  automation_remote_token: '',
})

const enabledProviders = computed(() => providers.value.filter((item) => item.enabled))
const providerModels = computed(() => models.value.filter((item) => item.provider_id === form.default_ai_provider_id))

async function load() {
  const [settingsResult, providerResult, modelResult] = await Promise.all([
    api.get('/api/settings'),
    api.get('/api/ai/providers'),
    api.get('/api/ai/models'),
  ])
  providers.value = providerResult.data.items
  models.value = modelResult.data.items
  Object.assign(form, settingsResult.data.settings)
  syncAutomationToken()
}

function selectDefaultModel() {
  const available = providerModels.value
  if (!available.some((item) => item.id === form.default_ai_model_id)) {
    form.default_ai_model_id = available.find((item) => item.is_default)?.id || available[0]?.id || null
  }
}

async function save() {
  saving.value = true
  try {
    await api.put('/api/settings', form)
    syncAutomationToken()
    ElMessage.success('系统设置已保存')
    await load()
  } catch (error) {
    ElMessage.error(error.response?.data?.detail || '保存设置失败')
  } finally {
    saving.value = false
  }
}

function syncAutomationToken() {
  setAutomationToken(form.automation_remote_token)
}

defineExpose({ load })
onMounted(load)
</script>
