<template>
  <div class="myapp map-container">
    <MapCadViewer
      ref="viewerRef"
      :map-config="mapConfig"
      :boundaries="boundaryConfig"
      :markers="markers"
      :start-in-cad-mode="START_IN_CAD_MODE"
      @mode-change="onModeChange"
      @feature-select="onFeatureSelect"
      @marker-click="onMarkerClick"
      @marker-open-cad="onMarkerOpenCad"
      @icon-placed="onIconPlaced"
      @icon-moved="onIconMoved"
    />

    <!-- ============ CAD 模式外部工具栏 ============ -->
    <template v-if="isCadMode">
      <div class="cad-toolbar">
        <button class="cad-btn" @click="goBackToMap" title="返回地图">← 返回地图</button>
        <button class="cad-btn" @click="toggleLayerPanel" title="图层管理">📑 图层</button>
        <button class="cad-btn" :class="{ active: currentMode === 'drawing' }" @click="toggleDrawing" title="绘制模式">✏️ 绘制</button>
        <button class="cad-btn" @click="zoomFit" title="缩放至全图">⊞ 全图</button>
      </div>

      <!-- 绘制模式工具栏 -->
      <div v-if="currentMode === 'drawing'" class="drawing-toolbar" style="display: none">
        <span class="drawing-label">点击地图放置图标</span>
        <div class="drawing-icons">
          <button
            v-for="item in svgIconsStatic"
            :key="item.type"
            :class="item.type"
            class="icon-btn"
            @click="selectIcon(item)"
            :title="item.name"
          ></button>
        </div>
        <button class="cad-btn" @click="clearIcons">清除</button>
      </div>
    </template>

    <template v-else>
      <div class="cad-toolbar">
        <button class="cad-btn" @click="changeView" title="切换城市">切换城市</button>
        <button class="cad-btn" @click="setMapView([113.7, 37.8], 8, 1000)" title="切换中心点">切换中心点</button>
      </div>
    </template> </div
  ><div v-if="!isTopLevel" class="map-reset-btn">
    <Button :loading="mapLoading" type="primary" @click="revertStack">返回上级</Button>
  </div>
  <div v-if="cadOpened" class="map-cad-btn">
    <a-select
      v-model:value="fileId"
      :options="fileOptions"
      :fieldNames="{ label: 'fileName', value: 'wjId' }"
      :style="{ minWidth: '200px' }"
      @change="toggleCADMap(true)"
    ></a-select>
  </div>
  <!-- 省域地图监测区图例（图3-1） -->
  <div v-if="!cadOpened" class="map-legend">
    <div class="legend-title">图例</div>
    <div class="legend-row"><span class="legend-dot legend-dot-red"></span>疑似隐蔽工作面</div>
    <div class="legend-row"><span class="legend-dot legend-dot-orange"></span>风量不足</div>
    <div class="legend-row"><span class="legend-dot legend-dot-yellow"></span>数据掉线</div>
    <div class="legend-row"><span class="legend-dot legend-dot-green"></span>监测正常</div>
  </div>
  <!-- 矿端通风系统图监测区图例（图3-3） -->
  <div v-if="cadOpened" class="map-legend">
    <div class="legend-title">图例</div>
    <div class="legend-row"><span class="legend-dot legend-dot-green"></span>测风正常</div>
    <div class="legend-row"><span class="legend-dot legend-dot-orange"></span>风量不足</div>
    <div class="legend-row"><span class="legend-dot legend-dot-red-dashed"></span>缺失测风点</div>
    <div class="legend-row"><span class="legend-line-red"></span>疑似隐蔽巷道</div>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, onUnmounted, computed, createApp } from 'vue';
  // 本地调试组件时使用
  import 'map-cad-viewer/dist/map-cad-viewer.css';
  import { MapCadViewer } from 'map-cad-viewer';
  import type { CadData, MapConfig, BoundaryConfig, MapMarker } from 'map-cad-viewer/dist/types/index.d';
  // 直接加载打包好的组件
  // import { MapCadViewer } from '/@/components/map/map-cad-viewer.es';
  // import '/@/components/map/map-cad-viewer.css';
  // import type { CadData, MapConfig, BoundaryConfig, MapMarker } from '/@/components/map/types/index.d';

  import { Button } from 'ant-design-vue';
  import { useAppStore } from '/@/store/modules/app';

  import { useMineDepartmentStore } from '/@/store/modules/mine';
  import { get, last } from 'lodash-es';

  const props = defineProps<{
    silence: boolean;
  }>();

  const appStore = useAppStore();
  const mineStore = useMineDepartmentStore();
  const mapContainer = ref<HTMLElement>();
  const mapLoading = ref(false);

  // CAD是否可见
  const cadOpened = ref<boolean>();

  const DEFAULT_NODE = {
    id: mineStore.getRootId!,
    name: '根节点',
    parentId: null,
    longitude: 109.425873,
    latitude: 35.83317,
    zoom: 6,
    isLeaf: false,
  };

  // 用于存储历史节点的栈，实现返回上一级功能
  const historyStack = ref([DEFAULT_NODE]);
  const isTopLevel = computed(() => get(historyStack.value, 'length', 1) === 1);
  const fileOptions = ref<any[]>([]);
  const fileId = ref();

  // 设置地图中当前的参数以供其他页面使用
  appStore.setSimpleMapParams({ deptId: mineStore.getRootId, isLeaf: mineStore.getRoot?.isLeaf });

  const viewerRef = ref<InstanceType<typeof MapCadViewer>>();
  // _dwg_req_newcal@

  // ===== 启动配置 =====
  /** 启动后默认进入的视图：false=地图页面, true=CAD 图纸页面 */
  const START_IN_CAD_MODE = false;

  /** 地图配置 */
  const mapConfig: Partial<MapConfig> = {
    center: [114.0, 38.0],
    zoom: 5,
    tileUrl: 'http://182.92.126.35:9999/sys/common/static/map/{z}/{x}/{y}.png',
  };

  const boundaryConfig: BoundaryConfig = {
    provinces: ['山东省', '山西省'],
    cities: [],
    counties: [],
    fillColor: [129, 230, 246, 30],
    strokeColor: [59, 130, 246, 160],
    regionColors: {
      石家庄市: { fillColor: [50, 280, 50, 30], strokeColor: [50, 280, 50, 200] },
      太原市: { fillColor: [140, 20, 112, 30], strokeColor: [140, 20, 112, 180] },
      保定市: { fillColor: [140, 120, 12, 30], strokeColor: [140, 120, 12, 180] },
    },
  };

  const markers: MapMarker[] = [
    { coords: [113.2, 37.8], label: '4', color: [255, 60, 60, 250], fontColor: [255, 255, 255, 255], borderColor: [0, 0, 0, 255] },
    {
      coords: [112.7, 38.6],
      label: '',
      color: [60, 200, 60, 250],
      fontColor: [255, 255, 255, 255],
      borderColor: [0, 0, 0, 255],
      switchToCad: true,
      popup: {
        title: '煤矿 #1',
        items: [
          { subtitle: '矿井名称', content: '一号煤矿' },
          { subtitle: '设计产能', content: '120 万吨/年' },
          { subtitle: '开采深度', content: '850 m' },
          { subtitle: '通风方式', content: '中央并列式' },
        ],
      },
    },
  ];

  const cadData = ref<CadData | undefined>();
  const currentIconId = ref('speed');

  /**
   * App.vue — 应用主入口
   *
   * 集成 MapCadViewer 组件，提供：
   * - 地图配置（默认使用内网瓦片服务）
   * - 行政区划边界（高亮省市区域）
   * - 标注点及 CAD 模式切换
   * - 工具栏：CAD 绘制模式（风门/传感器/密闭/测风装置）
   *
   * 数据流：
   * 1. 页面加载 → 获取 /features.json → 传给 MapCadViewer
   * 2. 用户点击标注点 → switchToCadMode(marker, cadData)
   * 3. 用户点击工具栏图标 → toggleDrawingMode / clearPlacedIcons
   */

  // 内置的 4 种绘制图标定义（用于工具栏按钮的 SVG 预览和内联 HTML）
  const svgIconsStatic = [
    {
      type: 'gate',
      name: '风门',
      iconUrl: '/icons/gate.svg',
      svg: "<svg width='20' height='20' viewBox='0 0 20 20'><rect x='4' y='2' width='12' height='16' rx='2' fill='none' stroke='#4dc9f6' stroke-width='1.5'/><line x1='7' y1='6' x2='13' y2='6' stroke='#4dc9f6' stroke-width='1.5'/><line x1='7' y1='10' x2='13' y2='10' stroke='#4dc9f6' stroke-width='1.5'/><line x1='7' y1='14' x2='13' y2='14' stroke='#4dc9f6' stroke-width='1.5'/></svg>",
    },
    {
      type: 'modelsensor',
      name: '传感器',
      iconUrl: '/icons/modelsensor.svg',
      svg: "<svg width='20' height='20' viewBox='0 0 20 20'><circle cx='10' cy='10' r='6' fill='none' stroke='#44ff88' stroke-width='1.5'/><circle cx='10' cy='10' r='2' fill='#44ff88'/></svg>",
    },
    {
      type: 'obfurage',
      name: '密闭',
      iconUrl: '/icons/obfurage.svg',
      svg: "<svg width='20' height='20' viewBox='0 0 20 20'><rect x='4' y='3' width='12' height='14' fill='none' stroke='#ff6644' stroke-width='1.5'/><line x1='4' y1='3' x2='16' y2='17' stroke='#ff6644' stroke-width='1.5'/></svg>",
    },
    {
      type: 'speed',
      name: '测风装置',
      iconUrl: '/icons/speed.svg',
      svg: "<svg width='20' height='20' viewBox='0 0 20 20'><polygon points='10,2 18,18 2,18' fill='none' stroke='#ffaa00' stroke-width='1.5'/><line x1='10' y1='2' x2='10' y2='12' stroke='#ffaa00' stroke-width='1.5'/><line x1='6' y1='14' x2='14' y2='14' stroke='#ffaa00' stroke-width='1.5'/></svg>",
    },
  ];

  function onModeChange(mode: string) {
    console.log('Viewer mode changed:', mode);
    currentMode.value = mode as any;
  }

  const currentMode = ref<'map' | 'cad' | 'drawing'>('map');
  const isCadMode = computed(() => currentMode.value === 'cad' || currentMode.value === 'drawing');

  function onFeatureSelect(feature: any) {
    console.log('Selected feature:', feature.id, feature.typename, 'layer:', feature.layer);
  }

  function onMarkerClick(marker: any) {
    console.log('Marker clicked:', marker.label, 'coords:', marker.coords, 'switchToCad:', marker.switchToCad, 'popup:', marker.popup);
  }

  function onMarkerOpenCad(marker: any) {
    console.log('Marker title clicked, opening CAD:', marker.label);
    if (cadData.value) {
      viewerRef.value?.switchToCadMode(marker, cadData.value);
    }
  }
  // 切换当前选择的省，市，和描点,重新绘制蒙版和标识
  function changeView() {
    const boundary: BoundaryConfig = {
      provinces: [],
      cities: ['太原市', '晋中市', '长治市'],
      counties: [],
      fillColor: [129, 230, 246, 30],
      strokeColor: [59, 130, 246, 160],
      regionColors: {
        太原市: { fillColor: [50, 280, 50, 30], strokeColor: [50, 280, 50, 200] },
        晋中市: { fillColor: [140, 20, 112, 30], strokeColor: [140, 20, 112, 180] },
      },
    };

    const newMarkers: MapMarker[] = [
      { coords: [112.7, 37.8], label: '2', color: [255, 60, 60, 250], fontColor: [255, 255, 255, 255], borderColor: [0, 0, 0, 255] },
      {
        coords: [112.2, 38.2],
        label: '',
        color: [60, 200, 60, 250],
        fontColor: [255, 255, 255, 255],
        borderColor: [0, 0, 0, 255],
        switchToCad: true,
        popup: {
          title: '太原市',
          items: [
            { subtitle: '矿井名称', content: '一号煤矿' },
            { subtitle: '设计产能', content: '120 万吨/年' },
          ],
        },
      },
    ];
    viewerRef.value?.changeView(boundary, newMarkers);
    setMapView([112.7, 37.8], 7.2, 1000);
  }
  /** 切换地图中心点和缩放级别，仅在地图模式下生效 */
  // 飞到位置，zoom 14，动画 1 秒
  //setMapView([113.7, 38.6], 14, 1000)
  function setMapView(center: [number, number], zoom: number, duration: number = 500) {
    viewerRef.value?.setMapView(center, zoom, duration);
  }
  // CAD 控制方法
  function goBackToMap() {
    viewerRef.value?.goBackToMap();
  }
  function toggleLayerPanel() {
    viewerRef.value?.toggleLayerPanel();
  }
  function toggleDrawing() {
    const item = svgIconsStatic.find((i) => i.type === currentIconId.value);
    if (!item) return;
    viewerRef.value?.toggleDrawingMode({
      type: item.type,
      iconUrl: item.iconUrl,
      name: item.name,
    });
  }
  function zoomFit() {
    viewerRef.value?.zoomToFit();
  }
  function selectIcon(item: { type: string; name: string; iconUrl: string }) {
    currentIconId.value = item.type;
    const tool = { type: item.type, iconUrl: item.iconUrl, name: item.name };
    if (currentMode.value === 'drawing' && viewerRef.value) {
      viewerRef.value.setDrawingTool(tool);
    } else {
      viewerRef.value?.setSelectedIcon(item.type);
    }
  }
  function clearIcons() {
    viewerRef.value?.clearPlacedIcons();
  }

  function onIconPlaced(icon: any) {
    console.log('Icon placed:', icon);
  }

  function onIconMoved(icon: any) {
    console.log('Icon moved:', icon);
  }

  onMounted(async () => {
    try {
      const resp = await fetch('/hll.json');
      const data: CadData = await resp.json();
      cadData.value = data;
      console.log(`Loaded ${data.features.length} CAD features`);

      // 根据配置选择初始视图
      if (START_IN_CAD_MODE && viewerRef.value) {
        // 不飞向标注点，直接进入 CAD 全图视图
        viewerRef.value.switchToCadMode(undefined, data);
      }
    } catch (e) {
      console.warn('Could not load hll.json (expected in dev)', e);
    }
  });
</script>

<style lang="less">
  .map-container {
    flex: 1;
    height: 100%;
    width: 100%;
    position: fixed;
    top: 0;
    left: 0;
    z-index: @simple-map-z-index;
    // filter: grayscale(80%) invert(0%) sepia(10%) hue-rotate(150deg) saturate(200%) brightness(100%) contrast(100%);

    canvas {
      /* width: 1920px !important;
      height: 948px !important; */
    }
  }

  /* 图例浮层 */
  .map-legend {
    position: fixed;
    bottom: 24px;
    left: 24px;
    z-index: @simple-map-z-index + 1;
    background: rgba(255, 255, 255, 0.92);
    border-radius: 8px;
    padding: 10px 14px;
    font-size: 12px;
    line-height: 1.8;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
    color: #333;
    min-width: 140px;
    pointer-events: none;

    .legend-title {
      font-weight: 600;
      margin-bottom: 4px;
      font-size: 13px;
    }
    .legend-row {
      display: flex;
      align-items: center;
      gap: 6px;
    }
    .legend-dot {
      display: inline-block;
      width: 10px;
      height: 10px;
      border-radius: 50%;
      flex-shrink: 0;
    }
    .legend-dot-green {
      background: #52c41a;
    }
    .legend-dot-orange {
      background: #fa8c16;
    }
    .legend-dot-yellow {
      background: #fadb14;
    }
    .legend-dot-red {
      background: #f5222d;
    }
    .legend-dot-red-dashed {
      background: transparent;
      border: 2px dashed #f5222d;
    }
    .legend-line-red {
      display: inline-block;
      width: 14px;
      height: 3px;
      background: #f5222d;
      flex-shrink: 0;
    }
  }
</style>
<style>
  /* CAD 工具栏 — 由 App.vue 控制界面 */
  .cad-toolbar {
    position: absolute;
    top: 12px;
    left: 50%;
    transform: translateX(-50%);
    z-index: 400;
    display: flex;
    gap: 6px;
    background: rgba(20, 20, 30, 0.9);
    border: 1px solid rgba(255, 255, 255, 0.15);
    border-radius: 8px;
    padding: 6px 10px;
    backdrop-filter: blur(8px);
  }
  .cad-btn {
    background: rgba(255, 255, 255, 0.08);
    border: 1px solid rgba(255, 255, 255, 0.12);
    color: #ccc;
    padding: 6px 12px;
    border-radius: 6px;
    font-size: 12px;
    cursor: pointer;
    transition: all 0.15s;
    white-space: nowrap;
  }
  .cad-btn:hover {
    background: rgba(255, 255, 255, 0.15);
    color: #fff;
  }
  .cad-btn.active {
    background: rgba(59, 130, 246, 0.4);
    border-color: rgba(59, 130, 246, 0.6);
    color: #fff;
  }

  .drawing-toolbar {
    position: absolute;
    bottom: 24px;
    left: 50%;
    transform: translateX(-50%);
    z-index: 400;
    display: flex;
    align-items: center;
    gap: 8px;
    background: rgba(20, 20, 30, 0.92);
    border: 1px solid rgba(255, 255, 255, 0.15);
    border-radius: 8px;
    padding: 8px 14px;
    backdrop-filter: blur(8px);
  }
  .drawing-label {
    color: #aaa;
    font-size: 12px;
  }
  .drawing-icons {
    display: flex;
    gap: 4px;
  }
  .icon-btn {
    background: rgba(255, 255, 255, 0.06);
    border: 1px solid rgba(255, 255, 255, 0.1);
    border-radius: 6px;
    padding: 4px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 32px;
    height: 32px;
    transition: all 0.15s;
  }
  .gate {
    background: url(./assets/icons/gate.svg) center no-repeat;
    background-size: 100% 100%;
  }
  .speed {
    background: url(./assets/icons/speed.svg) center no-repeat;
    background-size: 100% 100%;
  }
  .modelsensor {
    background: url(./assets/icons/modelsensor.svg) center no-repeat;
    background-size: 100% 100%;
  }
  .obfurage {
    background: url(./assets/icons/obfurage.svg) center no-repeat;
    background-size: 100% 100%;
  }
</style>
