<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="query-section">
        <el-select
            v-model="selectedEnergyType"
            placeholder="请选择能源类型"
            style="width: 200px"
        >
          <el-option label="用电量 (kWh)" value="electricity" />
          <el-option label="用水量 (t)" value="water" />
          <el-option label="用气量 (m³)" value="gas" />
        </el-select>
        <el-button
            type="primary"
            @click="fetchEnergyData"
        >
          查询
        </el-button>
      </div>
      <h2 v-if="selectedNodeName">{{ selectedNodeName }} 能耗使用情况</h2>

      <div class="progress-card" v-if="energyData">
        <div class="progress-header">
          <span>总限值：{{ energyData.limit }} {{ unit }}</span>
          <span>已使用：{{ energyData.used }} {{ unit }}</span>
          <span>剩余：{{ energyData.remaining }} {{ unit }}</span>
          <span>使用率：{{ energyData.percentage }}%</span>
        </div>
        <el-progress
            :percentage="energyData.percentage"
            :status="progressStatus"
            :stroke-width="20"
        ></el-progress>
      </div>

      <div class="tip" v-else>
        请选择左侧区域和能源类型后点击“查询”按钮
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, 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 selectedNodeName = computed(() => selectedNode.value ? selectedNode.value.itemName : '');
const selectedEnergyType = ref('electricity');
const unit = computed(() => {
  switch (selectedEnergyType.value) {
    case 'electricity':
      return 'kWh';
    case 'water':
      return 't';
    case 'gas':
      return 'm³';
    default:
      return '';
  }
});
const energyData = ref(null);

const progressStatus = computed(() => {
  if (!energyData.value) return '';
  return energyData.value.percentage >= 100 ? 'exception' : '';
});

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;
  selectedEnergyType.value = 'electricity'; // 默认选择电
  fetchEnergyData(); // 自动触发查询
};

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

  // 模拟数据 - 实际项目中应该调用API获取
  const limit = Math.random() * 10000 + 5000; // 总限值
  const used = Math.random() * limit; // 已使用
  const remaining = limit - used; // 剩余
  const percentage = (used / limit) * 100; // 使用率

  energyData.value = {
    limit: parseFloat(limit.toFixed(2)),
    used: parseFloat(used.toFixed(2)),
    remaining: parseFloat(remaining.toFixed(2)),
    percentage: parseFloat(percentage.toFixed(2))
  };
};

onMounted(() => {
  getList();
});
</script>

<style scoped>
.app {
  display: flex;
  background-color: #f5f7fa;
  color: #333;
  overflow: hidden;
}

.sidebar {
  width: 300px;
  padding: 20px;
  background-color: #fff;
  border-right: 1px solid #ddd;
}

.tree-container {
  height: 84vh;
  overflow-y: auto;
}

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

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

.query-section {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  align-items: center;
}

.progress-card {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.progress-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.tip {
  color: #999;
  margin-top: 20px;
}

/* 左侧树形表格高亮样式 */
: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;
}
</style>
