<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>
      <el-button @click="loadApis">
        <el-icon><Refresh /></el-icon>
        刷新
      </el-button>
      <el-button type="info" @click="showHelpDialog = true">
        <el-icon><InfoFilled /></el-icon>
        帮助说明
      </el-button>
    </div>
    
    <!-- API统计卡片 -->
    <div class="stats-cards">
      <el-card class="stat-card">
        <div class="stat-item">
          <div class="stat-number">{{ apiStats.total_endpoints }}</div>
          <div class="stat-label">总API数</div>
        </div>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-item">
          <div class="stat-number">{{ apiStats.active_endpoints }}</div>
          <div class="stat-label">激活API</div>
        </div>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-item">
          <div class="stat-number">{{ apiStats.total_calls }}</div>
          <div class="stat-label">总调用次数</div>
        </div>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-item">
          <div class="stat-number">{{ apiStats.avg_response_time }}s</div>
          <div class="stat-label">平均响应时间</div>
        </div>
      </el-card>
    </div>
    
    <!-- 筛选栏 -->
    <div class="filter-bar">
      <el-select v-model="filterStatus" placeholder="API状态" clearable @change="loadApis">
        <el-option label="全部" value="" />
        <el-option label="激活" value="active" />
        <el-option label="停用" value="inactive" />
      </el-select>
    </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="path" label="API路径" width="200" />
      <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="call_count" label="调用次数" width="100" />
      <el-table-column prop="avg_response_time" label="平均响应时间" width="120" />
      <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="250" fixed="right">
        <template #default="scope">
          <el-button size="small" @click="testApi(scope.row)">测试</el-button>
          <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="isEditMode ? '编辑API' : '封装新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="API路径" prop="path">
          <el-input v-model="apiForm.path" placeholder="请输入API路径，例如：/api/image-classification" />
        </el-form-item>
        <el-form-item label="HTTP方法" prop="method">
          <el-select v-model="apiForm.method" placeholder="选择HTTP方法">
            <el-option label="GET" value="GET" />
            <el-option label="POST" value="POST" />
            <el-option label="PUT" value="PUT" />
            <el-option label="DELETE" value="DELETE" />
          </el-select>
        </el-form-item>
        <el-form-item label="选择算法" prop="algorithm_id">
          <el-select v-model="apiForm.algorithm_id" placeholder="选择算法" @change="handleAlgorithmChange">
            <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="是否公开">
          <el-switch v-model="apiForm.is_public" />
        </el-form-item>
        <el-form-item label="是否需要认证">
          <el-switch v-model="apiForm.requires_auth" />
        </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="closeDialog">取消</el-button>
          <el-button type="primary" @click="saveApi">保存</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 测试API对话框 -->
    <el-dialog
      v-model="showTestDialog"
      title="测试API"
      width="60%"
    >
      <el-form :model="testForm" ref="testFormRef">
        <el-form-item label="API信息">
          <div class="api-info">
            <p><strong>API名称：</strong>{{ testingApi?.name }}</p>
            <p><strong>API路径：</strong>{{ testingApi?.path }}</p>
            <p><strong>HTTP方法：</strong>{{ testingApi?.method }}</p>
          </div>
        </el-form-item>
        <el-form-item label="请求数据">
          <el-input
            v-model="testForm.payload"
            type="textarea"
            :rows="10"
            placeholder='请输入JSON格式的请求数据，例如：{"text":"测试数据","number":123}'
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showTestDialog = false">取消</el-button>
          <el-button type="primary" @click="executeTest" :loading="testing">测试</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 帮助说明对话框 -->
    <el-dialog
      v-model="showHelpDialog"
      title="API管理说明"
      width="70%"
      :close-on-click-modal="false"
    >
      <div class="help-dialog-content">
        <el-collapse v-model="activeHelpSections">
          <el-collapse-item title="什么是API管理？" name="what">
            <div class="help-section">
              <p><strong>API管理</strong>是智能算法展示平台的核心功能，用于封装和管理算法API端点。</p>
              <p>它将算法服务封装成统一的API接口，提供标准化的调用方式，支持权限控制、流量限制等功能。</p>
              <el-divider />
              <h4>主要功能：</h4>
              <ul>
                <li><strong>API封装</strong>：将算法服务封装成标准化的API端点</li>
                <li><strong>权限控制</strong>：配置API的访问权限和角色限制</li>
                <li><strong>流量限制</strong>：设置API的调用频率限制</li>
                <li><strong>API测试</strong>：在线测试API是否正常工作</li>
                <li><strong>调用统计</strong>：统计API的调用次数和成功率</li>
              </ul>
            </div>
          </el-collapse-item>
          
          <el-collapse-item title="为什么需要API管理？" name="why">
            <div class="help-section">
              <h4>解决的问题：</h4>
              <ul>
                <li><strong>接口标准化</strong>：统一API调用方式，降低集成复杂度</li>
                <li><strong>权限管理</strong>：精细控制API的访问权限</li>
                <li><strong>流量控制</strong>：防止API被滥用，保护服务稳定性</li>
                <li><strong>监控统计</strong>：实时监控API调用情况</li>
                <li><strong>文档生成</strong>：自动生成API文档</li>
              </ul>
              <el-divider />
              <h4>应用场景：</h4>
              <ul>
                <li><strong>对外开放</strong>：为外部应用提供算法API</li>
                <li><strong>内部集成</strong>：为其他系统提供算法服务</li>
                <li><strong>API市场</strong>：发布API到API市场供他人使用</li>
                <li><strong>微服务架构</strong>：构建基于API的微服务架构</li>
              </ul>
            </div>
          </el-collapse-item>
          
          <el-collapse-item title="如何使用API管理？" name="how">
            <div class="help-section">
              <h4>使用流程：</h4>
              <el-steps :active="currentStep" finish-status="success" align-center>
                <el-step title="选择算法" description="选择要封装的算法和版本" />
                <el-step title="配置API" description="设置API路径、权限等配置" />
                <el-step title="测试API" description="测试API是否正常工作" />
                <el-step title="发布API" description="发布API供他人使用" />
              </el-steps>
              
              <el-divider />
              
              <h4>详细步骤：</h4>
              <ol>
                <li><strong>选择算法</strong>：从算法列表中选择要封装的算法和版本</li>
                <li><strong>配置API</strong>：设置API名称、路径、HTTP方法等</li>
                <li><strong>设置权限</strong>：配置是否需要认证、允许的角色等</li>
                <li><strong>流量限制</strong>：设置API的调用频率限制</li>
                <li><strong>测试API</strong>：使用测试功能验证API是否正常</li>
                <li><strong>发布API</strong>：将API设置为公开状态供他人使用</li>
              </ol>
            </div>
          </el-collapse-item>
          
          <el-collapse-item title="API配置说明" name="config">
            <div class="help-section">
              <h4>配置项说明：</h4>
              <el-table :data="configDescriptions" style="width: 100%">
                <el-table-column prop="item" label="配置项" width="150" />
                <el-table-column prop="description" label="说明" />
                <el-table-column prop="example" label="示例" />
              </el-table>
            </div>
          </el-collapse-item>
          
          <el-collapse-item title="常见问题" name="faq">
            <div class="help-section">
              <el-collapse accordion>
                <el-collapse-item title="API调用失败怎么办？">
                  <p>检查以下几点：</p>
                  <ul>
                    <li>关联的算法服务是否正在运行</li>
                    <li>API路径是否正确</li>
                    <li>请求参数格式是否正确</li>
                    <li>是否有足够的权限调用API</li>
                  </ul>
                </el-collapse-item>
                
                <el-collapse-item title="如何设置API权限？">
                  <p>权限配置包括：</p>
                  <ul>
                    <li><strong>是否需要认证</strong>：控制API是否需要用户登录</li>
                    <li><strong>允许的角色</strong>：限制只有特定角色可以调用</li>
                    <li><strong>是否公开</strong>：公开API不需要认证即可访问</li>
                  </ul>
                </el-collapse-item>
                
                <el-collapse-item title="如何设置流量限制？">
                  <p>流量限制配置：</p>
                  <ul>
                    <li><strong>最大请求数</strong>：在时间窗口内的最大请求数</li>
                    <li><strong>时间窗口</strong>：限制的时间范围（秒）</li>
                    <li>示例：{"max_requests": 100, "window": 60} 表示每分钟最多100次请求</li>
                  </ul>
                </el-collapse-item>
                
                <el-collapse-item title="如何查看API调用统计？">
                  <p>统计信息包括：</p>
                  <ul>
                    <li><strong>总调用次数</strong>：API被调用的总次数</li>
                    <li><strong>成功次数</strong>：调用成功的次数</li>
                    <li><strong>错误次数</strong>：调用失败的次数</li>
                    <li><strong>平均响应时间</strong>：API的平均响应时间</li>
                  </ul>
                </el-collapse-item>
              </el-collapse>
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showHelpDialog = false">关闭</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, Refresh, InfoFilled } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { apiManagementService, type ApiEndpoint } from '../../services/apiManagement'

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

// 状态管理
const apis = ref<ApiEndpoint[]>([])
const algorithms = ref<any[]>([])
const versions = ref<any[]>([])
const showAddDialog = ref(false)
const showTestDialog = ref(false)
const showHelpDialog = ref(false)
const isEditMode = ref(false)
const filterStatus = ref('')
const apiFormRef = ref()
const testFormRef = ref()
const testingApi = ref<ApiEndpoint | null>(null)
const testing = ref(false)

const apiForm = ref({
  name: '',
  path: '',
  method: 'POST',
  algorithm_id: '',
  version_id: '',
  is_public: false,
  requires_auth: true,
  description: ''
})

const testForm = ref({
  payload: '{"text":"测试数据","number":123}'
})

const apiStats = ref({
  total_endpoints: 0,
  active_endpoints: 0,
  total_calls: '0',
  total_success: '0',
  total_errors: '0',
  avg_response_time: '0.00'
})

const configDescriptions = ref([
  {
    item: 'API名称',
    description: 'API的显示名称，用于标识和区分不同的API',
    example: '图像分类API'
  },
  {
    item: 'API路径',
    description: 'API的访问路径，客户端通过此路径调用API',
    example: '/api/image-classification'
  },
  {
    item: 'HTTP方法',
    description: 'API支持的HTTP方法',
    example: 'POST'
  },
  {
    item: '是否公开',
    description: 'API是否对外公开，公开API不需要认证即可访问',
    example: 'true'
  },
  {
    item: '是否需要认证',
    description: 'API调用是否需要用户认证',
    example: 'true'
  }
])

// 帮助说明相关状态
const activeHelpSections = ref<string[]>(['what'])
const currentStep = ref(0)

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

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

// 加载API列表
const loadApis = async () => {
  try {
    const result = await apiManagementService.getApiEndpoints(filterStatus.value)
    apis.value = result.endpoints
  } catch (error) {
    console.error('加载API列表失败:', error)
    ElMessage.error('加载API列表失败')
  }
}

// 加载API统计
const loadApiStats = async () => {
  try {
    const stats = await apiManagementService.getApiStats()
    apiStats.value = stats
  } catch (error) {
    console.error('加载API统计失败:', error)
  }
}

// 加载算法列表
const loadAlgorithms = async () => {
  try {
    await algorithmStore.fetchAlgorithms()
    algorithms.value = algorithmStore.algorithms
  } catch (error) {
    console.error('加载算法列表失败:', error)
    ElMessage.error('加载算法列表失败')
  }
}

// 加载版本列表
const loadVersions = async (algorithmId: string) => {
  if (algorithmId) {
    const algorithm = algorithmStore.algorithms.find((a: any) => 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) {
      try {
        await apiManagementService.createApiEndpoint(apiForm.value)
        ElMessage.success('API封装成功')
        closeDialog()
        await loadApis()
        await loadApiStats()
      } catch (error: any) {
        console.error('添加API失败:', error)
        ElMessage.error(error.message || '添加API失败')
      }
    }
  })
}

// 编辑API
const editApi = (api: ApiEndpoint) => {
  isEditMode.value = true
  apiForm.value = {
    name: api.name,
    path: api.path,
    method: api.method,
    algorithm_id: api.algorithm_id,
    version_id: api.version_id,
    is_public: api.is_public,
    requires_auth: true,
    description: api.description
  }
  showAddDialog.value = true
}

// 更新API
const updateApi = async () => {
  if (!apiFormRef.value) return
  
  await apiFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        const apiId = apis.value.find((a: ApiEndpoint) => a.name === apiForm.value.name)?.id || ''
        await apiManagementService.updateApiEndpoint(apiId, apiForm.value)
        ElMessage.success('API更新成功')
        closeDialog()
        await loadApis()
      } catch (error: any) {
        console.error('更新API失败:', error)
        ElMessage.error(error.message || '更新API失败')
      }
    }
  })
}

// 保存API
const saveApi = async () => {
  if (isEditMode.value) {
    await updateApi()
  } else {
    await addApi()
  }
}

// 删除API
const deleteApi = async (apiId: string) => {
  try {
    await ElMessageBox.confirm('确定要删除此API吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await apiManagementService.deleteApiEndpoint(apiId)
    ElMessage.success('API删除成功')
    await loadApis()
    await loadApiStats()
  } catch (error: any) {
    console.error('删除API失败:', error)
    ElMessage.error(error.message || '删除API失败')
  }
}

// 测试API
const testApi = (api: ApiEndpoint) => {
  testingApi.value = api
  testForm.value.payload = '{"text":"测试数据","number":123}'
  showTestDialog.value = true
}

// 执行测试
const executeTest = async () => {
  if (!testFormRef.value || !testingApi.value) return
  
  try {
    const payload = JSON.parse(testForm.value.payload)
    testing.value = true
    
    const result = await apiManagementService.testApiEndpoint(testingApi.value.id, payload)
    
    if (result.success) {
      ElMessage.success(`API测试成功，响应时间：${result.response_time.toFixed(2)}秒`)
      ElMessage.info(`响应结果：${JSON.stringify(result.result)}`)
    } else {
      ElMessage.error(`API测试失败：${result.error}`)
    }
  } catch (error: any) {
    console.error('测试API失败:', error)
    ElMessage.error(error.message || '测试API失败')
  } finally {
    testing.value = false
  }
}

// 关闭对话框
const closeDialog = () => {
  showAddDialog.value = false
  isEditMode.value = false
  apiForm.value = {
    name: '',
    path: '',
    method: 'POST',
    algorithm_id: '',
    version_id: '',
    is_public: false,
    requires_auth: true,
    description: ''
  }
  if (apiFormRef.value) {
    apiFormRef.value.resetFields()
  }
}

// 加载数据
onMounted(async () => {
  await loadAlgorithms()
  await loadApis()
  await loadApiStats()
})
</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;
}

.stats-cards {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  flex: 1;
  min-width: 150px;
}

.stat-item {
  text-align: center;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

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

.filter-bar .el-select {
  width: 200px;
}

.api-info {
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.api-info p {
  margin: 8px 0;
  line-height: 1.6;
}

.help-section {
  padding: 10px 20px;
}

.help-section h4 {
  margin: 15px 0 10px 0;
  color: #333;
  font-size: 15px;
}

.help-section p {
  margin: 8px 0;
  line-height: 1.6;
  color: #606266;
}

.help-section ul,
.help-section ol {
  margin: 10px 0;
  padding-left: 20px;
}

.help-section li {
  margin: 8px 0;
  line-height: 1.6;
  color: #606266;
}

.help-section strong {
  color: #303133;
  font-weight: 600;
}

.help-dialog-content {
  max-height: 70vh;
  overflow-y: auto;
  padding: 10px 0;
}

@media (max-width: 768px) {
  .stats-cards {
    flex-wrap: wrap;
  }
  
  .stat-card {
    flex: 1 1 200px;
  }
  
  .el-table {
    font-size: 14px;
  }
  
  .el-table-column {
    min-width: 120px;
  }
  
  .action-bar {
    text-align: center;
  }
  
  .filter-bar {
    text-align: center;
  }
  
  .filter-bar .el-select {
    width: 100%;
  }
}
</style>