<template>
  <div class="app">
    <!-- 左侧区域 -->
    <div class="sidebar">
      <!-- 日期选择 -->
      <div class="date-picker">
        <input type="date" v-model="startDate" placeholder="开始日期" />
        <span>-</span>
        <input type="date" v-model="endDate" placeholder="结束日期" />
      </div>

      <!-- 树形结构 -->
      <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>

      <!-- 生成报告按钮 -->
      <button class="generate-report-btn" @click="generateReport">生成分析报告</button>
    </div>

    <!-- 右侧区域 -->
    <div class="main-content">
      <!-- 分析报告 -->
      <div class="report-container">
        <button @click="printReport" class="print-btn">打印</button>
        <div class="qy">
          <h1>分析报告</h1>
          <p>{{ startDate }} ~ {{ endDate }}</p>

          <!-- 用能统计 -->
          <!-- 用能统计 -->
          <h3 v-if="energyStatistics.length > 0">1、用能统计</h3>
          <el-table v-if="energyStatistics.length > 0" :data="energyStatistics" border style="width: 60%;margin: 0 auto">
            <el-table-column prop="category" label="分类" width="180" />
            <el-table-column prop="value" label="数值" />
            <el-table-column prop="ringRatio" label="环比（%）" />
            <el-table-column prop="yearOnYearRatio" label="同比（%）" />
          </el-table>
          <!-- 用电量详细说明 -->

          <p v-if="electricityUsage">
            <h3>2、用电量</h3>
            本周期内，共计使用电力 {{ electricityUsage }} kWh，最大用电量 {{ peakElectricity }} kW，最大负荷发生时间 {{ peakTime }}。
          </p>

          <!-- 图表区域 -->
          <div class="chart-section">
            <div v-for="(chartData, index) in chartDatas" :key="index" class="chart-item">
              <h4>图表 {{ index + 1 }}</h4>
              <div :id="`chart${index}`" :ref="`chartRef${index}`" class="chart" style="width: 100%; height: 300px;"></div>
            </div>
          </div>
        </div>

      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue';
import * as echarts from 'echarts';
import { listTopology } from '@/api/device/topology'; // 假设你有这些接口
import { ElMessage } from 'element-plus';

// 数据定义
const startDate = ref('2025-05-01');
const endDate = ref('2025-05-08');
const topologyList = ref([]);
const loading = ref(true);
const selectedNode = ref(null);
const energyStatistics = ref([]); // 初始化为空数组
const electricityUsage = ref(''); // 初始化为空
const peakElectricity = ref(''); // 初始化为空
const peakTime = ref(''); // 初始化为空
const generateReport = async () => {
  if (!selectedNode.value) {
    alert('请先选择一个节点');
    return;
  }

  // 生成用能统计数据
  energyStatistics.value = [
    {
      category: '用电量',
      value: `${(Math.random() * 1000 + 1000).toFixed(2)} kWh`,
      ringRatio: `${(Math.random() * 10).toFixed(2)}↑`,
      yearOnYearRatio: `${(Math.random() * 15 + 100).toFixed(2)}↑`
    },
    {
      category: '用水量',
      value: `${(Math.random() * 50).toFixed(2)} t`,
      ringRatio: `${(Math.random() * 10).toFixed(2)}↑`,
      yearOnYearRatio: `${(Math.random() * 15 + 100).toFixed(2)}↑`
    },
    {
      category: '综合能耗',
      value: `${(Math.random() * 300).toFixed(2)} kgce`,
      ringRatio: `${(Math.random() * 10).toFixed(2)}↑`,
      yearOnYearRatio: `${(Math.random() * 15 + 100).toFixed(2)}↑`
    },
    {
      category: '碳排放量',
      value: `${(Math.random() * 2000).toFixed(2)} kg`,
      ringRatio: `${(Math.random() * 10).toFixed(2)}↑`,
      yearOnYearRatio: `${(Math.random() * 15 + 100).toFixed(2)}↑`
    }
  ];

  // 生成用电量数据
  electricityUsage.value = (Math.random() * 1000 + 1000).toFixed(2);
  peakElectricity.value = (Math.random() * 100 + 200).toFixed(2);
  peakTime.value = `${Math.floor(Math.random() * 12) + 1}-${Math.floor(Math.random() * 30) + 1}`;

  if (!selectedNode.value) {
    alert('请先选择一个节点');
    return;
  }

  // 模拟生成报告内容
  electricityUsage.value = Math.random() * 1000 + 1000; // 随机生成用电量
  peakElectricity.value = Math.random() * 100 + 200; // 随机生成最大用电量
  peakTime.value = `${Math.floor(Math.random() * 12) + 1}-${Math.floor(Math.random() * 30) + 1}`; // 随机生成时间

  // 更新图表数据 - 改为随机生成
  chartDatas.value = [
    {
      title: '用电量分布',
      data: Array(7).fill(0).map(() => Math.floor(Math.random() * 200) + 50)
    },
    {
      title: '用水量分布',
      data: Array(7).fill(0).map(() => Math.floor(Math.random() * 100) + 30)
    },
    {
      title: '综合能耗分布',
      data: Array(7).fill(0).map(() => Math.floor(Math.random() * 300) + 100)
    },
    {
      title: '碳排放量分布',
      data: Array(7).fill(0).map(() => Math.floor(Math.random() * 80) + 20)
    },
  ];

  // 初始化或更新图表
  await nextTick();
  chartDatas.value.forEach((chartData, index) => {
    const chartInstance = echarts.getInstanceByDom(document.getElementById(`chart${index}`));
    if (chartInstance) {
      updateChart(index, chartData);
    } else {
      initChart(index, chartData);
    }
  });
};

// 图表数据
const chartDatas = ref([]);

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

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

// 生成报告
/*const generateReport = async () => {
  if (!selectedNode.value) {
    alert('请先选择一个节点');
    return;
  }

  // 模拟生成报告内容
  electricityUsage.value = Math.random() * 1000 + 1000; // 随机生成用电量
  peakElectricity.value = Math.random() * 100 + 200; // 随机生成最大用电量
  peakTime.value = `${Math.floor(Math.random() * 12) + 1}-${Math.floor(Math.random() * 30) + 1}`; // 随机生成时间

  // 更新图表数据
  chartDatas.value = [
    { title: '用电量分布', data: [120, 200, 150, 80, 70, 110, 130] },
    { title: '用水量分布', data: [80, 100, 120, 90, 110, 130, 150] },
    { title: '综合能耗分布', data: [200, 250, 300, 220, 280, 320, 350] },
    { title: '碳排放量分布', data: [50, 60, 70, 55, 65, 75, 80] },
  ];

  // 初始化图表
  await nextTick(); // 确保 DOM 更新完成
  chartDatas.value.forEach((chartData, index) => {
    initChart(index, chartData);
  });
};*/

// 初始化图表
const initChart = (index, chartData) => {
  const chartDom = document.getElementById(`chart${index}`);
  const chartInstance = echarts.init(chartDom);

  const option = {
    title: { text: chartData.title, left: 'center' },
    tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
    xAxis: {
      type: 'category',
      data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
      axisLabel: { color: '#333' }
    },
    yAxis: {
      type: 'value',
      axisLabel: { color: '#333' }
    },
    series: [
      {
        name: chartData.title,
        type: 'bar',
        data: chartData.data,
        itemStyle: { color: getRandomColor() }
      }
    ],
    grid: {
      top: 30,
      bottom: 30,
      left: 60,
      right: 20
    }
  };

  chartInstance.setOption(option);
};

// 更新图表
const updateChart = (index, chartData) => {
  const chartInstance = echarts.getInstanceByDom(document.getElementById(`chart${index}`));
  if (chartInstance) {
    chartInstance.setOption({
      series: [{ data: chartData.data }]
    });
  }
};

// 页面初始化时加载数据
onMounted(() => {
  getList();
});

// 随机颜色生成函数
function getRandomColor() {
  const letters = '0123456789ABCDEF';
  let color = '#';
  for (let i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}

const printReport = async () => {
  // 获取所有图表实例并生成图片
  const chartImages = [];
  for (let i = 0; i < chartDatas.value.length; i++) {
    const chartInstance = echarts.getInstanceByDom(document.getElementById(`chart${i}`));
    if (chartInstance) {
      const img = new Image();
      img.src = chartInstance.getDataURL({
        type: 'png',
        pixelRatio: 2,
        backgroundColor: '#fff'
      });
      chartImages.push(img);
    }
  }

  // 等待所有图片加载完成
  await Promise.all(chartImages.map(img => new Promise(resolve => {
    img.onload = resolve;
  })));

  // 创建打印内容
  const printWindow = window.open('', '_blank');
  printWindow.document.write(`
    <html>
      <head>
        <title>分析报告</title>
        <style>
          body { font-family: Arial; padding: 20px; }
          table { width: 60%; margin: 20px auto; border-collapse: collapse; }
          th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
          .chart-img { width: 100%; margin: 20px 0; }
        </style>
      </head>
      <body>
        <h1>分析报告</h1>
        <p>${startDate.value} ~ ${endDate.value}</p>

        <h3>1、用能统计</h3>
        <table border="1">
          <tr>
            <th>分类</th>
            <th>数值</th>
            <th>环比（%）</th>
            <th>同比（%）</th>
          </tr>
          ${energyStatistics.value.map(item => `
            <tr>
              <td>${item.category}</td>
              <td>${item.value}</td>
              <td>${item.ringRatio}</td>
              <td>${item.yearOnYearRatio}</td>
            </tr>
          `).join('')}
        </table>

        <h3>2、用电量</h3>
        <p>
          本周期内，共计使用电力 ${electricityUsage.value} kWh，最大用电量 ${peakElectricity.value} kW，最大负荷发生时间 ${peakTime.value}。
        </p>

        <h3>3、图表分析</h3>
        ${chartImages.map((img, index) => `
          <h4>图表 ${index + 1}</h4>
          <img class="chart-img" src="${img.src}" />
        `).join('')}
      </body>
    </html>
  `);
  printWindow.document.close();
  printWindow.focus();
  setTimeout(() => {
    printWindow.print();
    printWindow.close();
  }, 500);
};

</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: 990px; /* 可根据需要调整高度 */
  overflow-y: auto;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}
.qy{
  background-color: white;
  width: 1000px;
  margin: 0 auto;
  border: 1px solid #ddd;
}
/* 报告打印按钮*/
.print-btn {
  position: absolute;
  top: 30px;
  left: 380px;
  padding: 8px 16px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  z-index: 100;
}

@media print {
  .print-btn {
    display: none;
  }
  body * {
    visibility: hidden;
  }
  .qy, .qy * {
    visibility: visible;
  }
  .qy {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
  }
}

.app {
  display: flex;
  background-color: #15203b;
  color: white;
  overflow: hidden; /* 防止外层滚动条 */
}

.sidebar {
  width: 350px;
  padding: 10px;
  background-color: white;
}

.report-container {
  text-align: center;
  height: calc(100vh - 124px);
  overflow-y: auto;
  padding: 20px;
  border: 1px solid #ddd; /* 新增边框 */
  border-radius: 8px; /* 圆角边框 */
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1); /* 阴影效果 */
  background-color: white; /* 白色背景 */
}

.chart-section {
  display: flex;
  flex-direction: column; /* 改为垂直排列 */
  align-items: center;
  gap: 20px;
  margin: 20px auto;
  padding-bottom: 20px;
  width: 100%;
}

.chart-item {
  width: 90%; /* 增加宽度 */
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.date-picker input {
  padding: 6px 10px;
  border: none;
  border-radius: 4px;
  background-color: white;
  color: #090909;
  border: 1px solid #ddd;
  margin-right: 10px;
}

.generate-report-btn {
  padding: 10px 20px;
  background-color: #2196f3;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-top: 20px;
  width: 100%;
}

.tree-container {
  height: 70vh; /* 调整高度计算方式 */
  overflow-y: auto;

  background-color: white;
  color: #000000;
}

.custom-table {
  background-color: inherit;
  color: inherit;
}

.main-content {
  flex: 1;
  padding: 20px;
  background-color: #fff;
  color: #333;
  overflow-y: hidden;
}

.chart-item {
  width: 48%;
  margin-bottom: 20px;
}

.chart {
  border: 1px solid #ddd;
  border-radius: 8px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

/* 表格样式 */
.el-table {
  margin-top: 20px;
}

.el-table th {
  background-color: #2196f3;
  color: white;
}
</style>
