<template>
  <div class="mcp-service-management">
    <div class="header">
      <div class="header-content">
        <h1 class="page-title">MCP服务管理</h1>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="addService">
          <el-icon><Plus /></el-icon>
          添加服务
        </el-button>
      </div>
    </div>

    <div class="search-bar">
      <div class="search-left">
        <el-input
          v-model="searchQuery"
          placeholder="搜索服务名称或描述"
          clearable
          style="width: 300px"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-select v-model="filterStatus" placeholder="服务状态" style="width: 120px;">
          <el-option label="全部" value="" />
          <el-option label="启用" value="active" />
          <el-option label="禁用" value="inactive" />
        </el-select>
      </div>
      <div class="search-right">
        <el-button @click="refreshServices">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <div class="service-grid">
      <div 
        v-for="service in services" 
        :key="service.id" 
        class="service-card"
      >
        <div class="card-header">
          <div class="service-info">
            <h3 class="service-name">{{ service.name }}</h3>
            <span class="service-type">{{ service.type }}</span>
          </div>
          <el-tag :type="service.status === 'active' ? 'success' : 'danger'" size="small">
            {{ service.status === 'active' ? '启用' : '禁用' }}
          </el-tag>
        </div>

        <div class="card-content">
          <div class="description">
            {{ service.description || '无描述信息' }}
          </div>
          
          <div class="service-stats">
            <div class="stat-item">
              <span class="label">地址:</span>
              <span class="value">{{ service.url }}</span>
            </div>
          </div>
          
          <div class="workflow-status">
            <div class="version">
              创建时间: {{ formatDate(service.created_at) }}
            </div>
            <div class="version">
              更新时间: {{ formatDate(service.updated_at) }}
            </div>
          </div>
        </div>

        <div class="card-actions">
          <el-button size="small" @click="viewService(service)">
            <el-icon><View /></el-icon>
            查看
          </el-button>
          <el-button size="small" @click="editService(service)">
            <el-icon><Edit /></el-icon>
            编辑
          </el-button>
          <el-button 
            size="small" 
            :type="service.status === 'active' ? 'warning' : 'success'"
            @click="toggleServiceStatus(service)"
          >
            <el-icon>{{ service.status === 'active' ? 'Close' : 'Check' }}</el-icon>
            {{ service.status === 'active' ? '禁用' : '启用' }}
          </el-button>
          <el-button size="small" type="danger" @click="deleteService(service)">
            <el-icon><Delete /></el-icon>
            删除
          </el-button>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="services.length === 0 && !loading" class="empty-state">
        <el-empty description="暂无MCP服务" />
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-state">
        <el-skeleton :rows="3" animated />
      </div>
    </div>

    <!-- 添加/编辑服务对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditing ? '编辑服务' : '添加服务'"
      width="500px"
    >
      <el-form :model="formData" label-width="80px">
        <el-form-item label="名称" required>
          <el-input v-model="formData.name" placeholder="请输入服务名称" />
        </el-form-item>
        <el-form-item label="类型" required>
          <el-select v-model="formData.type" placeholder="请选择服务类型">
            <el-option label="API服务" value="api" />
            <el-option label="数据库服务" value="database" />
            <el-option label="消息服务" value="message" />
            <el-option label="其他服务" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="地址" required>
          <el-input v-model="formData.url" placeholder="请输入服务地址" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入服务描述"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="formData.status" active-value="active" inactive-value="inactive" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveService">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

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

// 服务类型定义
interface MCPService {
  id: string
  name: string
  type: string
  url: string
  description: string
  status: 'active' | 'inactive'
  created_at: string
  updated_at: string
}

// 表单数据类型定义
interface FormData {
  id?: string
  name: string
  type: string
  url: string
  description: string
  status: 'active' | 'inactive'
}

// 响应式数据
const services = ref<MCPService[]>([])
const loading = ref(false)
const searchQuery = ref('')
const filterStatus = ref('')
const dialogVisible = ref(false)
const isEditing = ref(false)
const formData = ref<FormData>({
  name: '',
  type: 'api',
  url: '',
  description: '',
  status: 'active'
})

// 模拟数据
const mockServices: MCPService[] = [
  {
    id: '1',
    name: '用户认证服务',
    type: 'api',
    url: 'http://localhost:8001/auth',
    description: '处理用户认证和授权的服务',
    status: 'active',
    created_at: '2024-01-01T10:00:00Z',
    updated_at: '2024-01-01T10:00:00Z'
  },
  {
    id: '2',
    name: '数据存储服务',
    type: 'database',
    url: 'mongodb://localhost:27017/mcp',
    description: 'MCP系统的数据存储服务',
    status: 'active',
    created_at: '2024-01-02T14:30:00Z',
    updated_at: '2024-01-02T14:30:00Z'
  },
  {
    id: '3',
    name: '消息队列服务',
    type: 'message',
    url: 'amqp://localhost:5672',
    description: '处理系统消息的队列服务',
    status: 'inactive',
    created_at: '2024-01-03T09:15:00Z',
    updated_at: '2024-01-03T09:15:00Z'
  }
]

// 加载服务列表
const loadServices = () => {
  loading.value = true
  // 模拟API请求
  setTimeout(() => {
    services.value = mockServices
    loading.value = false
  }, 500)
}

// 刷新服务列表
const refreshServices = () => {
  loadServices()
}

// 添加服务
const addService = () => {
  isEditing.value = false
  formData.value = {
    name: '',
    type: 'api',
    url: '',
    description: '',
    status: 'active'
  }
  dialogVisible.value = true
}

// 编辑服务
const editService = (service: MCPService) => {
  isEditing.value = true
  formData.value = {
    id: service.id,
    name: service.name,
    type: service.type,
    url: service.url,
    description: service.description,
    status: service.status
  }
  dialogVisible.value = true
}

// 查看服务
const viewService = (service: MCPService) => {
  ElMessage.info(`查看服务: ${service.name}`)
  // 这里可以实现查看服务详情的逻辑
}

// 保存服务
const saveService = () => {
  // 表单验证
  if (!formData.value.name) {
    ElMessage.error('请输入服务名称')
    return
  }
  if (!formData.value.url) {
    ElMessage.error('请输入服务地址')
    return
  }

  // 模拟保存服务
  setTimeout(() => {
    if (isEditing.value) {
      // 编辑现有服务
      const index = services.value.findIndex(s => s.id === formData.value.id)
      if (index !== -1) {
        services.value[index] = {
          ...services.value[index],
          ...formData.value,
          updated_at: new Date().toISOString()
        }
      }
      ElMessage.success('服务更新成功')
    } else {
      // 添加新服务
      const newService: MCPService = {
        id: (services.value.length + 1).toString(),
        ...formData.value,
        created_at: new Date().toISOString(),
        updated_at: new Date().toISOString()
      }
      services.value.push(newService)
      ElMessage.success('服务添加成功')
    }
    dialogVisible.value = false
  }, 500)
}

// 切换服务状态
const toggleServiceStatus = (service: MCPService) => {
  const newStatus = service.status === 'active' ? 'inactive' : 'active'
  ElMessageBox.confirm(
    `确定要${newStatus === 'active' ? '启用' : '禁用'}服务"${service.name}"吗？`,
    '确认操作',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 模拟更新状态
    setTimeout(() => {
      const index = services.value.findIndex(s => s.id === service.id)
      if (index !== -1) {
        services.value[index].status = newStatus
        services.value[index].updated_at = new Date().toISOString()
      }
      ElMessage.success(`服务已${newStatus === 'active' ? '启用' : '禁用'}`)
    }, 300)
  }).catch(() => {
    // 用户取消操作
  })
}

// 删除服务
const deleteService = (service: MCPService) => {
  ElMessageBox.confirm(
    `确定要删除服务"${service.name}"吗？此操作不可恢复。`,
    '确认删除',
    {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'error'
    }
  ).then(() => {
    // 模拟删除服务
    setTimeout(() => {
      const index = services.value.findIndex(s => s.id === service.id)
      if (index !== -1) {
        services.value.splice(index, 1)
      }
      ElMessage.success('服务删除成功')
    }, 300)
  }).catch(() => {
    // 用户取消操作
  })
}

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 生命周期钩子
onMounted(() => {
  loadServices()
})
</script>

<style scoped>
.mcp-service-management {
  padding: 16px;
  background: #0f172a;
  height: 100vh;
  width: 100%;
  box-sizing: border-box;
  overflow-y: auto;
  overflow-x: hidden;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 20px;
  background: #1e293b;
  border: 1px solid #475569;
  border-radius: 6px;
  max-width: 100%;
}

.page-title {
  margin: 0;
  color: #f1f5f9;
  font-size: 24px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.search-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 20px;
  background: #1e293b;
  border: 1px solid #475569;
  border-radius: 6px;
  gap: 12px;
  flex-wrap: wrap;
}

.search-left {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.search-right {
  display: flex;
  align-items: center;
  gap: 8px;
}

.search-bar :deep(.el-input__inner) {
  background-color: #34495e;
  border-color: #4a5f7a;
  color: #e2e8f0;
  
  &:focus {
    background-color: #4a5f7a;
    border-color: #6366f1;
    box-shadow: 0 0 0 2px rgba(99, 102, 241, 0.2);
  }
}

.search-bar :deep(.el-input__prefix-icon) {
  color: #95a5a6;
}

.service-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 16px;
  margin-bottom: 16px;
  width: 100%;
}

.service-card {
  background: #1e293b;
  border: 1px solid #475569;
  border-radius: 6px;
  padding: 20px;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.service-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(99, 102, 241, 0.1), transparent);
  transition: left 0.5s ease;
}

.service-card:hover::before {
  left: 100%;
}

.service-card:hover {
  background: #334155;
  border-color: #6366f1;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(99, 102, 241, 0.15);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.service-info {
  flex: 1;
}

.service-name {
  font-size: 18px;
  font-weight: 600;
  margin: 0 0 4px 0;
  color: #f1f5f9;
  flex: 1;
  margin-right: 12px;
}

.service-type {
  font-size: 12px;
  color: #94a3b8;
  background: rgba(148, 163, 184, 0.1);
  padding: 2px 8px;
  border-radius: 4px;
}

.card-content {
  margin-bottom: 16px;
}

.description {
  color: #94a3b8;
  font-size: 14px;
  line-height: 1.6;
  margin: 0 0 12px 0;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.service-stats {
  margin-bottom: 12px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
  color: #94a3b8;
  font-size: 13px;
  font-weight: 500;
}

.stat-item .label {
  color: #cbd5e1;
  font-size: 12px;
}

.stat-item .value {
  color: #e2e8f0;
  font-size: 13px;
  word-break: break-all;
}

.workflow-status {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.version {
  color: #94a3b8;
  font-size: 13px;
  font-weight: 500;
  flex: 1;
}

.card-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
  flex-wrap: wrap;
}

.empty-state {
  grid-column: 1 / -1;
  text-align: center;
  padding: 60px 40px;
  color: #94a3b8;
  font-size: 16px;
  background: #1e293b;
  border: 1px solid #475569;
  border-radius: 6px;
  margin: 16px 0;
}

.loading-state {
  grid-column: 1 / -1;
  padding: 20px 40px;
  background: #1e293b;
  border: 1px solid #475569;
  border-radius: 6px;
  margin: 16px 0;
}

:deep(.el-button--primary) {
  background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%) !important;
  border-color: #6366f1 !important;
  color: white !important;
}

:deep(.el-button--primary:hover) {
  background: linear-gradient(135deg, #5855eb 0%, #7c3aed 100%) !important;
  border-color: #5855eb !important;
  transform: translateY(-1px) !important;
  box-shadow: 0 4px 12px rgba(99, 102, 241, 0.4) !important;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .mcp-service-management {
    padding: 12px;
  }
  
  .service-grid {
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 12px;
  }
  
  .header,
  .search-bar {
    padding: 16px;
  }
}

@media (max-width: 768px) {
  .mcp-service-management {
    padding: 8px;
  }
  
  .service-grid {
    grid-template-columns: 1fr;
    gap: 12px;
  }
  
  .header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .page-title {
    font-size: 20px;
  }
  
  .search-bar {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .service-card {
    padding: 16px;
  }
}
</style>