<template>
  <div class="container">
    <!-- 统计卡片 -->
    <a-row :gutter="16" class="stats-row">
      <a-col :xs="24" :sm="12" :lg="6">
        <a-card class="stats-card" :bordered="false">
          <div class="stats-content">
            <div class="stats-icon stats-icon-primary">
              <icon-eye />
            </div>
            <div class="stats-info">
              <div class="stats-title">监控总数</div>
              <div class="stats-value">{{ stats.total }}</div>
              <div class="stats-desc">活跃监控项目</div>
            </div>
          </div>
        </a-card>
      </a-col>
      <a-col :xs="24" :sm="12" :lg="6">
        <a-card class="stats-card" :bordered="false">
          <div class="stats-content">
            <div class="stats-icon stats-icon-success">
              <icon-check-circle-fill />
            </div>
            <div class="stats-info">
              <div class="stats-title">正常运行</div>
              <div class="stats-value">{{ stats.online }}</div>
              <div class="stats-desc">
                <a-tag color="green" size="small">{{ Math.round(stats.total > 0 ? (stats.online / stats.total) * 100 : 0) }}%</a-tag>
              </div>
            </div>
          </div>
        </a-card>
      </a-col>
      <a-col :xs="24" :sm="12" :lg="6">
        <a-card class="stats-card" :bordered="false">
          <div class="stats-content">
            <div class="stats-icon stats-icon-warning">
              <icon-exclamation-circle-fill />
            </div>
            <div class="stats-info">
              <div class="stats-title">今日告警</div>
              <div class="stats-value">{{ stats.today_alert_count }}</div>
              <div class="stats-desc">当日告警数</div>
            </div>
          </div>
        </a-card>
      </a-col>
      <a-col :xs="24" :sm="12" :lg="6">
        <a-card class="stats-card" :bordered="false">
          <div class="stats-content">
            <div class="stats-icon stats-icon-primary">
              <icon-clock-circle />
            </div>
            <div class="stats-info">
              <div class="stats-title">平均响应</div>
              <div class="stats-value">
                {{ Math.round(stats.avg_response_time_ms) }}
                <span class="stats-unit">ms</span>
              </div>
              <div class="stats-desc">全设备平均</div>
            </div>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <!-- 图表区域 -->
    <a-row :gutter="16" class="chart-row">
      <a-col :xs="24" :lg="12">
        <a-card title="响应时间趋势" :bordered="false">
          <template #extra>
            <a-space>
              <span class="legend-item">
                <span class="legend-dot legend-dot-1"></span>
                <span>平均</span>
              </span>
              <span class="legend-item">
                <span class="legend-dot legend-dot-2"></span>
                <span>P95</span>
              </span>
            </a-space>
          </template>
          <div class="chart-container">
            <Chart :options="responseTimeChartOptions" height="280px" />
          </div>
        </a-card>
      </a-col>
      <a-col :xs="24" :lg="12">
        <a-card title="可用性报告" :bordered="false">
          <template #extra>
            <span class="text-muted">本月可用性统计</span>
          </template>
          <div class="availability-list">
            <div v-for="item in availabilityData" :key="item.name" class="availability-item">
              <div class="availability-header">
                <span class="availability-name">{{ item.name }}</span>
                <span :class="['availability-value', `status-${item.status}`]">{{ item.uptime }}%</span>
              </div>
              <a-progress :percent="item.uptime" :status="item.progressStatus" :stroke-width="8" :show-text="false" />
            </div>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <!-- 监控列表 -->
    <a-card title="监控列表" :bordered="false">
      <a-table :data="tableData" :columns="columns" :loading="loading" :pagination="false" row-key="name">
        <template #status="{ record }">
          <a-tag :color="getStatusColor(record.status)" bordered>
            {{ getStatusText(record.status) }}
          </a-tag>
        </template>

        <template #url="{ record }">
          <a :href="record.target_url" target="_blank" class="url-link">
            {{ record.target_url }}
            <icon-launch class="link-icon" />
          </a>
        </template>

        <template #responseTime="{ record }">
          {{ record.response_time ? `${Math.round(record.response_time)}ms` : '-' }}
        </template>

        <template #uptime="{ record }">
          {{ record.status === 'online' ? '99.9%' : '-' }}
        </template>

        <template #lastCheck="{ record }">
          {{ formatLastCheckTime(record.last_check_time) }}
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { IconEye, IconCheckCircleFill, IconExclamationCircleFill, IconClockCircle, IconLaunch } from '@arco-design/web-vue/es/icon'
import Chart from '@/components/chart/index.vue'
import type { TableColumnData } from '@arco-design/web-vue/es/table/interface'
import {
  fetchUrlDeviceStatsOverview,
  fetchUrlDeviceResponseTimeTrend,
  fetchUrlDeviceStatusDistribution,
  fetchUrlDeviceList,
  type UrlDeviceItem,
  type UrlDeviceStatsOverview,
  type ResponseTimePoint,
  type StatusDistributionItem,
} from '@/api/ops/url-device'

/** 统计概览数据 */
const stats = ref<UrlDeviceStatsOverview>({
  total: 0,
  online: 0,
  today_alert_count: 0,
  avg_response_time_ms: 0,
})

/** 表格加载状态 */
const loading = ref(false)
/** 统计数据加载状态 */
const statsLoading = ref(false)
/** 图表加载状态 */
const chartLoading = ref(false)

/** 表格列配置 */
const columns: TableColumnData[] = [
  {
    title: '名称',
    dataIndex: 'name',
    width: 150,
  },
  {
    title: 'URL',
    dataIndex: 'url',
    slotName: 'url',
    width: 280,
  },
  {
    title: '状态',
    dataIndex: 'status',
    slotName: 'status',
    width: 100,
    align: 'center',
  },
  {
    title: '响应时间',
    dataIndex: 'responseTime',
    slotName: 'responseTime',
    width: 100,
    align: 'center',
  },
  {
    title: '可用率',
    dataIndex: 'uptime',
    slotName: 'uptime',
    width: 100,
    align: 'center',
  },
  {
    title: '最后检查',
    dataIndex: 'lastCheck',
    slotName: 'lastCheck',
    width: 120,
    align: 'center',
  },
]

/** 设备列表数据 */
const tableData = ref<UrlDeviceItem[]>([])

/** 可用性报告数据 */
const availabilityData = ref<{ name: string; uptime: number; status: string; progressStatus: 'success' | 'warning' | 'danger' }[]>([])

/** 响应时间趋势图表配置 */
const responseTimeChartOptions = ref({
  tooltip: {
    trigger: 'axis',
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true,
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: [] as string[],
  },
  yAxis: {
    type: 'value',
    name: 'ms',
  },
  series: [
    {
      name: '平均响应',
      type: 'line',
      smooth: true,
      data: [] as number[],
      areaStyle: {
        opacity: 0.1,
      },
      lineStyle: {
        width: 2,
        color: '#165DFF',
      },
      itemStyle: {
        color: '#165DFF',
      },
    },
  ],
})

/**
 * 获取状态对应的标签颜色
 * @param status - 设备状态
 * @returns Arco Design 标签颜色值
 */
const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    online: 'green',
    offline: 'red',
    error: 'orange',
  }
  return colorMap[status] || 'gray'
}

/**
 * 获取状态的中文显示文本
 * @param status - 设备状态
 * @returns 中文状态文本
 */
const getStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    online: '正常',
    offline: '离线',
    error: '错误',
  }
  return textMap[status] || status
}

/**
 * 格式化最后检查时间为相对时间
 * @param time - ISO 时间字符串
 * @returns 格式化后的相对时间文本（如"刚刚"、"5分钟前"）
 */
const formatLastCheckTime = (time: string | null) => {
  if (!time) return '-'
  const date = new Date(time)
  const now = new Date()
  const diffMs = now.getTime() - date.getTime()
  const diffMins = Math.floor(diffMs / 60000)
  if (diffMins < 1) return '刚刚'
  if (diffMins < 60) return `${diffMins}分钟前`
  const diffHours = Math.floor(diffMins / 60)
  if (diffHours < 24) return `${diffHours}小时前`
  return `${Math.floor(diffHours / 24)}天前`
}

/**
 * 获取统计概览数据
 */
const fetchStatsOverview = async () => {
  statsLoading.value = true
  try {
    const response: any = await fetchUrlDeviceStatsOverview()
    if (response && response.details) {
      stats.value = response.details
    }
  } catch (error) {
    console.error('获取统计概览失败:', error)
  } finally {
    statsLoading.value = false
  }
}

/**
 * 获取响应时间趋势数据并更新图表
 */
const fetchResponseTimeTrend = async () => {
  chartLoading.value = true
  try {
    const response: any = await fetchUrlDeviceResponseTimeTrend()
    console.log('response', response)
    if (response && response.details && response.details.points) {
      const points: ResponseTimePoint[] = response.details.points
      responseTimeChartOptions.value.xAxis.data = points.map((p) => {
        const date = new Date(p.hour)
        return `${String(date.getHours()).padStart(2, '0')}:00`
      })
      responseTimeChartOptions.value.series[0].data = points.map((p) => p.avg_response_time_ms)
    }
  } catch (error) {
    console.error('获取响应时间趋势失败:', error)
  } finally {
    chartLoading.value = false
  }
}

/**
 * 获取设备状态分布数据并更新可用性报告
 */
const fetchStatusDistribution = async () => {
  try {
    const response: any = await fetchUrlDeviceStatusDistribution()
    if (response && response.details && response.details.by_status) {
      const distribution: StatusDistributionItem[] = response.details.by_status
      const total = response.details.total || 0
      availabilityData.value = distribution.map((item) => {
        const uptime = total > 0 ? (item.status === 'online' ? 99.9 : item.status === 'error' ? 95 : 98) : 0
        const progressStatus = item.status === 'online' ? 'success' : item.status === 'error' ? 'danger' : 'warning'
        return {
          name: `${item.status} (${item.count})`,
          uptime,
          status: item.status,
          progressStatus,
        }
      })
    }
  } catch (error) {
    console.error('获取状态分布失败:', error)
  }
}

/**
 * 获取设备列表数据
 */
const fetchDeviceList = async () => {
  loading.value = true
  try {
    const response: any = await fetchUrlDeviceList({ page: 1, size: 100 })
    if (response && response.details) {
      tableData.value = response.details.data || []
    }
  } catch (error) {
    console.error('获取设备列表失败:', error)
  } finally {
    loading.value = false
  }
}

/**
 * 并行获取所有页面数据
 */
const fetchData = async () => {
  await Promise.all([fetchStatsOverview(), fetchResponseTimeTrend(), fetchStatusDistribution(), fetchDeviceList()])
}

/** 组件挂载时获取数据 */
onMounted(() => {
  fetchData()
})
</script>

<script lang="ts">
export default {
  name: 'URLMonitor',
}
</script>

<style scoped lang="less">
.container {
  padding: 16px;
}

.stats-row {
  margin-bottom: 16px;
}

.stats-card {
  height: 100%;

  :deep(.arco-card-body) {
    padding: 16px;
  }

  .stats-content {
    display: flex;
    align-items: flex-start;
    gap: 12px;
  }

  .stats-icon {
    width: 48px;
    height: 48px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24px;
    flex-shrink: 0;

    &.stats-icon-primary {
      background-color: rgba(var(--primary-1), 1);
      color: rgb(var(--primary-6));
    }

    &.stats-icon-success {
      background-color: rgba(var(--green-1), 1);
      color: rgb(var(--green-6));
    }

    &.stats-icon-warning {
      background-color: rgba(var(--orange-1), 1);
      color: rgb(var(--orange-6));
    }
  }

  .stats-info {
    flex: 1;
    min-width: 0;
  }

  .stats-title {
    font-size: 14px;
    color: var(--color-text-3);
    margin-bottom: 4px;
  }

  .stats-value {
    font-size: 24px;
    font-weight: 600;
    color: var(--color-text-1);
    line-height: 1.2;
  }

  .stats-unit {
    font-size: 14px;
    font-weight: normal;
    margin-left: 2px;
  }

  .stats-desc {
    margin-top: 4px;
    font-size: 12px;
    color: var(--color-text-3);
  }
}

.text-success {
  color: rgb(var(--success-6));
}

.text-muted {
  color: var(--color-text-3);
  font-size: 12px;
}

.chart-row {
  margin-bottom: 16px;

  .arco-card {
    height: 100%;
  }

  .chart-container {
    width: 100%;
    height: 280px;
  }
}

.legend-item {
  display: inline-flex;
  align-items: center;
  font-size: 12px;
  color: var(--color-text-3);
  margin-left: 16px;

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

    &.legend-dot-1 {
      background-color: #165dff;
    }

    &.legend-dot-2 {
      background-color: #ff7d00;
    }
  }
}

.availability-list {
  height: 280px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 8px 0;

  .availability-item {
    .availability-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 8px;

      .availability-name {
        font-size: 14px;
        color: var(--color-text-2);
      }

      .availability-value {
        font-size: 14px;
        font-weight: 500;

        &.status-success {
          color: rgb(var(--success-6));
        }

        &.status-warning {
          color: rgb(var(--warning-6));
        }

        &.status-error {
          color: rgb(var(--danger-6));
        }
      }
    }
  }
}

.url-link {
  color: rgb(var(--primary-6));
  text-decoration: none;
  display: inline-flex;
  align-items: center;
  gap: 4px;

  &:hover {
    text-decoration: underline;
  }

  .link-icon {
    font-size: 12px;
    opacity: 0;
    transition: opacity 0.2s;
  }

  &:hover .link-icon {
    opacity: 1;
  }
}
</style>
