<template>
  <div class="admin-api-management-container">
    <!-- 页面标题 -->
    <h1>API管理</h1>
    
    <!-- 操作栏 -->
    <div class="action-bar">
      <el-button type="primary" @click="showAddDialog = true">
        <el-icon><plus /></el-icon>
        封装新API
      </el-button>
    </div>
    
    <!-- API列表 -->
    <el-table :data="apis" style="width: 100%">
      <el-table-column prop="name" label="API名称" width="200" />
      <el-table-column prop="algorithm_name" label="算法名称" width="180" />
      <el-table-column prop="version" label="版本" width="120" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 'active' ? 'success' : 'info'">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="created_at" label="创建时间" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.created_at) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button size="small" @click="editApi(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteApi(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 封装API对话框 -->
    <el-dialog
      v-model="showAddDialog"
      title="封装新API"
      width="70%"
    >
      <el-form :model="apiForm" :rules="apiRules" ref="apiFormRef">
        <el-form-item label="API名称" prop="name">
          <el-input v-model="apiForm.name" placeholder="请输入API名称" />
        </el-form-item>
        <el-form-item label="选择算法" prop="algorithm_id">
          <el-select v-model="apiForm.algorithm_id" placeholder="选择算法">
            <el-option 
              v-for="algorithm in algorithms" 
              :key="algorithm.id" 
              :label="algorithm.name" 
              :value="algorithm.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="选择版本" prop="version_id">
          <el-select v-model="apiForm.version_id" placeholder="选择版本">
            <el-option 
              v-for="version in versions" 
              :key="version.id" 
              :label="version.version" 
              :value="version.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="API路径" prop="path">
          <el-input v-model="apiForm.path" placeholder="请输入API路径，例如：/api/predict" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="apiForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入API描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddDialog = false">取消</el-button>
          <el-button type="primary" @click="addApi">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAlgorithmStore } from '../../stores/algorithm'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

// 获取路由和存储
const router = useRouter()
const algorithmStore = useAlgorithmStore()

// 状态管理
const apis = ref([])
const algorithms = ref([])
const versions = ref([])
const showAddDialog = ref(false)
const apiFormRef = ref()
const apiForm = ref({
  name: '',
  algorithm_id: '',
  version_id: '',
  path: '',
  description: ''
})

// 表单验证规则
const apiRules = ref({
  name: [
    { required: true, message: '请输入API名称', trigger: 'blur' }
  ],
  algorithm_id: [
    { required: true, message: '请选择算法', trigger: 'blur' }
  ],
  version_id: [
    { required: true, message: '请选择版本', trigger: 'blur' }
  ],
  path: [
    { required: true, message: '请输入API路径', trigger: 'blur' }
  ]
})

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleString()
}

// 加载API列表
const loadApis = async () => {
  // 这里应该调用后端API获取API列表
  // 暂时模拟数据
  apis.value = [
    {
      id: 'api-1',
      name: '图像分类API',
      algorithm_name: 'ResNet50',
      version: '1.0.0',
      status: 'active',
      created_at: new Date().toISOString()
    },
    {
      id: 'api-2',
      name: '文本分类API',
      algorithm_name: 'BERT',
      version: '1.0.0',
      status: 'active',
      created_at: new Date().toISOString()
    }
  ]
}

// 加载算法列表
const loadAlgorithms = async () => {
  await algorithmStore.fetchAlgorithms()
  algorithms.value = algorithmStore.algorithms
}

// 加载版本列表
const loadVersions = async (algorithmId: string) => {
  if (algorithmId) {
    const algorithm = algorithmStore.algorithms.find(a => a.id === algorithmId)
    if (algorithm && algorithm.versions) {
      versions.value = algorithm.versions
    }
  }
}

// 监听算法选择变化
const handleAlgorithmChange = (algorithmId: string) => {
  loadVersions(algorithmId)
}

// 添加API
const addApi = async () => {
  if (!apiFormRef.value) return
  
  // 验证表单
  await apiFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      // 这里应该调用后端API添加API
      // 暂时模拟添加
      console.log('添加API:', apiForm.value)
      ElMessage.success('API封装成功')
      
      // 关闭对话框
      showAddDialog.value = false
      
      // 重置表单
      apiForm.value = {
        name: '',
        algorithm_id: '',
        version_id: '',
        path: '',
        description: ''
      }
      
      // 重新加载API列表
      await loadApis()
    }
  })
}

// 编辑API
const editApi = (api: any) => {
  // 这里应该打开编辑对话框，暂时打印
  console.log('编辑API:', api)
}

// 删除API
const deleteApi = (apiId: string) => {
  // 这里应该调用后端API删除API，暂时打印
  console.log('删除API:', apiId)
  ElMessage.success('API删除成功')
  // 重新加载API列表
  loadApis()
}

// 加载数据
onMounted(async () => {
  await loadAlgorithms()
  await loadApis()
})
</script>

<style scoped>
.admin-api-management-container {
  width: 100%;
}

.admin-api-management-container h1 {
  font-size: 24px;
  margin-bottom: 20px;
  color: #333;
}

.action-bar {
  margin-bottom: 20px;
}

@media (max-width: 768px) {
  .el-table {
    font-size: 14px;
  }
  
  .el-table-column {
    min-width: 120px;
  }
  
  .action-bar {
    text-align: center;
  }
}
</style>