<template>
  <div class="equipment-abnormal">
    <!-- 左侧面板 -->
    <div class="left-panel">
      <!-- 搜索 -->
      <div class="panel-card search-card">
        <div class="panel-title"><el-icon><Search /></el-icon> 快速查询</div>
        <el-input v-model="searchKey" placeholder="设备名称/编号/地址" clearable prefix-icon="Search" size="default" />
        <el-select v-model="levelFilter" placeholder="异常等级" clearable style="width:100%;margin-top:10px">
          <el-option label="严重" value="严重" />
          <el-option label="一般" value="一般" />
          <el-option label="轻微" value="轻微" />
        </el-select>
        <el-select v-model="typeFilter" placeholder="设备类型" clearable style="width:100%;margin-top:10px">
          <el-option label="阀门" value="阀门" />
          <el-option label="调压器" value="调压器" />
          <el-option label="流量计" value="流量计" />
          <el-option label="窨井盖" value="窨井盖" />
          <el-option label="终端节点" value="终端节点" />
          <el-option label="检查井" value="检查井" />
        </el-select>
        <el-select v-model="statusFilter" placeholder="处理状态" clearable style="width:100%;margin-top:10px">
          <el-option label="待处理" value="待处理" />
          <el-option label="处理中" value="处理中" />
          <el-option label="已修复" value="已修复" />
        </el-select>
        <div style="display:flex;gap:8px;margin-top:10px">
          <el-button type="primary" size="small" @click="handleQuery" style="flex:1">查询</el-button>
          <el-button size="small" @click="handleReset" style="flex:1">重置</el-button>
        </div>
      </div>

      <!-- 异常等级分布 -->
      <div class="panel-card">
        <div class="panel-title"><el-icon><PieChart /></el-icon> 异常等级分布</div>
        <div class="level-list">
          <div class="level-item critical">
            <span class="level-dot"></span>
            <span class="level-label">严重</span>
            <span class="level-count">{{ stats.critical }}</span>
          </div>
          <div class="level-item warning">
            <span class="level-dot"></span>
            <span class="level-label">一般</span>
            <span class="level-count">{{ stats.normal }}</span>
          </div>
          <div class="level-item minor">
            <span class="level-dot"></span>
            <span class="level-label">轻微</span>
            <span class="level-count">{{ stats.minor }}</span>
          </div>
        </div>
      </div>

      <!-- 设备类型统计 -->
      <div class="panel-card">
        <div class="panel-title"><el-icon><Histogram /></el-icon> 设备类型统计</div>
        <div class="type-list">
          <div class="type-item" v-for="item in deviceTypeStats" :key="item.name">
            <span class="type-name">{{ item.name }}</span>
            <span class="type-bar-bg"><span class="type-bar" :style="{width: (item.count/stats.total*100)+'%', background: item.color}"></span></span>
            <span class="type-count">{{ item.count }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 右侧内容区 -->
    <div class="right-panel">
      <!-- 统计卡片 -->
      <div class="stats-row">
        <div class="stat-card stat-total">
          <div class="stat-icon"><el-icon size="22"><WarningFilled /></el-icon></div>
          <div class="stat-info">
            <div class="stat-label">异常设备总数</div>
            <div class="stat-value">{{ stats.total }} <small>台</small></div>
          </div>
        </div>
        <div class="stat-card stat-today">
          <div class="stat-icon"><el-icon size="22"><Clock /></el-icon></div>
          <div class="stat-info">
            <div class="stat-label">今日新增</div>
            <div class="stat-value">{{ stats.today }} <small>台</small></div>
          </div>
        </div>
        <div class="stat-card stat-rate">
          <div class="stat-icon"><el-icon size="22"><TrendCharts /></el-icon></div>
          <div class="stat-info">
            <div class="stat-label">异常占比</div>
            <div class="stat-value">{{ stats.rate }} <small>%</small></div>
          </div>
        </div>
        <div class="stat-card stat-processed">
          <div class="stat-icon"><el-icon size="22"><CircleCheckFilled /></el-icon></div>
          <div class="stat-info">
            <div class="stat-label">已修复</div>
            <div class="stat-value">{{ stats.processed }} <small>台</small></div>
          </div>
        </div>
        <div class="stat-card stat-pending">
          <div class="stat-icon"><el-icon size="22"><Warning /></el-icon></div>
          <div class="stat-info">
            <div class="stat-label">待处理</div>
            <div class="stat-value">{{ stats.pending }} <small>台</small></div>
          </div>
        </div>
        <div class="stat-card stat-process-rate">
          <div class="stat-icon"><el-icon size="22"><DataAnalysis /></el-icon></div>
          <div class="stat-info">
            <div class="stat-label">修复率</div>
            <div class="stat-value">{{ stats.processRate }} <small>%</small></div>
          </div>
        </div>
      </div>

      <!-- 图表区域 - 上方: 趋势图(全宽) -->
      <div class="chart-card chart-trend">
        <div class="chart-header">
          <span class="chart-title">设备异常趋势图</span>
          <span class="chart-subtitle">近15天运行数据 (2026-05-29 ~ 2026-06-12)</span>
          <div class="chart-legend-custom">
            <span class="legend-tag tag-total">异常总数</span>
            <span class="legend-tag tag-new">新增异常</span>
            <span class="legend-tag tag-fixed">已修复</span>
          </div>
        </div>
        <div id="trendChart" class="chart-body chart-body-large" style="height:340px"></div>
      </div>

      <!-- 图表区域 - 下方: 两个图表并排 -->
      <div class="charts-row">
        <div class="chart-card chart-half">
          <div class="chart-header">
            <span class="chart-title">异常类型分布</span>
          </div>
          <div id="typeChart" class="chart-body" style="height:290px"></div>
        </div>
        <div class="chart-card chart-half">
          <div class="chart-header">
            <span class="chart-title">设备异常等级与处理状态</span>
          </div>
          <div id="levelChart" class="chart-body" style="height:290px"></div>
        </div>
      </div>

      <!-- 异常设备列表 -->
      <div class="table-card">
        <div class="table-header">
          <span class="table-title">异常设备列表</span>
          <span class="table-count">共 {{ filteredTableData.length }} 条记录</span>
        </div>
        <el-table :data="paginatedData" border stripe v-loading="loading" max-height="460" size="small">
          <el-table-column prop="id" label="序号" width="56" align="center" />
          <el-table-column prop="deviceCode" label="设备编号" min-width="140" show-overflow-tooltip />
          <el-table-column prop="deviceName" label="设备名称" min-width="150" show-overflow-tooltip />
          <el-table-column prop="deviceType" label="设备类型" width="100" />
          <el-table-column prop="level" label="异常等级" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="levelTagType(row.level)" size="small">{{ row.level }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="alarmDesc" label="异常描述" min-width="220" show-overflow-tooltip />
          <el-table-column prop="address" label="安装地址" min-width="200" show-overflow-tooltip />
          <el-table-column prop="alarmTime" label="异常时间" width="168" />
          <el-table-column prop="processStatus" label="处理状态" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="row.processStatus === '已修复' ? 'success' : row.processStatus === '处理中' ? 'warning' : 'danger'" size="small">
                {{ row.processStatus }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" fixed="right" align="center">
            <template #default="{ row }">
              <el-button type="primary" link size="small" @click="handleDetail(row)">详情</el-button>
              <el-button v-if="row.processStatus === '待处理'" type="warning" link size="small" @click="handleProcess(row)">处理</el-button>
              <el-button v-if="row.processStatus === '处理中'" type="success" link size="small" @click="handleComplete(row)">完成</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="table-footer">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="filteredTableData.length"
            layout="total, prev, pager, next"
            :page-sizes="[10, 20]"
            small
            background
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, nextTick, onBeforeUnmount, onMounted, reactive, ref } from 'vue'
import * as echarts from 'echarts'
import { Clock, CircleCheckFilled, DataAnalysis, Histogram, PieChart, Search, TrendCharts, Warning, WarningFilled } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const loading = ref(false)
const searchKey = ref('')
const levelFilter = ref('')
const typeFilter = ref('')
const statusFilter = ref('')
const currentPage = ref(1)
const pageSize = ref(10)

let trendChart = null
let typeChart = null
let levelChart = null

// ==================== 统计数据 ====================
const stats = reactive({
  total: 28,
  today: 3,
  rate: 7.2,
  processed: 18,
  pending: 10,
  processRate: 64.3,
  critical: 10,
  normal: 10,
  minor: 8
})

const deviceTypeStats = ref([
  { name: '阀门', count: 4, color: '#e63946' },
  { name: '调压器', count: 3, color: '#f77f00' },
  { name: '流量计', count: 4, color: '#2d6a4f' },
  { name: '窨井盖', count: 5, color: '#7f4f24' },
  { name: '终端节点', count: 2, color: '#6c757d' },
  { name: '检查井', count: 1, color: '#b08968' }
])

// ==================== 趋势数据 ====================
const trendDates = [
  '05-29', '05-30', '05-31', '06-01', '06-02', '06-03', '06-04',
  '06-05', '06-06', '06-07', '06-08', '06-09', '06-10', '06-11', '06-12'
]
const trendTotalData   = [24, 26, 25, 28, 27, 25, 24, 26, 28, 29, 27, 28, 30, 28, 28]
const trendNewData     = [ 3,  5,  2,  6,  4,  2,  1,  3,  5,  4,  2,  3,  5,  3,  3]
const trendProcessedData = [20, 21, 23, 22, 23, 23, 23, 23, 23, 25, 25, 25, 25, 25, 18]

// ==================== 表格数据 ====================
const tableData = ref([
  { id: '1', deviceCode:'GD-FM-001', deviceName:'辰州北路阀门', deviceType:'阀门', level:'严重', alarmDesc:'阀门开度异常，远程控制无响应，现场检查阀体锈蚀严重，存在燃气泄漏风险', address:'辰州北路与天宁路交叉口北侧50米', alarmTime:'2026-06-12 04:23:15', processStatus:'待处理' },
  { id: '2', deviceCode:'GD-TY-001', deviceName:'辰州路调压站', deviceType:'调压器', level:'严重', alarmDesc:'出口压力波动超限，调压器膜片老化，压力调节范围偏离正常值±15%', address:'辰州中路县政府东侧200米', alarmTime:'2026-06-12 02:15:42', processStatus:'处理中' },
  { id: '3', deviceCode:'GD-LL-002', deviceName:'迎宾西路计量站', deviceType:'流量计', level:'一般', alarmDesc:'流量计量偏差超出允许范围，瞬时流量数据跳变，疑似传感器零点漂移', address:'迎宾西路与古城路交叉口', alarmTime:'2026-06-11 18:47:30', processStatus:'处理中' },
  { id: '4', deviceCode:'GD-FM-003', deviceName:'古城北路阀门', deviceType:'阀门', level:'一般', alarmDesc:'阀门关闭不到位，密封面疑似有异物卡滞，泄漏检测仪报警', address:'古城北路中段天宁路南侧100米', alarmTime:'2026-06-11 11:32:08', processStatus:'待处理' },
  { id: '5', deviceCode:'YJ-JG-004', deviceName:'迎宾路窨井盖', deviceType:'窨井盖', level:'严重', alarmDesc:'井盖倾斜位移超过安全阈值，井盖锁失效，存在行人及车辆安全隐患', address:'迎宾中路公交站台北侧', alarmTime:'2026-06-11 06:55:20', processStatus:'待处理' },
  { id: '6', deviceCode:'GD-LL-001', deviceName:'辰州北路计量站', deviceType:'流量计', level:'轻微', alarmDesc:'通讯延迟偏高，数据上报间隔从15秒延长至45秒，4G信号强度偏弱', address:'辰州北路与滨江路交叉口附近', alarmTime:'2026-06-10 22:10:05', processStatus:'已修复' },
  { id: '7', deviceCode:'GD-TY-003', deviceName:'建设路调压柜', deviceType:'调压器', level:'一般', alarmDesc:'调压柜门锁损坏，柜内温湿度传感器读数偏高，可能存在进水风险', address:'建设西路中段加油站对面', alarmTime:'2026-06-10 14:28:45', processStatus:'已修复' },
  { id: '8', deviceCode:'YJ-JG-001', deviceName:'辰州北路窨井盖', deviceType:'窨井盖', level:'轻微', alarmDesc:'井盖表面沉降3cm，低于路面标高，不影响通行但需定期监测', address:'辰州北路北段人行道', alarmTime:'2026-06-10 08:15:33', processStatus:'已修复' },
  { id: '9', deviceCode:'GD-FM-004', deviceName:'迎宾东路阀门', deviceType:'阀门', level:'一般', alarmDesc:'阀门操作扭矩偏大，电动执行机构电流异常升高，需润滑维护', address:'迎宾东路东段靠近沅陵大道', alarmTime:'2026-06-09 16:42:18', processStatus:'已修复' },
  { id: '10', deviceCode:'GD-ZD-002', deviceName:'天宁东路终端', deviceType:'终端节点', level:'严重', alarmDesc:'终端设备离线超过48小时，主备电源均失效，可能遭施工破坏或被盗', address:'天宁东路末端靠近古城路', alarmTime:'2026-06-09 03:08:55', processStatus:'处理中' },
  { id: '11', deviceCode:'GD-TY-002', deviceName:'古城路调压站', deviceType:'调压器', level:'一般', alarmDesc:'调压站周边有施工活动，振动监测值超标，建议现场确认施工影响范围', address:'古城中路沅陵一中北侧', alarmTime:'2026-06-08 20:35:12', processStatus:'已修复' },
  { id: '12', deviceCode:'YJ-JG-005', deviceName:'建设路窨井盖', deviceType:'窨井盖', level:'轻微', alarmDesc:'井盖标识磨损严重，编号无法辨识，需重新喷涂或更换标识牌', address:'建设东路商铺门前人行道', alarmTime:'2026-06-08 12:50:40', processStatus:'已修复' },
  { id: '13', deviceCode:'GD-FM-002', deviceName:'辰州中路阀门', deviceType:'阀门', level:'严重', alarmDesc:'阀门井内积水超过警戒线，排水泵未自动启动，可能淹没电动执行机构', address:'辰州中路与迎宾路交叉口', alarmTime:'2026-06-07 19:22:07', processStatus:'已修复' },
  { id: '14', deviceCode:'GD-LL-003', deviceName:'建设东路计量柜', deviceType:'流量计', level:'一般', alarmDesc:'计量柜显示屏背光故障，夜间无法读取数据，不影响计量精度', address:'建设东路滨江路口附近', alarmTime:'2026-06-07 09:14:28', processStatus:'已修复' },
  { id: '15', deviceCode:'YJ-JG-006', deviceName:'滨江路窨井盖', deviceType:'窨井盖', level:'轻微', alarmDesc:'井盖铰链锈蚀松动，开启闭合有异响，建议润滑或更换铰链部件', address:'滨江路沿江步道观景台旁', alarmTime:'2026-06-06 15:30:55', processStatus:'已修复' },
  { id: '16', deviceCode:'GD-ZD-001', deviceName:'沅陵县政府终端', deviceType:'终端节点', level:'一般', alarmDesc:'终端存储空间使用率达到92%，历史数据清理策略未生效', address:'辰州中街县政府办公大楼', alarmTime:'2026-06-06 08:45:12', processStatus:'已修复' },
  { id: '17', deviceCode:'YJ-JC-001', deviceName:'辰州路检查井', deviceType:'检查井', level:'一般', alarmDesc:'检查井内可燃气体浓度检测值持续偏高，超标时长超过2小时', address:'辰州中路地下燃气管线上方', alarmTime:'2026-06-05 23:18:40', processStatus:'处理中' },
  { id: '18', deviceCode:'GD-FM-001', deviceName:'辰州北路阀门', deviceType:'阀门', level:'轻微', alarmDesc:'阀门控制箱密封条老化脱落，雨水渗入痕迹明显，需更换密封件', address:'辰州北路与天宁路交叉口北侧50米', alarmTime:'2026-06-05 10:42:33', processStatus:'已修复' }
])

const filteredTableData = computed(() => {
  let data = tableData.value
  if (searchKey.value) {
    const kw = searchKey.value.toLowerCase()
    data = data.filter(row =>
      row.deviceName.includes(kw) || row.deviceCode.toLowerCase().includes(kw) || row.address.includes(kw)
    )
  }
  if (levelFilter.value) data = data.filter(row => row.level === levelFilter.value)
  if (typeFilter.value) data = data.filter(row => row.deviceType === typeFilter.value)
  if (statusFilter.value) data = data.filter(row => row.processStatus === statusFilter.value)
  return data
})

const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  return filteredTableData.value.slice(start, start + pageSize.value)
})

// ==================== 工具函数 ====================
function levelTagType(level) {
  if (level === '严重') return 'danger'
  if (level === '一般') return 'warning'
  return 'info'
}

function handleQuery() {
  currentPage.value = 1
}

function handleReset() {
  searchKey.value = ''
  levelFilter.value = ''
  typeFilter.value = ''
  statusFilter.value = ''
  currentPage.value = 1
}

function handleDetail(row) {
  ElMessageBox.alert(
    `<div style="line-height:2.2;font-size:14px;">
      <p><b>设备编号：</b>${row.deviceCode}</p>
      <p><b>设备名称：</b>${row.deviceName}</p>
      <p><b>设备类型：</b>${row.deviceType}</p>
      <p><b>异常等级：</b><span style="color:${row.level==='严重'?'#e63946':row.level==='一般'?'#f77f00':'#909399'}">${row.level}</span></p>
      <p><b>异常描述：</b>${row.alarmDesc}</p>
      <p><b>安装地址：</b>${row.address}</p>
      <p><b>异常时间：</b>${row.alarmTime}</p>
      <p><b>处理状态：</b>${row.processStatus}</p>
    </div>`,
    '设备异常详情',
    { dangerouslyUseHTMLString: true, confirmButtonText: '关闭', customClass: 'detail-dialog' }
  )
}

function handleProcess(row) {
  ElMessageBox.confirm(`确认开始处理设备「${row.deviceName}」的异常？系统将自动派发工单至运维班组。`, '处理确认', {
    confirmButtonText: '确认处理',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    row.processStatus = '处理中'
    ElMessage.success(`已派发工单，设备「${row.deviceName}」处理中`)
  }).catch(() => {})
}

function handleComplete(row) {
  ElMessageBox.confirm(`确认设备「${row.deviceName}」的异常已修复完成？`, '修复确认', {
    confirmButtonText: '确认修复',
    cancelButtonText: '取消',
    type: 'success'
  }).then(() => {
    row.processStatus = '已修复'
    ElMessage.success(`设备「${row.deviceName}」异常已修复`)
  }).catch(() => {})
}

// ==================== ECharts ====================
function initTrendChart() {
  const dom = document.getElementById('trendChart')
  if (!dom) return
  if (trendChart) trendChart.dispose()
  trendChart = echarts.init(dom)
  trendChart.setOption({
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(255,255,255,0.96)',
      borderColor: '#e0e4ea',
      textStyle: { color: '#2c3e50', fontSize: 13 }
    },
    legend: {
      data: ['异常总数', '新增异常', '已修复'],
      top: 0,
      textStyle: { color: '#606a78', fontSize: 12 }
    },
    grid: { left: 52, right: 44, top: 44, bottom: 32 },
    xAxis: {
      type: 'category',
      data: trendDates,
      boundaryGap: false,
      axisLabel: { color: '#9098a6', fontSize: 12 },
      axisLine: { lineStyle: { color: '#d0d5dd' } }
    },
    yAxis: {
      type: 'value',
      name: '数量(台)',
      nameTextStyle: { color: '#9098a6', fontSize: 12 },
      axisLabel: { color: '#9098a6', fontSize: 12 },
      splitLine: { lineStyle: { color: '#f0f2f6', type: 'dashed' } }
    },
    series: [
      {
        name: '异常总数', type: 'line',
        data: trendTotalData, smooth: true, symbol: 'circle', symbolSize: 6,
        lineStyle: { width: 3, color: '#e63946' },
        itemStyle: { color: '#e63946', borderColor: '#fff', borderWidth: 2 },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(230,57,70,0.15)' },
            { offset: 1, color: 'rgba(230,57,70,0.0)' }
          ])
        }
      },
      {
        name: '新增异常', type: 'line',
        data: trendNewData, smooth: true, symbol: 'emptyCircle', symbolSize: 6,
        lineStyle: { width: 2.5, color: '#f77f00' },
        itemStyle: { color: '#f77f00', borderColor: '#f77f00', borderWidth: 2 }
      },
      {
        name: '已修复', type: 'line',
        data: trendProcessedData, smooth: true, symbol: 'diamond', symbolSize: 7,
        lineStyle: { width: 2.5, color: '#2a9d8f', type: 'dashed' },
        itemStyle: { color: '#2a9d8f', borderColor: '#fff', borderWidth: 2 }
      }
    ]
  })
}

function initTypeChart() {
  const dom = document.getElementById('typeChart')
  if (!dom) return
  if (typeChart) typeChart.dispose()
  typeChart = echarts.init(dom)
  const categories = ['通讯故障', '设备老化', '外部损坏', '传感器故障', '电源问题', '其他']
  const values = [8, 7, 5, 4, 3, 1]
  const colors = ['#457b9d', '#e76f51', '#e63946', '#f77f00', '#6c757d', '#b08968']
  typeChart.setOption({
    tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
    grid: { left: 46, right: 20, top: 16, bottom: 32 },
    xAxis: {
      type: 'category',
      data: categories,
      axisLabel: { color: '#9098a6', fontSize: 11, rotate: 15 },
      axisLine: { lineStyle: { color: '#d0d5dd' } }
    },
    yAxis: {
      type: 'value', name: '数量(台)',
      axisLabel: { color: '#9098a6', fontSize: 11 },
      splitLine: { lineStyle: { color: '#f0f2f6', type: 'dashed' } }
    },
    series: [{
      type: 'bar',
      data: values.map((v, i) => ({ value: v, itemStyle: { color: colors[i], borderRadius: [4, 4, 0, 0] } })),
      barWidth: 28,
      label: { show: true, position: 'top', color: '#4e5969', fontSize: 12, fontWeight: 600 }
    }]
  })
}

function initLevelChart() {
  const dom = document.getElementById('levelChart')
  if (!dom) return
  if (levelChart) levelChart.dispose()
  levelChart = echarts.init(dom)
  levelChart.setOption({
    tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
    legend: {
      data: ['待处理', '处理中', '已修复'],
      top: 0,
      textStyle: { color: '#606a78', fontSize: 12 }
    },
    grid: { left: 46, right: 20, top: 44, bottom: 28 },
    xAxis: {
      type: 'category',
      data: ['严重', '一般', '轻微'],
      axisLabel: { color: '#9098a6', fontSize: 12 },
      axisLine: { lineStyle: { color: '#d0d5dd' } }
    },
    yAxis: {
      type: 'value', name: '数量(台)',
      axisLabel: { color: '#9098a6', fontSize: 11 },
      splitLine: { lineStyle: { color: '#f0f2f6', type: 'dashed' } },
      nameTextStyle: { color: '#9098a6', fontSize: 11 }
    },
    series: [
      {
        name: '待处理', type: 'bar',
        data: [3, 3, 4], barWidth: 30, barGap: '20%',
        itemStyle: { color: '#e63946', borderRadius: [4, 4, 0, 0] }
      },
      {
        name: '处理中', type: 'bar',
        data: [2, 3, 0], barWidth: 30,
        itemStyle: { color: '#f77f00', borderRadius: [4, 4, 0, 0] }
      },
      {
        name: '已修复', type: 'bar',
        data: [5, 7, 6], barWidth: 30,
        itemStyle: { color: '#2a9d8f', borderRadius: [4, 4, 0, 0] }
      }
    ]
  })
}

function initCharts() {
  try { initTrendChart() } catch (e) { console.warn('趋势图初始化失败：', e) }
  try { initTypeChart() } catch (e) { console.warn('类型分布图初始化失败：', e) }
  try { initLevelChart() } catch (e) { console.warn('等级统计图初始化失败：', e) }
}

function resizeCharts() {
  trendChart?.resize()
  typeChart?.resize()
  levelChart?.resize()
}

onMounted(async () => {
  await nextTick()
  initCharts()
  window.addEventListener('resize', resizeCharts)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeCharts)
  trendChart?.dispose()
  typeChart?.dispose()
  levelChart?.dispose()
})
</script>

<style scoped>
.equipment-abnormal {
  display: flex;
  gap: 16px;
  padding: 16px;
  background: #f0f2f6;
  min-height: calc(100vh - 84px);
}

/* ========== 左侧面板 ========== */
.left-panel {
  width: 280px;
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
  gap: 14px;
}

.panel-card {
  background: #fff;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 12px rgba(15, 35, 95, 0.04);
}

.panel-title {
  font-size: 14px;
  font-weight: 700;
  color: #1f2d3d;
  margin-bottom: 14px;
  display: flex;
  align-items: center;
  gap: 8px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f2f6;
}

.panel-title .el-icon { color: #1890ff; }

/* 等级列表 */
.level-list { display: flex; flex-direction: column; gap: 8px; }
.level-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 8px 12px;
  border-radius: 8px;
  background: #f8fafc;
  cursor: pointer;
  transition: all 0.2s;
}
.level-item:hover { background: #eef2f8; transform: translateX(4px); }
.level-dot { width: 10px; height: 10px; border-radius: 50%; }
.level-item.critical .level-dot { background: #e63946; box-shadow: 0 0 6px rgba(230,57,70,0.4); }
.level-item.warning .level-dot { background: #f77f00; box-shadow: 0 0 6px rgba(247,127,0,0.4); }
.level-item.minor .level-dot { background: #457b9d; box-shadow: 0 0 6px rgba(69,123,157,0.4); }
.level-label { flex: 1; font-size: 13px; color: #4e5969; }
.level-count { font-size: 18px; font-weight: 700; color: #1f2d3d; }

/* 设备类型列表 */
.type-list { display: flex; flex-direction: column; gap: 10px; }
.type-item { display: flex; align-items: center; gap: 10px; }
.type-name { width: 56px; font-size: 12px; color: #606a78; text-align: right; flex-shrink: 0; }
.type-bar-bg { flex: 1; height: 8px; background: #f0f2f6; border-radius: 4px; overflow: hidden; }
.type-bar { height: 100%; border-radius: 4px; transition: width 0.6s ease; }
.type-count { width: 24px; font-size: 12px; font-weight: 600; color: #1f2d3d; text-align: right; flex-shrink: 0; }

/* ========== 右侧内容区 ========== */
.right-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 16px;
  min-width: 0;
}

/* 统计卡片 */
.stats-row {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  gap: 12px;
}

.stat-card {
  background: #fff;
  border-radius: 12px;
  padding: 14px 16px;
  box-shadow: 0 2px 12px rgba(15, 35, 95, 0.04);
  display: flex;
  align-items: center;
  gap: 14px;
  cursor: pointer;
  transition: all 0.25s;
}
.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(15, 35, 95, 0.1);
}

.stat-icon {
  width: 44px; height: 44px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}
.stat-total .stat-icon { background: #fef0f0; color: #e63946; }
.stat-today .stat-icon { background: #fff3e6; color: #f77f00; }
.stat-rate .stat-icon { background: #fef5e7; color: #e76f51; }
.stat-processed .stat-icon { background: #e8f8f5; color: #2a9d8f; }
.stat-pending .stat-icon { background: #eaf2f8; color: #457b9d; }
.stat-process-rate .stat-icon { background: #e8f5e9; color: #2d6a4f; }

.stat-label { font-size: 12px; color: #9098a6; margin-bottom: 4px; }
.stat-value { font-size: 24px; font-weight: 700; color: #1f2d3d; line-height: 1.1; }
.stat-value small { font-size: 12px; color: #9098a6; font-weight: 400; }

/* 图表卡片 */
.chart-card {
  background: #fff;
  border-radius: 12px;
  padding: 16px 20px;
  box-shadow: 0 2px 12px rgba(15, 35, 95, 0.04);
  display: flex;
  flex-direction: column;
}

.chart-trend { /* 全宽 */ }

.charts-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 14px;
}
.chart-half { flex: 1; }

.chart-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 6px;
  flex-wrap: wrap;
}

.chart-title {
  font-size: 15px;
  font-weight: 700;
  color: #1f2d3d;
}

.chart-subtitle {
  font-size: 12px;
  color: #a0a9b6;
}

.chart-legend-custom {
  margin-left: auto;
  display: flex;
  gap: 8px;
}

.legend-tag {
  font-size: 11px;
  padding: 2px 10px;
  border-radius: 10px;
  color: #fff;
}
.tag-total { background: #e63946; }
.tag-new { background: #f77f00; }
.tag-fixed { background: #2a9d8f; }

.chart-body {
  flex: 1;
  min-height: 280px;
}
.chart-body-large {
  min-height: 330px;
}

/* 表格卡片 */
.table-card {
  background: #fff;
  border-radius: 12px;
  padding: 16px 20px;
  box-shadow: 0 2px 12px rgba(15, 35, 95, 0.04);
}

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

.table-title {
  font-size: 15px;
  font-weight: 700;
  color: #1f2d3d;
}

.table-count {
  font-size: 12px;
  color: #9098a6;
}

.table-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 12px;
}

/* ========== 响应式 ========== */
@media (max-width: 1600px) {
  .stats-row { grid-template-columns: repeat(3, 1fr); }
  .left-panel { width: 260px; }
}

@media (max-width: 1400px) {
  .equipment-abnormal { flex-direction: column; }
  .left-panel { width: 100%; flex-direction: row; flex-wrap: wrap; }
  .left-panel .panel-card { flex: 1; min-width: 240px; }
  .charts-row { grid-template-columns: 1fr; }
}

@media (max-width: 768px) {
  .stats-row { grid-template-columns: repeat(2, 1fr); }
}
</style>
