<template>
  <div class="content">
    <div class="viewer-area">
      <div :id="containerId" ref="viewerRef" class="viewer-canvas"></div>

      <div v-if="viewerReady" class="coord-bar">
        <span>X: {{ currentCoord.x.toFixed(2) }}</span>
        <span>Y: {{ currentCoord.y.toFixed(2) }}</span>
        <span v-if="placingMode" class="placing-hint">| 放置: {{ placingDevice?.name }} (Esc取消)</span>
      </div>
    </div>

    <div class="device-panel" :class="{ collapsed: panelCollapsed }">
      <div class="panel-header" @click="panelCollapsed = !panelCollapsed">
        <span class="panel-title">设备列表</span>
        <span class="panel-toggle">{{ panelCollapsed ? '展开' : '收起' }}</span>
      </div>
      <div v-show="!panelCollapsed" class="panel-body">
        <a-table :columns="columns" :data-source="devices" :pagination="false" row-key="id" size="small" :scroll="{ y: 360 }">
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'index'">{{ devices.indexOf(record) + 1 }}</template>
            <template v-if="column.key === 'status'">
              <a-tag :color="statusColor(record.status)">{{ statusText(record.status) }}</a-tag>
            </template>
            <template v-if="column.key === 'action'">
              <a-button type="primary" size="small" :disabled="placingMode" @click="enterPlacingMode(record)">布点</a-button>
            </template>
            <template v-if="column.key === 'markerStatus'">
              <a-tag v-if="record.markerId" color="green">已布</a-tag>
              <span v-else style="color: rgba(255, 255, 255, 0.35); font-size: 12px">-</span>
            </template>
          </template>
        </a-table>
      </div>
    </div>

    <a-modal v-model:open="modalVisible" :title="(monitoringData?.deviceName || '') + ' - 监测数据'" :footer="null" width="420px">
      <div v-if="monitoringData" class="monitor-data">
        <div class="monitor-row"
          ><span class="monitor-key">时间戳</span><span>{{ monitoringData.timestamp }}</span></div
        >
        <div class="monitor-row"
          ><span class="monitor-key">风速</span><span>{{ monitoringData.windSpeed }} m/s</span></div
        >
        <div class="monitor-row"
          ><span class="monitor-key">瓦斯浓度</span><span>{{ monitoringData.gasConcentration }}%</span></div
        >
        <div class="monitor-row"
          ><span class="monitor-key">温度</span><span>{{ monitoringData.temperature }}°C</span></div
        >
        <div class="monitor-row"
          ><span class="monitor-key">压力</span><span>{{ monitoringData.pressure }} Pa</span></div
        >
        <div class="monitor-row"
          ><span class="monitor-key">粉尘浓度</span><span>{{ monitoringData.dustDensity }} mg/m³</span></div
        >
        <div class="monitor-row"
          ><span class="monitor-key">运行状态</span
          ><a-tag :color="monitoringData.status === '正常' ? 'green' : 'red'">{{ monitoringData.status }}</a-tag></div
        >
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, onUnmounted, reactive } from 'vue';
  import { Viewer2d, ViewerEvent, CoordinateUtils, THREE } from '@x-viewer/core';
  import { CSS3DRenderer, CSS3DObject } from 'three/examples/jsm/renderers/CSS3DRenderer.js';
  import { CSS2DObject } from 'three/examples/jsm/renderers/CSS2DRenderer.js';
  import { useAppStoreWithOut } from '/@/store/modules/app';
  import dayjs from 'dayjs';

  // ==================== 类型 ====================

  interface DeviceInfo {
    id: string;
    name: string;
    type: string;
    status: 'online' | 'offline' | 'alarm';
    markerId: string | null;
  }

  // ==================== 常量 ====================

  const containerId = 'dwg-viewer-canvas';
  const dwgSrc = '/dwg/2026年2月总平面布置图_无高程.dwg';
  const fontFiles = [
    '/dwg/simplex.shx',
    '/dwg/hztxt.shx',
    '/dwg/arial.ttf',
    '/dwg/Microsoft_YaHei.ttf',
    '/dwg/Microsoft_YaHei_Regular.typeface.json',
  ];
  let markerIdCounter = 0;

  // ==================== 表格 ====================

  // 设备列表表格列
  const columns = [
    { title: '#', key: 'index', width: 36 },
    { title: '设备名称', dataIndex: 'name', ellipsis: true },
    { title: '类型', dataIndex: 'type', width: 56 },
    { title: '状态', key: 'status', width: 54 },
    { title: '操作', key: 'action', width: 56 },
    { title: '布点', key: 'markerStatus', width: 48 },
  ];
  // 设备列表数据
  const devices = ref<DeviceInfo[]>([
    // { id: 'd001', name: '1#瓦斯传感器', type: '传感器', status: 'online', markerId: null },
    // { id: 'd002', name: '2#瓦斯传感器', type: '传感器', status: 'online', markerId: null },
    // { id: 'd003', name: '主通风机', type: '风机', status: 'online', markerId: null },
    // { id: 'd004', name: '局部通风机', type: '风机', status: 'offline', markerId: null },
    // { id: 'd005', name: '风门A', type: '风门', status: 'online', markerId: null },
    // { id: 'd006', name: '风速传感器-1', type: '传感器', status: 'alarm', markerId: null },
    // { id: 'd007', name: '温度传感器-1', type: '传感器', status: 'online', markerId: null },
    // { id: 'd008', name: '风窗B', type: '风窗', status: 'online', markerId: null },
  ]);
  // 状态颜色映射
  function statusColor(s: string) {
    return { online: 'green', offline: 'gray', alarm: 'red' }[s] || 'default';
  }
  // 状态文本映射
  function statusText(s: string) {
    return { online: '在线', offline: '离线', alarm: '报警' }[s] || s;
  }
  // 模拟监测数据
  function getMockMonitoring(deviceId: string) {
    const d = devices.value.find((x) => x.id === deviceId);
    return {
      deviceId,
      deviceName: d?.name || '未知',
      timestamp: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      windSpeed: +(Math.random() * 5 + 1.5).toFixed(2),
      gasConcentration: +(Math.random() * 0.5 + 0.15).toFixed(3),
      temperature: +(Math.random() * 8 + 20).toFixed(1),
      pressure: +(Math.random() * 100 + 900).toFixed(0),
      dustDensity: +(Math.random() * 3 + 0.5).toFixed(2),
      status: d?.status === 'online' ? '正常' : d?.status === 'alarm' ? '异常' : '离线',
    };
  }

  // ==================== 状态 ====================

  const viewerRef = ref<HTMLElement | null>(null);
  const viewerReady = ref(false);
  let viewer: Viewer2d | null = null;

  const panelCollapsed = ref(true);
  const placingMode = ref(false);
  const placingDevice = ref<DeviceInfo | null>(null);
  const currentCoord = reactive({ x: 0, y: 0, z: 0 });

  // 存储 marker：markerId → { deviceId, worldPos, domEl }
  const markersMap = new Map<
    string,
    {
      deviceId: string;
      worldPos: { x: number; y: number };
      mesh: THREE.Mesh;
      iconSprite: THREE.Sprite;
      cssLabel: CSS2DObject;
    }
  >();
  const allMeshes: THREE.Mesh[] = [];
  const allIconSprites: THREE.Sprite[] = [];
  const allCssLabels: CSS2DObject[] = [];
  const textureLoader = new THREE.TextureLoader();

  const monitoringData = ref<ReturnType<typeof getMockMonitoring> | null>(null);
  const modalVisible = ref(false);

  // ==================== 核心：坐标转换 ====================

  // 参照 useEvent.ts: 画布容器有强制缩放 (widthScale/heightScale)，需校准坐标
  function scaledScreenCoord(e: { clientX: number; clientY: number }, container: HTMLElement): THREE.Vector2 {
    const appStore = useAppStoreWithOut();
    const ws = appStore.getWidthScale;
    const hs = appStore.getHeightScale;
    const rect = container.getBoundingClientRect();
    // X: (event.clientX / ws - rect.left) = NDC*clientWidth
    // Y: (event.clientY - rect.top) / hs   = NDC*clientHeight (reversed)
    return new THREE.Vector2(e.clientX / ws - rect.left, (e.clientY - rect.top) / hs);
  }

  function getHitResult(event: MouseEvent): { x: number; y: number } | null {
    if (!viewer) return null;
    const container = document.getElementById(containerId);
    if (!container) return null;
    const sc = scaledScreenCoord(event, container);
    const worldPos = CoordinateUtils.screen2World(sc, viewer.camera, container);
    if (!worldPos) return null;
    return { x: worldPos.x, y: worldPos.y };
  }

  // ==================== 放置模式 ====================

  let floatingDot: HTMLElement | null = null;

  function enterPlacingMode(device: DeviceInfo) {
    if (!viewer) return;
    if (device.markerId) removeMarker(device.markerId);
    placingMode.value = true;
    placingDevice.value = device;

    // 创建浮动跟随圆点
    if (!floatingDot) {
      floatingDot = document.createElement('div');
      floatingDot.id = 'floating-dot';
      floatingDot.style.cssText = `
        position:absolute; width:20px; height:20px; transform:translate(-50%,-50%);
        background:#ff4d4f; border:3px solid #fff; border-radius:50%;
        box-shadow:0 0 14px rgba(255,77,79,0.8); pointer-events:none; z-index:501;
      `;
      const cont = document.getElementById(containerId);
      if (cont) cont.appendChild(floatingDot);
    }
    if (floatingDot) floatingDot.style.display = '';

    console.log(`[布点] 进入放置模式: ${device.name}`);
  }
  // 退出放置模式
  function exitPlacingMode() {
    placingMode.value = false;
    placingDevice.value = null;
    if (floatingDot) floatingDot.style.display = 'none';
  }
  // 放置 marker
  function placeMarker(device: DeviceInfo, location: { x: number; y: number }) {
    if (!viewer) return;
    markerIdCounter++;
    const markerId = `m${markerIdCounter}`;

    // 动态半径：基于当前视口大小
    const cam = viewer.camera as THREE.OrthographicCamera;
    const frustumH = cam.top - cam.bottom;
    const radius = frustumH * 0.008;

    // THREE.Mesh 实心圆点 — 绘制在场景中，随模型移动
    const geom = new THREE.CircleGeometry(100, 32);
    const mat = new THREE.MeshBasicMaterial({
      color: 0xff4d4f,
      side: THREE.DoubleSide,
      depthTest: false,
      depthWrite: false,
    });
    const mesh = new THREE.Mesh(geom, mat);
    mesh.position.set(location.x, location.y, 0);
    mesh.renderOrder = 999;
    mesh.matrixAutoUpdate = true; // 覆盖 scene.matrixAutoUpdate=false
    mesh.updateMatrixWorld(); // 立即计算世界矩阵
    mesh.userData = { markerId, deviceId: device.id };
    viewer.scene.add(mesh);
    allMeshes.push(mesh);

    // 精灵图标（safetymonitor3D.png）
    const tex = textureLoader.load('/texture/safetymonitor3D.png');
    const spriteMat = new THREE.SpriteMaterial({ map: tex, depthTest: false, depthWrite: false, transparent: true });
    const icon = new THREE.Sprite(spriteMat);
    icon.position.set(location.x, location.y, 0);
    const iconSize = frustumH * 0.015;
    icon.scale.set(iconSize * 200, iconSize * 200, 1);
    icon.renderOrder = 1000;
    icon.matrixAutoUpdate = true;
    icon.updateMatrixWorld();
    viewer.scene.add(icon);
    allIconSprites.push(icon);

    // CSS2DObject 风速标签（图标上方）
    const labelDiv = document.createElement('div');
    labelDiv.textContent = `${+(Math.random() * 3 + 1.5).toFixed(1)} m/s`;
    labelDiv.style.cssText =
      'color:#00ffcc;font-size:22px;font-weight:bold;background:rgba(0,0,0,0.7);padding:2px 6px;border-radius:3px;white-space:nowrap;';
    const cssLabel = new CSS2DObject(labelDiv);
    cssLabel.position.set(location.x, location.y + 150, 0.1);
    cssLabel.matrixAutoUpdate = true;
    cssLabel.updateMatrixWorld();
    viewer.scene.add(cssLabel);
    allCssLabels.push(cssLabel);

    markersMap.set(markerId, {
      deviceId: device.id,
      worldPos: { x: location.x, y: location.y },
      mesh,
      iconSprite: icon,
      cssLabel,
    });
    device.markerId = markerId;
    console.log(`[布点] 设备=${device.name} X=${location.x.toFixed(2)} Y=${location.y.toFixed(2)} r=${radius.toFixed(2)}`);
    exitPlacingMode();
  }
  // 移除 marker
  function removeMarker(markerId: string) {
    if (!viewer) return;
    const m = markersMap.get(markerId);
    if (!m) return;
    const dev = devices.value.find((d) => d.markerId === markerId);
    if (dev) dev.markerId = null;
    viewer.scene.remove(m.mesh);
    m.mesh.geometry.dispose();
    (m.mesh.material as THREE.Material).dispose();
    viewer.scene.remove(m.iconSprite);
    (m.iconSprite.material as THREE.SpriteMaterial).map?.dispose();
    m.iconSprite.material.dispose();
    const ci = allCssLabels.indexOf(m.cssLabel);
    if (ci > -1) allCssLabels.splice(ci, 1);

    const idx = allMeshes.indexOf(m.mesh);
    if (idx > -1) allMeshes.splice(idx, 1);
    const si = allIconSprites.indexOf(m.iconSprite);
    if (si > -1) allIconSprites.splice(si, 1);
    markersMap.delete(markerId);
  }

  let infoPanel: HTMLElement | null = null;
  // 显示 marker 信息面板
   function showMarkerInfo(markerId: string) {
    const m = markersMap.get(markerId);
    if (!m || !viewer) return;
    const data = getMockMonitoring(m.deviceId);
    const container = document.getElementById(containerId);
    if (!container) return;

    // 移除旧 panel
    infoPanel?.remove();

    // Marker 世界坐标 → 屏幕坐标
    const sp = CoordinateUtils.world2Screen(new THREE.Vector3(m.worldPos.x, m.worldPos.y, 0), viewer.camera, container);

    infoPanel = document.createElement('div');
    infoPanel.style.cssText = `
      position:absolute; left:${sp.x + 16}px; top:${sp.y - 10}px;
      background:rgba(0,0,0,0.88); color:#fff; font-size:12px;
      border:1px solid rgba(255,255,255,0.2); border-radius:6px;
      padding:8px 10px; white-space:nowrap; z-index:600;
      pointer-events:auto; line-height:1.8;
    `;
    infoPanel.innerHTML = `
      <div style="display:flex;justify-content:space-between;margin-bottom:4px;">
        <b>${data.deviceName}</b>
        <span style="cursor:pointer;color:#aaa;margin-left:12px;" id="info-close">&times;</span>
      </div>
      <div>风速: ${data.windSpeed} m/s</div>
      <div>瓦斯浓度: ${data.gasConcentration}%</div>
      <div>温度: ${data.temperature}°C</div>
      <div>时间: ${data.timestamp}</div>
      <div>状态: <span style="color:${data.status === '正常' ? '#52c41a' : '#ff4d4f'}">${data.status}</span></div>
    `;
    container.appendChild(infoPanel);
    infoPanel.querySelector('#info-close')?.addEventListener('click', () => infoPanel?.remove());
    // 点击其他地方关闭
    const closeHandler = (e: MouseEvent) => {
      if (!infoPanel?.contains(e.target as Node)) {
        infoPanel?.remove();
        infoPanel = null;
        document.removeEventListener('click', closeHandler);
      }
    };
    setTimeout(() => document.addEventListener('click', closeHandler), 100);
  }
  // 点击 marker 事件
  function onMarkerClick(markerId: string) {
    console.log(`[标记点击] marker=${markerId}`);
    showMarkerInfo(markerId);
  }

  // ==================== 初始化 ====================

  onMounted(async () => {
    // 初始化 viewer
    try {
      viewer = new Viewer2d({
        containerId,
        enableSpinner: true,
        enableProgressBar: true,
        enableLayoutBar: true,
      });
      await viewer.setFont(fontFiles);
      await viewer.loadModel({ modelId: 'main-plan', name: '总平面布置图', src: dwgSrc }, (event: ProgressEvent) => {
        if (event.total > 0) console.log(`加载: ${Math.round((event.loaded / event.total) * 100)}%`);
      });

      viewer.goToHomeView();
      viewerReady.value = true;
      // initCss();

      console.log('[DWG] Viewer2d 就绪');

      // === 参照官方示例: ViewerEvent.MouseClick ===
      viewer.addEventListener(ViewerEvent.MouseClick, (data: any) => {
        if (!viewer) return;

        // 获取 world 坐标用于实时显示
        const container = document.getElementById(containerId);
        if (data?.event && container) {
          const sc = scaledScreenCoord(data.event, container);
          const wp = CoordinateUtils.screen2World(sc, viewer.camera, container);
          if (wp) {
            currentCoord.x = wp.x;
            currentCoord.y = wp.y;
            currentCoord.z = wp.z;
          }
        }

        // 检测是否点击了已有 marker mesh
        if (!placingMode.value && data?.event && container) {
          const sc2 = scaledScreenCoord(data.event, container);
          const hit = viewer.pickObject(sc2);
          if (hit?.object?.userData?.markerId) {
            onMarkerClick(hit.object.userData.markerId as string);
            return;
          }
        }

        // 点击空白背景 → 放置 marker
        if (!data?.entityData && !data?.markupData && !data?.measureData) {
          if (placingMode.value && placingDevice.value) {
            const location = getHitResult(data.event);
            if (location) placeMarker(placingDevice.value, location);
          }
        }

        viewer.renderer.render(viewer.scene, viewer.camera);
        viewer.getCssRender().render(viewer.scene, viewer.camera);
        css3DRenderer?.render(viewer.scene, viewer.camera);
      });

      // === 鼠标移动：实时更新坐标 + 浮动圆点跟随 ===
      const container = document.getElementById(containerId);
      if (container) {
        container.addEventListener('mousemove', (e: MouseEvent) => {
          if (!viewer) return;
          // 浮动圆点跟随鼠标（缩放校准后坐标，与 marker 放置位置一致）
          const sc = scaledScreenCoord(e, container);
          if (floatingDot && placingMode.value) {
            floatingDot.style.left = sc.x + 'px';
            floatingDot.style.top = sc.y + 'px';
          }
          // 世界坐标
          const wp = CoordinateUtils.screen2World(sc, viewer.camera, container);
          if (wp) {
            currentCoord.x = wp.x;
            currentCoord.y = wp.y;
            currentCoord.z = wp.z;
          }

          css3DRenderer?.render(viewer.scene, viewer.camera);
        });
      }

      // === Mesh 标记在场景坐标系中，随模型自动移动，无需 CameraChange 更新 ===
    } catch (err) {
      console.error('[DWG] 初始化失败:', err);
    }
  });
  /** 键盘事件处理：Esc 键退出放置模式 */
  const onKeydown = (e: KeyboardEvent) => {
    if (e.key === 'Escape' && placingMode.value) exitPlacingMode();
  };
  // 注册键盘事件监听
   onMounted(() => window.addEventListener('keydown', onKeydown));

  /** 组件卸载时清理：移除事件监听、销毁所有 marker、释放 viewer 资源 */
  onUnmounted(() => {
    window.removeEventListener('keydown', onKeydown);
    floatingDot?.remove();
    floatingDot = null;
    if (viewer) {
      allMeshes.forEach((m) => {
        viewer!.scene.remove(m);
        m.geometry.dispose();
        (m.material as THREE.Material).dispose();
      });
      allMeshes.length = 0;
      allIconSprites.forEach((s) => {
        viewer!.scene.remove(s);
        (s.material as THREE.SpriteMaterial).map?.dispose();
        s.material.dispose();
      });
      allIconSprites.length = 0;
      allCssLabels.forEach((l) => viewer!.scene?.remove(l));
      allCssLabels.length = 0;
    }
    markersMap.clear();
    if (viewer) {
      viewer.destroy?.();
      viewer = null;
    }
  });
</script>

<style lang="less">
  /* 参照官方示例 hotpoint 样式 */
  .hotpoint {
    opacity: 0.85;
    pointer-events: auto;
  }
  .hotpoint-dot {
    width: 16px;
    height: 16px;
    cursor: pointer;
    background: #ff4d4f;
    border: 2px solid #fff;
    border-radius: 50%;
    box-shadow: 0 0 10px rgba(255, 77, 79, 0.8);
  }
  .hotpoint-dot:hover {
    box-shadow: 0 0 16px rgba(255, 100, 100, 0.9);
    background: #ff6666;
  }
  .hotpoint-panel {
    position: absolute;
    top: 20px;
    left: -75px;
    min-width: 120px;
    background: rgba(0, 0, 0, 0.85);
    border: 1px solid rgba(255, 255, 255, 0.2);
    border-radius: 6px;
    color: #fff;
    font-size: 12px;
  }
  .hotpoint-close {
    text-align: right;
    padding: 2px 6px;
    cursor: pointer;
    color: #aaa;
    font-size: 14px;
    &:hover {
      color: #fff;
    }
  }
  .hotpoint-body {
    padding: 4px 8px 8px;
    min-height: 30px;
    white-space: nowrap;
  }
  .hide {
    display: none;
  }
</style>

<style lang="less" scoped>
  @import '/@/design/theme.less';

  .content {
    width: 100%;
    height: 100%;
    position: relative;
    overflow: hidden;
  }

  .viewer-area {
    width: 100%;
    height: 100%;
    position: relative;
  }
  .viewer-canvas {
    width: 100%;
    height: 100%;
    position: relative;
  }

  .coord-bar {
    position: absolute;
    bottom: 8px;
    left: 50%;
    transform: translateX(-50%);
    padding: 6px 16px;
    background: rgba(0, 0, 0, 0.78);
    border-radius: 6px;
    color: #fff;
    font-size: 13px;
    font-family: Consolas, Monaco, monospace;
    z-index: 200;
    pointer-events: none;
    white-space: nowrap;
    > span {
      margin: 0 4px;
    }
    .placing-hint {
      color: #faad14;
    }
  }

  .device-panel {
    position: absolute;
    top: 8px;
    right: 8px;
    width: 300px;
    z-index: 300;
    background: var(--vent-device-manager-box-bg, rgba(20, 20, 40, 0.94));
    border: 1px solid var(--vent-device-manager-box-border, rgba(255, 255, 255, 0.15));
    border-radius: 8px;
    overflow: hidden;
    &.collapsed {
      width: auto;
    }
    .panel-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 8px 12px;
      cursor: pointer;
      border-bottom: 1px solid rgba(255, 255, 255, 0.08);
      .panel-title {
        font-size: 14px;
        font-weight: 600;
        color: #e0e0e0;
      }
      .panel-toggle {
        font-size: 12px;
        color: rgba(255, 255, 255, 0.5);
      }
    }
    .panel-body {
      padding: 6px;
    }
  }

  .monitor-data {
    .monitor-row {
      display: flex;
      padding: 8px 0;
      border-bottom: 1px solid #f0f0f0;
      font-size: 14px;
    }
    .monitor-row:last-child {
      border-bottom: none;
    }
    .monitor-key {
      width: 72px;
      color: #888;
      flex-shrink: 0;
    }
  }
</style>
