<template>
  <div class="panel">
    <div class="toolbar">
      <div class="filters">
        <el-select v-model="form.provider_id" placeholder="AI 服务商" style="width: 220px" @change="selectDefaultModel">
          <el-option v-for="provider in enabledProviders" :key="provider.id" :label="provider.name" :value="provider.id" />
        </el-select>
        <el-select v-model="form.model_id" placeholder="AI 模型" style="width: 220px">
          <el-option
            v-for="model in providerModels"
            :key="model.id"
            :label="model.display_name || model.name"
            :value="model.id"
          />
        </el-select>
        <span class="muted">温度</span>
        <el-input-number v-model="form.temperature" :min="0" :max="2" :step="0.1" />
        <el-button type="primary" :loading="loading" @click="send">发送</el-button>
      </div>
    </div>

    <el-input v-model="form.prompt" class="prompt-box" type="textarea" placeholder="输入测试提示词" />
    <div style="margin-top: 12px">
      <div class="section-title">输出</div>
      <pre class="raw-output">{{ output || '暂无输出' }}</pre>
    </div>
  </div>
</template>

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

const providers = ref([])
const models = ref([])
const loading = ref(false)
const output = ref('')
const form = reactive({
  provider_id: null,
  model_id: null,
  temperature: 0.2,
  prompt: '请用一句话回答：你已经可以连接了吗？',
})

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

async function loadOptions() {
  const [providerResult, modelResult] = await Promise.all([
    api.get('/api/ai/providers'),
    api.get('/api/ai/models'),
  ])
  providers.value = providerResult.data.items
  models.value = modelResult.data.items
  form.provider_id = enabledProviders.value[0]?.id || null
  selectDefaultModel()
}

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

async function send() {
  if (!form.provider_id || !form.model_id || !form.prompt.trim()) {
    ElMessage.warning('请选择服务商、模型并输入内容')
    return
  }
  loading.value = true
  try {
    const { data } = await api.post('/api/ai/test', {
      provider_id: form.provider_id,
      model_id: form.model_id,
      prompt: form.prompt,
      temperature: form.temperature,
    })
    output.value = data.content
  } catch (error) {
    ElMessage.error(error.response?.data?.detail || 'AI 测试失败')
  } finally {
    loading.value = false
  }
}

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