<template>
  <div class="server-detail-page">
    <!-- 顶部导航栏 -->
    <div class="page-header">
      <div class="header-left">
        <a-button type="text" @click="goBack">
          <template #icon><icon-left /></template>
          返回
        </a-button>
        <a-divider direction="vertical" />
        <span class="server-name">{{ serverName }}</span>
        <a-tag :color="getStatusColor(serverStatus)" size="small">{{ getStatusText(serverStatus) }}</a-tag>
      </div>
      <div class="header-right">
        <a-button @click="handleRemoteControl">
          <template #icon><icon-desktop /></template>
          远程登录
        </a-button>
        <a-button type="primary" @click="handleRestart">
          <template #icon><icon-refresh /></template>
          重启
        </a-button>
      </div>
    </div>

    <!-- 主体内容 -->
    <div class="page-body">
      <a-tabs v-model:active-key="activeTab" class="detail-tabs">
        <a-tab-pane key="overview" title="实例详情">
          <a-descriptions :column="2" bordered class="info-descriptions">
            <a-descriptions-item label="唯一标识">{{ record.unique_id || '-' }}</a-descriptions-item>
            <a-descriptions-item label="服务器名称">{{ record.name || '-' }}</a-descriptions-item>
            <a-descriptions-item label="服务器类型">{{ getServerTypeText(record.server_type) }}</a-descriptions-item>
            <a-descriptions-item label="操作系统">{{ record.os || '-' }}</a-descriptions-item>
            <a-descriptions-item label="位置信息">{{ record.location || '-' }}</a-descriptions-item>
            <a-descriptions-item label="标签">{{ record.tags || '-' }}</a-descriptions-item>
            <a-descriptions-item label="IP地址">{{ record.ip || '-' }}</a-descriptions-item>
            <a-descriptions-item label="远程端口">{{ record.remote_port || '-' }}</a-descriptions-item>
            <a-descriptions-item label="Agent URL">{{ record.agent_url || '-' }}</a-descriptions-item>
            <a-descriptions-item label="数据采集">
              <a-tag :color="record.data_collection ? 'green' : 'gray'">
                {{ record.data_collection ? '已开启' : '未开启' }}
              </a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="采集间隔">
              {{ record.collection_interval ? `${record.collection_interval}分钟` : '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="备注信息" :span="2">{{ record.remark || '-' }}</a-descriptions-item>
          </a-descriptions>
        </a-tab-pane>

        <a-tab-pane key="monitor" title="监控">
          <div class="monitor-section">
            <div class="time-selector">
              <a-radio-group v-model="timeRange" type="button">
                <a-radio value="1h">1小时</a-radio>
                <a-radio value="3h">3小时</a-radio>
                <a-radio value="6h">6小时</a-radio>
                <a-radio value="12h">12小时</a-radio>
                <a-radio value="1d">1天</a-radio>
                <a-radio value="3d">3天</a-radio>
                <a-radio value="7d">7天</a-radio>
                <a-radio value="14d">14天</a-radio>
                <a-radio value="custom">自定义</a-radio>
              </a-radio-group>
            </div>

            <a-row :gutter="20" class="charts-row">
              <a-col :span="8" class="chart-col">
                <div class="chart-card">
                  <div class="chart-header">
                    <span class="chart-title">CPU使用率_宿主机视角 (%)</span>
                    <div class="chart-actions">
                      <a-select v-model="cpuMetric" size="small" style="width: 120px">
                        <a-option value="average">平均值</a-option>
                        <a-option value="max">最大值</a-option>
                        <a-option value="min">最小值</a-option>
                      </a-select>
                      <icon-settings />
                    </div>
                  </div>
                  <v-chart :option="cpuOption" class="chart" autoresize />
                  <div class="chart-legend">
                    <span class="legend-item">
                      <span class="legend-dot green"></span>
                      (ECS)CPU使用率_平均值
                    </span>
                    <span class="legend-item">
                      <span class="legend-dot blue"></span>
                      (ECS)CPU使用率_最小值
                    </span>
                    <span class="legend-item">
                      <span class="legend-dot purple"></span>
                      (ECS)CPU使用率_最大值
                    </span>
                  </div>
                </div>
              </a-col>

              <a-col :span="8" class="chart-col">
                <div class="chart-card">
                  <div class="chart-header">
                    <span class="chart-title">总带宽 (bit/s)</span>
                    <div class="chart-actions">
                      <a-select v-model="bandwidthMetric" size="small" style="width: 120px">
                        <a-option value="average">平均值</a-option>
                        <a-option value="max">最大值</a-option>
                      </a-select>
                      <icon-settings />
                    </div>
                  </div>
                  <v-chart :option="bandwidthOption" class="chart" autoresize />
                  <div class="chart-legend">
                    <span class="legend-item">
                      <span class="legend-dot green"></span>
                      内网流入带宽
                    </span>
                    <span class="legend-item">
                      <span class="legend-dot blue"></span>
                      内网流出带宽
                    </span>
                  </div>
                </div>
              </a-col>

              <a-col :span="8" class="chart-col">
                <div class="chart-card">
                  <div class="chart-header">
                    <span class="chart-title">公网带宽 (bit/s)</span>
                    <div class="chart-actions">
                      <a-select v-model="publicBandwidthMetric" size="small" style="width: 120px">
                        <a-option value="average">平均值</a-option>
                        <a-option value="max">最大值</a-option>
                      </a-select>
                      <icon-settings />
                    </div>
                  </div>
                  <v-chart :option="publicBandwidthOption" class="chart" autoresize />
                  <div class="chart-legend">
                    <span class="legend-item">
                      <span class="legend-dot blue"></span>
                      公网流入带宽
                    </span>
                    <span class="legend-item">
                      <span class="legend-dot green"></span>
                      公网流出带宽
                    </span>
                  </div>
                </div>
              </a-col>
            </a-row>

            <a-row :gutter="20" class="charts-row">
              <a-col :span="8" class="chart-col">
                <div class="chart-card">
                  <div class="chart-header">
                    <span class="chart-title">公网流出带宽使用率 (%)</span>
                    <div class="chart-actions">
                      <a-select v-model="bandwidthUsageMetric" size="small" style="width: 120px">
                        <a-option value="average">平均值</a-option>
                        <a-option value="max">最大值</a-option>
                      </a-select>
                      <icon-settings />
                    </div>
                  </div>
                  <v-chart :option="bandwidthUsageOption" class="chart" autoresize />
                  <div class="chart-legend">
                    <span class="legend-item">
                      <span class="legend-dot blue"></span>
                      (ECS)公网流出带宽使用率
                    </span>
                  </div>
                </div>
              </a-col>

              <a-col :span="8" class="chart-col">
                <div class="chart-card">
                  <div class="chart-header">
                    <span class="chart-title">磁盘读取写入BPS (bytes/s)</span>
                    <div class="chart-actions">
                      <a-select v-model="diskMetric" size="small" style="width: 120px">
                        <a-option value="average">平均值</a-option>
                        <a-option value="max">最大值</a-option>
                      </a-select>
                      <icon-settings />
                    </div>
                  </div>
                  <v-chart :option="diskBpsOption" class="chart" autoresize />
                  <div class="chart-legend">
                    <span class="legend-item">
                      <span class="legend-dot blue"></span>
                      (ECS)所有磁盘读取BPS
                    </span>
                    <span class="legend-item">
                      <span class="legend-dot green"></span>
                      (ECS)所有磁盘写入BPS
                    </span>
                  </div>
                </div>
              </a-col>

              <a-col :span="8" class="chart-col">
                <div class="chart-card">
                  <div class="chart-header">
                    <span class="chart-title">磁盘读取写入IOPS (Count/Second)</span>
                    <div class="chart-actions">
                      <a-select v-model="diskIopsMetric" size="small" style="width: 120px">
                        <a-option value="average">平均值</a-option>
                        <a-option value="max">最大值</a-option>
                      </a-select>
                      <icon-settings />
                    </div>
                  </div>
                  <v-chart :option="diskIopsOption" class="chart" autoresize />
                  <div class="chart-legend">
                    <span class="legend-item">
                      <span class="legend-dot blue"></span>
                      (ECS)所有磁盘每秒读取次数
                    </span>
                    <span class="legend-item">
                      <span class="legend-dot green"></span>
                      (ECS)所有磁盘每秒写入次数
                    </span>
                  </div>
                </div>
              </a-col>
            </a-row>

            <a-row :gutter="20" class="charts-row">
              <a-col :span="8" class="chart-col">
                <div class="chart-card">
                  <div class="chart-header">
                    <span class="chart-title">同时连接数 (Count)</span>
                    <div class="chart-actions">
                      <a-select v-model="connectionMetric" size="small" style="width: 120px">
                        <a-option value="average">平均值</a-option>
                        <a-option value="max">最大值</a-option>
                      </a-select>
                      <icon-settings />
                    </div>
                  </div>
                  <v-chart :option="connectionOption" class="chart" autoresize />
                  <div class="chart-legend">
                    <span class="legend-item">
                      <span class="legend-dot blue"></span>
                      同时连接数
                    </span>
                  </div>
                </div>
              </a-col>

              <a-col :span="8" class="chart-col">
                <div class="chart-card">
                  <div class="chart-header">
                    <span class="chart-title">RDMA流量使用信息 (bit/s)</span>
                    <div class="chart-actions">
                      <a-select v-model="rdmaMetric" size="small" style="width: 120px">
                        <a-option value="average">平均值</a-option>
                        <a-option value="max">最大值</a-option>
                      </a-select>
                      <icon-settings />
                    </div>
                  </div>
                  <v-chart :option="rdmaOption" class="chart" autoresize />
                  <div class="chart-legend">
                    <span class="legend-item"></span>
                  </div>
                </div>
              </a-col>

              <a-col :span="8" class="chart-col">
                <div class="chart-card">
                  <div class="chart-header">
                    <span class="chart-title">RDMA资源使用信息 (Count)</span>
                    <div class="chart-actions">
                      <a-select v-model="rdmaResourceMetric" size="small" style="width: 120px">
                        <a-option value="average">平均值</a-option>
                        <a-option value="max">最大值</a-option>
                      </a-select>
                      <icon-settings />
                    </div>
                  </div>
                  <v-chart :option="rdmaResourceOption" class="chart" autoresize />
                  <div class="chart-legend">
                    <span class="legend-item"></span>
                  </div>
                </div>
              </a-col>
            </a-row>
          </div>
        </a-tab-pane>

        <a-tab-pane key="operation" title="操作记录">
          <div class="operation-records">
            <a-empty description="暂无操作记录" />
          </div>
        </a-tab-pane>
      </a-tabs>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Message, Modal } from '@arco-design/web-vue'
import { IconLeft, IconDesktop, IconRefresh, IconSettings } from '@arco-design/web-vue/es/icon'
import VChart from 'vue-echarts'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart } from 'echarts/charts'
import { TitleComponent, TooltipComponent, LegendComponent, GridComponent, DataZoomComponent } from 'echarts/components'

use([CanvasRenderer, LineChart, TitleComponent, TooltipComponent, LegendComponent, GridComponent, DataZoomComponent])

const route = useRoute()
const router = useRouter()

// 服务器信息
const serverId = computed(() => route.query.id as string)
const serverName = computed(() => (route.query.name as string) || '服务器详情')
const serverStatus = computed(() => (route.query.status as string) || 'offline')

// 模拟从API获取数据
const record = ref<any>({
  id: serverId.value,
  name: (route.query.name as string) || '服务器详情',
  status: (route.query.status as string) || 'offline',
  server_type: 'physical',
  os: 'CentOS 7.9',
  unique_id: `SERVER-${serverId.value}`,
  location: '机房A-机柜01',
  tags: '生产环境,核心服务',
  ip: (route.query.ip as string) || '-',
  remote_port: 22,
  agent_url: 'http://192.168.1.100:8080',
  data_collection: true,
  collection_interval: 5,
  remark: '核心业务服务器',
})

const activeTab = ref('overview')
const timeRange = ref('1h')
const cpuMetric = ref('average')
const bandwidthMetric = ref('average')
const publicBandwidthMetric = ref('average')
const bandwidthUsageMetric = ref('average')
const diskMetric = ref('average')
const diskIopsMetric = ref('average')
const connectionMetric = ref('average')
const rdmaMetric = ref('average')
const rdmaResourceMetric = ref('average')

const generateTimeData = (count: number) => {
  const now = Date.now()
  const data = []
  for (let i = count - 1; i >= 0; i--) {
    data.push(new Date(now - i * 60000).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }))
  }
  return data
}

const generateRandomData = (count: number, min: number, max: number) => {
  return Array.from({ length: count }, () => Math.floor(Math.random() * (max - min + 1)) + min)
}

const timeData = generateTimeData(60)

const baseOption = {
  tooltip: {
    trigger: 'axis',
    backgroundColor: 'rgba(255,255,255,0.95)',
    borderColor: '#e5e6eb',
    textStyle: {
      color: '#1d2129',
    },
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true,
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: timeData,
    axisLabel: {
      fontSize: 10,
    },
  },
  yAxis: {
    type: 'value',
    axisLabel: {
      fontSize: 10,
    },
  },
  dataZoom: [
    {
      type: 'inside',
      start: 0,
      end: 100,
    },
  ],
}

const cpuOption = computed(() => ({
  ...baseOption,
  series: [
    {
      name: '平均值',
      type: 'line',
      smooth: true,
      data: generateRandomData(60, 20, 80),
      lineStyle: { color: '#00b42a' },
      itemStyle: { color: '#00b42a' },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: 'rgba(0, 180, 42, 0.3)' },
            { offset: 1, color: 'rgba(0, 180, 42, 0.05)' },
          ],
        },
      },
    },
    {
      name: '最小值',
      type: 'line',
      smooth: true,
      data: generateRandomData(60, 10, 40),
      lineStyle: { color: '#165dff' },
      itemStyle: { color: '#165dff' },
    },
    {
      name: '最大值',
      type: 'line',
      smooth: true,
      data: generateRandomData(60, 50, 95),
      lineStyle: { color: '#722ed1' },
      itemStyle: { color: '#722ed1' },
    },
  ],
}))

const bandwidthOption = computed(() => ({
  ...baseOption,
  series: [
    {
      name: '内网流入带宽',
      type: 'line',
      smooth: true,
      data: generateRandomData(60, 100000, 500000),
      lineStyle: { color: '#00b42a' },
      itemStyle: { color: '#00b42a' },
    },
    {
      name: '内网流出带宽',
      type: 'line',
      smooth: true,
      data: generateRandomData(60, 50000, 300000),
      lineStyle: { color: '#165dff' },
      itemStyle: { color: '#165dff' },
    },
  ],
}))

const publicBandwidthOption = computed(() => ({
  ...baseOption,
  series: [
    {
      name: '公网流入带宽',
      type: 'line',
      smooth: true,
      data: generateRandomData(60, 50000, 200000),
      lineStyle: { color: '#165dff' },
      itemStyle: { color: '#165dff' },
    },
    {
      name: '公网流出带宽',
      type: 'line',
      smooth: true,
      data: generateRandomData(60, 30000, 150000),
      lineStyle: { color: '#00b42a' },
      itemStyle: { color: '#00b42a' },
    },
  ],
}))

const bandwidthUsageOption = computed(() => ({
  ...baseOption,
  series: [
    {
      name: '公网流出带宽使用率',
      type: 'line',
      smooth: true,
      data: generateRandomData(60, 5, 30),
      lineStyle: { color: '#165dff' },
      itemStyle: { color: '#165dff' },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: 'rgba(22, 93, 255, 0.3)' },
            { offset: 1, color: 'rgba(22, 93, 255, 0.05)' },
          ],
        },
      },
    },
  ],
}))

const diskBpsOption = computed(() => ({
  ...baseOption,
  series: [
    {
      name: '磁盘读取BPS',
      type: 'line',
      smooth: true,
      data: generateRandomData(60, 10000, 100000),
      lineStyle: { color: '#165dff' },
      itemStyle: { color: '#165dff' },
    },
    {
      name: '磁盘写入BPS',
      type: 'line',
      smooth: true,
      data: generateRandomData(60, 20000, 150000),
      lineStyle: { color: '#00b42a' },
      itemStyle: { color: '#00b42a' },
    },
  ],
}))

const diskIopsOption = computed(() => ({
  ...baseOption,
  series: [
    {
      name: '磁盘读取IOPS',
      type: 'line',
      smooth: true,
      data: generateRandomData(60, 50, 500),
      lineStyle: { color: '#165dff' },
      itemStyle: { color: '#165dff' },
    },
    {
      name: '磁盘写入IOPS',
      type: 'line',
      smooth: true,
      data: generateRandomData(60, 100, 800),
      lineStyle: { color: '#00b42a' },
      itemStyle: { color: '#00b42a' },
    },
  ],
}))

const connectionOption = computed(() => ({
  ...baseOption,
  series: [
    {
      name: '同时连接数',
      type: 'line',
      smooth: true,
      data: generateRandomData(60, 100, 500),
      lineStyle: { color: '#165dff' },
      itemStyle: { color: '#165dff' },
    },
  ],
}))

const rdmaOption = computed(() => ({
  ...baseOption,
  series: [],
}))

const rdmaResourceOption = computed(() => ({
  ...baseOption,
  series: [],
}))

const getStatusColor = (status?: string) => {
  const colorMap: Record<string, string> = {
    online: 'green',
    offline: 'red',
    maintenance: 'orange',
    retired: 'gray',
  }
  return colorMap[status || ''] || 'gray'
}

const getStatusText = (status?: string) => {
  const textMap: Record<string, string> = {
    online: '在线',
    offline: '离线',
    maintenance: '维护中',
    retired: '已退役',
  }
  return textMap[status || ''] || '-'
}

const getServerTypeText = (type?: string) => {
  const typeMap: Record<string, string> = {
    physical: '物理服务器',
    virtual: '虚拟服务器',
    cloud: '云服务器',
  }
  return typeMap[type || ''] || '-'
}

const handleRemoteControl = () => {
  router.push({
    path: '/dc/remote',
    query: {
      id: record.value.id,
      name: record.value.name,
      ip: record.value.ip,
      status: record.value.status,
    },
  })
}

const handleRestart = () => {
  Modal.confirm({
    title: '确认重启',
    content: `确认重启服务器 ${record.value.name} 吗？`,
    onOk: () => {
      Message.info('正在发送重启指令...')
    },
  })
}

const goBack = () => {
  router.back()
}
</script>

<style scoped lang="less">
.server-detail-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f0f2f5;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 24px;
    background: #fff;
    border-bottom: 1px solid #e5e6eb;

    .header-left {
      display: flex;
      align-items: center;
      gap: 12px;

      .server-name {
        font-size: 16px;
        font-weight: 500;
      }
    }

    .header-right {
      display: flex;
      gap: 12px;
    }
  }

  .page-body {
    flex: 1;
    overflow: auto;
    padding: 16px;

    .detail-tabs {
      background: #fff;
      border-radius: 4px;
      padding: 20px;

      :deep(.arco-tabs-header) {
        margin-bottom: 20px;
      }
    }
  }
}

.info-descriptions {
  :deep(.arco-descriptions-item-label) {
    width: 140px;
    background: #f7f8fa;
  }
}

.monitor-section {
  .time-selector {
    margin-bottom: 20px;
  }

  .charts-row {
    margin-bottom: 20px;
  }

  .chart-col {
    margin-bottom: 20px;
  }

  .chart-card {
    background: #fff;
    border-radius: 4px;
    padding: 16px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);

    .chart-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12px;

      .chart-title {
        font-size: 14px;
        font-weight: 500;
        color: #1d2129;
      }

      .chart-actions {
        display: flex;
        align-items: center;
        gap: 8px;
      }
    }

    .chart {
      height: 200px;
    }

    .chart-legend {
      margin-top: 12px;
      display: flex;
      flex-wrap: wrap;
      gap: 16px;

      .legend-item {
        display: flex;
        align-items: center;
        gap: 6px;
        font-size: 12px;
        color: #4e5969;

        .legend-dot {
          width: 8px;
          height: 8px;
          border-radius: 50%;

          &.green {
            background: #00b42a;
          }

          &.blue {
            background: #165dff;
          }

          &.purple {
            background: #722ed1;
          }
        }
      }
    }
  }
}

.operation-records {
  padding: 40px 0;
}
</style>
