<template>
  <div class="configuration-management">
    <!-- 查询条件区域 -->
    <el-card class="filter-card">
      <el-form :model="queryParams" ref="searchForm" :inline="true" class="search-form">
        <!-- 组态图基础信息 -->
        <el-form-item label="组态图ID">
          <el-input v-model="queryParams.configId" placeholder="请输入组态图ID" clearable />
        </el-form-item>

        <el-form-item label="版本号">
          <el-input v-model="queryParams.version" placeholder="请输入版本号" clearable />
        </el-form-item>

        <!-- 监控参数条件 -->
        <el-form-item label="参数名称">
          <el-input v-model="queryParams.paramName" placeholder="请输入参数名称（如温度）" clearable />
        </el-form-item>

        <!-- 可视化设置条件 -->
        <el-form-item label="显示格式">
          <el-select v-model="queryParams.displayFormat" placeholder="请选择显示格式" style="width: 180px;">
            <el-option label="全部" value="" />
            <el-option label="数值" value="NUMERIC" />
            <el-option label="百分比" value="PERCENTAGE" />
            <el-option label="小数" value="DECIMAL" />
          </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="configList"
          border
          size="small"
          v-loading="isLoading"
          row-key="configId"
          @row-click="handleRowClick"
      >
        <el-table-column label="组态图ID" prop="configId" align="center" width="140" />
        <el-table-column label="图纸路径" prop="drawingPath" align="left" min-width="200">
          <template #default="scope">
            <el-link :href="scope.row.drawingPath" type="primary" target="_blank">查看图纸</el-link>
          </template>
        </el-table-column>
        <el-table-column label="版本号" prop="version" align="center" width="100" />
        <el-table-column label="绑定设备数" align="center" width="100">
          <template #default="scope">
            {{ scope.row.deviceBindings.length }}台
          </template>
        </el-table-column>
        <el-table-column label="监控参数" align="center" min-width="200">
          <template #default="scope">
            <div v-for="(param, index) in scope.row.monitorParams" :key="index">
              {{ param.name }}: {{ param.value }}{{ param.unit }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="显示格式" prop="displayFormat" align="center" width="100">
          <template #default="scope">
            {{ mapDisplayFormat(scope.row.displayFormat) }}
          </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">{{ detailConfig.configId }}</el-descriptions-item>
        <el-descriptions-item label="图纸路径" span="1">
          <el-link :href="detailConfig.drawingPath" type="primary" target="_blank">{{ detailConfig.drawingPath }}</el-link>
        </el-descriptions-item>
        <el-descriptions-item label="版本号" span="1">{{ detailConfig.version }}</el-descriptions-item>
        <el-descriptions-item label="关联三维场景" span="1">{{ detailConfig.associatedSceneId }}</el-descriptions-item>
        <el-descriptions-item label="热点跳转参数" span="2">
          <pre class="small-text">{{ detailConfig.hotspotParams }}</pre>
        </el-descriptions-item>
      </el-descriptions>

      <!-- 设备绑定信息 -->
      <el-card class="mt-4" title="设备绑定信息">
        <el-table :data="detailConfig.deviceBindings" border size="small">
          <el-table-column label="设备ID" prop="deviceId" align="center" width="140" />
          <el-table-column label="X坐标" prop="x" align="center" width="100" />
          <el-table-column label="Y坐标" prop="y" align="center" width="100" />
          <el-table-column label="设备位置" align="center" width="200">
            <template #default="scope">
              <div class="device-marker" :style="{ left: scope.row.x + 'px', top: scope.row.y + 'px' }">
                {{ scope.row.deviceId }}
              </div>
            </template>
          </el-table-column>
        </el-table>
        <!-- 模拟组态图背景 -->
        <div class="configuration-preview" @click="handleCanvasClick">
          <div v-for="device in detailConfig.deviceBindings" :key="device.deviceId"
               class="device-point" :style="{ left: device.x + 'px', top: device.y + 'px' }">
            {{ device.deviceId }}
          </div>
        </div>
      </el-card>

      <!-- 监控参数与可视化设置 -->
      <el-card class="mt-4" title="监控参数与可视化设置">
        <el-tabs v-model="activeTab" type="card">
          <el-tab-pane label="监控参数">
            <el-table :data="detailConfig.monitorParams" border size="small">
              <el-table-column label="参数名称" prop="name" align="center" width="140" />
              <el-table-column label="实时读数" prop="value" align="center" width="120" />
              <el-table-column label="单位" prop="unit" align="center" width="100" />
              <el-table-column label="可视化展示" align="center" width="200">
                <template #default="scope">
                  <div class="gauge-container">
                    <div class="gauge" :style="{ width: getGaugeWidth(scope.row) + '%', backgroundColor: getColor(scope.row) }"></div>
                    <span class="gauge-value">{{ scope.row.value }}{{ scope.row.unit }}</span>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="颜色阈值">
            <pre class="small-text">{{ detailConfig.colorThresholds }}</pre>
          </el-tab-pane>
          <el-tab-pane label="闪烁规则">
            <pre class="small-text">{{ detailConfig.blinkRules }}</pre>
          </el-tab-pane>
          <el-tab-pane label="显示格式">
            <el-tag type="info">{{ mapDisplayFormat(detailConfig.displayFormat) }}</el-tag>
          </el-tab-pane>
        </el-tabs>
      </el-card>

      <template #footer>
        <el-button @click="detailDialogOpen = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import { ElMessage } from 'element-plus';
import {getBuildingEquipmentMonitoringConfigurationList} from "@/api/buildingEquipmentMonitoring/buildingEquipmentMonitoring.js";

// 查询参数
const queryParams = reactive({
  configId: '',
  version: '',
  deviceId: '',
  paramName: '',
  displayFormat: '',
  pageNum: 1,
  pageSize: 10,
  interfaceName: "二维组态图管理"
});

// 表格数据
const configList = ref([]);
const total = ref(0);
const isLoading = ref(false);
const detailDialogOpen = ref(false);
const detailConfig = ref({});
const activeTab = ref('监控参数');

// 获取数据
const getList = async () => {
  isLoading.value = true;
  try {
    let response = await getBuildingEquipmentMonitoringConfigurationList(queryParams);
    let filteredData = response.data.list;

    // 组态图ID过滤
    if (queryParams.configId) {
      filteredData = filteredData.filter(item => item.configId.includes(queryParams.configId));
    }

    // 版本号过滤
    if (queryParams.version) {
      filteredData = filteredData.filter(item => item.version.includes(queryParams.version));
    }

    // 设备ID过滤
    if (queryParams.deviceId) {
      filteredData = filteredData.filter(item =>
          item.deviceBindings.some(binding => binding.deviceId.includes(queryParams.deviceId))
      );
    }

    // 参数名称过滤
    if (queryParams.paramName) {
      filteredData = filteredData.filter(item =>
          item.monitorParams.some(param => param.name.includes(queryParams.paramName))
      );
    }

    // 显示格式过滤
    if (queryParams.displayFormat) {
      filteredData = filteredData.filter(item => item.displayFormat === queryParams.displayFormat);
    }

    // 分页处理
    total.value = response.data.total;
    configList.value = filteredData;
  } catch (error) {
    ElMessage.error('获取组态图数据失败');
    console.error(error);
  } finally {
    isLoading.value = false;
  }
};

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

// 重置
const resetSearch = () => {
  queryParams.configId = '';
  queryParams.version = '';
  queryParams.deviceId = '';
  queryParams.paramName = '';
  queryParams.displayFormat = '';
  queryParams.pageNum = 1;
  getList();
};

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

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

// 行点击事件（打开详情弹窗）
const handleRowClick = (row) => {
  detailConfig.value = JSON.parse(JSON.stringify(row));
  detailDialogOpen.value = true;
};

// 显示格式映射
const mapDisplayFormat = (format) => {
  return {
    'NUMERIC': '数值',
    'PERCENTAGE': '百分比',
    'DECIMAL': '小数',
  }[format] || format;
};

// 计算仪表宽度
const getGaugeWidth = (param) => {
  // 简单示例：根据参数值计算宽度百分比
  if (param.name === '温度') return param.value * 2;
  if (param.name === '压力') return param.value * 50;
  if (param.name === '电流') return param.value * 15;
  if (param.name === '风速') return param.value * 15;
  if (param.name === '烟雾浓度') return param.value * 100;
  if (param.name === '水压') return param.value * 50;
  if (param.name === '流量') return param.value * 2;
  if (param.name === '负载率') return param.value;
  if (param.name === '电压') return param.value / 2.2;
  if (param.name === '照度') return param.value / 5;
  if (param.name === '频率') return param.value * 2;
  if (param.name === '功率因数') return param.value * 100;
  if (param.name === '湿度') return param.value;
  if (param.name === '气压') return param.value;
  if (param.name === 'PH值') return param.value * 10;
  if (param.name === '浊度') return param.value * 10;
  if (param.name === '库存量') return param.value / 10;
  if (param.name === '出入库速率') return param.value * 2;
  return 50;
};

// 根据参数获取颜色
const getColor = (param) => {
  try {
    const thresholds = JSON.parse(detailConfig.value.colorThresholds || '{}');
    const paramThresholds = thresholds[param.name] || {};

    // 简单示例：根据参数值判断颜色
    const value = param.value;
    if (param.name === '温度') {
      return value > 30 ? '#ff4500' : '#ffd700';
    }
    if (param.name === '压力') {
      return value > 1.5 ? '#ff6347' : '#90ee90';
    }
    // 其他参数颜色逻辑...

    return '#409eff'; // 默认颜色
  } catch (error) {
    return '#409eff';
  }
};

// 模拟组态图点击
const handleCanvasClick = (event) => {
  const rect = event.currentTarget.getBoundingClientRect();
  const x = event.clientX - rect.left;
  const y = event.clientY - rect.top;

  // 实际项目中可以添加设备拖拽放置等功能
  console.log(`点击坐标: (${x}, ${y})`);
};

getList()
</script>

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

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

.small-text {
  font-size: 12px;
  color: #909399;
}

.mt-4 {
  margin-top: 16px;
}

.configuration-preview {
  position: relative;
  height: 300px;
  border: 1px solid #ebeef5;
  margin-top: 10px;
  background-color: #f5f7fa;
  background-image:
      linear-gradient(#ebeef5 1px, transparent 1px),
      linear-gradient(90deg, #ebeef5 1px, transparent 1px);
  background-size: 20px 20px;
}

.device-point {
  position: absolute;
  width: 30px;
  height: 30px;
  background-color: #409eff;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  cursor: pointer;
  transform: translate(-50%, -50%);
  transition: all 0.2s;
}

.device-point:hover {
  transform: translate(-50%, -50%) scale(1.2);
  z-index: 10;
}

.gauge-container {
  height: 24px;
  background-color: #e9ecef;
  border-radius: 4px;
  overflow: hidden;
  position: relative;
}

.gauge {
  height: 100%;
  transition: width 0.5s;
}

.gauge-value {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  font-size: 12px;
  color: #333;
}
</style>
