<template>
  <div ref="wrapperRef" class="maintain-kb-wrapper bg absolute top-0 left-0 size-full z-10">
    <div class="mx-a overflow-hidden" :style="targetWrapperStyle">
      <div class="maintain-kb-screen bg" :style="targetAreaStyle">
        <header class="header">维修统计</header>

        <main class="maintain-kb-content">
          <section class="summary-grid">
            <button class="summary-card stat-card" type="button">
              <span class="stat-icon-wrapper">
                <Icon icon="ep:data-line" class="stat-icon" />
              </span>
              <span class="stat-title">MTTR</span>
              <strong class="stat-value">{{ statsData.productCategoryCount }}</strong>
              <span class="stat-label">平均解决时间</span>
            </button>

            <button class="summary-card stat-card" type="button">
              <span class="stat-icon-wrapper">
                <Icon icon="ep:trend-charts" class="stat-icon" />
              </span>
              <span class="stat-title">近一周工单数量</span>
              <span class="stat-pair">
                <span>
                  <em>故障上报</em>
                  <strong>{{ week.failureWeek }}</strong>
                </span>
                <span>
                  <em>维修工单</em>
                  <strong>{{ week.maintainWeek }}</strong>
                </span>
              </span>
            </button>

            <button class="summary-card stat-card" type="button">
              <span class="stat-icon-wrapper">
                <Icon icon="ep:calendar" class="stat-icon" />
              </span>
              <span class="stat-title">近一月工单数量</span>
              <span class="stat-pair">
                <span>
                  <em>故障上报</em>
                  <strong>{{ month.failureMonth }}</strong>
                </span>
                <span>
                  <em>维修工单</em>
                  <strong>{{ month.maintainMonth }}</strong>
                </span>
              </span>
            </button>

            <button class="summary-card stat-card" type="button">
              <span class="stat-icon-wrapper">
                <Icon icon="ep:pie-chart" class="stat-icon" />
              </span>
              <span class="stat-title">工单总数量</span>
              <span class="stat-pair">
                <span>
                  <em>故障上报</em>
                  <strong>{{ total.failureTotal }}</strong>
                </span>
                <span>
                  <em>维修工单</em>
                  <strong>{{ total.maintainTotal }}</strong>
                </span>
              </span>
            </button>
          </section>

          <section class="status-grid">
            <el-card class="panel chart-panel" shadow="never">
              <div class="panel-title">
                <div class="icon-decorator">
                  <span></span>
                  <span></span>
                </div>
                故障上报状态统计
              </div>
              <div class="gauge-grid gauge-grid--failure">
                <div class="chart-item">
                  <div ref="reportingChartRef" class="gauge-chart"></div>
                  <div class="chart-label">
                    <span class="label-dot label-dot-blue"></span>
                    <span class="label-text">上报中</span>
                  </div>
                </div>
                <div class="chart-item">
                  <div ref="dealFinishedChartRef" class="gauge-chart"></div>
                  <div class="chart-label">
                    <span class="label-dot label-dot-orange"></span>
                    <span class="label-text">处理完成</span>
                  </div>
                </div>
                <div class="chart-item">
                  <div ref="transOrderChartRef" class="gauge-chart"></div>
                  <div class="chart-label">
                    <span class="label-dot label-dot-purple"></span>
                    <span class="label-text">转工单</span>
                  </div>
                </div>
                <div class="chart-item">
                  <div ref="orderFinishChartRef" class="gauge-chart"></div>
                  <div class="chart-label">
                    <span class="label-dot label-dot-cyan"></span>
                    <span class="label-text">工单处理完成</span>
                  </div>
                </div>
              </div>
            </el-card>

            <el-card class="panel chart-panel" shadow="never">
              <div class="panel-title">
                <div class="icon-decorator">
                  <span></span>
                  <span></span>
                </div>
                维修工单状态统计
              </div>
              <div class="gauge-grid gauge-grid--maintain">
                <div class="chart-item">
                  <div ref="writeChartRef" class="gauge-chart"></div>
                  <div class="chart-label">
                    <span class="label-dot label-dot-indigo"></span>
                    <span class="label-text">待填写</span>
                  </div>
                </div>
                <div class="chart-item">
                  <div ref="finishedChartRef" class="gauge-chart"></div>
                  <div class="chart-label">
                    <span class="label-dot label-dot-emerald"></span>
                    <span class="label-text">已完成</span>
                  </div>
                </div>
              </div>
            </el-card>
          </section>

          <section class="trend-section">
            <el-card class="panel trend-panel" shadow="never">
              <div class="panel-title">
                <div class="icon-decorator">
                  <span></span>
                  <span></span>
                </div>
                近一年数量统计
              </div>
              <div ref="chartContainer" class="bar-chart-container"></div>
            </el-card>
          </section>
        </main>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts" name="Index">
import * as echarts from 'echarts/core'
import { BarChart } from 'echarts/charts' // 显式导入柱状图模块

import {
  GridComponent,
  LegendComponent,
  TitleComponent,
  ToolboxComponent,
  TooltipComponent
} from 'echarts/components'
import { GaugeChart, LineChart, PieChart } from 'echarts/charts'
import { LabelLayout, UniversalTransition } from 'echarts/features'
import { CanvasRenderer } from 'echarts/renderers'
import {
  IotStatisticsDeviceMessageSummaryRespVO,
  IotStatisticsSummaryRespVO
} from '@/api/iot/statistics'
import { formatDate } from '@/utils/formatTime'
import { IotStatApi } from '@/api/pms/stat'
import { DESIGN_HEIGHT, DESIGN_WIDTH } from '@/utils/kb'

// TODO @super：参考下 /Users/yunai/Java/yudao-ui-admin-vue3/src/views/mall/home/index.vue，拆一拆组件

/** IoT 首页 */
defineOptions({ name: 'IoTHome' })

// TODO @super：使用下 Echart 组件，参考 yudao-ui-admin-vue3/src/views/mall/home/components/TradeTrendCard.vue 等
echarts.use([
  TooltipComponent,
  LegendComponent,
  PieChart,
  CanvasRenderer,
  LabelLayout,
  TitleComponent,
  ToolboxComponent,
  GridComponent,
  LineChart,
  UniversalTransition,
  GaugeChart,
  BarChart
])

const timeRange = ref('7d') // 修改默认选择为近一周
const dateRange = ref<[Date, Date] | null>(null)

const queryParams = reactive({
  startTime: Date.now() - 7 * 24 * 60 * 60 * 1000, // 设置默认开始时间为 7 天前
  endTime: Date.now() // 设置默认结束时间为当前时间
})
const wrapperRef = ref<HTMLDivElement>()
const scale = ref(1)

let resizeObserver: ResizeObserver | null = null
let resizeRaf = 0

const targetWrapperStyle = computed(() => ({
  width: `${DESIGN_WIDTH * scale.value}px`,
  height: `${DESIGN_HEIGHT * scale.value}px`
}))

const targetAreaStyle = computed(() => ({
  '--kb-scale': scale.value,
  width: `${DESIGN_WIDTH * scale.value}px`,
  height: `${DESIGN_HEIGHT * scale.value}px`
}))

function updateScale() {
  cancelAnimationFrame(resizeRaf)

  resizeRaf = requestAnimationFrame(() => {
    const wrapper = wrapperRef.value
    if (!wrapper) return

    const { clientWidth, clientHeight } = wrapper
    if (!clientWidth || !clientHeight) return

    scale.value = Math.min(clientWidth / DESIGN_WIDTH, clientHeight / DESIGN_HEIGHT)
    nextTick(handleResize)
  })
}

// const deviceCountChartRef = ref() // 设备数量统计的图表
const reportingChartRef = ref() // 在线设备统计的图表
const dealFinishedChartRef = ref() // 离线设备统计的图表
const transOrderChartRef = ref() // 待激活设备统计的图表
const orderFinishChartRef = ref()
const deviceMessageCountChartRef = ref() // 上下行消息量统计的图表
const writeChartRef = ref() // 上下行消息量统计的图表
const finishedChartRef = ref() // 上下行消息量统计的图表
const chartInstances: echarts.ECharts[] = []

// 基础统计数据
// TODO @super：初始为 -1，然后界面展示先是加载中？试试用 cursor 改哈
const statsData = ref<IotStatisticsSummaryRespVO>({
  productCategoryCount: 0,
  productCount: 0,
  deviceCount: 0,
  deviceMessageCount: 0,
  productCategoryTodayCount: 0,
  productTodayCount: 0,
  deviceTodayCount: 0,
  deviceMessageTodayCount: 0,
  deviceOnlineCount: 0,
  deviceOfflineCount: 0,
  deviceInactiveCount: 0,
  productCategoryDeviceCounts: {}
})

const day = ref({
  failureDay: undefined,
  maintainDay: undefined
})
const week = ref({
  failureWeek: undefined,
  maintainWeek: undefined
})
const month = ref({
  failureMonth: undefined,
  maintainMonth: undefined
})
const total = ref({
  failureTotal: undefined,
  maintainTotal: undefined
})

const status = ref({
  failureStatus: {
    reporting: 0,
    trans: 0,
    finished: 0,
    orderFinished: 0
  },
  maintainStatus: {
    finished: 0,
    todo: 0
  }
})
// 消息统计数据
const messageStats = ref<IotStatisticsDeviceMessageSummaryRespVO>({
  upstreamCounts: {},
  downstreamCounts: {}
})

/** 处理快捷时间范围选择 */
const handleTimeRangeChange = (timeRange: string) => {
  const now = Date.now()
  let startTime: number

  // TODO @super：这个的计算，看看能不能结合 dayjs 简化。因为 1h、24h、7d 感觉是比较标准的。如果没有，抽到 utils/formatTime.ts 作为一个工具方法
  switch (timeRange) {
    case '1h':
      startTime = now - 60 * 60 * 1000
      break
    case '24h':
      startTime = now - 24 * 60 * 60 * 1000
      break
    case '7d':
      startTime = now - 7 * 24 * 60 * 60 * 1000
      break
    default:
      return
  }

  // 清空日期选择器
  dateRange.value = null

  // 更新查询参数
  queryParams.startTime = startTime
  queryParams.endTime = now

  // 重新获取数据
  getStats()
}

/** 处理自定义日期范围选择 */
const handleDateRangeChange = (value: [Date, Date] | null) => {
  if (value) {
    // 清空快捷选项
    timeRange.value = ''

    // 更新查询参数
    queryParams.startTime = value[0].getTime()
    queryParams.endTime = value[1].getTime()

    // 重新获取数据
    getStats()
  }
}

/** 获取统计数据 */
const getStats = async () => {
  // 获取基础统计数据
  IotStatApi.getMainDay().then((res) => {
    day.value = res
  })
  IotStatApi.getMainWeek().then((res) => {
    week.value = res
  })
  IotStatApi.getMainMonth().then((res) => {
    month.value = res
  })
  IotStatApi.getMainTotal().then((res) => {
    total.value = res
  })
  IotStatApi.getMainStatus().then((res) => {
    status.value = res
    initCharts()
  })
  // statsData.value = await ProductCategoryApi.getIotStatisticsSummary()

  //
  // // 获取消息统计数据
  // messageStats.value = await ProductCategoryApi.getIotStatisticsDeviceMessageSummary(queryParams)

  // 初始化图表
}

/** 初始化图表 */
const initCharts = () => {
  disposeChartInstances()
  // 设备数量统计
  // echarts.init(deviceCountChartRef.value).setOption({
  //   tooltip: {
  //     trigger: 'item'
  //   },
  //   legend: {
  //     top: '5%',
  //     right: '10%',
  //     align: 'left',
  //     orient: 'vertical',
  //     icon: 'circle'
  //   },
  //   series: [
  //     {
  //       name: 'Access From',
  //       type: 'pie',
  //       radius: ['50%', '80%'],
  //       avoidLabelOverlap: false,
  //       center: ['30%', '50%'],
  //       label: {
  //         show: false,
  //         position: 'outside'
  //       },
  //       emphasis: {
  //         label: {
  //           show: true,
  //           fontSize: 20,
  //           fontWeight: 'bold'
  //         }
  //       },
  //       labelLine: {
  //         show: false
  //       },
  //       data: Object.entries(statsData.value.productCategoryDeviceCounts).map(([name, value]) => ({
  //         name,
  //         value
  //       }))
  //     }
  //   ]
  // })

  // 上报中
  initGaugeChart(
    reportingChartRef.value,
    status.value.failureStatus.reporting === undefined ? 0 : status.value.failureStatus.reporting,
    '#0d9'
  )
  // 处理完成
  initGaugeChart(
    dealFinishedChartRef.value,
    status.value.failureStatus.finished === undefined ? 0 : status.value.failureStatus.finished,
    '#f50'
  )
  // 转工单
  initGaugeChart(
    transOrderChartRef.value,
    status.value.failureStatus.trans === undefined ? 0 : status.value.failureStatus.trans,
    '#05b'
  )
  // 工单完成
  initGaugeChart(
    orderFinishChartRef.value,
    status.value.failureStatus.orderFinished === undefined
      ? 0
      : status.value.failureStatus.orderFinished,
    '#05b'
  )
  // 待填写
  initGaugeChart(
    writeChartRef.value,
    status.value.maintainStatus.todo === undefined ? 0 : status.value.maintainStatus.todo,
    '#05b'
  )
  //已完成
  initGaugeChart(
    finishedChartRef.value,
    status.value.maintainStatus.finished === undefined ? 0 : status.value.maintainStatus.finished,
    '#05b'
  )
  // 消息量统计
  //initMessageChart()
}

/** 初始化仪表盘图表 */
const initGaugeChart = (el: any, value: number, color: string) => {
  if (!el) return

  const chart = echarts.init(el)
  chartInstances.push(chart)
  chart.setOption({
    series: [
      {
        type: 'gauge',
        startAngle: 360,
        endAngle: 0,
        min: 0,
        max: statsData.value.deviceCount || 100, // 使用设备总数作为最大值
        progress: {
          show: true,
          width: 12,
          itemStyle: {
            color: color
          }
        },
        axisLine: {
          lineStyle: {
            width: 12,
            color: [[1, '#E5E7EB']]
          }
        },
        axisTick: { show: false },
        splitLine: { show: false },
        axisLabel: { show: false },
        pointer: { show: false },
        anchor: { show: false },
        title: { show: false },
        detail: {
          valueAnimation: true,
          fontSize: 24,
          fontWeight: 'bold',
          fontFamily: 'Inter, sans-serif',
          color: color,
          offsetCenter: [0, '0'],
          formatter: (value: number) => {
            return `${value} `
          }
        },
        data: [{ value: value }]
      }
    ]
  })
}

/** 初始化消息统计图表 */
const initMessageChart = () => {
  // 获取所有时间戳并排序
  // TODO @super：一些 idea 里的红色报错，要去处理掉噢。
  const timestamps = Array.from(
    new Set([
      ...messageStats.value.upstreamCounts.map((item) => Number(Object.keys(item)[0])),
      ...messageStats.value.downstreamCounts.map((item) => Number(Object.keys(item)[0]))
    ])
  ).sort((a, b) => a - b) // 确保时间戳从小到大排序

  // 准备数据
  const xdata = timestamps.map((ts) => formatDate(ts, 'YYYY-MM-DD HH:mm'))
  const upData = timestamps.map((ts) => {
    const item = messageStats.value.upstreamCounts.find(
      (count) => Number(Object.keys(count)[0]) === ts
    )
    return item ? Object.values(item)[0] : 0
  })
  const downData = timestamps.map((ts) => {
    const item = messageStats.value.downstreamCounts.find(
      (count) => Number(Object.keys(count)[0]) === ts
    )
    return item ? Object.values(item)[0] : 0
  })

  // 配置图表
  echarts.init(deviceMessageCountChartRef.value).setOption({
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(255, 255, 255, 0.9)',
      borderColor: '#E5E7EB',
      textStyle: {
        color: '#374151'
      }
    },
    legend: {
      data: ['上行消息量', '下行消息量'],
      textStyle: {
        color: '#374151',
        fontWeight: 500
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: xdata,
      axisLine: {
        lineStyle: {
          color: '#E5E7EB'
        }
      },
      axisLabel: {
        color: '#6B7280'
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        lineStyle: {
          color: '#E5E7EB'
        }
      },
      axisLabel: {
        color: '#6B7280'
      },
      splitLine: {
        lineStyle: {
          color: '#F3F4F6'
        }
      }
    },
    series: [
      {
        name: '上行消息量',
        type: 'line',
        smooth: true, // 添加平滑曲线
        data: upData,
        itemStyle: {
          color: '#3B82F6'
        },
        lineStyle: {
          width: 2
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(59, 130, 246, 0.2)' },
            { offset: 1, color: 'rgba(59, 130, 246, 0)' }
          ])
        }
      },
      {
        name: '下行消息量',
        type: 'line',
        smooth: true, // 添加平滑曲线
        data: downData,
        itemStyle: {
          color: '#10B981'
        },
        lineStyle: {
          width: 2
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(16, 185, 129, 0.2)' },
            { offset: 1, color: 'rgba(16, 185, 129, 0)' }
          ])
        }
      }
    ]
  })
}

const chartContainer = ref(null)
let chartInstance: echarts.ECharts | null = null

const disposeChartInstances = () => {
  chartInstances.splice(0).forEach((instance) => instance.dispose())
}

// 生成过去12个月份的标签 (格式: YYYY-MM)
const generateMonthLabels = () => {
  const months = []
  const date = new Date()
  for (let i = 11; i >= 0; i--) {
    const tempDate = new Date(date.getFullYear(), date.getMonth() - i, 1)
    const year = tempDate.getFullYear()
    const month = String(tempDate.getMonth() + 1).padStart(2, '0')
    months.push(`${year}-${month}`)
  }
  return months
}

// 模拟数据获取
const fetchChartData = async () => {
  // 模拟异步请求
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        months: generateMonthLabels(),
        faults: [20, 30, 100, 40, 20, 50, 70, 80, 60, 90, 100, 100],
        repairs: [10, 30, 90, 30, 10, 20, 60, 50, 22, 34, 70, 85]
      })
    }, 300)
  })
}

// 初始化图表配置
const initChart = async () => {
  if (!chartContainer.value) return

  // 获取数据
  const { months, faults, repairs } = await fetchChartData()

  // ECharts配置
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: (params) => {
        return `${params[0].axisValue}<br/>
                ${params[0].marker} ${params[0].seriesName}: ${params[0].value}<br/>
                ${params[1].marker} ${params[1].seriesName}: ${params[1].value}`
      }
    },
    legend: {
      data: ['故障上报数量', '维修工单数量'],
      top: 25
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: months,
      axisLabel: {
        rotate: 45,
        margin: 15
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: (value) => Math.floor(value).toString()
      }
    },
    series: [
      {
        name: '故障上报数量',
        type: 'bar',
        barGap: 0,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#83bff6' },
            { offset: 0.5, color: '#188df0' },
            { offset: 1, color: '#188df0' }
          ]),
          borderRadius: [5, 5, 0, 0]
        },
        emphasis: {
          focus: 'series'
        },
        data: faults
      },
      {
        name: '维修工单数量',
        type: 'bar',
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#ffb600' },
            { offset: 0.5, color: '#d3a137' },
            { offset: 1, color: '#d3a137' }
          ]),
          borderRadius: [5, 5, 0, 0]
        },
        emphasis: {
          focus: 'series'
        },
        data: repairs
      }
    ]
  }

  // 初始化图表
  chartInstance?.dispose()
  chartInstance = echarts.init(chartContainer.value)
  chartInstance.setOption(option)

  handleResize()
}

// 自适应调整
const handleResize = () => {
  chartInstance?.resize()
  chartInstances.forEach((instance) => instance.resize())
}
/** 初始化 */
onMounted(() => {
  nextTick(updateScale)
  resizeObserver = new ResizeObserver(updateScale)
  if (wrapperRef.value) {
    resizeObserver.observe(wrapperRef.value)
  }
  window.addEventListener('resize', updateScale)

  getStats()
  initChart()
})
onUnmounted(() => {
  resizeObserver?.disconnect()
  window.removeEventListener('resize', updateScale)
  cancelAnimationFrame(resizeRaf)
  disposeChartInstances()
  chartInstance?.dispose()
  chartInstance = null
})
</script>

<style lang="scss" scoped>
@import url('@/styles/kb.scss');

// 响应式优化
@media (width <= 1200px) {
  .stat-value {
    font-size: 28px;
  }

  .stat-sub-value {
    font-size: 24px;
  }
}

@media (width <= 768px) {
  .stat-card {
    margin-bottom: 16px;
  }

  .chart-item {
    padding: 8px;
  }

  .gauge-chart {
    height: 140px;
  }
}

// 统计卡片基础样式
.stat-card {
  position: relative;
  overflow: hidden;
  background: linear-gradient(180deg, #fff 0%, #f4f8ff 100%);
  border: 1px solid rgb(207 220 237 / 90%);
  border-radius: 12px;
  box-shadow:
    inset 0 1px 0 rgb(255 255 255 / 95%),
    inset 0 -10px 24px rgb(210 225 244 / 26%),
    0 10px 24px rgb(32 66 120 / 8%);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

  &:hover {
    transform: translateY(-4px);
    box-shadow:
      inset 0 1px 0 rgb(255 255 255 / 98%),
      inset 0 -12px 26px rgb(204 220 243 / 32%),
      0 16px 32px rgb(32 66 120 / 12%);
  }

  :deep(.el-card__body) {
    padding: 0;
  }
}

// 渐变色背景
.stat-card-gradient-1 {
  background: radial-gradient(circle at top left, rgb(121 164 255 / 16%), transparent 42%),
    linear-gradient(180deg, #fff 0%, #f4f8ff 100%);
}

.stat-card-gradient-2 {
  background: radial-gradient(circle at top left, rgb(118 186 255 / 14%), transparent 42%),
    linear-gradient(180deg, #fff 0%, #f3f8ff 100%);
}

.stat-card-gradient-3 {
  background: radial-gradient(circle at top left, rgb(96 154 241 / 14%), transparent 42%),
    linear-gradient(180deg, #fff 0%, #f5f9ff 100%);
}

.stat-card-gradient-4 {
  background: radial-gradient(circle at top left, rgb(137 176 242 / 14%), transparent 42%),
    linear-gradient(180deg, #fff 0%, #f4f8fe 100%);
}

// 统计内容区域
.stat-content {
  padding: 20px;
  color: #1f2a44;
}

.stat-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
}

.stat-icon-wrapper {
  display: flex;
  width: 48px;
  height: 48px;
  background: linear-gradient(180deg, rgb(255 255 255 / 96%) 0%, rgb(232 240 252 / 92%) 100%);
  border: 1px solid rgb(205 219 239 / 90%);
  border-radius: 12px;
  box-shadow:
    inset 0 1px 0 rgb(255 255 255 / 95%),
    inset 0 -6px 12px rgb(205 220 242 / 34%),
    0 6px 14px rgb(66 104 168 / 8%);
  align-items: center;
  justify-content: center;
}

.stat-icon {
  font-size: 24px;
  color: #5d79b7;
}

.stat-title {
  font-size: 16px;
  font-weight: 600;
  color: #000;
}

.stat-divider {
  margin: 12px 0;
  border-color: rgb(201 214 234 / 85%);
}

.stat-body {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.stat-label {
  margin-bottom: 4px;
  font-size: 13px;
  color: #7182a1;
}

.stat-value {
  font-size: 36px;
  font-weight: 700;
  line-height: 1;
  color: #1f2f54;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stat-sub-label {
  font-size: 13px;
  color: #7182a1;
}

.stat-sub-value {
  font-size: 28px;
  font-weight: 700;
  line-height: 1;
  color: #1f2f54;
}

// 图表卡片增强样式
.chart-card-enhanced {
  background: linear-gradient(180deg, #fff 0%, #f5f9ff 100%);
  border: 1px solid rgb(207 220 237 / 90%);
  border-radius: 12px;
  box-shadow:
    inset 0 1px 0 rgb(255 255 255 / 96%),
    inset 0 -12px 26px rgb(212 226 244 / 20%),
    0 10px 24px rgb(32 66 120 / 7%);
  transition: all 0.3s ease;

  &:hover {
    border-color: rgb(193 209 231 / 95%);
    box-shadow:
      inset 0 1px 0 rgb(255 255 255 / 98%),
      inset 0 -14px 30px rgb(208 223 244 / 24%),
      0 16px 30px rgb(32 66 120 / 10%);
  }

  :deep(.el-card__header) {
    padding: 16px 20px;
    background: linear-gradient(90deg, rgb(244 248 255 / 96%) 0%, rgb(255 255 255 / 98%) 100%);
    border-bottom: 1px solid rgb(223 232 245 / 95%);
    box-shadow: inset 0 -1px 0 rgb(255 255 255 / 78%);
  }

  :deep(.el-card__body) {
    padding: 20px;
  }
}

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

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

.chart-title-dot {
  width: 8px;
  height: 8px;
  background: linear-gradient(135deg, #84aef7 0%, #5e87d8 100%);
  border-radius: 50%;
  box-shadow:
    0 0 0 4px rgb(122 162 235 / 12%),
    0 2px 6px rgb(86 124 189 / 24%);
}

.chart-title {
  font-size: 16px;
  font-weight: 600;
  letter-spacing: 0.3px;
  color: #233554;
}

.chart-grid {
  min-height: 220px;
}

.chart-item {
  display: flex;
  padding: 12px;
  border-radius: 12px;
  transition: all 0.2s ease;
  flex-direction: column;
  align-items: center;

  &:hover {
    background: linear-gradient(180deg, rgb(244 248 255 / 90%) 0%, rgb(237 244 255 / 95%) 100%);
    box-shadow:
      inset 0 1px 0 rgb(255 255 255 / 86%),
      inset 0 -8px 16px rgb(212 225 243 / 22%);
  }
}

.gauge-chart {
  width: 100%;
  height: 160px;
}

.chart-label {
  display: flex;
  padding: 6px 12px;
  margin-top: 8px;
  background: linear-gradient(180deg, rgb(255 255 255 / 96%) 0%, rgb(242 247 255 / 96%) 100%);
  border: 1px solid rgb(216 228 244 / 95%);
  border-radius: 20px;
  box-shadow:
    inset 0 1px 0 rgb(255 255 255 / 90%),
    0 4px 10px rgb(58 90 145 / 6%);
  transition: all 0.2s ease;
  align-items: center;
  gap: 6px;

  .chart-item:hover & {
    background: linear-gradient(180deg, rgb(255 255 255 / 98%) 0%, rgb(238 244 255 / 98%) 100%);
    border-color: rgb(201 217 239 / 98%);
  }
}

.label-dot {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
}

.label-dot-blue {
  background: #3b82f6;
  box-shadow: 0 0 0 2px rgb(59 130 246 / 20%);
}

.label-dot-orange {
  background: #f97316;
  box-shadow: 0 0 0 2px rgb(249 115 22 / 20%);
}

.label-dot-purple {
  background: #8b5cf6;
  box-shadow: 0 0 0 2px rgb(139 92 246 / 20%);
}

.label-dot-cyan {
  background: #06b6d4;
  box-shadow: 0 0 0 2px rgb(6 182 212 / 20%);
}

.label-dot-indigo {
  background: #6366f1;
  box-shadow: 0 0 0 2px rgb(99 102 241 / 20%);
}

.label-dot-emerald {
  background: #10b981;
  box-shadow: 0 0 0 2px rgb(16 185 129 / 20%);
}

.label-text {
  font-size: 13px;
  font-weight: 500;
  color: #64748f;
}

.bar-chart-container {
  width: 100%;
  height: 350px;
  background: linear-gradient(180deg, rgb(252 254 255 / 90%) 0%, rgb(244 249 255 / 92%) 100%);
  border-radius: 12px;
  box-shadow:
    inset 0 1px 0 rgb(255 255 255 / 92%),
    inset 0 -10px 20px rgb(217 230 245 / 16%);
}

.maintain-kb-wrapper {
  overflow: hidden;
}

.maintain-kb-screen {
  display: flex;
  overflow: hidden;
  color: #24364f;
  flex-direction: column;
}

.maintain-kb-content {
  display: flex;
  height: calc(100% - 52px * var(--kb-scale));
  min-height: 0;
  padding: calc(44px * var(--kb-scale)) calc(20px * var(--kb-scale)) calc(20px * var(--kb-scale));
  flex-direction: column;
  gap: calc(12px * var(--kb-scale));
}

.summary-grid {
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  gap: calc(12px * var(--kb-scale));
  flex: 0 0 calc(154px * var(--kb-scale));
}

.status-grid {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: calc(12px * var(--kb-scale));
  flex: 0 0 calc(300px * var(--kb-scale));
  min-height: 0;
}

.trend-section {
  min-height: 0;
  flex: 1;
}

.chart-panel,
.trend-panel {
  height: 100%;
  overflow: hidden;

  :deep(.el-card__body) {
    display: flex;
    height: 100%;
    min-height: 0;
    padding: 0;
    flex-direction: column;
  }
}

.stat-card {
  display: grid;
  height: 100%;
  min-width: 0;
  padding: calc(14px * var(--kb-scale));
  text-align: left;
  cursor: default;
  background: linear-gradient(180deg, rgb(255 255 255 / 42%) 0%, rgb(213 227 249 / 28%) 100%);
  border: 1px solid rgb(255 255 255 / 74%);
  border-radius: calc(16px * var(--kb-scale));
  box-shadow:
    inset 0 1px 0 rgb(255 255 255 / 78%),
    0 calc(6px * var(--kb-scale)) calc(14px * var(--kb-scale)) rgb(63 103 171 / 7%);
  grid-template-rows: auto auto 1fr;
  grid-template-columns: auto 1fr;
  gap: calc(8px * var(--kb-scale)) calc(12px * var(--kb-scale));

  &:hover {
    border-color: rgb(76 132 214 / 26%);
    transform: translateY(calc(-2px * var(--kb-scale)));
    box-shadow:
      inset 0 1px 0 rgb(255 255 255 / 84%),
      0 calc(10px * var(--kb-scale)) calc(20px * var(--kb-scale)) rgb(63 103 171 / 11%);
  }
}

.stat-icon-wrapper {
  display: flex;
  width: calc(44px * var(--kb-scale));
  height: calc(44px * var(--kb-scale));
  background: linear-gradient(180deg, rgb(255 255 255 / 96%) 0%, rgb(232 240 252 / 92%) 100%);
  border: 1px solid rgb(205 219 239 / 90%);
  border-radius: calc(12px * var(--kb-scale));
  box-shadow:
    inset 0 1px 0 rgb(255 255 255 / 95%),
    inset 0 calc(-6px * var(--kb-scale)) calc(12px * var(--kb-scale)) rgb(205 220 242 / 34%),
    0 calc(6px * var(--kb-scale)) calc(14px * var(--kb-scale)) rgb(66 104 168 / 8%);
  align-items: center;
  justify-content: center;
  grid-row: 1 / span 2;
}

.stat-icon {
  font-size: calc(24px * var(--kb-scale));
  color: #1f5bb8;
}

.stat-title {
  min-width: 0;
  font-family: YouSheBiaoTiHei, sans-serif;
  font-size: calc(22px * var(--kb-scale));
  font-weight: normal;
  line-height: 1.1;
  color: #03409b;
}

.stat-label {
  font-size: calc(13px * var(--kb-scale));
  font-weight: 700;
  color: #536986;
}

.stat-value {
  font-family: YouSheBiaoTiHei, sans-serif;
  font-size: calc(42px * var(--kb-scale));
  font-weight: normal;
  line-height: 1;
  color: #1f5bb8;
  grid-column: 1 / -1;
}

.stat-pair {
  display: grid;
  min-width: 0;
  grid-column: 1 / -1;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: calc(10px * var(--kb-scale));

  span {
    display: flex;
    min-width: 0;
    padding: calc(8px * var(--kb-scale)) calc(10px * var(--kb-scale));
    overflow: hidden;
    background: linear-gradient(180deg, rgb(255 255 255 / 30%) 0%, rgb(213 227 249 / 18%) 100%);
    border: 1px solid rgb(255 255 255 / 48%);
    border-radius: calc(10px * var(--kb-scale));
    flex-direction: column;
    gap: calc(6px * var(--kb-scale));
  }

  em {
    overflow: hidden;
    font-size: calc(12px * var(--kb-scale));
    font-style: normal;
    font-weight: 700;
    color: #536986;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  strong {
    font-family: YouSheBiaoTiHei, sans-serif;
    font-size: calc(28px * var(--kb-scale));
    font-weight: normal;
    line-height: 1;
    color: #1f5bb8;
  }
}

.gauge-grid {
  display: grid;
  min-height: 0;
  padding: calc(12px * var(--kb-scale)) calc(14px * var(--kb-scale)) calc(16px * var(--kb-scale));
  gap: calc(12px * var(--kb-scale));
  flex: 1;
}

.gauge-grid--failure {
  grid-template-columns: repeat(4, minmax(0, 1fr));
}

.gauge-grid--maintain {
  grid-template-columns: repeat(2, minmax(0, 1fr));
}

.chart-item {
  display: flex;
  min-width: 0;
  min-height: 0;
  padding: calc(8px * var(--kb-scale));
  background: linear-gradient(180deg, rgb(255 255 255 / 42%) 0%, rgb(213 227 249 / 28%) 100%);
  border: 1px solid rgb(255 255 255 / 54%);
  border-radius: calc(14px * var(--kb-scale));
  box-shadow:
    inset 0 1px 0 rgb(255 255 255 / 64%),
    0 calc(5px * var(--kb-scale)) calc(12px * var(--kb-scale)) rgb(63 103 171 / 6%);
  align-items: center;
  flex-direction: column;
}

.gauge-chart {
  width: 100%;
  min-height: 0;
  flex: 1;
}

.chart-label {
  display: flex;
  height: calc(28px * var(--kb-scale));
  padding: 0 calc(10px * var(--kb-scale));
  background: linear-gradient(180deg, rgb(255 255 255 / 88%) 0%, rgb(242 247 255 / 76%) 100%);
  border: 1px solid rgb(216 228 244 / 78%);
  border-radius: calc(999px * var(--kb-scale));
  box-shadow:
    inset 0 1px 0 rgb(255 255 255 / 90%),
    0 calc(4px * var(--kb-scale)) calc(10px * var(--kb-scale)) rgb(58 90 145 / 6%);
  align-items: center;
  gap: calc(6px * var(--kb-scale));
}

.label-dot {
  width: calc(8px * var(--kb-scale));
  height: calc(8px * var(--kb-scale));
}

.label-text {
  overflow: hidden;
  font-size: calc(13px * var(--kb-scale));
  font-weight: 700;
  color: #536986;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.bar-chart-container {
  width: 100%;
  min-height: 0;
  padding: calc(8px * var(--kb-scale)) calc(12px * var(--kb-scale)) calc(14px * var(--kb-scale));
  background: transparent;
  box-shadow: none;
  flex: 1;
}

:deep(.el-card) {
  --el-card-bg-color: transparent;
}
</style>
