<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="content-header">
        <h1 class="page-title">
          <i class="el-icon-data-analysis"></i>
          能耗监控系统
          <div class="breadcrumb" v-if="selectedNodeName">
            <span>当前选择：</span>
            <el-tag type="primary" size="large">{{ selectedNodeName }}</el-tag>
          </div>
        </h1>

      </div>

      <!-- 查询控制面板 -->
      <div class="control-panel">
        <div class="query-section">
          <div class="query-item">
            <label>能源类型：</label>
            <el-select
                v-model="selectedEnergyType"
                placeholder="请选择能源类型"
                size="large"
                style="width: 200px"
            >
              <el-option label="用电量 (kWh)" value="electricity">
                <i class="el-icon-lightning" style="margin-right: 8px;"></i>
                用电量 (kWh)
              </el-option>
              <el-option label="用水量 (t)" value="water">
                <i class="el-icon-water-cup" style="margin-right: 8px;"></i>
                用水量 (t)
              </el-option>
              <el-option label="用气量 (m³)" value="gas">
                <i class="el-icon-wind-power" style="margin-right: 8px;"></i>
                用气量 (m³)
              </el-option>
            </el-select>
          </div>

          <div class="query-item">
            <label>时间范围：</label>
            <el-select v-model="timeRange" size="large" style="width: 150px">
              <el-option label="今日" value="today" />
              <el-option label="本周" value="week" />
              <el-option label="本月" value="month" />
              <el-option label="本年" value="year" />
            </el-select>
          </div>

          <el-button
              type="primary"
              size="large"
              @click="fetchEnergyData"
              :loading="queryLoading"
              icon="el-icon-search"
          >
            查询数据
          </el-button>
        </div>
      </div>

      <!-- 数据展示区域 -->
      <div class="data-display" v-if="energyData">
        <!-- 统计卡片 -->
        <div class="stats-cards">
          <div class="stat-card limit-card">
            <div class="card-icon">
              <i class="el-icon-aim"></i>
            </div>
            <div class="card-content">
              <div class="card-title">总限值</div>
              <div class="card-value">{{ energyData.limit }} <span class="unit">{{ unit }}</span></div>
            </div>
          </div>

          <div class="stat-card used-card">
            <div class="card-icon">
              <i class="el-icon-pie-chart"></i>
            </div>
            <div class="card-content">
              <div class="card-title">已使用</div>
              <div class="card-value">{{ energyData.used }} <span class="unit">{{ unit }}</span></div>
            </div>
          </div>

          <div class="stat-card remaining-card">
            <div class="card-icon">
              <i class="el-icon-coin"></i>
            </div>
            <div class="card-content">
              <div class="card-title">剩余量</div>
              <div class="card-value">{{ energyData.remaining }} <span class="unit">{{ unit }}</span></div>
            </div>
          </div>

          <div class="stat-card percentage-card" :class="{ 'warning': energyData.percentage >= 80, 'danger': energyData.percentage >= 95 }">
            <div class="card-icon">
              <i class="el-icon-data-line"></i>
            </div>
            <div class="card-content">
              <div class="card-title">使用率</div>
              <div class="card-value">{{ energyData.percentage }}%</div>
            </div>
          </div>
        </div>

        <!-- 进度条展示 -->
        <div class="progress-section">
          <div class="section-title">
            <h3>使用情况详情</h3>
            <div class="progress-legend">
              <span class="legend-item normal">
                <span class="legend-color normal"></span>
                正常 (0-79%)
              </span>
              <span class="legend-item warning">
                <span class="legend-color warning"></span>
                警告 (80-94%)
              </span>
              <span class="legend-item danger">
                <span class="legend-color danger"></span>
                超限 (95%+)
              </span>
            </div>
          </div>

          <div class="progress-card">
            <div class="progress-info">
              <div class="progress-text">
                <span class="current-usage">当前使用：{{ energyData.used }} {{ unit }}</span>
                <span class="usage-rate" :class="getUsageRateClass()">{{ energyData.percentage }}%</span>
              </div>
              <div class="progress-bar-container">
                <el-progress
                    :percentage="energyData.percentage"
                    :status="progressStatus"
                    :stroke-width="24"
                    :show-text="false"
                    class="custom-progress"
                ></el-progress>
              </div>
              <div class="progress-marks">
                <span class="mark start">0</span>
                <span class="mark warning">80%</span>
                <span class="mark danger">95%</span>
                <span class="mark end">{{ energyData.limit }} {{ unit }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 趋势分析 -->
        <div class="trend-section">
          <div class="section-title">
            <h3>使用趋势分析</h3>
          </div>
          <div class="trend-cards">
            <div class="trend-card">
              <div class="trend-header">
                <span class="trend-title">日均使用量</span>
                <i class="el-icon-trend-charts"></i>
              </div>
              <div class="trend-value">{{ dailyAverage }} {{ unit }}</div>
              <div class="trend-change positive">
                <i class="el-icon-top"></i>
                较昨日 +5.2%
              </div>
            </div>

            <div class="trend-card">
              <div class="trend-header">
                <span class="trend-title">预计剩余天数</span>
                <i class="el-icon-time"></i>
              </div>
              <div class="trend-value">{{ remainingDays }} 天</div>
              <div class="trend-change negative">
                <i class="el-icon-bottom"></i>
                较上周 -2天
              </div>
            </div>

            <div class="trend-card">
              <div class="trend-header">
                <span class="trend-title">效率评级</span>
                <i class="el-icon-medal"></i>
              </div>
              <div class="trend-value">{{ efficiencyGrade }}</div>
              <div class="trend-change">
                <el-rate v-model="efficiencyRating" disabled show-score text-color="#ff9900" score-template="{value}"></el-rate>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div class="empty-state" v-else>
        <div class="empty-icon">
          <i class="el-icon-data-board"></i>
        </div>
        <div class="empty-text">
          <h3>暂无数据</h3>
          <p>请选择左侧区域节点和能源类型后点击"查询数据"按钮</p>
        </div>
      </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 queryLoading = ref(false);
const selectedNode = ref(null);
const selectedNodeName = computed(() => selectedNode.value ? selectedNode.value.itemName : '');
const selectedEnergyType = ref('electricity');
const timeRange = ref('today');
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 '';
  if (energyData.value.percentage >= 95) return 'exception';
  if (energyData.value.percentage >= 80) return 'warning';
  return 'success';
});

const dailyAverage = computed(() => {
  if (!energyData.value) return 0;
  return (energyData.value.used / 30).toFixed(2);
});

const remainingDays = computed(() => {
  if (!energyData.value || dailyAverage.value <= 0) return 0;
  return Math.floor(energyData.value.remaining / dailyAverage.value);
});

const efficiencyGrade = computed(() => {
  if (!energyData.value) return 'N/A';
  const percentage = energyData.value.percentage;
  if (percentage < 60) return '优秀';
  if (percentage < 80) return '良好';
  if (percentage < 95) return '一般';
  return '需改进';
});

const efficiencyRating = computed(() => {
  if (!energyData.value) return 0;
  const percentage = energyData.value.percentage;
  if (percentage < 60) return 5;
  if (percentage < 80) return 4;
  if (percentage < 95) return 3;
  return 2;
});

const getUsageRateClass = () => {
  if (!energyData.value) return '';
  if (energyData.value.percentage >= 95) return 'danger';
  if (energyData.value.percentage >= 80) return 'warning';
  return 'normal';
};

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;
  energyData.value = null; // 清空之前的数据
};

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

  try {
    queryLoading.value = true;

    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 1000));

    // 模拟数据 - 实际项目中应该调用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))
    };

    ElMessage.success('数据查询成功');
  } catch (error) {
    ElMessage.error('查询数据失败');
  } finally {
    queryLoading.value = false;
  }
};

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

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

.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: 0;
  background-color: #f8fafc;
  overflow-y: auto;
}

/* 顶部标题栏 */
.content-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 24px 32px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.page-title {
  margin: 0 0 12px 0;
  font-size: 28px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 12px;
}

.breadcrumb {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  opacity: 0.9;
}

/* 控制面板 */
.control-panel {
  background: white;
  margin: 24px 32px;
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.query-section {
  display: flex;
  gap: 24px;
  align-items: end;
  flex-wrap: wrap;
}

.query-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.query-item label {
  font-weight: 500;
  color: #374151;
  font-size: 14px;
}

/* 数据展示区域 */
.data-display {
  margin: 0 32px 32px 32px;
}

/* 统计卡片 */
.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 20px;
  margin-bottom: 32px;
}

.stat-card {
  background: white;
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  display: flex;
  align-items: center;
  gap: 16px;
  transition: all 0.3s ease;
  border-left: 4px solid #e5e7eb;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.limit-card {
  border-left-color: #3b82f6;
}

.used-card {
  border-left-color: #f59e0b;
}

.remaining-card {
  border-left-color: #10b981;
}

.percentage-card {
  border-left-color: #6366f1;
}

.percentage-card.warning {
  border-left-color: #f59e0b;
  background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
}

.percentage-card.danger {
  border-left-color: #ef4444;
  background: linear-gradient(135deg, #fee2e2 0%, #fecaca 100%);
}

.card-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.limit-card .card-icon {
  background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
}

.used-card .card-icon {
  background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
}

.remaining-card .card-icon {
  background: linear-gradient(135deg, #10b981 0%, #059669 100%);
}

.percentage-card .card-icon {
  background: linear-gradient(135deg, #6366f1 0%, #4f46e5 100%);
}

.card-content {
  flex: 1;
}

.card-title {
  font-size: 14px;
  color: #6b7280;
  margin-bottom: 4px;
  font-weight: 500;
}

.card-value {
  font-size: 24px;
  font-weight: 700;
  color: #111827;
  display: flex;
  align-items: baseline;
  gap: 4px;
}

.unit {
  font-size: 14px;
  color: #6b7280;
  font-weight: 400;
}

/* 进度条区域 */
.progress-section {
  background: white;
  padding: 32px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  margin-bottom: 32px;
}

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

.section-title h3 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #111827;
}

.progress-legend {
  display: flex;
  gap: 16px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: #6b7280;
}

.legend-color {
  width: 12px;
  height: 12px;
  border-radius: 2px;
}

.legend-color.normal {
  background-color: #10b981;
}

.legend-color.warning {
  background-color: #f59e0b;
}

.legend-color.danger {
  background-color: #ef4444;
}

.progress-card {
  background: #f8fafc;
  padding: 24px;
  border-radius: 8px;
  border: 1px solid #e5e7eb;
}

.progress-info {
  width: 100%;
}

.progress-text {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.current-usage {
  font-size: 16px;
  font-weight: 500;
  color: #374151;
}

.usage-rate {
  font-size: 20px;
  font-weight: 700;
  padding: 4px 12px;
  border-radius: 20px;
}

.usage-rate.normal {
  color: #059669;
  background-color: #d1fae5;
}

.usage-rate.warning {
  color: #d97706;
  background-color: #fef3c7;
}

.usage-rate.danger {
  color: #dc2626;
  background-color: #fee2e2;
}

.progress-bar-container {
  margin-bottom: 12px;
}

.progress-marks {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #6b7280;
}

.mark {
  position: relative;
}

.mark.warning::before,
.mark.danger::before {
  content: '';
  position: absolute;
  top: -28px;
  left: 50%;
  transform: translateX(-50%);
  width: 2px;
  height: 20px;
  background-color: currentColor;
}

.mark.warning {
  color: #f59e0b;
}

.mark.danger {
  color: #ef4444;
}

/* 趋势分析 */
.trend-section {
  background: white;
  padding: 32px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.trend-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 20px;
}

.trend-card {
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  padding: 24px;
  border-radius: 12px;
  border: 1px solid #e2e8f0;
  transition: all 0.3s ease;
}

.trend-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
}

.trend-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.trend-title {
  font-size: 14px;
  color: #64748b;
  font-weight: 500;
}

.trend-header i {
  font-size: 20px;
  color: #94a3b8;
}

.trend-value {
  font-size: 28px;
  font-weight: 700;
  color: #1e293b;
  margin-bottom: 8px;
}

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

.trend-change.positive {
  color: #059669;
}

.trend-change.negative {
  color: #dc2626;
}

.trend-change i {
  font-size: 12px;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80px 32px;
  text-align: center;
}

.empty-icon {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  background: linear-gradient(135deg, #f3f4f6 0%, #e5e7eb 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 24px;
}

.empty-icon i {
  font-size: 48px;
  color: #9ca3af;
}

.empty-text h3 {
  margin: 0 0 8px 0;
  font-size: 20px;
  color: #374151;
}

.empty-text p {
  margin: 0;
  color: #6b7280;
  font-size: 14px;
}

/* 自定义进度条样式 */
:deep(.custom-progress .el-progress-bar__outer) {
  background-color: #f3f4f6;
  border-radius: 12px;
}

:deep(.custom-progress .el-progress-bar__inner) {
  border-radius: 12px;
  transition: all 0.3s ease;
}

/* Element Plus 组件样式覆盖 */
:deep(.el-select .el-input__inner) {
  border-radius: 8px;
}

:deep(.el-button) {
  border-radius: 8px;
  font-weight: 500;
}

:deep(.el-tag) {
  border-radius: 20px;
  font-weight: 500;
}

/* 左侧树形表格样式保持不变 */
: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;
}

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

  .trend-cards {
    grid-template-columns: 1fr;
  }
}

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

  .content-header {
    padding: 16px 20px;
  }

  .page-title {
    font-size: 24px;
  }

  .control-panel,
  .data-display {
    margin: 16px 20px;
  }

  .stats-cards {
    grid-template-columns: 1fr;
  }

  .query-section {
    flex-direction: column;
    align-items: stretch;
  }

  .query-item {
    width: 100%;
  }

  .query-item .el-select {
    width: 100% !important;
  }
}
</style>
