<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="floor-summary" v-if="selectedNode">
        <h2>{{ selectedNode.itemName }} 总体能耗</h2>
        <el-table :data="energyStatistics" border style="width: 100%">
          <el-table-column prop="category" label="能耗类型"></el-table-column>
          <el-table-column prop="value" label="数值"></el-table-column>
          <el-table-column prop="ringRatio" label="环比"></el-table-column>
          <el-table-column prop="yearOnYearRatio" label="同比"></el-table-column>
        </el-table>
        <div class="summary-details">
          <p>总用电量: {{ electricityUsage }} kWh</p>
          <p>总用水量: {{ waterUsage }} t</p>
          <p>综合能耗: {{ totalEnergyConsumption }} kgce</p>
          <p>峰值用电量: {{ peakElectricity }} kW</p>
          <p>峰值时间: {{ peakTime }}</p>
        </div>
      </div>
    </div>
  </div>
</template>

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

// 数据定义
const topologyList = ref([]);
const loading = ref(true);
const selectedNode = ref(null);

// 总体能耗数据
const energyStatistics = ref([]);
const electricityUsage = ref('');
const peakElectricity = ref('');
const peakTime = ref('');
const waterUsage = ref('');
const totalEnergyConsumption = 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;
    topologyList.value = injectDeviceNodes(topologyList.value);
  } 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;
  loadFloorEnergyData();
};

// 加载楼层总体能耗数据
const loadFloorEnergyData = () => {
  // 模拟数据 - 实际项目中应该调用API获取
  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)}↑`
    }
  ];
  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}`;

  // 新增用水量和综合能耗数据
  waterUsage.value = (Math.random() * 50).toFixed(2);
  totalEnergyConsumption.value = (Math.random() * 300).toFixed(2);
};

function injectDeviceNodes(treeData) {
  return treeData.map(node => {
    const newNode = {...node};

    // 递归处理子节点
    if (newNode.children && newNode.children.length > 0) {
      newNode.children = injectDeviceNodes(newNode.children);
    }

    // 处理当前节点的 deviceId
    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;
  });
}
// 页面初始化时加载数据
onMounted(() => {
  getList();
});
</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;
}
.main-content {
  flex: 1;
  padding: 20px;
  background-color: #fff;
  color: #333;
  overflow-y: hidden;
}
.floor-summary {
  margin-bottom: 20px;
  padding: 15px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}
.summary-details {
  margin-top: 10px;
  font-size: 14px;
  color: #555;
}
.el-table {
  margin-top: 20px;
}
.el-table th {
  background-color: #2196f3;
  color: white;
}

.app {
  display: flex;
}

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

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

.floor-summary {
  margin-left: 20px;
  padding: 15px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}
</style>
