<template>
  <div class="admin-services-container">
    <!-- 页面标题 -->
    <h1>算法服务管理</h1>
    
    <!-- 操作栏 -->
    <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="showServiceDetailDialog = false">
        <el-icon><View /></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="last_heartbeat" label="最后心跳" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.last_heartbeat) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <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>
        </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="启动时间">{{ formatDate(selectedService.start_time) }}</el-descriptions-item>
          <el-descriptions-item label="最后心跳">{{ formatDate(selectedService.last_heartbeat) }}</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>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { Refresh, View, Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'

// 路由
const router = useRouter()

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

// 计算服务统计信息
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 {
    // 这里应该调用后端API获取服务列表
    // 暂时使用模拟数据
    services.value = [
      {
        id: '1',
        service_id: 'service-001',
        name: '图像分类服务',
        algorithm_name: 'image-classification',
        version: '1.0.0',
        status: 'running',
        host: '192.168.1.100',
        port: 8000,
        api_url: 'http://192.168.1.100:8000/execute',
        start_time: new Date().toISOString(),
        last_heartbeat: new Date().toISOString(),
        description: '基于ResNet的图像分类服务',
        config: {
          cpu_limit: '2核',
          memory_limit: '4GB',
          replicas: 2,
          timeout: 30
        },
        logs: [
          '[2024-01-01 10:00:00] 服务启动成功',
          '[2024-01-01 10:05:00] 注册到服务中心',
          '[2024-01-01 10:10:00] 处理请求: 图像分类',
          '[2024-01-01 10:15:00] 请求处理完成，耗时: 120ms'
        ]
      },
      {
        id: '2',
        service_id: 'service-002',
        name: '文本分类服务',
        algorithm_name: 'text-classification',
        version: '1.0.0',
        status: 'stopped',
        host: '192.168.1.101',
        port: 8001,
        api_url: 'http://192.168.1.101:8001/execute',
        start_time: new Date().toISOString(),
        last_heartbeat: new Date().toISOString(),
        description: '基于BERT的文本分类服务',
        config: {
          cpu_limit: '4核',
          memory_limit: '8GB',
          replicas: 1,
          timeout: 60
        },
        logs: [
          '[2024-01-01 09:00:00] 服务启动成功',
          '[2024-01-01 09:30:00] 服务停止'
        ]
      },
      {
        id: '3',
        service_id: 'service-003',
        name: '目标检测服务',
        algorithm_name: 'object-detection',
        version: '2.0.0',
        status: 'running',
        host: '192.168.1.102',
        port: 8002,
        api_url: 'http://192.168.1.102:8002/execute',
        start_time: new Date().toISOString(),
        last_heartbeat: new Date().toISOString(),
        description: '基于YOLOv5的目标检测服务',
        config: {
          cpu_limit: '8核',
          memory_limit: '16GB',
          replicas: 1,
          timeout: 120
        },
        logs: [
          '[2024-01-01 11:00:00] 服务启动成功',
          '[2024-01-01 11:05:00] 注册到服务中心',
          '[2024-01-01 11:10:00] 处理请求: 目标检测',
          '[2024-01-01 11:15:00] 请求处理完成，耗时: 500ms'
        ]
      }
    ]
    console.log('服务列表加载完成')
  } catch (error) {
    console.error('加载服务列表失败:', error)
    ElMessage.error('加载服务列表失败')
  }
}

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

// 启动服务
const startService = async (service: any) => {
  try {
    console.log('启动服务:', service.name)
    // 这里应该调用后端API启动服务
    
    // 模拟启动服务
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 更新服务状态
    service.status = 'running'
    ElMessage.success('服务启动成功')
  } 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)
    // 这里应该调用后端API停止服务
    
    // 模拟停止服务
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 更新服务状态
    service.status = 'stopped'
    ElMessage.success('服务停止成功')
  } catch (error) {
    // 用户取消操作
  }
}

// 重启服务
const restartService = async (service: any) => {
  try {
    console.log('重启服务:', service.name)
    // 这里应该调用后端API重启服务
    
    // 模拟重启服务
    service.status = 'restarting'
    await new Promise(resolve => setTimeout(resolve, 2000))
    service.status = 'running'
    
    ElMessage.success('服务重启成功')
  } catch (error) {
    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;
}

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

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