<template>
  <div class="admin-services-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-icon">
        <el-icon><Cpu /></el-icon>
      </div>
      <h1>算法服务管理</h1>
    </div>
    
    <!-- 操作栏 -->
    <div class="action-bar">
      <el-button type="primary" @click="refreshServices">
        <el-icon><Refresh /></el-icon>
        刷新服务列表
      </el-button>
      <el-button type="success" @click="navigateToServiceRegistration">
        <el-icon><Plus /></el-icon>
        注册新服务
      </el-button>
      <el-button type="info" @click="showHelpDialog = true">
        <el-icon><InfoFilled /></el-icon>
        帮助说明
      </el-button>
    </div>
    
    <!-- 服务状态统计 -->
    <div class="status-stats">
      <el-card class="stat-card">
        <div class="stat-item">
          <div class="stat-number">{{ totalServices }}</div>
          <div class="stat-label">总服务数</div>
        </div>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-item">
          <div class="stat-number">{{ runningServices }}</div>
          <div class="stat-label">运行中</div>
        </div>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-item">
          <div class="stat-number">{{ stoppedServices }}</div>
          <div class="stat-label">已停止</div>
        </div>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-item">
          <div class="stat-number">{{ errorServices }}</div>
          <div class="stat-label">异常</div>
        </div>
      </el-card>
    </div>
    
    <!-- 服务列表 -->
    <el-table :data="services" style="width: 100%" @row-click="handleRowClick">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="name" label="服务名称" width="200" />
      <el-table-column prop="service_id" label="服务ID" width="200" />
      <el-table-column prop="algorithm_name" label="算法名称" width="150" />
      <el-table-column prop="version" label="版本" width="100" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag 
            :type="getStatusType(scope.row.status)"
          >
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="host" label="主机" width="150" />
      <el-table-column prop="port" label="端口" width="80" />
      <el-table-column prop="api_url" label="API地址" />
      <el-table-column prop="health_check" label="健康检查" width="200">
        <template #default="scope">
          <el-link :href="scope.row.api_url + '/health'" target="_blank" type="primary">
            {{ scope.row.api_url }}/health
          </el-link>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="240">
        <template #default="scope">
          <el-button size="small" @click="startService(scope.row)" v-if="scope.row.status === 'stopped'">启动</el-button>
          <el-button size="small" type="warning" @click="stopService(scope.row)" v-else-if="scope.row.status === 'running'">停止</el-button>
          <el-button size="small" @click="restartService(scope.row)">重启</el-button>
          <el-button size="small" type="primary" @click="viewServiceDetail(scope.row)">详情</el-button>
          <el-button size="small" type="danger" @click="deleteService(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 服务详情对话框 -->
    <el-dialog
      v-model="showServiceDetailDialog"
      title="服务详情"
      width="80%"
    >
      <div v-if="selectedService" class="service-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="服务名称">{{ selectedService.name }}</el-descriptions-item>
          <el-descriptions-item label="服务ID">{{ selectedService.service_id }}</el-descriptions-item>
          <el-descriptions-item label="算法名称">{{ selectedService.algorithm_name }}</el-descriptions-item>
          <el-descriptions-item label="版本">{{ selectedService.version }}</el-descriptions-item>
          <el-descriptions-item label="状态">{{ selectedService.status }}</el-descriptions-item>
          <el-descriptions-item label="主机">{{ selectedService.host }}</el-descriptions-item>
          <el-descriptions-item label="端口">{{ selectedService.port }}</el-descriptions-item>
          <el-descriptions-item label="API地址">{{ selectedService.api_url }}</el-descriptions-item>
          <el-descriptions-item label="健康检查">
            <el-link :href="selectedService.api_url + '/health'" target="_blank" type="primary">
              {{ selectedService.api_url }}/health
            </el-link>
          </el-descriptions-item>
          <el-descriptions-item label="服务信息">
            <el-link :href="selectedService.api_url + '/info'" target="_blank" type="primary">
              {{ selectedService.api_url }}/info
            </el-link>
          </el-descriptions-item>
          <el-descriptions-item label="启动时间">{{ formatDate(selectedService.start_time) }}</el-descriptions-item>
          <el-descriptions-item label="服务描述" :span="2">{{ selectedService.description }}</el-descriptions-item>
        </el-descriptions>
        
        <!-- 服务配置 -->
        <div class="service-config">
          <h3>服务配置</h3>
          <el-card>
            <pre>{{ JSON.stringify(selectedService.config, null, 2) }}</pre>
          </el-card>
        </div>
        
        <!-- 服务日志 -->
        <div class="service-logs">
          <h3>服务日志</h3>
          <el-card>
            <div class="logs-container">
              <div v-for="(log, index) in selectedService.logs" :key="index" class="log-item">
                {{ log }}
              </div>
            </div>
          </el-card>
        </div>
      </div>
      <div v-else>
        <el-empty description="请选择一个服务查看详情" />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showServiceDetailDialog = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 帮助说明对话框 -->
    <el-dialog
      v-model="showHelpDialog"
      title="算法服务管理说明"
      width="70%"
      :close-on-click-modal="false"
    >
      <div class="help-dialog-content">
        <el-collapse v-model="activeHelpSections">
          <el-collapse-item title="什么是算法服务管理？" name="what">
            <div class="help-section">
              <p><strong>算法服务管理</strong>是智能算法展示平台的核心功能，用于管理从算法仓库部署的算法服务。</p>
              <p>它将您的算法代码转换为可调用的API服务，让算法能够通过HTTP接口被其他应用调用。</p>
              <el-divider />
              <h4>主要功能：</h4>
              <ul>
                <li><strong>服务注册</strong>：将算法仓库中的算法部署为独立的服务</li>
                <li><strong>服务监控</strong>：实时监控服务的运行状态和健康情况</li>
                <li><strong>服务控制</strong>：启动、停止、重启已部署的服务</li>
                <li><strong>服务调用</strong>：通过统一接口调用算法服务</li>
                <li><strong>日志查看</strong>：查看服务运行日志，便于问题排查</li>
              </ul>
            </div>
          </el-collapse-item>
          
          <el-collapse-item title="为什么需要服务管理？" name="why">
            <div class="help-section">
              <h4>解决的问题：</h4>
              <ul>
                <li><strong>算法隔离</strong>：每个算法运行在独立的环境中，避免相互干扰</li>
                <li><strong>资源管理</strong>：统一管理CPU、内存等资源分配</li>
                <li><strong>高可用性</strong>：支持服务的自动重启和故障恢复</li>
                <li><strong>负载均衡</strong>：支持多实例部署，提高并发处理能力</li>
                <li><strong>版本管理</strong>：同时运行不同版本的算法，便于A/B测试</li>
              </ul>
              <el-divider />
              <h4>应用场景：</h4>
              <ul>
                <li><strong>算法展示</strong>：为客户演示算法效果和能力</li>
                <li><strong>API服务</strong>：为其他应用提供算法调用接口</li>
                <li><strong>性能测试</strong>：对比不同算法的效果和性能</li>
                <li><strong>生产部署</strong>：将算法部署到生产环境提供服务</li>
              </ul>
            </div>
          </el-collapse-item>
          
          <el-collapse-item title="如何使用服务管理？" name="how">
            <div class="help-section">
              <h4>使用流程：</h4>
              <el-steps :active="currentStep" finish-status="success" align-center>
                <el-step title="上传算法代码" description="将算法代码上传到Gitea仓库" />
                <el-step title="注册服务" description="从仓库选择算法并注册为服务" />
                <el-step title="部署服务" description="系统自动部署服务并启动" />
                <el-step title="调用服务" description="通过API或前端页面调用算法" />
              </el-steps>
              
              <el-divider />
              
              <h4>详细步骤：</h4>
              <ol>
                <li><strong>上传算法代码</strong>：在"算法仓库管理"中上传您的算法项目代码</li>
                <li><strong>注册服务</strong>：点击"注册新服务"按钮，选择要部署的算法</li>
                <li><strong>配置服务</strong>：设置服务名称、端口、环境变量等配置</li>
                <li><strong>启动服务</strong>：系统会自动部署并启动服务</li>
                <li><strong>测试调用</strong>：使用服务调用功能测试算法是否正常工作</li>
                <li><strong>监控服务</strong>：查看服务状态、日志和性能指标</li>
              </ol>
            </div>
          </el-collapse-item>
          
          <el-collapse-item title="服务状态说明" name="status">
            <div class="help-section">
              <h4>服务状态类型：</h4>
              <el-table :data="statusDescriptions" style="width: 100%">
                <el-table-column prop="status" label="状态" width="120">
                  <template #default="scope">
                    <el-tag :type="getStatusType(scope.row.status)">
                      {{ scope.row.status }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="description" label="说明" />
                <el-table-column prop="action" label="建议操作" width="150" />
              </el-table>
            </div>
          </el-collapse-item>
          
          <el-collapse-item title="常见问题" name="faq">
            <div class="help-section">
              <el-collapse accordion>
                <el-collapse-item title="服务无法启动怎么办？">
                  <p>检查以下几点：</p>
                  <ul>
                    <li>算法代码是否有语法错误</li>
                    <li>依赖包是否正确安装</li>
                    <li>端口是否被占用</li>
                    <li>查看服务日志获取详细错误信息</li>
                  </ul>
                </el-collapse-item>
                
                <el-collapse-item title="如何调用已部署的服务？">
                  <p>有三种调用方式：</p>
                  <ul>
                    <li><strong>前端调用</strong>：在算法调用页面选择服务进行调用</li>
                    <li><strong>API调用</strong>：使用POST /api/v1/services/call接口调用</li>
                    <li><strong>网关调用</strong>：通过API网关统一调用所有算法</li>
                  </ul>
                </el-collapse-item>
                
                <el-collapse-item title="如何验证服务是否正常运行？">
                  <p>可以通过以下方式验证服务状态：</p>
                  <ul>
                    <li><strong>健康检查</strong>：访问服务的 /health 端点</li>
                    <li><strong>服务信息</strong>：访问服务的 /info 端点</li>
                    <li><strong>直接访问</strong>：在浏览器中访问服务的API地址</li>
                  </ul>
                  <p>例如，如果服务的API地址是 http://0.0.0.0:8005，可以访问：</p>
                  <ul>
                    <li>http://0.0.0.0:8005/health - 健康检查端点</li>
                    <li>http://0.0.0.0:8005/info - 服务信息端点</li>
                  </ul>
                  <p>正常情况下，/health 端点会返回 {"status": "healthy", "service": "服务名"}</p>
                </el-collapse-item>
                
                <el-collapse-item title="服务性能如何优化？">
                  <p>优化建议：</p>
                  <ul>
                    <li>调整服务配置中的超时时间</li>
                    <li>增加服务的并发处理能力</li>
                    <li>使用更高效的算法实现</li>
                    <li>考虑使用GPU加速</li>
                  </ul>
                </el-collapse-item>
                
                <el-collapse-item title="如何查看服务日志？">
                  <p>点击服务列表中的"详情"按钮，在弹出的对话框中可以查看：</p>
                  <ul>
                    <li>服务基本信息</li>
                    <li>服务配置详情</li>
                    <li>实时运行日志</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, computed, onMounted } from 'vue'
import { Refresh, View, Plus, InfoFilled, Cpu } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { serviceManagementApi } from '../../services/serviceManagement'

// 路由
const router = useRouter()

// 状态管理
const services = ref<any[]>([])
const showServiceDetailDialog = ref(false)
const showHelpDialog = ref(false)
const selectedService = ref<any>(null)

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

// 服务状态说明数据
const statusDescriptions = ref([
  {
    status: 'running',
    description: '服务正在正常运行，可以接收和处理请求',
    action: '可以调用服务'
  },
  {
    status: 'stopped',
    description: '服务已停止，无法接收请求',
    action: '点击启动按钮启动服务'
  },
  {
    status: 'error',
    description: '服务运行出错，需要检查日志排查问题',
    action: '查看日志并修复问题后重启'
  },
  {
    status: 'starting',
    description: '服务正在启动中，请稍候',
    action: '等待启动完成'
  },
  {
    status: 'stopping',
    description: '服务正在停止中，请稍候',
    action: '等待停止完成'
  }
])

// 计算服务统计信息
const totalServices = computed(() => services.value.length)
const runningServices = computed(() => services.value.filter(s => s.status === 'running').length)
const stoppedServices = computed(() => services.value.filter(s => s.status === 'stopped').length)
const errorServices = computed(() => services.value.filter(s => s.status === 'error').length)

// 获取状态类型
const getStatusType = (status: string) => {
  switch (status) {
    case 'running':
      return 'success'
    case 'stopped':
      return 'info'
    case 'error':
      return 'danger'
    default:
      return 'warning'
  }
}

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

// 加载服务列表
const loadServices = async () => {
  try {
    const result = await serviceManagementApi.getServices()
    if (result.success) {
      // 处理服务数据，添加缺失的字段
      services.value = result.services.map((service: any) => ({
        ...service,
        last_heartbeat: service.last_heartbeat || null,
        start_time: service.start_time || null,
        description: service.description || '',
        config: service.config || {},
        logs: []
      }))
      console.log('服务列表加载完成', services.value)
    } else {
      throw new Error(result.message || '获取服务列表失败')
    }
  } catch (error) {
    console.error('加载服务列表失败:', error)
    ElMessage.error('加载服务列表失败')
  }
}

// 刷新服务列表
const refreshServices = async () => {
  await loadServices()
  ElMessage.success('服务列表已刷新')
}

// 启动服务
const startService = async (service: any) => {
  try {
    console.log('启动服务:', service.name)
    
    const result = await serviceManagementApi.startService(service.service_id)
    
    if (result.success) {
      ElMessage.success('服务启动成功')
      await refreshServices()
    } else {
      ElMessage.error(`服务启动失败: ${result.message}`)
    }
  } catch (error) {
    console.error('启动服务失败:', error)
    ElMessage.error('启动服务失败')
  }
}

// 停止服务
const stopService = async (service: any) => {
  try {
    await ElMessageBox.confirm(`确定要停止服务 ${service.name} 吗？`, '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    console.log('停止服务:', service.name)
    
    const result = await serviceManagementApi.stopService(service.service_id)
    
    if (result.success) {
      ElMessage.success('服务停止成功')
      await refreshServices()
    } else {
      ElMessage.error(`服务停止失败: ${result.message}`)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('停止服务失败:', error)
      ElMessage.error('停止服务失败')
    }
  }
}

// 重启服务
const restartService = async (service: any) => {
  try {
    console.log('重启服务:', service.name)
    
    const result = await serviceManagementApi.restartService(service.service_id)
    
    if (result.success) {
      ElMessage.success('服务重启成功')
      await refreshServices()
    } else {
      ElMessage.error(`服务重启失败: ${result.message}`)
    }
  } catch (error) {
    console.error('重启服务失败:', error)
    ElMessage.error('重启服务失败')
  }
}

// 删除服务
const deleteService = async (service: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除服务 "${service.name}" 吗？此操作不可恢复。`,
      '删除确认',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const result = await serviceManagementApi.deleteService(service.service_id)
    
    if (result.success) {
      ElMessage.success('服务删除成功')
      await refreshServices()
    } else {
      ElMessage.error(`服务删除失败: ${result.message}`)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除服务失败:', error)
      ElMessage.error('删除服务失败')
    }
  }
}

// 查看服务详情
const viewServiceDetail = (service: any) => {
  selectedService.value = service
  showServiceDetailDialog.value = true
}

// 处理行点击
const handleRowClick = (row: any) => {
  selectedService.value = row
}

// 导航到服务注册页面
const navigateToServiceRegistration = () => {
  router.push('/admin/service-registration')
}

// 组件挂载时加载服务列表
onMounted(async () => {
  await loadServices()
})
</script>

<style scoped>
.admin-services-container {
  padding: 20px;
}

.page-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e4e7ed;
}

.header-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 48px;
  height: 48px;
  border-radius: 12px;
  background: linear-gradient(135deg, #409eff 0%, #67c23a 100%);
  color: white;
  font-size: 24px;
}

.page-header h1 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

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

.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;
}

.status-stats {
  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;
}

.service-detail {
  padding: 20px 0;
}

.service-config,
.service-logs {
  margin-top: 30px;
}

.service-config h3,
.service-logs h3 {
  margin-bottom: 15px;
  color: #333;
}

.logs-container {
  max-height: 300px;
  overflow-y: auto;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  font-family: 'Courier New', Courier, monospace;
  font-size: 14px;
}

.log-item {
  margin-bottom: 8px;
  line-height: 1.4;
}

.log-item:nth-child(odd) {
  background-color: rgba(0, 0, 0, 0.02);
  padding: 2px 4px;
  border-radius: 2px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .status-stats {
    flex-wrap: wrap;
  }
  
  .stat-card {
    flex: 1 1 200px;
  }
}

@media (max-width: 768px) {
  .admin-services-container {
    padding: 10px;
  }
  
  .status-stats {
    flex-direction: column;
  }
  
  .stat-card {
    flex: 1 1 100%;
  }
}
</style>