<script setup lang="ts">
import { ref, onMounted } from 'vue'
import api from '../api'
import { ElMessage, ElMessageBox } from 'element-plus'

interface ModelConfig {
  id: number
  name: string
  base_url: string
  api_key: string
  model_name: string
}

const models = ref<ModelConfig[]>([])
const dialogVisible = ref(false)
const testing = ref(false)
const isEdit = ref(false)
const editId = ref<number | null>(null)

const form = ref({
  name: '',
  base_url: 'https://api.openai.com/v1',
  api_key: '',
  model_name: 'gpt-3.5-turbo'
})

const fetchModels = async () => {
  const res = await api.get('/models')
  models.value = res.data
}

const resetForm = () => {
  form.value = {
    name: '',
    base_url: 'https://api.openai.com/v1',
    api_key: '',
    model_name: 'gpt-3.5-turbo'
  }
  isEdit.value = false
  editId.value = null
}

const handleAdd = () => {
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row: ModelConfig) => {
  isEdit.value = true
  editId.value = row.id
  form.value = {
    name: row.name,
    base_url: row.base_url,
    api_key: row.api_key,
    model_name: row.model_name
  }
  dialogVisible.value = true
}

const handleDelete = (id: number) => {
  ElMessageBox.confirm('确认删除该模型配置？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      await api.delete(`/models/${id}`)
      ElMessage.success('删除成功')
      fetchModels()
    } catch (e) {
      ElMessage.error('删除失败')
    }
  })
}

const handleSave = async () => {
  try {
    if (isEdit.value && editId.value) {
      await api.put(`/models/${editId.value}`, form.value)
      ElMessage.success('更新成功')
    } else {
      await api.post('/models', form.value)
      ElMessage.success('添加成功')
    }
    dialogVisible.value = false
    fetchModels()
  } catch (e) {
    ElMessage.error(isEdit.value ? '更新失败' : '添加失败')
  }
}

const handleTest = async () => {
  if (!form.value.base_url || !form.value.api_key || !form.value.model_name) {
    ElMessage.warning('请填写完整信息（API地址、Key、模型ID）')
    return
  }
  
  testing.value = true
  try {
    const res = await api.post('/models/test', form.value)
    ElMessage.success({
      message: `连接成功: ${res.data.message}`,
      duration: 5000
    })
  } catch (e: any) {
    const errorMsg = e.response?.data?.detail || '连接失败'
    ElMessage.error(errorMsg)
  } finally {
    testing.value = false
  }
}

onMounted(fetchModels)
</script>

<template>
  <div class="models-view">
    <div class="toolbar">
      <el-button type="primary" @click="handleAdd">添加模型配置</el-button>
    </div>
    <el-table :data="models" style="width: 100%">
      <el-table-column prop="id" label="ID" width="60" />
      <el-table-column prop="name" label="配置名称" />
      <el-table-column prop="model_name" label="模型ID" />
      <el-table-column prop="base_url" label="API地址" show-overflow-tooltip />
      <el-table-column label="API Key">
        <template #default="scope">
          <span>{{ scope.row.api_key ? '********' : '无' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑模型配置' : '添加模型配置'">
      <el-form :model="form" label-width="120px">
        <el-form-item label="配置名称">
          <el-input v-model="form.name" placeholder="例如：OpenAI 生产环境" />
        </el-form-item>
        <el-form-item label="API地址">
          <el-input v-model="form.base_url" placeholder="https://api.openai.com/v1" />
        </el-form-item>
        <el-form-item label="API Key">
          <el-input v-model="form.api_key" type="password" show-password />
        </el-form-item>
        <el-form-item label="模型ID">
          <el-input v-model="form.model_name" placeholder="例如：gpt-4o" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleTest" :loading="testing" type="success" plain>测试连接</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.toolbar {
  margin-bottom: 20px;
}
</style>
