<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 class="energy-ranking" v-if="showRanking">
        <div class="ranking-controls">
          <el-select v-model="rankingType" placeholder="选择能耗类型">
            <el-option label="电量" value="electricity"></el-option>
            <el-option label="水量" value="water"></el-option>
            <el-option label="气量" value="gas"></el-option>
          </el-select>

          <el-select v-model="timeRange" placeholder="选择时间范围">
            <el-option label="日" value="day"></el-option>
            <el-option label="月" value="month"></el-option>
            <el-option label="年" value="year"></el-option>
          </el-select>

          <el-select v-model="department" placeholder="选择科室" v-if="showDepartment">
            <el-option
                v-for="dept in departments"
                :key="dept.id"
                :label="dept.name"
                :value="dept.id">
            </el-option>
          </el-select>

          <button @click="loadRankingData" class="ranking-btn">查询排名</button>
        </div>

        <el-table :data="rankingData" border style="width: 100%">
          <el-table-column prop="rank" label="排名" width="80"></el-table-column>
          <el-table-column prop="name" label="区域"></el-table-column>
          <el-table-column prop="value" :label="rankingTypeLabel"></el-table-column>
          <el-table-column prop="ratio" label="占比(%)"></el-table-column>
        </el-table>
        <div class="chart-row">
          <div ref="pieChartRef" class="chart-container"></div>
          <div ref="barChartRef" class="chart-container"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick,watch } 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 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;
  // 默认选择电量+日
  rankingType.value = 'electricity';
  timeRange.value = 'day';
  // 自动触发查询
  loadRankingData();
};

// 能耗排名相关数据
const showRanking = ref(true);
const rankingType = ref('electricity');
const timeRange = ref('day');
const department = ref('');
const departments = ref([]);
const rankingData = ref([]);
const showDepartment = computed(() => selectedNode.value?.type === 'department');

const rankingTypeLabel = computed(() => {
  switch(rankingType.value) {
    case 'electricity': return '用电量(kWh)';
    case 'water': return '用水量(t)';
    case 'gas': return '用气量(m³)';
    default: return '';
  }
});

// 修改查询按钮点击事件
const onQueryClick = () => {
  if (!rankingType.value || !timeRange.value) {
    ElMessage.warning('请选择能耗类型和时间范围');
    return;
  }
  loadRankingData();
};

const loadRankingData = async () => {
  try {
    if (!selectedNode.value) return;

    // 根据选择类型构建查询参数
    const params = {
      type: rankingType.value,
      range: timeRange.value,
      nodeId: selectedNode.value.itemId
    };

    if (showDepartment.value && department.value) {
      params.departmentId = department.value;
    }

    // 生成随机区域名称和模拟数据
    const generateRandomData = () => {
      const data = [];
      const regions = ['东区', '西区', '南区', '北区', '中区', 'A栋', 'B栋', 'C栋', 'D栋', 'E栋'];
      const maxValue = rankingType.value === 'electricity' ? 2000 :
          rankingType.value === 'water' ? 1000 : 500;

      // 随机打乱区域名称
      const shuffledRegions = [...regions].sort(() => 0.5 - Math.random());

      for (let i = 0; i < 10; i++) {
        const value = Math.floor(Math.random() * maxValue);
        data.push({
          rank: i + 1,
          name: shuffledRegions[i],
          value: value,
          ratio: `${Math.round((value / maxValue) * 100)}%`
        });
      }
      return data;
    };

    rankingData.value = generateRandomData();
  } catch (error) {
    ElMessage.error('获取排名数据失败');
  }
};

const pieChartRef = ref(null);
let pieChartInstance = null;

// 渲染图表
const renderChart = () => {
  if (!pieChartRef.value || !rankingData.value.length) return;

  if (!pieChartInstance) {
    pieChartInstance = echarts.init(pieChartRef.value);
  }

  const option = {
    title: {
      text: `${rankingTypeLabel.value}排名`,
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: rankingData.value.map(item => item.name)
    },
    series: [
      {
        name: '占比',
        type: 'pie',
        radius: '50%',
        data: rankingData.value.map(item => ({
          value: item.value,
          name: item.name
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  };

  pieChartInstance.setOption(option);
};

// 监听数据变化重新渲染图表
watch(rankingData, () => {
  nextTick(() => {
    renderChart();
  });
}, { deep: true });

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

const barChartRef = ref(null);
let barChartInstance = null;

// 渲染柱状图
const renderBarChart = () => {
  if (!barChartRef.value || !rankingData.value.length) return;

  if (!barChartInstance) {
    barChartInstance = echarts.init(barChartRef.value);
  }

  const option = {
    title: {
      text: `${rankingTypeLabel.value}排名柱状图`,
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    xAxis: {
      type: 'category',
      data: rankingData.value.map(item => item.name),
      axisLabel: {
        rotate: 30
      }
    },
    yAxis: {
      type: 'value',
      name: rankingTypeLabel.value
    },
    series: [{
      name: '能耗值',
      type: 'bar',
      data: rankingData.value.map(item => item.value),
      itemStyle: {
        color: function(params) {
          const colorList = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de'];
          return colorList[params.dataIndex % colorList.length];
        }
      }
    }]
  };

  barChartInstance.setOption(option);
};

// 监听数据变化重新渲染图表
watch(rankingData, () => {
  nextTick(() => {
    renderBarChart();
  });
}, { deep: true });

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

onBeforeUnmount(() => {
  if (pieChartInstance) {
    pieChartInstance.dispose();
    pieChartInstance = null;
  }
  if (barChartInstance) {
    barChartInstance.dispose();
    barChartInstance = null;
  }
  window.removeEventListener('resize', () => {
    if (pieChartInstance) pieChartInstance.resize();
    if (barChartInstance) barChartInstance.resize();
  });
});
// 页面初始化时加载数据
onMounted(() => {
  getList();
});

</script>

<style scoped>
.chart-row {
  display: flex;
  gap: 20px;
  margin-top: 20px;
}

.chart-container {
  flex: 1;
  height: 300px;
  min-width: 0; /* 防止图表溢出 */
}
.energy-ranking {
  margin-bottom: 20px;
  padding: 15px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.ranking-controls {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
}

.ranking-controls .el-select {
  width: 150px;
}

.ranking-btn {
  padding: 8px 16px;
  background-color: #2196f3;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}



/* 左侧树形表格高亮样式 */
: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: 90vh; /* 调整高度计算方式 */
  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>
