<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="请选择显示格式" clearable 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
          v-loading="isLoading"
          row-key="configId"
          @row-click="handleRowClick"
          style="width: 100%"
          :height="tableHeight"
      >
        <el-table-column label="组态图ID" prop="configId" align="center" width="140" />
        <el-table-column label="图纸预览" align="center" width="120">
          <template #default="scope">
<!--            <el-image
                :src="generateThumbnail(scope.row)"
                :preview-src-list="[generateFullDrawing(scope.row)]"
                fit="contain"
                style="width: 80px; height: 60px; cursor: pointer;"
                :preview-teleported="true"
            >--> <!--设置为空的数组 不显示预览图片的功能-->
              <el-image
                :src="generateThumbnail(scope.row)"
                :preview-src-list="[]"
                fit="contain"
                style="width: 80px; height: 60px; cursor: pointer;"
                :preview-teleported="true"
            >
              <template #error>
                <div class="image-slot">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column label="图纸名称" prop="drawingName" align="left" min-width="180" show-overflow-tooltip>
          <template #default="scope">
            <el-link type="primary" @click.stop="viewDrawing(scope.row)">
              <el-icon><View /></el-icon>
              {{ scope.row.drawingName || `组态图_${scope.row.configId}.svg` }}
            </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">
            <el-tag type="primary">{{ scope.row.deviceBindings?.length || 0 }}台</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="监控参数" align="left" min-width="250">
          <template #default="scope">
            <div class="param-list">
              <el-tag
                  v-for="(param, index) in scope.row.monitorParams?.slice(0, 3)"
                  :key="index"
                  size="small"
                  class="param-tag"
                  :type="getParamTagType(param)"
              >
                {{ param.name }}: {{ param.value }}{{ param.unit }}
              </el-tag>
              <el-tag v-if="scope.row.monitorParams?.length > 3" size="small" type="info">
                +{{ scope.row.monitorParams.length - 3 }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="150" fixed="right">
          <template #default="scope">
            <el-button type="primary" link size="small" @click.stop="handleRowClick(scope.row)">
              详情
            </el-button>
            <el-button type="success" link size="small" @click.stop="downloadDrawing(scope.row)">
              下载
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <el-pagination
          v-show="total > 0"
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
          class="pagination-container"
      />
    </el-card>

    <!-- 图纸查看弹窗 -->
    <el-dialog
        v-model="drawingDialogOpen"
        :title="`图纸查看 - ${currentDrawingConfig?.drawingName || '组态图'}`"
        width="90%"
        top="5vh"
        destroy-on-close
    >
      <div class="drawing-viewer">
        <div class="drawing-toolbar">
          <el-button-group>
            <el-button @click="zoomIn" :icon="ZoomIn">放大</el-button>
            <el-button @click="zoomOut" :icon="ZoomOut">缩小</el-button>
            <el-button @click="resetZoom" :icon="Refresh">重置</el-button>
            <el-button @click="downloadCurrentDrawing" :icon="Download" type="primary">下载图纸</el-button>
          </el-button-group>
          <span class="zoom-info">缩放: {{ Math.round(drawingZoom * 100) }}%</span>
        </div>
        <div class="drawing-container" ref="drawingContainer">
          <div
              class="drawing-content"
              :style="{ transform: `scale(${drawingZoom})` }"
              v-html="currentDrawingSvg"
          ></div>
        </div>
      </div>
    </el-dialog>

    <!-- 详情弹窗 -->
    <el-dialog
        v-model="detailDialogOpen"
        title="组态图详情"
        width="80%"
        top="5vh"
        destroy-on-close
    >
      <el-descriptions :column="2" border class="mb-4">
        <el-descriptions-item label="组态图ID">{{ detailConfig.configId }}</el-descriptions-item>
        <el-descriptions-item label="版本号">
          <el-tag>{{ detailConfig.version }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="图纸名称">
          {{ detailConfig.drawingName || `组态图_${detailConfig.configId}.svg` }}
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ formatDate(detailConfig.createTime) }}
        </el-descriptions-item>
      </el-descriptions>

      <!-- 图纸预览 -->
      <el-card class="mb-4">
        <template #header>
          <div class="card-header">
            <span>图纸预览</span>
            <el-button type="primary" size="small" @click="viewDrawing(detailConfig)">
              <el-icon><View /></el-icon>
              查看大图
            </el-button>
          </div>
        </template>
        <div class="detail-drawing-preview" v-html="generateFullDrawing(detailConfig)"></div>
      </el-card>

      <!-- 设备绑定信息（保持原有代码） -->
      <el-card class="mb-4">
        <template #header>
          <div class="card-header">
            <span>设备绑定信息</span>
            <el-tag type="primary">共 {{ detailConfig.deviceBindings?.length || 0 }} 台设备</el-tag>
          </div>
        </template>

        <div class="device-binding-container">
          <div class="device-list">
            <el-table
                :data="detailConfig.deviceBindings"
                border
                size="small"
                max-height="300"
            >
              <el-table-column label="设备ID" prop="deviceId" align="center" width="120" />
              <el-table-column label="X坐标" prop="x" align="center" width="80" />
              <el-table-column label="Y坐标" prop="y" align="center" width="80" />
              <el-table-column label="状态" align="center" width="80">
                <template #default="scope">
                  <el-tag :type="getDeviceStatusType(scope.row)">
                    {{ getDeviceStatus(scope.row) }}
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <div class="configuration-preview" @click="handleCanvasClick">
            <div
                v-for="device in detailConfig.deviceBindings"
                :key="device.deviceId"
                class="device-point"
                :class="{ 'device-active': isDeviceActive(device) }"
                :style="{ left: device.x + 'px', top: device.y + 'px' }"
                @click.stop="selectDevice(device)"
            >
              <el-tooltip :content="`设备ID: ${device.deviceId}`" placement="top">
                <span>{{ device.deviceId.slice(-4) }}</span>
              </el-tooltip>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 监控参数与可视化设置（保持原有代码） -->
      <el-card>
        <template #header>
          <span>监控参数与可视化设置</span>
        </template>

        <el-tabs v-model="activeTab" type="card">
          <el-tab-pane label="监控参数" name="params">
            <el-table :data="detailConfig.monitorParams" border size="small">
              <el-table-column label="参数名称" prop="name" align="center" width="140" />
              <el-table-column label="实时读数" align="center" width="120">
                <template #default="scope">
                  <span class="value-text" :style="{ color: getValueColor(scope.row) }">
                    {{ formatValue(scope.row) }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column label="单位" prop="unit" align="center" width="80" />
              <el-table-column label="可视化展示" align="center" min-width="200">
                <template #default="scope">
                  <div class="gauge-container">
                    <div
                        class="gauge"
                        :style="{
                        width: getGaugeWidth(scope.row) + '%',
                        backgroundColor: getGaugeColor(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-tabs>
      </el-card>

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

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue';
import { ElMessage } from 'element-plus';
import {
  Search,
  Refresh,
  View,
  Picture,
  ZoomIn,
  ZoomOut,
  Download
} from '@element-plus/icons-vue';
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 drawingDialogOpen = ref(false);
const detailConfig = ref({});
const activeTab = ref('params');
const selectedDevice = ref(null);
const tableHeight = ref(600);
const drawingZoom = ref(1);
const currentDrawingConfig = ref(null);
const currentDrawingSvg = ref('');

// 生成SVG组态图
const generateSVGDrawing = (config) => {
  const width = 800;
  const height = 600;
  const devices = config.deviceBindings || [];
  const params = config.monitorParams || [];

  // 根据配置ID生成不同的布局样式
  const layoutType = parseInt(config.configId.slice(-1)) % 3;

  let svg = `
    <svg width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg">
      <defs>
        <pattern id="grid" width="20" height="20" patternUnits="userSpaceOnUse">
          <path d="M 20 0 L 0 0 0 20" fill="none" stroke="#e0e0e0" stroke-width="1"/>
        </pattern>
        <filter id="shadow">
          <feDropShadow dx="2" dy="2" stdDeviation="3" flood-opacity="0.3"/>
        </filter>
      </defs>

      <!-- 背景 -->
      <rect width="${width}" height="${height}" fill="#f8f9fa"/>
      <rect width="${width}" height="${height}" fill="url(#grid)"/>

      <!-- 标题 -->
      <text x="${width/2}" y="30" text-anchor="middle" font-size="20" font-weight="bold" fill="#303133">
        ${config.drawingName || `组态图 - ${config.configId}`}
            </text>

      <!-- 版本信息 -->
      <text x="${width-20}" y="20" text-anchor="end" font-size="12" fill="#909399">
        v${config.version}
      </text>
  `;

  // 根据布局类型生成不同的图形
  if (layoutType === 0) {
    // 布局1: 中央控制室布局
    svg += `
      <!-- 主控制台 -->
      <rect x="200" y="100" width="400" height="300" rx="10" fill="#e6f7ff" stroke="#1890ff" stroke-width="2" filter="url(#shadow)"/>
      <text x="400" y="130" text-anchor="middle" font-size="16" font-weight="bold" fill="#1890ff">主控制台</text>

      <!-- 设备区域 -->
      <g id="device-area">
        <rect x="50" y="150" width="120" height="200" rx="5" fill="#f0f9ff" stroke="#69c0ff" stroke-width="1.5"/>
        <text x="110" y="175" text-anchor="middle" font-size="14" fill="#096dd9">设备区A</text>

        <rect x="630" y="150" width="120" height="200" rx="5" fill="#f0f9ff" stroke="#69c0ff" stroke-width="1.5"/>
        <text x="690" y="175" text-anchor="middle" font-size="14" fill="#096dd9">设备区B</text>
      </g>

      <!-- 管道连接 -->
      <path d="M 170 250 L 200 250" stroke="#52c41a" stroke-width="3" fill="none" marker-end="url(#arrowhead)"/>
      <path d="M 600 250 L 630 250" stroke="#52c41a" stroke-width="3" fill="none" marker-end="url(#arrowhead)"/>

      <!-- 箭头标记 -->
      <defs>
        <marker id="arrowhead" markerWidth="10" markerHeight="7" refX="9" refY="3.5" orient="auto">
          <polygon points="0 0, 10 3.5, 0 7" fill="#52c41a"/>
        </marker>
      </defs>
    `;
  } else if (layoutType === 1) {
    // 布局2: 流程图布局
    svg += `
      <!-- 流程容器 -->
      <g id="process-flow">
        <!-- 起始节点 -->
        <circle cx="100" cy="300" r="40" fill="#95de64" stroke="#52c41a" stroke-width="2" filter="url(#shadow)"/>
        <text x="100" y="305" text-anchor="middle" font-size="14" fill="white" font-weight="bold">开始</text>

        <!-- 处理节点 -->
        <rect x="200" y="260" width="150" height="80" rx="5" fill="#ffd666" stroke="#faad14" stroke-width="2" filter="url(#shadow)"/>
        <text x="275" y="290" text-anchor="middle" font-size="14" fill="#614700">数据处理</text>
        <text x="275" y="310" text-anchor="middle" font-size="12" fill="#8c6800">处理中...</text>

        <!-- 决策节点 -->
        <path d="M 450 300 L 500 250 L 550 300 L 500 350 Z" fill="#ff9c6e" stroke="#ff7a45" stroke-width="2" filter="url(#shadow)"/>
        <text x="500" y="305" text-anchor="middle" font-size="14" fill="white">判断</text>

        <!-- 结束节点 -->
        <circle cx="700" cy="300" r="40" fill="#ff7875" stroke="#ff4d4f" stroke-width="2" filter="url(#shadow)"/>
        <text x="700" y="305" text-anchor="middle" font-size="14" fill="white" font-weight="bold">结束</text>

        <!-- 流程线 -->
        <path d="M 140 300 L 200 300" stroke="#333" stroke-width="2" marker-end="url(#arrow)"/>
        <path d="M 350 300 L 450 300" stroke="#333" stroke-width="2" marker-end="url(#arrow)"/>
        <path d="M 550 300 L 660 300" stroke="#333" stroke-width="2" marker-end="url(#arrow)"/>
      </g>

      <defs>
        <marker id="arrow" markerWidth="10" markerHeight="10" refX="8" refY="3" orient="auto" markerUnits="strokeWidth">
          <path d="M0,0 L0,6 L9,3 z" fill="#333"/>
        </marker>
      </defs>
    `;
  } else {
    // 布局3: 仪表盘布局
    svg += `
      <!-- 仪表盘容器 -->
      <g id="dashboard">
        <!-- 主仪表盘 -->
        <circle cx="400" cy="250" r="120" fill="none" stroke="#e0e0e0" stroke-width="20"/>
        <circle cx="400" cy="250" r="120" fill="none" stroke="#52c41a" stroke-width="20"
                stroke-dasharray="${Math.PI * 240 * 0.7} ${Math.PI * 240 * 0.3}"
                stroke-dashoffset="${Math.PI * 240 * 0.25}"
                transform="rotate(-90 400 250)"/>
        <text x="400" y="250" text-anchor="middle" font-size="36" font-weight="bold" fill="#52c41a">75%</text>
        <text x="400" y="280" text-anchor="middle" font-size="14" fill="#666">系统负载</text>

        <!-- 小仪表盘 -->
        <g transform="translate(150, 400)">
          <circle cx="0" cy="0" r="50" fill="#f0f2f5" stroke="#d9d9d9" stroke-width="2"/>
          <text x="0" y="5" text-anchor="middle" font-size="20" font-weight="bold" fill="#1890ff">23°C</text>
          <text x="0" y="25" text-anchor="middle" font-size="12" fill="#666">温度</text>
        </g>

        <g transform="translate(400, 400)">
          <circle cx="0" cy="0" r="50" fill="#f0f2f5" stroke="#d9d9d9" stroke-width="2"/>
          <text x="0" y="5" text-anchor="middle" font-size="20" font-weight="bold" fill="#fa8c16">1.2MPa</text>
          <text x="0" y="25" text-anchor="middle" font-size="12" fill="#666">压力</text>
        </g>

        <g transform="translate(650, 400)">
          <circle cx="0" cy="0" r="50" fill="#f0f2f5" stroke="#d9d9d9" stroke-width="2"/>
          <text x="0" y="5" text-anchor="middle" font-size="20" font-weight="bold" fill="#a0d911">5.5A</text>
          <text x="0" y="25" text-anchor="middle" font-size="12" fill="#666">电流</text>
        </g>
      </g>
    `;
  }

  // 添加设备标记
  devices.forEach((device, index) => {
    const status = Math.random() > 0.8 ? '#ff4d4f' : '#52c41a';
    svg += `
      <g transform="translate(${device.x}, ${device.y})">
        <circle cx="0" cy="0" r="15" fill="${status}" opacity="0.8" filter="url(#shadow)">
          <animate attributeName="r" values="15;18;15" dur="2s" repeatCount="indefinite"/>
        </circle>
        <text x="0" y="5" text-anchor="middle" font-size="10" fill="white" font-weight="bold">
          ${device.deviceId.slice(-4)}
        </text>
      </g>
    `;
  });

  // 添加实时数据显示
  if (params.length > 0) {
    svg += `
      <g id="realtime-data" transform="translate(20, 450)">
        <rect x="0" y="0" width="760" height="130" rx="5" fill="rgba(255,255,255,0.9)" stroke="#d9d9d9" stroke-width="1"/>
        <text x="10" y="25" font-size="14" font-weight="bold" fill="#333">实时监控数据</text>
    `;

    params.forEach((param, index) => {
      const x = 20 + (index % 4) * 180;
      const y = 50 + Math.floor(index / 4) * 40;
      svg += `
        <g transform="translate(${x}, ${y})">
          <text font-size="12" fill="#666">${param.name}:</text>
          <text x="60" font-size="14" font-weight="bold" fill="${getParamColor(param)}">
            ${param.value}${param.unit}
          </text>
        </g>
      `;
    });

    svg += '</g>';
  }

  svg += '</svg>';
  return svg;
};

// 生成缩略图
const generateThumbnail = (config) => {
  const svg = generateSVGDrawing(config);
  const blob = new Blob([svg], { type: 'image/svg+xml' });
  return URL.createObjectURL(blob);
};

// 生成完整图纸
const generateFullDrawing = (config) => {
  return generateSVGDrawing(config);
};

// 查看图纸
const viewDrawing = (config) => {
  currentDrawingConfig.value = config;
  currentDrawingSvg.value = generateFullDrawing(config);
  drawingDialogOpen.value = true;
  drawingZoom.value = 1;
};

// 下载图纸
const downloadDrawing = (config) => {
  const svg = generateSVGDrawing(config);
  const blob = new Blob([svg], { type: 'image/svg+xml' });
  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.download = `${config.drawingName || `组态图_${config.configId}`}.svg`;
  link.click();
  URL.revokeObjectURL(url);
  ElMessage.success('图纸下载成功');
};

// 下载当前查看的图纸
const downloadCurrentDrawing = () => {
  if (currentDrawingConfig.value) {
    downloadDrawing(currentDrawingConfig.value);
  }
};

// 缩放控制
const zoomIn = () => {
  drawingZoom.value = Math.min(drawingZoom.value + 0.2, 3);
};

const zoomOut = () => {
  drawingZoom.value = Math.max(drawingZoom.value - 0.2, 0.5);
};

const resetZoom = () => {
  drawingZoom.value = 1;
};

// 获取参数颜色
const getParamColor = (param) => {
  const value = param.value;
  const name = param.name;

  if (name === '温度') {
    return value > 30 ? '#ff4d4f' : value > 25 ? '#fa8c16' : '#52c41a';
  }
  if (name === '压力') {
    return value > 1.5 ? '#ff4d4f' : value > 1.2 ? '#fa8c16' : '#52c41a';
  }
  return '#1890ff';
};

// 计算表格高度
const calculateTableHeight = () => {
  const windowHeight = window.innerHeight;
  tableHeight.value = windowHeight - 320;
};

onMounted(() => {
  calculateTableHeight();
  window.addEventListener('resize', calculateTableHeight);
  getList();
});

onUnmounted(() => {
  window.removeEventListener('resize', calculateTableHeight);
  // 清理生成的URL对象
  configList.value.forEach(config => {
    if (config._thumbnailUrl) {
      URL.revokeObjectURL(config._thumbnailUrl);
    }
  });
});

// 获取数据（添加图纸名称）
const getList = async () => {
  isLoading.value = true;
  try {
    const response = await getBuildingEquipmentMonitoringConfigurationList(queryParams);
    let filteredData = response.data.list || [];

    // 为每个配置添加图纸名称
    filteredData = filteredData.map(item => ({
      ...item,
      drawingName: `${item.configId}_组态图_v${item.version}`,
      createTime: new Date().toISOString()
    }));

    // 应用过滤条件
    if (queryParams.configId) {
      filteredData = filteredData.filter(item =>
          item.configId.toLowerCase().includes(queryParams.configId.toLowerCase())
      );
    }

    if (queryParams.version) {
      filteredData = filteredData.filter(item =>
          item.version.includes(queryParams.version)
      );
    }

    if (queryParams.paramName) {
      filteredData = filteredData.filter(item =>
          item.monitorParams?.some(param =>
              param.name.toLowerCase().includes(queryParams.paramName.toLowerCase())
          )
      );
    }

    if (queryParams.displayFormat) {
      filteredData = filteredData.filter(item =>
          item.displayFormat === queryParams.displayFormat
      );
    }

    total.value = filteredData.length;

    // 分页处理
    const start = (queryParams.pageNum - 1) * queryParams.pageSize;
    const end = start + queryParams.pageSize;
    configList.value = filteredData.slice(start, end);

  } 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;
  selectedDevice.value = null;
};

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

// 获取参数标签类型
const getParamTagType = (param) => {
  const value = param.value;
  const name = param.name;

  if (name === '温度') {
    return value > 30 ? 'danger' : value > 25 ? 'warning' : 'success';
  }
  if (name === '压力') {
    return value > 1.5 ? 'danger' : value > 1.2 ? 'warning' : 'success';
  }
  return 'primary';
};

// 格式化数值
const formatValue = (param) => {
  const format = detailConfig.value.displayFormat;
  const value = param.value;

  switch (format) {
    case 'PERCENTAGE':
      return `${value}%`;
    case 'DECIMAL':
      return value.toFixed(2);
    case 'NUMERIC':
    default:
      return Math.round(value).toString();
  }
};

// 获取数值颜色
const getValueColor = (param) => {
  const value = param.value;
  const name = param.name;

  if (name === '温度') {
    return value > 30 ? '#f56c6c' : value > 25 ? '#e6a23c' : '#67c23a';
  }
  if (name === '压力') {
    return value > 1.5 ? '#f56c6c' : value > 1.2 ? '#e6a23c' : '#67c23a';
  }
  return '#409eff';
};

// 计算仪表宽度
const getGaugeWidth = (param) => {
  const maxValues = {
    '温度': 50,
    '压力': 2,
    '电流': 10,
    '风速': 10,
    '烟雾浓度': 1,
    '水压': 2,
    '流量': 100,
    '负载率': 100,
    '电压': 220,
    '照度': 500,
    '频率': 50,
    '功率因数': 1,
    '湿度': 100,
    '气压': 100,
    'PH值': 14,
    '浊度': 10,
    '库存量': 1000,
    '出入库速率': 50
  };

  const max = maxValues[param.name] || 100;
  const percentage = (param.value / max) * 100;
  return Math.min(Math.max(percentage, 0), 100);
};

// 获取仪表颜色
const getGaugeColor = (param) => {
  const percentage = getGaugeWidth(param);
  if (percentage > 80) return '#f56c6c';
  if (percentage > 60) return '#e6a23c';
  return '#67c23a';
};

// 设备相关方法
const selectDevice = (device) => {
  selectedDevice.value = device;
  ElMessage.info(`已选择设备: ${device.deviceId}`);
};

const isDeviceActive = (device) => {
  return selectedDevice.value?.deviceId === device.deviceId;
};

const getDeviceStatus = (device) => {
  const random = Math.random();
  if (random > 0.9) return '离线';
  if (random > 0.8) return '告警';
  return '在线';
};

const getDeviceStatusType = (device) => {
  const status = getDeviceStatus(device);
  const typeMap = {
    '在线': 'success',
    '告警': 'warning',
    '离线': 'danger'
  };
  return typeMap[status];
};

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

  ElMessage.info(`点击坐标: (${x}, ${y})`);
};

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '未知';
  const date = new Date(dateStr);
  return date.toLocaleString('zh-CN');
};
</script>

<style scoped>
.configuration-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.filter-card {
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-form {
  padding: 10px 0;
}

.data-table {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.param-list {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.param-tag {
  margin: 2px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 图纸查看器样式 */
.drawing-viewer {
  height: 70vh;
  display: flex;
  flex-direction: column;
}

.drawing-toolbar {
  padding: 10px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.zoom-info {
  font-size: 14px;
  color: #606266;
  margin-left: 20px;
}

.drawing-container {
  flex: 1;
  overflow: auto;
  background-color: #fafafa;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.drawing-content {
  transform-origin: center center;
  transition: transform 0.3s ease;
}

/* 图片插槽样式 */
.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 20px;
}

/* 详情图纸预览 */
.detail-drawing-preview {
  width: 100%;
  height: 400px;
  overflow: auto;
  background-color: #fafafa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.detail-drawing-preview svg {
  max-width: 100%;
  height: auto;
}

/* 设备绑定容器 */
.device-binding-container {
  display: grid;
  grid-template-columns: 1fr 2fr;
  gap: 20px;
  height: 400px;
}

.device-list {
  overflow: auto;
}

.configuration-preview {
  position: relative;
  height: 100%;
  border: 2px solid #dcdfe6;
  border-radius: 4px;
  background-color: #fafafa;
  background-image:
      linear-gradient(#e4e7ed 1px, transparent 1px),
      linear-gradient(90deg, #e4e7ed 1px, transparent 1px);
  background-size: 20px 20px;
  overflow: hidden;
  cursor: crosshair;
}

.device-point {
  position: absolute;
  width: 40px;
  height: 40px;
  background-color: #409eff;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 10px;
  font-weight: bold;
  cursor: pointer;
  transform: translate(-50%, -50%);
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  z-index: 1;
}

.device-point:hover {
  transform: translate(-50%, -50%) scale(1.2);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
  z-index: 10;
}

.device-point.device-active {
  background-color: #67c23a;
  transform: translate(-50%, -50%) scale(1.3);
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(103, 194, 58, 0.7);
  }
  70% {
    box-shadow: 0 0 0 10px rgba(103, 194, 58, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(103, 194, 58, 0);
  }
}

.gauge-container {
  height: 24px;
  background-color: #ebeef5;
  border-radius: 12px;
  overflow: hidden;
  position: relative;
  box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1);
}

.gauge {
  height: 100%;
  transition: width 0.5s ease-out;
  border-radius: 12px;
  background-image: linear-gradient(to right, rgba(255, 255, 255, 0.2), transparent);
}

.gauge-value {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  font-size: 12px;
  font-weight: bold;
  color: #303133;
  text-shadow: 0 1px 2px rgba(255, 255, 255, 0.8);
}

.value-text {
  font-weight: bold;
  font-size: 14px;
}

.mb-4 {
  margin-bottom: 16px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .device-binding-container {
    grid-template-columns: 1fr;
    height: auto;
  }

  .configuration-preview {
    height: 400px;
    margin-top: 20px;
  }

  .drawing-viewer {
    height: 50vh;
  }
}

/* 打印样式 */
@media print {
  .drawing-toolbar {
    display: none;
  }

  .drawing-container {
    background: white;
  }
}

/* SVG 内嵌样式 */
:deep(svg text) {
  user-select: none;
}

:deep(svg .device-marker) {
  cursor: pointer;
}

:deep(svg .device-marker:hover) {
  opacity: 0.8;
}
</style>
