<template>
  <div class="app">
    <!-- 左侧区域 -->
    <div class="sidebar">
      <!-- 树形结构 -->
      <div class="tree-container">
        <el-table
            ref="tableRef"
            v-loading="loading"
            :data="topologyList"
            @current-change="handleNodeClick"
            row-key="itemId"
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
            :default-expand-all="true"
            :indent="24"
            class="custom-table"
            :show-header="false"
            :highlight-current-row="true"
            :border="false"
        >
          <el-table-column align="left" prop="itemName">
            <template #default="{ row }">
              <i
                  v-if="row.children && row.children.length > 0"
                  :class="row.expanded ? 'el-icon-folder-opened' : 'el-icon-folder'"
                  style="margin-right: 5px"
              ></i>
              <i v-else class="el-icon-document" style="margin-right: 5px"></i>
              {{ row.itemName }}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 右侧区域 -->
    <div class="main-content">
      <!-- 默认提示 -->
      <div v-if="!selectedNode" class="empty-state">
        <div class="empty-icon">
          <el-icon size="80" color="#d3d3d3">
            <DataAnalysis />
          </el-icon>
        </div>
        <h3>请选择左侧节点查看能耗数据</h3>
        <p>点击左侧树形结构中的任意节点，查看对应的能耗统计信息</p>
      </div>

      <!-- 能耗数据展示 -->
      <div v-else class="content-wrapper">
        <!-- 页面标题 -->
        <div class="page-header">
          <div class="header-left">
            <h1 class="page-title">
              <el-icon class="title-icon"><OfficeBuilding /></el-icon>
              {{ selectedNode.itemName }}
            </h1>
            <p class="page-subtitle">能耗监控与分析</p>
          </div>
          <div class="header-right">
            <el-button type="primary" :icon="Refresh" @click="refreshData" :loading="refreshLoading">
              刷新数据
            </el-button>
            <el-button :icon="Download" @click="exportData" :loading="exportLoading">
              导出报告
            </el-button>
          </div>
        </div>

        <!-- 关键指标卡片 -->
        <div class="metrics-grid">
          <div class="metric-card electricity">
            <div class="metric-icon">
              <el-icon size="24"><Lightning /></el-icon>
            </div>
            <div class="metric-content">
              <div class="metric-value">{{ electricityUsage }}</div>
              <div class="metric-unit">kWh</div>
              <div class="metric-label">总用电量</div>
              <div class="metric-trend up">
                <el-icon><TrendCharts /></el-icon>
                <span>+{{ electricityTrend }}%</span>
              </div>
            </div>
          </div>

          <div class="metric-card water">
            <div class="metric-icon">
              <el-icon size="24"><Drizzling /></el-icon>
            </div>
            <div class="metric-content">
              <div class="metric-value">{{ waterUsage }}</div>
              <div class="metric-unit">t</div>
              <div class="metric-label">总用水量</div>
              <div class="metric-trend up">
                <el-icon><TrendCharts /></el-icon>
                <span>+{{ waterTrend }}%</span>
              </div>
            </div>
          </div>

          <div class="metric-card energy">
            <div class="metric-icon">
              <el-icon size="24"><Cpu /></el-icon>
            </div>
            <div class="metric-content">
              <div class="metric-value">{{ totalEnergyConsumption }}</div>
              <div class="metric-unit">kgce</div>
              <div class="metric-label">综合能耗</div>
              <div class="metric-trend up">
                <el-icon><TrendCharts /></el-icon>
                <span>+{{ energyTrend }}%</span>
              </div>
            </div>
          </div>

          <div class="metric-card peak">
            <div class="metric-icon">
              <el-icon size="24"><DataLine /></el-icon>
            </div>
            <div class="metric-content">
              <div class="metric-value">{{ peakElectricity }}</div>
              <div class="metric-unit">kW</div>
              <div class="metric-label">峰值用电</div>
              <div class="metric-time">{{ peakTime }}</div>
            </div>
          </div>
        </div>

        <!-- 详细数据表格 -->
        <div class="data-section">
          <div class="section-header">
            <h2 class="section-title">
              <el-icon><DataBoard /></el-icon>
              详细能耗统计
            </h2>
            <div class="section-actions">
              <el-radio-group v-model="timeRange" size="small" @change="handleTimeRangeChange">
                <el-radio-button label="today">今日</el-radio-button>
                <el-radio-button label="week">本周</el-radio-button>
                <el-radio-button label="month">本月</el-radio-button>
                <el-radio-button label="year">本年</el-radio-button>
              </el-radio-group>
            </div>
          </div>

          <el-table
              :data="energyStatistics"
              class="energy-table"
              :header-cell-style="{ backgroundColor: '#f8f9fa', color: '#333' }"
              v-loading="tableLoading"
          >
            <el-table-column prop="category" label="能耗类型" width="120">
              <template #default="{ row }">
                <div class="category-cell">
                  <el-icon v-if="row.category === '用电量'" class="category-icon electricity-icon">
                    <Lightning />
                  </el-icon>
                  <el-icon v-else-if="row.category === '用水量'" class="category-icon water-icon">
                    <Drizzling />
                  </el-icon>
                  <el-icon v-else class="category-icon energy-icon">
                    <Cpu />
                  </el-icon>
                  {{ row.category }}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="value" label="当前数值" width="150">
              <template #default="{ row }">
                <div class="value-cell">{{ row.value }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="ringRatio" label="环比" width="120">
              <template #default="{ row }">
                <el-tag
                    :type="row.ringRatio.includes('↑') ? 'danger' : 'success'"
                    size="small"
                    class="trend-tag"
                >
                  {{ row.ringRatio }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="yearOnYearRatio" label="同比" width="120">
              <template #default="{ row }">
                <el-tag
                    :type="row.yearOnYearRatio.includes('↑') ? 'danger' : 'success'"
                    size="small"
                    class="trend-tag"
                >
                  {{ row.yearOnYearRatio }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template #default="{ row }">
                <el-button size="small" type="text" @click="viewDetails(row)">
                  <el-icon><View /></el-icon>
                  查看详情
                </el-button>
                <el-button size="small" type="text" @click="viewTrend(row)">
                  <el-icon><TrendCharts /></el-icon>
                  趋势分析
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 图表区域 -->
        <div class="charts-section">
          <div class="chart-container">
            <div class="chart-header">
              <h3>能耗趋势图</h3>
              <el-button-group size="small">
                <el-button :type="chartType === 'line' ? 'primary' : ''" @click="changeChartType('line')">
                  <el-icon><DataLine /></el-icon>
                  折线图
                </el-button>
                <el-button :type="chartType === 'bar' ? 'primary' : ''" @click="changeChartType('bar')">
                  <el-icon><DataBoard /></el-icon>
                  柱状图
                </el-button>
              </el-button-group>
            </div>
            <div ref="chartRef" class="chart-content" v-loading="chartLoading"></div>
          </div>
        </div>

        <!-- 告警信息 -->
        <div class="alerts-section" v-if="alerts.length > 0">
          <div class="section-header">
            <h2 class="section-title">
              <el-icon><Warning /></el-icon>
              能耗告警
            </h2>
          </div>
          <div class="alerts-list">
            <el-alert
                v-for="alert in alerts"
                :key="alert.id"
                :title="alert.title"
                :description="alert.description"
                :type="alert.type"
                :closable="false"
                show-icon
                class="alert-item"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 详情弹窗 -->
    <el-dialog
        v-model="detailDialogVisible"
        :title="`${currentDetailData?.category}详情`"
        width="800px"
        destroy-on-close
    >
      <div class="detail-content">
        <div class="detail-summary">
          <div class="summary-item">
            <span class="label">当前值：</span>
            <span class="value">{{ currentDetailData?.value }}</span>
          </div>
          <div class="summary-item">
            <span class="label">环比：</span>
            <span class="value">{{ currentDetailData?.ringRatio }}</span>
          </div>
          <div class="summary-item">
            <span class="label">同比：</span>
            <span class="value">{{ currentDetailData?.yearOnYearRatio }}</span>
          </div>
        </div>

        <el-table :data="detailTableData" class="detail-table">
          <el-table-column prop="time" label="时间" width="150" />
          <el-table-column prop="value" label="数值" width="120" />
          <el-table-column prop="unit" label="单位" width="80" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="row.status === '正常' ? 'success' : 'warning'" size="small">
                {{ row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" />
        </el-table>
      </div>
    </el-dialog>

    <!-- 趋势分析弹窗 -->
    <el-dialog
        v-model="trendDialogVisible"
        :title="`${currentTrendData?.category}趋势分析`"
        width="1000px"
        destroy-on-close
    >
      <div class="trend-content">
        <div class="trend-summary">
          <div class="trend-card">
            <h4>平均值</h4>
            <div class="trend-value">{{ trendAnalysis.average }}</div>
          </div>
          <div class="trend-card">
            <h4>最大值</h4>
            <div class="trend-value">{{ trendAnalysis.max }}</div>
          </div>
          <div class="trend-card">
            <h4>最小值</h4>
            <div class="trend-value">{{ trendAnalysis.min }}</div>
          </div>
          <div class="trend-card">
            <h4>增长率</h4>
            <div class="trend-value">{{ trendAnalysis.growthRate }}%</div>
          </div>
        </div>
        <div ref="trendChartRef" class="trend-chart" v-loading="trendChartLoading"></div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, watch } from 'vue';
import { listTopology } from '@/api/device/topology';
import { ElMessage } from 'element-plus';
import * as echarts from 'echarts';
import {
  DataAnalysis,
  OfficeBuilding,
  Refresh,
  Download,
  Lightning,
  Drizzling,
  Cpu,
  DataLine,
  DataBoard,
  TrendCharts,
  View,
  Warning
} from '@element-plus/icons-vue';

// 数据定义
const topologyList = ref([]);
const loading = ref(true);
const selectedNode = ref(null);
const timeRange = ref('month');
const chartType = ref('line');

// 加载状态
const refreshLoading = ref(false);
const exportLoading = ref(false);
const tableLoading = ref(false);
const chartLoading = ref(false);
const trendChartLoading = ref(false);

// 总体能耗数据
const energyStatistics = ref([]);
const electricityUsage = ref('');
const peakElectricity = ref('');
const peakTime = ref('');
const waterUsage = ref('');
const totalEnergyConsumption = ref('');

// 趋势数据
const electricityTrend = ref(0);
const waterTrend = ref(0);
const energyTrend = ref(0);

// 图表相关
const chartRef = ref(null);
const trendChartRef = ref(null);
let chartInstance = null;
let trendChartInstance = null;

// 弹窗相关
const detailDialogVisible = ref(false);
const trendDialogVisible = ref(false);
const currentDetailData = ref(null);
const currentTrendData = ref(null);
const detailTableData = ref([]);
// 继续上面的代码
const trendAnalysis = ref({
  average: 0,
  max: 0,
  min: 0,
  growthRate: 0
});

// 告警数据
const alerts = ref([
  {
    id: 1,
    title: '用电量异常',
    description: '当前用电量超过预设阈值15%，请及时检查设备运行状态',
    type: 'warning'
  },
  {
    id: 2,
    title: '峰值用电时间集中',
    description: '14:00-16:00时段用电量持续偏高，建议优化用电策略',
    type: 'info'
  }
]);

// 时间范围配置
const timeRangeConfig = {
  today: { label: '今日', days: 1 },
  week: { label: '本周', days: 7 },
  month: { label: '本月', days: 30 },
  year: { label: '本年', days: 365 }
};

// 获取树形数据
const getList = async () => {
  try {
    loading.value = true;
    const response = await listTopology({ pageNum: 1, pageSize: 10000 });
    topologyList.value = handleTree(response.rows, 'itemId', 'parentId', 'children');
    topologyList.value = injectDeviceNodes(topologyList.value);
  } catch (error) {
    ElMessage.error('加载数据失败');
  } finally {
    loading.value = false;
  }
};

// 处理树形结构的方法
const handleTree = (data, id, parentId, childrenName = 'children') => {
  const config = {
    id: id || 'id',
    parentId: parentId || 'parentId',
    childrenName: childrenName || 'children'
  };
  const tree = [];
  const map = {};
  data.forEach(item => (map[item[config.id]] = item));
  data.forEach(item => {
    const parent = map[item[config.parentId]];
    if (parent) {
      (parent[config.childrenName] || (parent[config.childrenName] = [])).push(item);
    } else {
      tree.push(item);
    }
  });
  return tree;
};

// 注入设备节点
function injectDeviceNodes(treeData) {
  return treeData.map(node => {
    const newNode = {...node};

    if (newNode.children && newNode.children.length > 0) {
      newNode.children = injectDeviceNodes(newNode.children);
    }

    if (newNode.deviceId && typeof newNode.deviceId === "string") {
      const deviceIds = newNode.deviceId.split(",").filter(Boolean);
      const deviceChildren = deviceIds.map(id => ({
        itemId: `${newNode.itemId}-${id}`,
        itemName: `设备: ${id}`,
        level: (newNode.level || 0) + 1,
        isDevice: true
      }));

      newNode.children = (newNode.children || []).concat(deviceChildren);
    }

    return newNode;
  });
}

// 点击节点
const handleNodeClick = (node) => {
  selectedNode.value = node;
  loadFloorEnergyData();
  nextTick(() => {
    initChart();
  });
};

// 时间范围变化处理
const handleTimeRangeChange = (value) => {
  tableLoading.value = true;
  setTimeout(() => {
    loadFloorEnergyData();
    updateChart();
    tableLoading.value = false;
  }, 500);
};

// 加载楼层总体能耗数据
const loadFloorEnergyData = () => {
  const config = timeRangeConfig[timeRange.value];
  const multiplier = getMultiplierByTimeRange(timeRange.value);

  // 根据时间范围生成不同的数据
  const baseElectricity = Math.random() * 500 + 500;
  const baseWater = Math.random() * 25 + 25;
  const baseEnergy = Math.random() * 150 + 150;

  electricityUsage.value = (baseElectricity * multiplier).toFixed(2);
  waterUsage.value = (baseWater * multiplier).toFixed(2);
  totalEnergyConsumption.value = (baseEnergy * multiplier).toFixed(2);

  // 生成趋势数据
  electricityTrend.value = (Math.random() * 20 - 5).toFixed(1);
  waterTrend.value = (Math.random() * 15 - 3).toFixed(1);
  energyTrend.value = (Math.random() * 25 - 8).toFixed(1);

  peakElectricity.value = (Math.random() * 100 + 200).toFixed(2);
  peakTime.value = generatePeakTime();

  // 生成统计数据
  energyStatistics.value = [
    {
      category: '用电量',
      value: `${electricityUsage.value} kWh`,
      ringRatio: `${electricityTrend.value}%${parseFloat(electricityTrend.value) >= 0 ? '↑' : '↓'}`,
      yearOnYearRatio: `${(Math.random() * 30 + 100).toFixed(1)}%↑`
    },
    {
      category: '用水量',
      value: `${waterUsage.value} t`,
      ringRatio: `${waterTrend.value}%${parseFloat(waterTrend.value) >= 0 ? '↑' : '↓'}`,
      yearOnYearRatio: `${(Math.random() * 25 + 105).toFixed(1)}%↑`
    },
    {
      category: '综合能耗',
      value: `${totalEnergyConsumption.value} kgce`,
      ringRatio: `${energyTrend.value}%${parseFloat(energyTrend.value) >= 0 ? '↑' : '↓'}`,
      yearOnYearRatio: `${(Math.random() * 35 + 110).toFixed(1)}%↑`
    }
  ];
};

// 根据时间范围获取倍数
const getMultiplierByTimeRange = (range) => {
  const multipliers = {
    today: 1,
    week: 7,
    month: 30,
    year: 365
  };
  return multipliers[range] || 1;
};

// 生成峰值时间
const generatePeakTime = () => {
  const ranges = {
    today: () => `${Math.floor(Math.random() * 24)}:${Math.floor(Math.random() * 60).toString().padStart(2, '0')}`,
    week: () => `周${Math.floor(Math.random() * 7) + 1} ${Math.floor(Math.random() * 24)}:00`,
    month: () => `${Math.floor(Math.random() * 30) + 1}日 ${Math.floor(Math.random() * 24)}:00`,
    year: () => `${Math.floor(Math.random() * 12) + 1}月${Math.floor(Math.random() * 30) + 1}日`
  };
  return ranges[timeRange.value]();
};

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return;

  chartLoading.value = true;

  setTimeout(() => {
    if (chartInstance) {
      chartInstance.dispose();
    }

    chartInstance = echarts.init(chartRef.value);
    updateChart();
    chartLoading.value = false;
  }, 300);
};

// 更新图表
const updateChart = () => {
  if (!chartInstance) return;

  const data = generateChartData();
  const option = {
    title: {
      text: `${timeRangeConfig[timeRange.value].label}能耗趋势`,
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'normal'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      data: ['用电量', '用水量', '综合能耗'],
      bottom: 10
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: data.categories,
      axisLine: {
        lineStyle: {
          color: '#e0e0e0'
        }
      }
    },
    yAxis: [
      {
        type: 'value',
        name: '用电量(kWh)/用水量(t)',
        position: 'left',
        axisLine: {
          lineStyle: {
            color: '#e0e0e0'
          }
        }
      },
      {
        type: 'value',
        name: '综合能耗(kgce)',
        position: 'right',
        axisLine: {
          lineStyle: {
            color: '#e0e0e0'
          }
        }
      }
    ],
    series: [
      {
        name: '用电量',
        type: chartType.value,
        data: data.electricity,
        itemStyle: {
          color: '#ff8c00'
        },
        smooth: true
      },
      {
        name: '用水量',
        type: chartType.value,
        data: data.water,
        itemStyle: {
          color: '#1e90ff'
        },
        smooth: true
      },
      {
        name: '综合能耗',
        type: chartType.value,
        yAxisIndex: 1,
        data: data.energy,
        itemStyle: {
          color: '#32cd32'
        },
        smooth: true
      }
    ]
  };

  chartInstance.setOption(option);
};

// 生成图表数据
const generateChartData = () => {
  const config = timeRangeConfig[timeRange.value];
  const categories = [];
  const electricity = [];
  const water = [];
  const energy = [];

  let points = 24; // 默认24个点
  if (timeRange.value === 'week') points = 7;
  else if (timeRange.value === 'month') points = 30;
  else if (timeRange.value === 'year') points = 12;

  for (let i = 0; i < points; i++) {
    // 生成时间标签
    let label = '';
    if (timeRange.value === 'today') {
      label = `${i}:00`;
    } else if (timeRange.value === 'week') {
      label = `周${i + 1}`;
    } else if (timeRange.value === 'month') {
      label = `${i + 1}日`;
    } else if (timeRange.value === 'year') {
      label = `${i + 1}月`;
    }

    categories.push(label);

    // 生成模拟数据
    const baseElec = parseFloat(electricityUsage.value) / points;
    const baseWater = parseFloat(waterUsage.value) / points;
    const baseEnergy = parseFloat(totalEnergyConsumption.value) / points;

    electricity.push((baseElec * (0.8 + Math.random() * 0.4)).toFixed(2));
    water.push((baseWater * (0.8 + Math.random() * 0.4)).toFixed(2));
    energy.push((baseEnergy * (0.8 + Math.random() * 0.4)).toFixed(2));
  }

  return { categories, electricity, water, energy };
};

// 切换图表类型
const changeChartType = (type) => {
  chartType.value = type;
  updateChart();
};

// 刷新数据
const refreshData = async () => {
  refreshLoading.value = true;
  try {
    await new Promise(resolve => setTimeout(resolve, 1000)); // 模拟API调用
    loadFloorEnergyData();
    updateChart();
    ElMessage.success('数据刷新成功');
  } catch (error) {
    ElMessage.error('刷新失败');
  } finally {
    refreshLoading.value = false;
  }
};

// 导出数据
const exportData = async () => {
  exportLoading.value = true;
  try {
    await new Promise(resolve => setTimeout(resolve, 1500)); // 模拟导出过程

    // 创建导出数据
    const exportContent = {
      节点名称: selectedNode.value.itemName,
      时间范围: timeRangeConfig[timeRange.value].label,
      总用电量: `${electricityUsage.value} kWh`,
      总用水量: `${waterUsage.value} t`,
      综合能耗: `${totalEnergyConsumption.value} kgce`,
      峰值用电: `${peakElectricity.value} kW`,
      峰值时间: peakTime.value,
      导出时间: new Date().toLocaleString()
    };

    // 实际项目中这里应该调用后端API生成Excel或PDF
    console.log('导出数据:', exportContent);
    ElMessage.success('报告导出成功');
  } catch (error) {
    ElMessage.error('导出失败');
  } finally {
    exportLoading.value = false;
  }
};

// 查看详情
const viewDetails = (row) => {
  currentDetailData.value = row;
  generateDetailData(row);
  detailDialogVisible.value = true;
};

// 生成详情数据
const generateDetailData = (row) => {
  const data = [];
  const config = timeRangeConfig[timeRange.value];
  let points = 10; // 详情显示最近10条记录

  for (let i = points - 1; i >= 0; i--) {
    const date = new Date();
    let timeStr = '';

    if (timeRange.value === 'today') {
      date.setHours(date.getHours() - i);
      timeStr = date.toLocaleTimeString();
    } else if (timeRange.value === 'week') {
      date.setDate(date.getDate() - i);
      timeStr = date.toLocaleDateString();
    } else if (timeRange.value === 'month') {
      date.setDate(date.getDate() - i * 3);
      timeStr = date.toLocaleDateString();
    } else {
      date.setMonth(date.getMonth() - i);
      timeStr = `${date.getFullYear()}年${date.getMonth() + 1}月`;
    }

    const baseValue = parseFloat(row.value.split(' ')[0]);
    const value = (baseValue * (0.8 + Math.random() * 0.4) / points).toFixed(2);
    const unit = row.value.split(' ')[1];

    data.push({
      time: timeStr,
      value: value,
      unit: unit,
      status: Math.random() > 0.8 ? '异常' : '正常',
      remark: Math.random() > 0.7 ? '数值偏高，需关注' : '运行正常'
    });
  }

  detailTableData.value = data;
};

// 趋势分析
const viewTrend = (row) => {
  currentTrendData.value = row;
  generateTrendAnalysis(row);
  trendDialogVisible.value = true;

  nextTick(() => {
    initTrendChart();
  });
};

// 生成趋势分析数据
const generateTrendAnalysis = (row) => {
  const baseValue = parseFloat(row.value.split(' ')[0]);
  const values = [];

  // 生成30天的历史数据
  for (let i = 0; i < 30; i++) {
    values.push(baseValue * (0.7 + Math.random() * 0.6));
  }

  const max = Math.max(...values);
  const min = Math.min(...values);
  const average = values.reduce((sum, val) => sum + val, 0) / values.length;
  const growthRate = ((values[values.length - 1] - values[0]) / values[0] * 100);

  trendAnalysis.value = {
    average: average.toFixed(2) + ' ' + row.value.split(' ')[1],
    max: max.toFixed(2) + ' ' + row.value.split(' ')[1],
    min: min.toFixed(2) + ' ' + row.value.split(' ')[1],
    growthRate: growthRate.toFixed(1)
  };
};

// 初始化趋势图表
const initTrendChart = () => {
  if (!trendChartRef.value) return;

  trendChartLoading.value = true;

  setTimeout(() => {
    if (trendChartInstance) {
      trendChartInstance.dispose();
    }

    trendChartInstance = echarts.init(trendChartRef.value);
    updateTrendChart();
    trendChartLoading.value = false;
  }, 300);
};

// 更新趋势图表
const updateTrendChart = () => {
  if (!trendChartInstance || !currentTrendData.value) return;

  const data = generateTrendChartData();
  const option = {
    title: {
      text: `${currentTrendData.value.category}30天趋势分析`,
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'normal'
      }
    },
    tooltip: {
      trigger: 'axis',
      formatter: function(params) {
        const param = params[0];
        return `${param.name}<br/>${param.seriesName}: ${param.value} ${currentTrendData.value.value.split(' ')[1]}`;
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: data.categories,
      axisLine: {
        lineStyle: {
          color: '#e0e0e0'
        }
      }
    },
    yAxis: {
      type: 'value',
      name: currentTrendData.value.value.split(' ')[1],
      axisLine: {
        lineStyle: {
          color: '#e0e0e0'
        }
      }
    },
    series: [
      {
        name: currentTrendData.value.category,
        type: 'line',
        data: data.values,
        smooth: true,
        itemStyle: {
          color: getColorByCategory(currentTrendData.value.category)
        },
        areaStyle: {
          opacity: 0.3
        },
        markPoint: {
          data: [
            { type: 'max', name: '最大值' },
            { type: 'min', name: '最小值' }
          ]
        },
        markLine: {
          data: [
            { type: 'average', name: '平均值' }
          ]
        }
      }
    ]
  };

  trendChartInstance.setOption(option);
};

// 生成趋势图表数据
const generateTrendChartData = () => {
  const categories = [];
  const values = [];
  const baseValue = parseFloat(currentTrendData.value.value.split(' ')[0]);

  for (let i = 29; i >= 0; i--) {
    const date = new Date();
    date.setDate(date.getDate() - i);
    categories.push(`${date.getMonth() + 1}/${date.getDate()}`);

    // 生成趋势数据，添加一些波动
    const trend = Math.sin(i * 0.2) * 0.1; // 添加周期性变化
    const noise = (Math.random() - 0.5) * 0.3; // 添加随机噪声
    const value = baseValue * (1 + trend + noise) / 30;
    values.push(Math.max(0, value).toFixed(2));
  }

  return { categories, values };
};

// 根据类别获取颜色
const getColorByCategory = (category) => {
  const colors = {
    '用电量': '#ff8c00',
    '用水量': '#1e90ff',
    '综合能耗': '#32cd32'
  };
  return colors[category] || '#409eff';
};

// 监听窗口大小变化，重新调整图表
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize();
  }
  if (trendChartInstance) {
    trendChartInstance.resize();
  }
};

// 页面初始化时加载数据
onMounted(() => {
  getList();
  window.addEventListener('resize', handleResize);
});

// 组件卸载时清理
onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose();
  }
  if (trendChartInstance) {
    trendChartInstance.dispose();
  }
  window.removeEventListener('resize', handleResize);
});

// 监听弹窗关闭，清理图表实例
watch(trendDialogVisible, (newVal) => {
  if (!newVal && trendChartInstance) {
    trendChartInstance.dispose();
    trendChartInstance = null;
  }
});
</script>

<style scoped>
/* 左侧树形表格样式保持不变 */
:deep(.custom-table .el-table__body tr.current-row > td) {
  background-color: #a6b9dd !important;
  border-radius: 12px !important;
  margin: 8px 0 !important;
}

:deep(.custom-table .el-table__body tr.current-row > td .cell) {
  color: #fff !important;
}

.custom-table :deep(.el-table__row) {
  background: transparent !important;
}

.custom-table :deep(.el-table__cell) {
  padding: 6px 0 !important;
  border: none !important;
}

.custom-table :deep(.el-table__cell .cell) {
  line-height: 15px !important;
  height: 15px !important;
}

.custom-table :deep(.el-table__inner-wrapper::before) {
  display: none;
}

.tree-container {
  height: 90vh;
  overflow-y: auto;
  background-color: white;
  color: #000000;
}

.app {
  display: flex;
  height: 90vh;
}

.sidebar {
  width: 300px;
  height: 100%;
  overflow: auto;
  background-color: white;
  border-right: 1px solid #e6e6e6;
}

/* 右侧主要内容区域样式 */
.main-content {
  flex: 1;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  overflow-y: auto;
}

/* 空状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  text-align: center;
  color: #909399;
}

.empty-state h3 {
  margin: 20px 0 10px;
  font-size: 18px;
  font-weight: 500;
}

.empty-state p {
  font-size: 14px;
  margin: 0;
}

/* 内容包装器 */
.content-wrapper {
  padding: 24px;
  max-width: 1400px;
  margin: 0 auto;
}

/* 页面头部 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 32px;
  padding: 24px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.header-left .page-title {
  display: flex;
  align-items: center;
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
}

.title-icon {
  margin-right: 12px;
  color: #409eff;
}

.page-subtitle {
  font-size: 14px;
  color: #909399;
  margin: 0;
}

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

/* 指标卡片网格 */
.metrics-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 20px;
  margin-bottom: 32px;
}

.metric-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  display: flex;
  align-items: center;
  transition: transform 0.2s, box-shadow 0.2s;
  position: relative;
  overflow: hidden;
}

.metric-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.12);
}

.metric-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
}

.metric-card.electricity::before {
  background: linear-gradient(90deg, #ffd700, #ff8c00);
}

.metric-card.water::before {
  background: linear-gradient(90deg, #00bfff, #1e90ff);
}

.metric-card.energy::before {
  background: linear-gradient(90deg, #32cd32, #228b22);
}

.metric-card.peak::before {
  background: linear-gradient(90deg, #ff6b6b, #ee5a24);
}

.metric-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
}

.electricity .metric-icon {
  background: linear-gradient(135deg, #ffd700, #ff8c00);
  color: white;
}

.water .metric-icon {
  background: linear-gradient(135deg, #00bfff, #1e90ff);
  color: white;
}

.energy .metric-icon {
  background: linear-gradient(135deg, #32cd32, #228b22);
  color: white;
}

.peak .metric-icon {
  background: linear-gradient(135deg, #ff6b6b, #ee5a24);
  color: white;
}

.metric-content {
  flex: 1;
}

.metric-value {
  font-size: 32px;
  font-weight: 700;
  color: #303133;
  line-height: 1;
  margin-bottom: 4px;
}

.metric-unit {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.metric-label {
  font-size: 16px;
  color: #606266;
  margin-bottom: 8px;
}

.metric-trend {
  display: flex;
  align-items: center;
  font-size: 12px;
  font-weight: 500;
}

.metric-trend.up {
  color: #f56c6c;
}

.metric-trend.down {
  color: #67c23a;
}

.metric-trend .el-icon {
  margin-right: 4px;
}

.metric-time {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

/* 数据区域 */
.data-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 32px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.section-title {
  display: flex;
  align-items: center;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.section-title .el-icon {
  margin-right: 8px;
  color: #409eff;
}

/* 表格样式 */
.energy-table {
  border-radius: 8px;
  overflow: hidden;
}

.category-cell {
  display: flex;
  align-items: center;
}

.category-icon {
  margin-right: 8px;
}

.electricity-icon {
  color: #ff8c00;
}

.water-icon {
  color: #1e90ff;
}

.energy-icon {
  color: #228b22;
}

.value-cell {
  font-weight: 600;
  font-size: 16px;
}

.trend-tag {
  font-weight: 500;
}

/* 图表区域 */
.charts-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 32px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.chart-container {
  width: 100%;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.chart-header h3 {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.chart-placeholder {
  height: 300px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #fafafa;
  border-radius: 8px;
  color: #909399;
}

.chart-placeholder p {
  margin-top: 16px;
  font-size: 14px;
}

/* 告警区域 */
.alerts-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.alerts-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.alert-item {
  border-radius: 8px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .metrics-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .content-wrapper {
    padding: 16px;
  }

  .page-header {
    flex-direction: column;
    gap: 16px;
  }

  .metrics-grid {
    grid-template-columns: 1fr;
  }

  .section-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
}

/* 滚动条样式 */
.main-content::-webkit-scrollbar {
  width: 6px;
}

.main-content::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.main-content::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.main-content::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 图表内容区域 */
.chart-content {
  height: 400px;
  width: 100%;
}

/* 详情弹窗样式 */
.detail-content {
  padding: 20px 0;
}

.detail-summary {
  display: flex;
  justify-content: space-around;
  margin-bottom: 24px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.summary-item {
  text-align: center;
}

.summary-item .label {
  display: block;
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.summary-item .value {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.detail-table {
  margin-top: 20px;
}

/* 趋势分析弹窗样式 */
.trend-content {
  padding: 20px 0;
}

.trend-summary {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  margin-bottom: 24px;
}

.trend-card {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  text-align: center;
  border-left: 4px solid #409eff;
}

.trend-card h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

.trend-value {
  font-size: 20px;
  font-weight: 600;
  color: #333;
}

.trend-chart {
  height: 400px;
  width: 100%;
}

/* 加载状态优化 */
.el-loading-mask {
  border-radius: 8px;
}

/* 响应式优化 */
@media (max-width: 768px) {
  .trend-summary {
    grid-template-columns: repeat(2, 1fr);
  }

  .detail-summary {
    flex-direction: column;
    gap: 16px;
  }

  .chart-content,
  .trend-chart {
    height: 300px;
  }
}

@media (max-width: 480px) {
  .trend-summary {
    grid-template-columns: 1fr;
  }
}

/* 表格优化 */
.energy-table .el-table__row:hover > td {
  background-color: #f5f7fa !important;
}

/* 按钮组优化 */
.el-button-group .el-button {
  border-radius: 0;
}

.el-button-group .el-button:first-child {
  border-top-left-radius: 4px;
  border-bottom-left-radius: 4px;
}

.el-button-group .el-button:last-child {
  border-top-right-radius: 4px;
  border-bottom-right-radius: 4px;
}

/* 弹窗优化 */
.el-dialog__body {
  padding: 20px 24px;
}

.el-dialog__header {
  padding: 20px 24px 10px;
  border-bottom: 1px solid #ebeef5;
}

/* 标签优化 */
.trend-tag {
  font-weight: 500;
  border: none;
}

/* 图表区域优化 */
.charts-section {
  min-height: 500px;
}

.chart-container {
  position: relative;
}

/* 空状态图标动画 */
.empty-icon {
  animation: float 3s ease-in-out infinite;
}

@keyframes float {
  0%, 100% {
    transform: translateY(0px);
  }
  50% {
    transform: translateY(-10px);
  }
}

/* 指标卡片悬停效果优化 */
.metric-card {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.metric-card:hover {
  transform: translateY(-4px) scale(1.02);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

/* 加载动画优化 */
.el-loading-spinner {
  margin-top: -21px;
}

.el-loading-spinner .circular {
  width: 42px;
  height: 42px;
}
</style>
