<template>
  <div class="area-management-system">
    <!-- 查询条件区域 -->
    <el-card class="filter-card">
      <el-form :model="queryParams" ref="searchForm" :inline="true" class="search-form">
        <!-- 区域层级条件 -->
        <el-form-item label="区域名称">
          <el-input v-model="queryParams.areaName" placeholder="请输入区域名称" clearable />
        </el-form-item>

        <el-form-item label="层级">
          <el-select v-model="queryParams.level" placeholder="请选择层级" style="width: 180px;">
            <el-option label="全部" value="" />
            <el-option label="一级区域" value="1" />
            <el-option label="二级区域" value="2" />
            <el-option label="三级区域" value="3" />
          </el-select>
        </el-form-item>

        <!-- 设备统计条件 -->
        <el-form-item label="设备类型">
          <el-select v-model="queryParams.deviceType" placeholder="请选择设备类型" style="width: 180px;">
            <el-option label="全部" value="" />
            <el-option label="控制器" value="CONTROLLER" />
            <el-option label="传感器" value="SENSOR" />
            <el-option label="执行器" value="ACTUATOR" />
            <el-option label="广播设备" value="BROADCASTER" />
            <el-option label="监控设备" value="MONITOR" />
          </el-select>
        </el-form-item>

        <!-- 状态过滤条件 -->
        <el-form-item label="设备状态">
          <el-select v-model="queryParams.status" placeholder="请选择设备状态" style="width: 180px;">
            <el-option label="全部" value="" />
            <el-option label="在线" value="在线" />
            <el-option label="故障" value="故障" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleSearch">搜索</el-button>
          <el-button icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格区域 -->
    <el-card class="data-table">
      <el-table
          :data="areaList"
          border
          size="small"
          v-loading="isLoading"
          row-key="areaId"
          @row-click="handleRowClick"
      >
        <el-table-column label="区域ID" prop="areaId" align="center"/>
        <el-table-column label="区域名称" prop="areaName" align="center"/>
        <el-table-column label="层级" prop="level" align="center" width="100">
          <template #default="scope">
            {{ scope.row.level === 1 ? '一级' : scope.row.level === 2 ? '二级' : '三级' }}
          </template>
        </el-table-column>
        <el-table-column label="设备总数" align="center" width="100">
          <template #default="scope">
            {{ scope.row.deviceStats.reduce((sum, stat) => sum + stat.count, 0) }}台
          </template>
        </el-table-column>
        <el-table-column label="平均在线率" align="center" width="120">
          <template #default="scope">
            {{ getAverageOnlineRate(scope.row.deviceStats).toFixed(1) }}%
          </template>
        </el-table-column>
        <el-table-column label="健康指数" align="center" width="160">
          <template #default="scope">
            <div>
              <span>{{ parseKeyMetrics(scope.row.keyMetrics).healthIndex }} 分</span>
              <el-progress
                  :percentage="parseKeyMetrics(scope.row.keyMetrics).healthIndex"
                  type="line"
                  :status="getHealthStatus(parseKeyMetrics(scope.row.keyMetrics).healthIndex)"
                  style="width: 120px; margin-top: 4px;"
              />
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
      />
    </el-card>

    <!-- 详情弹窗 -->
    <el-dialog :visible.sync="detailDialogOpen" title="区域详情" width="1000px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="区域ID" span="1">{{ detailArea.areaId }}</el-descriptions-item>
        <el-descriptions-item label="区域名称" span="1">{{ detailArea.areaName }}</el-descriptions-item>
        <el-descriptions-item label="父区域" span="1">
          {{ detailArea.parentAreaId || "无" }}
        </el-descriptions-item>
        <el-descriptions-item label="层级" span="1">
          {{ detailArea.level === 1 ? '一级区域' : detailArea.level === 2 ? '二级区域' : '三级区域' }}
        </el-descriptions-item>
        <el-descriptions-item label="关键指标" span="2">
          <div>平均能耗：{{ getKeyMetric(detailArea.keyMetrics, 0) }} kWh</div>
          <div>最大负载：{{ getKeyMetric(detailArea.keyMetrics, 1) }} W</div>
          <div>健康指数：{{ getKeyMetric(detailArea.keyMetrics, 2) }}分</div>
        </el-descriptions-item>
      </el-descriptions>

      <!-- 设备统计图表 -->
      <el-card class="mt-4" title="设备类型分布">
        <el-chart :height="300">
          <el-pie-chart
              :data="chartData"
              :options="pieOptions"
          />
        </el-chart>
      </el-card>

      <!-- 空间分布热力图 -->
      <el-card class="mt-4" title="设备位置热力图">
        <div class="heatmap-container">
          <div
              v-for="(point, index) in heatmapPoints"
              :key="index"
              class="heatmap-point"
              :style="{
              left: point.x + 'px',
              top: point.y + 'px',
              width: point.size * 2 + 'px',
              height: point.size * 2 + 'px',
              background: `rgba(255, 165, 0, ${point.opacity})`
            }"
          />
        </div>
      </el-card>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import { ElMessage, ElProgress } from 'element-plus';
import { getBuildingEquipmentMonitoringAreaList } from '@/api/buildingEquipmentMonitoring/buildingEquipmentMonitoring';

// 查询参数
const queryParams = reactive({
  areaName: '',
  level: '',
  deviceType: [],
  status: [],
  pageNum: 1,
  pageSize: 10,
});

// 表格数据
const areaList = ref([]);
const total = ref(0);
const isLoading = ref(false);
const detailDialogOpen = ref(false);
const detailArea = ref({});

// 图表数据
const chartData = ref([]);
const pieOptions = computed(() => ({
  title: { text: '设备类型占比' },
  legend: { orient: 'vertical', left: 'left' },
  series: [{ type: 'pie', radius: '50%', data: chartData.value }],
}));

// 热力图数据
const heatmapPoints = ref([]);

// 获取数据
const getList = async () => {
  isLoading.value = true;
  try {
    const response = await getBuildingEquipmentMonitoringAreaList(queryParams);
    areaList.value = response.data.list;
    total.value = response.data.total;
  } catch (error) {
    ElMessage.error('获取区域数据失败');
    console.error(error);
  } finally {
    isLoading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  queryParams.pageNum = 1;
  getList();
};

// 重置
const resetSearch = () => {
  queryParams.areaName = '';
  queryParams.level = '';
  queryParams.deviceType = [];
  queryParams.status = [];
  queryParams.pageNum = 1;
  getList();
};

// 分页
const handlePageChange = (newPage) => {
  queryParams.pageNum = newPage;
  getList();
};

const handleSizeChange = (newSize) => {
  queryParams.pageSize = newSize;
  queryParams.pageNum = 1;
  getList();
};

// 行点击事件（打开详情弹窗）
const handleRowClick = (row) => {
  detailArea.value = { ...row };
  // 解析设备统计数据
  chartData.value = row.deviceStats.map(stat => ({
    name: mapDeviceType(stat.deviceType),
    value: stat.count,
    itemStyle: { color: getDeviceTypeColor(stat.deviceType) }
  }));
  // 解析热力图数据
  parseHeatmapData(row.heatmapData);
  detailDialogOpen.value = true;
};

// 设备类型映射
const mapDeviceType = (type) => {
  return {
    'CONTROLLER': '控制器',
    'SENSOR': '传感器',
    'ACTUATOR': '执行器',
    'BROADCASTER': '广播设备',
    'MONITOR': '监控设备',
  }[type] || type;
};

// 设备类型颜色
const getDeviceTypeColor = (type) => {
  return {
    'CONTROLLER': '#409eff',
    'SENSOR': '#67c23a',
    'ACTUATOR': '#f56c6c',
    'BROADCASTER': '#e6a23c',
    'MONITOR': '#909399',
  }[type] || '#409eff';
};

// 计算平均在线率
const getAverageOnlineRate = (stats) => {
  if (stats.length === 0) return 0;
  return stats.reduce((sum, stat) => sum + stat.onlineRate, 0) / stats.length;
};

// 解析关键指标（平均能耗,最大负载,健康指数）
const parseKeyMetrics = (keyMetricsStr) => {
  const [averageEnergy, maxLoad, healthIndex] = keyMetricsStr.split(',').map(Number);
  return {
    averageEnergy: averageEnergy.toFixed(2), // 平均能耗保留两位小数
    maxLoad: maxLoad.toFixed(0), // 最大负载取整
    healthIndex: healthIndex.toFixed(0), // 健康指数取整
  };
};

// 获取健康指数进度条状态
const getHealthStatus = (healthIndex) => {
  if (healthIndex >= 90) return 'success'; // 绿色
  if (healthIndex >= 80) return 'warning'; // 黄色
  return 'danger'; // 红色
};

// 解析热力图数据
const parseHeatmapData = (heatmapStr) => {
  try {
    const { heatData } = JSON.parse(heatmapStr);
    heatmapPoints.value = heatData.map(([x, y, opacity], index) => ({
      id: `point-${index}`,
      x: x * 2 + 50, // 模拟坐标偏移
      y: y * 2 + 50,
      size: opacity * 20, // 气泡大小
      opacity: opacity // 透明度
    }));
  } catch (error) {
    heatmapPoints.value = [];
  }
};

// 初始加载数据
getList();
</script>

<style scoped>
.filter-card {
  margin-bottom: 20px;
  padding: 20px;
}

.data-table {
  min-height: 500px;
}

.el-chart {
  height: 300px;
}

.heatmap-container {
  position: relative;
  height: 400px;
  border: 1px solid #ebeef5;
  background-color: #f5f7fa;
  overflow: hidden;
}

.heatmap-point {
  position: absolute;
  border-radius: 50%;
  transition: all 0.2s;
}

.heatmap-point:hover {
  opacity: 1;
  transform: scale(1.2);
}
</style>
