<template>
  <MainLayout>
    <div class="model-configs-page">
      <el-card>
      <template #header>
        <div class="card-header">
          <h2>模型配置管理</h2>
          <el-button type="primary" @click="handleCreate">
            <el-icon><Plus /></el-icon>
            创建模型配置
          </el-button>
        </div>
      </template>

      <!-- 搜索和筛选 -->
      <div class="filters">
        <el-select
          v-model="providerFilter"
          placeholder="提供商筛选"
          style="width: 200px"
          clearable
          @change="handleSearch"
        >
          <el-option label="OpenAI" value="openai" />
          <el-option label="DeepSeek" value="deepseek" />
          <el-option label="Anthropic" value="anthropic" />
          <el-option label="本地模型" value="local" />
        </el-select>
        <el-button type="primary" @click="handleSearch" style="margin-left: 10px">
          <el-icon><Search /></el-icon>
          搜索
        </el-button>
        <el-button @click="handleRefresh">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>

      <!-- 模型配置列表 -->
      <el-table
        v-loading="modelConfigStore.loading"
        :data="modelConfigStore.modelConfigs"
        style="width: 100%; margin-top: 20px"
        stripe
      >
        <el-table-column prop="name" label="名称" width="200" />
        <el-table-column prop="provider" label="提供商" width="120">
          <template #default="{ row }">
            <el-tag>{{ row.provider.toUpperCase() }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="model_name" label="模型名称" width="200" />
        <el-table-column prop="base_url" label="API地址" show-overflow-tooltip />
        <el-table-column prop="created_at" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button link type="success" @click="handleTest(row)">
              <el-icon><Connection /></el-icon>
              测试
            </el-button>
            <el-button link type="danger" @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handlePageChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 创建/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form :model="form" label-width="120px" :rules="rules" ref="formRef">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入配置名称" />
        </el-form-item>
        <el-form-item label="提供商" prop="provider">
          <el-select v-model="form.provider" placeholder="选择提供商">
            <el-option label="OpenAI" value="openai" />
            <el-option label="DeepSeek" value="deepseek" />
            <el-option label="Anthropic" value="anthropic" />
            <el-option label="本地模型" value="local" />
          </el-select>
        </el-form-item>
        <el-form-item label="模型名称" prop="model_name">
          <el-input v-model="form.model_name" placeholder="例如: gpt-3.5-turbo, deepseek-chat" />
        </el-form-item>
        <el-form-item label="API密钥" prop="api_key">
          <el-input
            v-model="form.api_key"
            type="password"
            show-password
            placeholder="请输入API密钥"
          />
          <el-alert
            type="info"
            :closable="false"
            show-icon
            style="margin-top: 5px;"
          >
            <template #title>
              <div style="font-size: 12px;">
                API密钥将加密存储，不会在列表中显示
              </div>
            </template>
          </el-alert>
        </el-form-item>
        <el-form-item label="API地址" prop="base_url">
          <el-input
            v-model="form.base_url"
            placeholder="可选，例如: https://api.openai.com/v1"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 测试对话框 -->
    <el-dialog v-model="testDialogVisible" title="测试模型配置" width="500px">
      <div v-if="testing">
        <el-icon class="is-loading"><Loading /></el-icon>
        正在测试模型配置...
      </div>
      <div v-else-if="testResult">
        <el-alert
          :type="testResult.status === 'success' ? 'success' : 'error'"
          :title="testResult.message"
          :closable="false"
        />
      </div>
    </el-dialog>
    </div>
  </MainLayout>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import MainLayout from '@/components/MainLayout.vue'
import {
  Plus,
  Search,
  Refresh,
  Edit,
  Delete,
  Connection,
  Loading
} from '@element-plus/icons-vue'
import { useModelConfigStore } from '@/stores/modelConfig'
import type { ModelConfig } from '@/stores/modelConfig'

const modelConfigStore = useModelConfigStore()

// 搜索和筛选
const providerFilter = ref('')
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('创建模型配置')
const formRef = ref()
const submitting = ref(false)
const form = ref({
  name: '',
  provider: 'openai',
  model_name: '',
  api_key: '',
  base_url: ''
})
const currentConfigId = ref<string | null>(null)

// 测试
const testDialogVisible = ref(false)
const testing = ref(false)
const testResult = ref<any>(null)
const currentTestConfig = ref<ModelConfig | null>(null)

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入配置名称', trigger: 'blur' }
  ],
  provider: [
    { required: true, message: '请选择提供商', trigger: 'change' }
  ],
  model_name: [
    { required: true, message: '请输入模型名称', trigger: 'blur' }
  ],
  api_key: [
    { required: true, message: '请输入API密钥', trigger: 'blur' }
  ]
}

// 格式化日期
const formatDate = (dateStr: string) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN')
}

// 搜索
const handleSearch = async () => {
  currentPage.value = 1
  await loadModelConfigs()
}

// 刷新
const handleRefresh = async () => {
  providerFilter.value = ''
  currentPage.value = 1
  await loadModelConfigs()
}

// 加载模型配置列表
const loadModelConfigs = async () => {
  try {
    const configs = await modelConfigStore.fetchModelConfigs({
      provider: providerFilter.value || undefined,
      skip: (currentPage.value - 1) * pageSize.value,
      limit: pageSize.value
    })
    total.value = configs.length
  } catch (error: any) {
    ElMessage.error(error.response?.data?.detail || '加载模型配置列表失败')
  }
}

// 创建
const handleCreate = () => {
  dialogTitle.value = '创建模型配置'
  currentConfigId.value = null
  form.value = {
    name: '',
    provider: 'openai',
    model_name: '',
    api_key: '',
    base_url: ''
  }
  dialogVisible.value = true
}

// 编辑
const handleEdit = (config: ModelConfig) => {
  dialogTitle.value = '编辑模型配置'
  currentConfigId.value = config.id
  form.value = {
    name: config.name,
    provider: config.provider,
    model_name: config.model_name,
    api_key: '', // 不显示已有密钥
    base_url: config.base_url || ''
  }
  dialogVisible.value = true
}

// 测试
const handleTest = async (config: ModelConfig) => {
  currentTestConfig.value = config
  testDialogVisible.value = true
  testing.value = true
  testResult.value = null
  
  try {
    const result = await modelConfigStore.testModelConfig(config.id)
    testResult.value = result
    if (result.status === 'success') {
      ElMessage.success('模型配置测试成功')
    } else {
      ElMessage.error(result.message || '模型配置测试失败')
    }
  } catch (error: any) {
    testResult.value = {
      status: 'error',
      message: error.response?.data?.detail || '模型配置测试失败'
    }
    ElMessage.error(testResult.value.message)
  } finally {
    testing.value = false
  }
}

// 删除
const handleDelete = async (config: ModelConfig) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除模型配置 "${config.name}" 吗？此操作不可恢复。`,
      '确认删除',
      {
        type: 'error'
      }
    )
    await modelConfigStore.deleteModelConfig(config.id)
    ElMessage.success('删除成功')
    await loadModelConfigs()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.detail || '删除失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    
    submitting.value = true
    try {
      if (currentConfigId.value) {
        // 更新（如果api_key为空，则不更新）
        const updateData: any = {
          name: form.value.name,
          provider: form.value.provider,
          model_name: form.value.model_name,
          base_url: form.value.base_url || null
        }
        if (form.value.api_key) {
          updateData.api_key = form.value.api_key
        }
        await modelConfigStore.updateModelConfig(currentConfigId.value, updateData)
        ElMessage.success('更新成功')
      } else {
        // 创建
        await modelConfigStore.createModelConfig(form.value)
        ElMessage.success('创建成功')
      }
      dialogVisible.value = false
      await loadModelConfigs()
    } catch (error: any) {
      ElMessage.error(error.response?.data?.detail || '操作失败')
    } finally {
      submitting.value = false
    }
  })
}

// 对话框关闭
const handleDialogClose = () => {
  formRef.value?.resetFields()
  currentConfigId.value = null
}

// 分页变化
const handlePageChange = () => {
  loadModelConfigs()
}

// 初始化
onMounted(() => {
  loadModelConfigs()
})
</script>

<style scoped>
.model-configs-page {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
}

.filters {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
