<template>
  <div class="admin-service-registration-container">
    <!-- 页面标题 -->
    <h1>服务注册</h1>
    
    <!-- 操作说明 -->
    <el-card class="info-card">
      <template #header>
        <div class="card-header">
          <span>操作说明</span>
        </div>
      </template>
      <div class="info-content">
        <p>1. 选择要注册为服务的算法仓库</p>
        <p>2. 选择仓库中的算法</p>
        <p>3. 配置服务参数</p>
        <p>4. 提交注册请求</p>
      </div>
    </el-card>
    
    <!-- 注册表单 -->
    <el-card class="registration-card">
      <template #header>
        <div class="card-header">
          <span>服务注册表单</span>
        </div>
      </template>
      
      <el-form
        :model="serviceForm"
        :rules="rules"
        ref="serviceFormRef"
        label-width="120px"
        class="service-form"
      >
        <!-- 仓库选择 -->
        <el-form-item label="算法仓库" prop="repository_id">
          <el-select
            v-model="serviceForm.repository_id"
            placeholder="请选择算法仓库"
            @change="onRepositoryChange"
            class="w-full"
          >
            <el-option
              v-for="repo in repositories"
              :key="repo.id"
              :label="repo.name"
              :value="repo.id"
            >
              <div class="option-content">
                <div class="option-name">{{ repo.name }}</div>
                <div class="option-desc">{{ repo.description || '无描述' }}</div>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        
        <!-- 算法选择 -->
        <el-form-item label="算法" prop="algorithm_id">
          <el-select
            v-model="serviceForm.algorithm_id"
            placeholder="请选择算法"
            @change="onAlgorithmChange"
            class="w-full"
            :disabled="!serviceForm.repository_id"
          >
            <el-option
              v-for="algorithm in algorithms"
              :key="algorithm.id"
              :label="algorithm.name"
              :value="algorithm.id"
            >
              <div class="option-content">
                <div class="option-name">{{ algorithm.name }}</div>
                <div class="option-desc">{{ algorithm.description || '无描述' }}</div>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        
        <!-- 服务基本信息 -->
        <el-form-item label="服务名称" prop="name">
          <el-input
            v-model="serviceForm.name"
            placeholder="请输入服务名称"
            class="w-full"
          />
        </el-form-item>
        
        <el-form-item label="服务版本" prop="version">
          <el-input
            v-model="serviceForm.version"
            placeholder="请输入服务版本"
            class="w-full"
          />
        </el-form-item>
        
        <el-form-item label="服务描述" prop="description">
          <el-input
            v-model="serviceForm.description"
            type="textarea"
            placeholder="请输入服务描述"
            rows="3"
            class="w-full"
          />
        </el-form-item>
        
        <!-- 服务配置 -->
        <el-form-item label="服务类型" prop="service_type">
          <el-select
            v-model="serviceForm.service_type"
            placeholder="请选择服务类型"
            class="w-full"
          >
            <el-option label="HTTP REST API" value="http" />
            <el-option label="gRPC" value="grpc" />
            <el-option label="消息队列" value="mq" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="主机地址" prop="host">
          <el-input
            v-model="serviceForm.host"
            placeholder="请输入主机地址"
            class="w-full"
          />
        </el-form-item>
        
        <el-form-item label="服务端口" prop="port">
          <el-input-number
            v-model="serviceForm.port"
            :min="1"
            :max="65535"
            :step="1"
            class="w-full"
            placeholder="请输入服务端口"
          />
        </el-form-item>
        
        <el-form-item label="超时时间" prop="timeout">
          <el-input-number
            v-model="serviceForm.timeout"
            :min="1"
            :max="300"
            :step="1"
            class="w-full"
            placeholder="请输入超时时间（秒）"
          />
        </el-form-item>
        
        <!-- 高级配置 -->
        <el-form-item label="高级配置">
          <el-collapse>
            <el-collapse-item title="资源配置">
              <el-form-item label="CPU限制">
                <el-input
                  v-model="serviceForm.cpu_limit"
                  placeholder="例如：2核"
                  class="w-full"
                />
              </el-form-item>
              
              <el-form-item label="内存限制">
                <el-input
                  v-model="serviceForm.memory_limit"
                  placeholder="例如：4GB"
                  class="w-full"
                />
              </el-form-item>
              
              <el-form-item label="副本数">
                <el-input-number
                  v-model="serviceForm.replicas"
                  :min="1"
                  :max="10"
                  :step="1"
                  class="w-full"
                />
              </el-form-item>
            </el-collapse-item>
            
            <el-collapse-item title="健康检查">
              <el-form-item label="健康检查路径">
                <el-input
                  v-model="serviceForm.health_check_path"
                  placeholder="例如：/health"
                  class="w-full"
                />
              </el-form-item>
              
              <el-form-item label="健康检查间隔">
                <el-input-number
                  v-model="serviceForm.health_check_interval"
                  :min="1"
                  :max="60"
                  :step="1"
                  class="w-full"
                  placeholder="请输入健康检查间隔（秒）"
                />
              </el-form-item>
            </el-collapse-item>
          </el-collapse>
        </el-form-item>
        
        <!-- 提交按钮 -->
        <el-form-item>
          <div class="form-actions">
            <el-button type="primary" @click="submitForm" :loading="submitLoading">
              <el-icon><Check /></el-icon>
              提交注册
            </el-button>
            <el-button @click="resetForm">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 注册结果对话框 -->
    <el-dialog
      v-model="showResultDialog"
      :title="registrationResult.success ? '注册成功' : '注册失败'"
      width="60%"
    >
      <div v-if="registrationResult.success" class="result-success">
        <el-alert
          :title="'服务注册成功！'"
          type="success"
          show-icon
          :closable="false"
        />
        <el-descriptions :column="2" border style="margin-top: 20px;">
          <el-descriptions-item label="服务名称">{{ registrationResult.service?.name }}</el-descriptions-item>
          <el-descriptions-item label="服务ID">{{ registrationResult.service?.service_id }}</el-descriptions-item>
          <el-descriptions-item label="服务状态">{{ registrationResult.service?.status }}</el-descriptions-item>
          <el-descriptions-item label="API地址">{{ registrationResult.service?.api_url }}</el-descriptions-item>
          <el-descriptions-item label="主机" :span="2">{{ registrationResult.service?.host }}:{{ registrationResult.service?.port }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <div v-else class="result-error">
        <el-alert
          :title="'服务注册失败！'"
          type="error"
          show-icon
          :closable="false"
        />
        <el-card style="margin-top: 20px;">
          <pre>{{ registrationResult.error }}</pre>
        </el-card>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showResultDialog = false">关闭</el-button>
          <el-button
            v-if="registrationResult.success"
            type="primary"
            @click="navigateToServiceManagement"
          >
            查看服务管理
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

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

// 路由
const router = useRouter()

// 表单引用
const serviceFormRef = ref()

// 加载状态
const submitLoading = ref(false)

// 仓库和算法列表
const repositories = ref<any[]>([])
const algorithms = ref<any[]>([])

// 服务表单
const serviceForm = reactive({
  repository_id: '',
  algorithm_id: '',
  name: '',
  version: '1.0.0',
  description: '',
  service_type: 'http',
  host: '0.0.0.0',
  port: 8000,
  timeout: 30,
  cpu_limit: '2核',
  memory_limit: '4GB',
  replicas: 1,
  health_check_path: '/health',
  health_check_interval: 30
})

// 表单验证规则
const rules = {
  repository_id: [
    { required: true, message: '请选择算法仓库', trigger: 'blur' }
  ],
  algorithm_id: [
    { required: true, message: '请选择算法', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入服务名称', trigger: 'blur' },
    { min: 2, max: 50, message: '服务名称长度应在 2-50 个字符之间', trigger: 'blur' }
  ],
  version: [
    { required: true, message: '请输入服务版本', trigger: 'blur' }
  ],
  service_type: [
    { required: true, message: '请选择服务类型', trigger: 'blur' }
  ],
  host: [
    { required: true, message: '请输入主机地址', trigger: 'blur' }
  ],
  port: [
    { required: true, message: '请输入服务端口', trigger: 'blur' }
  ],
  timeout: [
    { required: true, message: '请输入超时时间', trigger: 'blur' }
  ]
}

// 注册结果
const showResultDialog = ref(false)
const registrationResult = reactive({
  success: false,
  service: null,
  error: ''
})

// 加载仓库列表
const loadRepositories = async () => {
  try {
    // 这里应该调用后端API获取仓库列表
    // 暂时使用模拟数据
    repositories.value = [
      {
        id: 'repo-001',
        name: '图像分类算法',
        description: '基于ResNet的图像分类算法仓库',
        type: 'python',
        status: 'active'
      },
      {
        id: 'repo-002',
        name: '文本分类算法',
        description: '基于BERT的文本分类算法仓库',
        type: 'python',
        status: 'active'
      },
      {
        id: 'repo-003',
        name: '目标检测算法',
        description: '基于YOLOv5的目标检测算法仓库',
        type: 'python',
        status: 'active'
      },
      {
        id: 'repo-004',
        name: '推荐系统算法',
        description: '基于协同过滤的推荐系统算法仓库',
        type: 'nodejs',
        status: 'active'
      }
    ]
    console.log('仓库列表加载完成')
  } catch (error) {
    console.error('加载仓库列表失败:', error)
    ElMessage.error('加载仓库列表失败')
  }
}

// 加载算法列表
const loadAlgorithms = async (repositoryId: string) => {
  try {
    // 这里应该根据仓库ID调用后端API获取算法列表
    // 暂时使用模拟数据
    algorithms.value = [
      {
        id: 'algo-001',
        name: 'ResNet图像分类',
        description: '使用ResNet50模型进行图像分类',
        repository_id: repositoryId,
        entry_point: 'model/predict.py'
      },
      {
        id: 'algo-002',
        name: 'MobileNet轻量分类',
        description: '使用MobileNet进行轻量级图像分类',
        repository_id: repositoryId,
        entry_point: 'model/mobilenet_predict.py'
      }
    ]
    console.log('算法列表加载完成')
  } catch (error) {
    console.error('加载算法列表失败:', error)
    ElMessage.error('加载算法列表失败')
  }
}

// 仓库选择变化
const onRepositoryChange = (repositoryId: string) => {
  if (repositoryId) {
    algorithms.value = []
    serviceForm.algorithm_id = ''
    loadAlgorithms(repositoryId)
  }
}

// 算法选择变化
const onAlgorithmChange = (algorithmId: string) => {
  if (algorithmId) {
    // 可以根据算法ID自动填充一些默认值
    const selectedAlgorithm = algorithms.value.find(a => a.id === algorithmId)
    if (selectedAlgorithm) {
      // 自动生成服务名称
      if (!serviceForm.name) {
        serviceForm.name = `${selectedAlgorithm.name}服务`
      }
    }
  }
}

// 提交表单
const submitForm = async () => {
  if (!serviceFormRef.value) return
  
  try {
    await serviceFormRef.value.validate()
    
    submitLoading.value = true
    
    // 构建服务配置
    const serviceConfig = {
      name: serviceForm.name,
      version: serviceForm.version,
      description: serviceForm.description,
      service_type: serviceForm.service_type,
      host: serviceForm.host,
      port: serviceForm.port,
      timeout: serviceForm.timeout,
      cpu_limit: serviceForm.cpu_limit,
      memory_limit: serviceForm.memory_limit,
      replicas: serviceForm.replicas,
      health_check_path: serviceForm.health_check_path,
      health_check_interval: serviceForm.health_check_interval
    }
    
    console.log('提交服务注册请求:', {
      repository_id: serviceForm.repository_id,
      algorithm_id: serviceForm.algorithm_id,
      service_config: serviceConfig
    })
    
    // 这里应该调用后端API注册服务
    // 暂时使用模拟数据
    await new Promise(resolve => setTimeout(resolve, 3000))
    
    // 模拟注册结果
    const mockService = {
      service_id: `service-${Date.now()}`,
      name: serviceForm.name,
      version: serviceForm.version,
      description: serviceForm.description,
      status: 'running',
      host: serviceForm.host,
      port: serviceForm.port,
      api_url: `http://${serviceForm.host}:${serviceForm.port}`,
      algorithm_id: serviceForm.algorithm_id,
      repository_id: serviceForm.repository_id,
      created_at: new Date().toISOString(),
      last_heartbeat: new Date().toISOString()
    }
    
    // 更新注册结果
    registrationResult.success = true
    registrationResult.service = mockService
    registrationResult.error = ''
    showResultDialog.value = true
    
    ElMessage.success('服务注册成功')
    
    // 重置表单
    resetForm()
  } catch (error: any) {
    console.error('服务注册失败:', error)
    registrationResult.success = false
    registrationResult.service = null
    registrationResult.error = error.message || '服务注册失败，请稍后重试'
    showResultDialog.value = true
    ElMessage.error('服务注册失败')
  } finally {
    submitLoading.value = false
  }
}

// 重置表单
const resetForm = () => {
  if (serviceFormRef.value) {
    serviceFormRef.value.resetFields()
  }
  // 重置算法列表
  algorithms.value = []
  // 重置默认值
  serviceForm.version = '1.0.0'
  serviceForm.service_type = 'http'
  serviceForm.host = '0.0.0.0'
  serviceForm.port = 8000
  serviceForm.timeout = 30
  serviceForm.cpu_limit = '2核'
  serviceForm.memory_limit = '4GB'
  serviceForm.replicas = 1
  serviceForm.health_check_path = '/health'
  serviceForm.health_check_interval = 30
}

// 跳转到服务管理页面
const navigateToServiceManagement = () => {
  showResultDialog.value = false
  router.push('/admin/services')
}

// 组件挂载时加载仓库列表
onMounted(async () => {
  await loadRepositories()
})
</script>

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

.info-card {
  margin-bottom: 20px;
}

.registration-card {
  margin-bottom: 20px;
}

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

.info-content {
  line-height: 1.6;
  color: #666;
}

.service-form {
  max-width: 800px;
}

.option-content {
  display: flex;
  flex-direction: column;
}

.option-name {
  font-weight: 500;
  margin-bottom: 4px;
}

.option-desc {
  font-size: 12px;
  color: #999;
  line-height: 1.4;
}

.form-actions {
  display: flex;
  gap: 10px;
  margin-top: 20px;
}

.result-success {
  padding: 20px 0;
}

.result-error {
  padding: 20px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .admin-service-registration-container {
    padding: 10px;
  }
  
  .service-form {
    max-width: 100%;
  }
  
  .form-actions {
    flex-direction: column;
  }
  
  .form-actions .el-button {
    width: 100%;
  }
}
</style>