<template>
  <div class="map-wrapper" :style="mapCssVars">
    <div ref="mapContainer" class="map-container"></div>

    <div class="map-legend" :style="privateStyle.legend" v-if="(!mode || mode === '路口')"
      :class="{ 'legend-hidden': !legendVisible }">
      <div class="legend-header">
        <div class="legend-title">图例</div>
        <div class="legend-close-btn" @click="toggleLegend">✕</div>
      </div>
      <div class="legend-list">
        <div class="legend-item all-select" @click="toggleAll">
          <div class="legend-dot"
            :style="{ backgroundColor: isAllSelected ? '#fff' : 'transparent', border: '1px solid #fff' }"></div>
          <div class="legend-label" style="font-weight: bold;">全选</div>
        </div>

        <div v-for="item in legendStatusConfig" class="legend-item" @click="toggleRouteVisible(item.name)" :key="item.name"
          :class="{ 'is-inactive': !activeLegends.includes(item.name) }">

          <div class="legend-dot"
            :style="{ backgroundColor: ['离线', '降级', '故障'].includes(item.name) ? 'transparent' : item.color }"
            :class="{ 'special-route': ['干线协调', '勤务路线'].includes(item.name), 'is-status-wrapper': ['离线', '降级', '故障'].includes(item.name) }">

            <span v-if="!['离线', '降级', '故障'].includes(item.name)">
              {{ item.name.charAt(0) }}
            </span>

            <img v-else
              :src="require(`@/assets/images/icon_${item.name === '离线' ? 'lixian' : item.name === '降级' ? 'jiangji' : 'guzhang'}.png`)"
              class="status-icon" />
          </div>

          <div class="legend-label">{{ item.name }}</div>
        </div>
      </div>
    </div>
    <div class="legend-show-btn" v-if="(!mode || mode === '路口') && !legendVisible" @click="toggleLegend" :style="legendShowBtnStyle">
      <div class="legend-show-icon">☰</div>
    </div>
  </div>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader';

export default {
  name: "TrafficMap",
  props: {
    amapKey: { type: String, default: '您的Key' },
    securityJsCode: { type: String, default: '您的安全密钥' },
    mode: { type: String, default: '', validator: (value) => ['', '路口', '干线', '特勤'].includes(value) }
  },
  data() {
    return {
      AMap: null,
      map: null,
      infoWindow: null,
      routeGroups: {},
      dotMarkers: [],
      privateStyle: {
        legend: {}
      },
      legendVisible: true,
      activeLegends: ["中心计划", "干线协调", "勤务路线", "定周期控制", "感应控制", "自适应控制", "手动控制", "特殊控制", "离线", "降级", "故障"],
      isComponentDestroyed: false,
      drawSeq: 0,
      driving: null,
      infoCloseTimer: null,
      activeInfoWindowId: null,
      isInfoWindowHovered: false,
      statusConfig: [
        { name: "中心计划", color: "#004CDE", type: "normal" },
        { name: "干线协调", color: "#13C373", type: "route" },
        { name: "勤务路线", color: "#BC301D", type: "route" },
        { name: "定周期控制", color: "#3296FA", type: "normal" },
        { name: "感应控制", color: "#FF864C", type: "normal" },
        { name: "自适应控制", color: "#9F6EFE", type: "normal" },
        { name: "手动控制", color: "#EB9F36", type: "normal" },
        { name: "特殊控制", color: "#A26218", type: "normal" },
        { name: "离线", color: "#7A7A7A", type: "abnormal" },
        { name: "降级", color: "#D9C13B", type: "abnormal" },
        { name: "故障", color: "#FF3938", type: "abnormal" }
      ],
      intersectionData: [],
      statusIntersections: {},
      currentZoomSize: 14, // 保存当前的动态尺寸
    };
  },
  mounted() {
    this.isComponentDestroyed = false;
    this.loadMapData().then(() => {
      this.classifyIntersectionsByStatus();
      this.updateMapByMode();
      this.initAMap();
      this.storeStatusCoordsToLocalStorage();
    });

    if (this.$route.path === '/home' || this.$route.path === '/watch') {
      this.privateStyle.legend = { right: "25%" };
    }
  },
  watch: {
    mode: {
      handler() {
        this.updateMapByMode();
        this.updateMapDisplay();
      },
      immediate: false
    }
  },
  beforeDestroy() {
    // 1. 立即设置销毁状态
    this.isComponentDestroyed = true;
    this.drawSeq += 1;

    // 2. 关闭弹窗
    if (this.infoWindow) {
      try {
        this.infoWindow.close();
      } catch (e) {
        console.warn('关闭信息窗口时出错:', e);
      }
      this.infoWindow = null;
    }

    // 3. 清理覆盖物引用
    if (this.routeGroups) {
      Object.values(this.routeGroups).forEach(overlays => {
        if (Array.isArray(overlays)) {
          overlays.forEach(o => {
            try {
              if (o.setMap) o.setMap(null);
            } catch (e) {
              console.warn('清理覆盖物时出错:', e);
            }
          });
        }
      });
      this.routeGroups = {};
    }

    // 4. 销毁地图实例并清空引用
    if (this.map) {
      try {
        this.map.destroy();
      } catch (e) {
        console.warn('销毁地图实例时出错:', e);
      }
      this.map = null;
    }

    // 5. 清理其他引用
    this.AMap = null;
    this.driving = null;
    if (this.infoCloseTimer) {
      clearTimeout(this.infoCloseTimer);
      this.infoCloseTimer = null;
    }
    this.activeInfoWindowId = null;
    this.isInfoWindowHovered = false;
  },
  computed: {
    isAllSelected() {
      return this.activeLegends.length === this.statusConfig.length;
    },
    isHomePage() {
      return this.$route && (this.$route.path === '/home' || this.$route.path === '/surve');
    },
    legendShowBtnStyle() {
      if (!this.isHomePage) return {};
      const right = (this.privateStyle.legend && this.privateStyle.legend.right) ? this.privateStyle.legend.right : '25%';
      return { right, borderRadius: '6px' };
    },
    legendStatusConfig() {
      if (!this.mode) return this.statusConfig;
      if (this.mode === '路口') {
        return this.statusConfig.filter(item => !['干线协调', '勤务路线'].includes(item.name));
      }
      return [];
    },
    // 自动计算并下发给所有 CSS 的变量字典
    mapCssVars() {
      const size = this.currentZoomSize;
      const specialSize = Math.max(16, size * 1.5);
      return {
        '--dot-size': `${size}px`,
        '--dot-padding': size >= 14 ? '2px' : '0px',
        '--text-display': size >= 14 ? 'flex' : 'none',
        '--text-size': `${Math.max(10, size - 2)}px`,
        '--special-size': `${specialSize}px`
      };
    }
  },
  methods: {
    /**
     * 动态加载地图数据
     * @returns {Promise<void>}
     */
    async loadMapData() {
      try {
        const mapDataModule = await import('@/mock/map_data_gaode.json');
        this.intersectionData = mapDataModule.default || [];
        console.log('地图数据加载成功，共', this.intersectionData.length, '个路口');
      } catch (error) {
        console.error('地图数据加载失败:', error);
        this.intersectionData = [];
      }
    },

    /**
     * 检查地图环境是否安全可用
     * @returns {boolean}
     */
    isMapReady() {
      return !this.isComponentDestroyed && this.map && typeof this.map.add === 'function';
    },

    /**
     * 将真实路口数据按状态类型分类
     */
    classifyIntersectionsByStatus() {
      const remainingData = this.intersectionData;
      const maxAbnormalCount = 4;
      const abnormalTotal = maxAbnormalCount * 3;
      const normalData = remainingData.slice(0, remainingData.length - abnormalTotal);
      const abnormalData = remainingData.slice(remainingData.length - abnormalTotal);
      const normalChunk = Math.ceil(normalData.length / 6);

      this.statusIntersections = {
        "中心计划": normalData.slice(0, normalChunk),
        "干线协调": [],
        "勤务路线": [],
        "定周期控制": normalData.slice(normalChunk, normalChunk * 2),
        "感应控制": normalData.slice(normalChunk * 2, normalChunk * 3),
        "自适应控制": normalData.slice(normalChunk * 3, normalChunk * 4),
        "手动控制": normalData.slice(normalChunk * 4, normalChunk * 5),
        "特殊控制": normalData.slice(normalChunk * 5),
        "离线": abnormalData.slice(0, maxAbnormalCount),
        "降级": abnormalData.slice(maxAbnormalCount, maxAbnormalCount * 2),
        "故障": abnormalData.slice(maxAbnormalCount * 2, maxAbnormalCount * 3)
      };
    },

    /**
     * 根据模式更新地图显示
     */
    updateMapByMode() {
      switch (this.mode) {
        case '路口':
          this.activeLegends = ["中心计划", "定周期控制", "感应控制", "自适应控制", "手动控制", "特殊控制", "离线", "降级", "故障"];
          break;
        case '干线':
          this.activeLegends = ["干线协调"];
          break;
        case '特勤':
          this.activeLegends = ["勤务路线"];
          break;
        default:
          this.activeLegends = this.statusConfig.map(item => item.name);
      }
    },

    /**
     * 更新地图显示状态
     */
    updateMapDisplay() {
      if (this.infoWindow) this.infoWindow.close();
      if (!this.isMapReady()) return;

      Object.keys(this.routeGroups).forEach(name => {
        const overlays = this.routeGroups[name];
        if (overlays && overlays.length > 0) {
          if (this.activeLegends.includes(name)) {
            this.map.add(overlays);
          } else {
            this.map.remove(overlays);
          }
        }
      });
    },

    /**
     * 初始化高德地图
     * @returns {Promise<void>}
     */
    async initAMap() {
      if (this.isComponentDestroyed) return;

      window._AMapSecurityConfig = { securityJsCode: this.securityJsCode };

      try {
        const AMap = await AMapLoader.load({
          key: this.amapKey,
          version: "2.0",
          plugins: ['AMap.Driving']
        });

        if (this.isComponentDestroyed) return;

        this.AMap = AMap;
        this.map = new AMap.Map(this.$refs.mapContainer, {
          zoom: 15,
          mapStyle: "amap://styles/darkblue",
          center: [116.663, 39.905]
        });

        this.driving = new AMap.Driving({ map: null, hideMarkers: true });

        this.map.on('complete', () => {
          if (!this.isComponentDestroyed) {
            this.drawStaticRoutes();
          }
        });

        this.map.on('zoomchange', () => {
          if (!this.isComponentDestroyed) {
            this.currentZoomSize = this.getDotSizeByZoom();
          }
        });
      } catch (err) {
        console.error('地图加载失败:', err);
      }
    },

    /**
     * 绘制静态路线和标记
     * @returns {Promise<void>}
     */
    async drawStaticRoutes() {
      if (!this.isMapReady()) return;

      this.drawSeq += 1;
      const drawSeq = this.drawSeq;

      this.clearAllRouteOverlays();

      const realRouteConfigs = {
        "干线协调": [
          { start: [116.6421, 39.9272], end: [116.6623, 39.9272], color: "#13C373", trunkId: 'trunk_1', trunkName: '古城南路与古城大街' },
          { start: [116.6623, 39.9272], end: [116.6825, 39.9272], color: "#13C373", trunkId: 'trunk_2', trunkName: '古城西路东口南一过街' },
          { start: [116.6426, 39.9221], end: [116.6628, 39.9221], color: "#13C373", trunkId: 'trunk_3', trunkName: '古城大街与古城北路' },
          { start: [116.6628, 39.9221], end: [116.683, 39.9221], color: "#13C373", trunkId: 'trunk_4', trunkName: '八角北路与八角东街' },
          { start: [116.6432, 39.9171], end: [116.66325, 39.9171], color: "#13C373", trunkId: 'trunk_5', trunkName: '古城西路与古城大街' },
          { start: [116.66325, 39.9171], end: [116.6833, 39.9171], color: "#13C373", trunkId: 'trunk_6', trunkName: '张台路与湖亦路路口' },
        ],
        "勤务路线": [
          { start: [116.6445, 39.8980], end: [116.6850, 39.8980], color: "#BC301D", dutyState: 'pending' },
          { start: [116.6850, 39.8980], end: [116.7250, 39.8980], color: "#BC301D", dutyState: 'active', progress: 0.45 },
          { start: [116.7250, 39.8980], end: [116.7650, 39.8980], color: "#BC301D", dutyState: 'done' }
        ]
      };

      for (const config of this.statusConfig) {
        if (this.isComponentDestroyed || drawSeq !== this.drawSeq) return;

        if (!realRouteConfigs[config.name]) {
          const intersections = this.statusIntersections[config.name] || [];
          const markers = intersections.map(item =>
            this.createTrafficLightMarker([item["位置-经度"], item["位置-纬度"]], {
              ...config,
              id: item["路口编号"],
              road: item["路口名称"] || '规划路口'
            })
          ).filter(Boolean);
          this.routeGroups[config.name] = markers;
          if (this.activeLegends.includes(config.name)) this.map.add(markers);
          continue;
        }

        this.routeGroups[config.name] = [];
        const lines = realRouteConfigs[config.name] || [];
        const trunkSegments = [];

        for (let lineIdx = 0; lineIdx < lines.length; lineIdx += 1) {
          if (this.isComponentDestroyed || drawSeq !== this.drawSeq) return;

          const line = lines[lineIdx];
          let path = null;
          try {
            path = await this.searchDrivingPathWithRetry(line.start, line.end);
          } catch (e) {
            path = null;
          }

          const overlays = this.buildRouteOverlaysFromPath({
            config,
            configName: config.name,
            line,
            lineIdx,
            path
          });

          if (config.name === '干线协调' && overlays.length > 0) {
            const name = line.trunkName || ('干线' + (lineIdx + 1));
            trunkSegments.push({
              id: line.trunkId || ('trunk_' + (lineIdx + 1)),
              label: name,
              intersections: Array.from({ length: 6 }, (_, k) => name + '_路口' + (k + 1)),
              distances: Array.from({ length: 6 }, (_, k) => k * 500),
              _lineIdx: lineIdx
            });
          }

          if (this.isComponentDestroyed || drawSeq !== this.drawSeq) return;

          if (overlays.length > 0) {
            this.routeGroups[config.name].push(...overlays);
            if (this.activeLegends.includes(config.name)) this.map.add(overlays);
          }

          await this.sleep(80);
        }

        if (config.name === '干线协调' && trunkSegments.length > 0) {
          this.$emit('bindTrunkMenuTree', trunkSegments);
        }
      }
    },

    /**
     * 清除所有路线覆盖物
     */
    clearAllRouteOverlays() {
      if (!this.isMapReady()) return;
      try {
        if (this.infoWindow) this.infoWindow.close();
      } catch (e) {
        void e;
      }

      Object.values(this.routeGroups || {}).forEach(overlays => {
        if (!Array.isArray(overlays) || overlays.length === 0) return;
        try {
          this.map.remove(overlays);
        } catch (e) {
          void e;
        }
        overlays.forEach(o => {
          try {
            if (o && typeof o.setMap === 'function') o.setMap(null);
          } catch (e) {
            void e;
          }
        });
      });

      this.routeGroups = {};
      this.dotMarkers = [];
    },

    /**
     * 休眠函数
     * @param {number} ms - 休眠毫秒数
     * @returns {Promise<void>}
     */
    sleep(ms) {
      return new Promise(resolve => setTimeout(resolve, ms));
    },

    /**
     * 带重试机制的路径规划
     * @param {Array<number>} start - 起点坐标 [lng, lat]
     * @param {Array<number>} end - 终点坐标 [lng, lat]
     * @returns {Promise<Array>} 路径点数组
     */
    async searchDrivingPathWithRetry(start, end) {
      if (!this.AMap || !this.driving || typeof this.driving.search !== 'function') {
        throw new Error('Driving not ready');
      }

      const maxAttempts = 3;
      let lastErr = null;
      for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
        try {
          return await this.withTimeout(this.searchDrivingPathOnce(start, end), 8000);
        } catch (e) {
          lastErr = e;
          await this.sleep(250 * attempt);
        }
      }
      throw lastErr || new Error('Driving search failed');
    },

    /**
     * 单次路径规划
     * @param {Array<number>} start - 起点坐标 [lng, lat]
     * @param {Array<number>} end - 终点坐标 [lng, lat]
     * @returns {Promise<Array>} 路径点数组
     */
    searchDrivingPathOnce(start, end) {
      return new Promise((resolve, reject) => {
        this.driving.search(start, end, (status, result) => {
          const route = result && result.routes && result.routes[0];
          if (status === 'complete' && route && Array.isArray(route.steps)) {
            const fullPath = [];
            route.steps.forEach(step => {
              if (step && Array.isArray(step.path)) fullPath.push(...step.path);
            });
            if (fullPath.length >= 2) resolve(fullPath);
            else reject(new Error('empty_path'));
            return;
          }
          reject(new Error(typeof status === 'string' ? status : 'driving_error'));
        });
      });
    },

    /**
     * 为Promise添加超时机制
     * @param {Promise} promise - 要执行的Promise
     * @param {number} timeoutMs - 超时毫秒数
     * @returns {Promise} 带超时的Promise
     */
    withTimeout(promise, timeoutMs) {
      return Promise.race([
        promise,
        new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), timeoutMs))
      ]);
    },

    /**
     * 从路径构建路线覆盖物
     * @param {Object} params - 参数对象
     * @param {Object} params.config - 配置对象
     * @param {string} params.configName - 配置名称
     * @param {Object} params.line - 路线配置
     * @param {number} params.lineIdx - 路线索引
     * @param {Array} params.path - 路径点数组
     * @returns {Array} 覆盖物数组
     */
    buildRouteOverlaysFromPath({ config, configName, line, lineIdx, path }) {
      if (!this.AMap || !this.map) return [];

      let basePath = path;
      if (!Array.isArray(basePath) || basePath.length < 2) {
        basePath = this.buildFallbackLinePath(line.start, line.end, 30);
      }

      const offsetVal = 0;
      const applyOffset = (p) => {
        const lng = p.lng || (p.getLng ? p.getLng() : (Array.isArray(p) ? Number(p[0]) : 0));
        const lat = p.lat || (p.getLat ? p.getLat() : (Array.isArray(p) ? Number(p[1]) : 0));
        return [lng + offsetVal, lat + offsetVal];
      };

      const allSegments = this.extractMainStraightSegments(basePath);
      const segments = configName === '干线协调'
        ? allSegments.slice(0, 1)
        : allSegments;
      const overlays = [];

      segments.forEach((rawSegmentPath, segmentIdx) => {
        if (!Array.isArray(rawSegmentPath) || rawSegmentPath.length < 2) return;

        const segmentPath = rawSegmentPath.map(p => applyOffset(p));

        if (configName === '勤务路线' && line.dutyState) {
          const state = line.dutyState; // 'pending' | 'active' | 'done'
          const progress = (state === 'active') ? Math.min(Math.max(Number(line.progress) || 0.5, 0), 1) : (state === 'done' ? 1 : 0);

          // 计算整段累计距离
          const dists = [0];
          let totalDist = 0;
          for (let j = 0; j < segmentPath.length - 1; j++) {
            totalDist += this.calcApproxDistance(segmentPath[j], segmentPath[j + 1]);
            dists.push(totalDist);
          }
          const splitDist = totalDist * progress;

          // 找切割点坐标（线性插值）
          let splitIdx = segmentPath.length - 1;
          let splitPoint = segmentPath[segmentPath.length - 1];
          for (let j = 0; j < dists.length - 1; j++) {
            if (splitDist >= dists[j] && splitDist <= dists[j + 1]) {
              const ratio = dists[j + 1] === dists[j] ? 0 : (splitDist - dists[j]) / (dists[j + 1] - dists[j]);
              const p1 = segmentPath[j], p2 = segmentPath[j + 1];
              splitPoint = [
                Number(p1[0]) + (Number(p2[0]) - Number(p1[0])) * ratio,
                Number(p1[1]) + (Number(p2[1]) - Number(p1[1])) * ratio
              ];
              splitIdx = j;
              break;
            }
          }

          // 已过段（灰色）
          const passedPath = [...segmentPath.slice(0, splitIdx + 1), splitPoint];
          if (passedPath.length >= 2) {
            overlays.push(new this.AMap.Polyline({
              path: passedPath,
              strokeColor: '#5A5A5A',
              strokeWeight: 6,
              strokeOpacity: 0.45,
              zIndex: 15
            }));
          }

          // 未过段（原红色），done 状态不绘制
          const remainPath = [splitPoint, ...segmentPath.slice(splitIdx + 1)];
          if (state !== 'done' && remainPath.length >= 2) {
            overlays.push(new this.AMap.Polyline({
              path: remainPath,
              strokeColor: line.color,
              strokeWeight: 6,
              strokeOpacity: 0.8,
              zIndex: 15
            }));
          }

          // 执行中：进度点脉冲 marker
          if (state === 'active') {
            overlays.push(new this.AMap.Marker({
              position: splitPoint,
              zIndex: 150,
              offset: new this.AMap.Pixel(-12, -12),
              bubble: true,
              content: `<div class="duty-progress-node" style="width:24px;height:24px;border-radius:50%;background:#BC301D;border:3px solid #fff;box-shadow:0 0 0 3px rgba(188,48,29,0.4);display:flex;justify-content:center;align-items:center;cursor:default;"><div style="width:8px;height:8px;border-radius:50%;background:#fff;"></div></div>`
            }));
          }

          // 方向箭头：已过段灰色低透明，未过段正常
          const targetSpacing = 0.0036;
          let arrowDist = targetSpacing / 2;
          while (arrowDist < totalDist) {
            let foundIdx = 0;
            for (let j = 0; j < dists.length - 1; j++) {
              if (arrowDist >= dists[j] && arrowDist <= dists[j + 1]) { foundIdx = j; break; }
            }
            const p1 = segmentPath[foundIdx], p2 = segmentPath[foundIdx + 1];
            if (p1 && p2) {
              const ratio = (arrowDist - dists[foundIdx]) / (dists[foundIdx + 1] - dists[foundIdx]);
              const midLng = Number(p1[0]) + (Number(p2[0]) - Number(p1[0])) * ratio;
              const midLat = Number(p1[1]) + (Number(p2[1]) - Number(p1[1])) * ratio;
              const isPassed = arrowDist <= splitDist;
              const rotation = this.calcBearingDeg(p1, p2) - 90;
              overlays.push(new this.AMap.Marker({
                position: [midLng, midLat],
                content: `<div style="transform:rotate(${rotation}deg);width:20px;height:10px;display:flex;align-items:center;pointer-events:none;opacity:${isPassed ? 0.2 : 0.85};filter:${isPassed ? 'grayscale(1)' : 'none'};"><img src="${require('@/assets/map/direction.png')}" style="width:100%;height:auto;" /></div>`,
                offset: new this.AMap.Pixel(-10, -5),
                zIndex: 20,
                bubble: true
              }));
            }
            arrowDist += targetSpacing;
          }

          // 路口圆点：已过置灰，未过正常
          const indices = this.pickEvenlySpacedIndices(segmentPath.length, 6);
          for (let i = 0; i < indices.length; i++) {
            const idx = indices[i];
            const p = segmentPath[idx];
            const lng = Number(p[0]), lat = Number(p[1]);
            if (Number.isNaN(lng) || Number.isNaN(lat)) continue;
            const dotDist = dists[idx] || 0;
            let markerType = 'normal';
            if (i === 0) markerType = 'start';
            else if (i === indices.length - 1) markerType = 'end';

            const isPastDot = dotDist <= splitDist;
            const dotConfig = isPastDot
              ? { ...config, color: '#5A5A5A', id: `MOCK-D-${lineIdx}-${segmentIdx}-${idx}`, road: `勤务路线路口-${lineIdx}-${segmentIdx}-${idx}` }
              : { ...config, id: `MOCK-D-${lineIdx}-${segmentIdx}-${idx}`, road: `勤务路线路口-${lineIdx}-${segmentIdx}-${idx}` };
            const dotType = isPastDot && markerType === 'normal' ? 'passed' : markerType;
            const marker = this.createTrafficLightMarker([lng, lat], dotConfig, dotType);
            if (marker) overlays.push(marker);
          }

        } else {
          // 非勤务路线 或 无 dutyState：原有逻辑
          const polyline = new this.AMap.Polyline({
            path: segmentPath,
            strokeColor: line.color,
            strokeWeight: 6,
            strokeOpacity: 0.8,
            zIndex: 15
          });
          overlays.push(polyline);

          const totalPoints = segmentPath.length;

          const pathDistances = [0];
          let totalPathDist = 0;
          for (let j = 0; j < totalPoints - 1; j++) {
            const d = this.calcApproxDistance(segmentPath[j], segmentPath[j+1]);
            totalPathDist += d;
            pathDistances.push(totalPathDist);
          }

          if (configName !== '干线协调') {
            const targetSpacing = configName === '勤务路线' ? 0.0036 : 0.0018;
            let currentTargetDist = targetSpacing / 2;

            while (currentTargetDist < totalPathDist) {
              let foundIdx = 0;
              for (let j = 0; j < pathDistances.length - 1; j++) {
                if (currentTargetDist >= pathDistances[j] && currentTargetDist <= pathDistances[j + 1]) {
                  foundIdx = j;
                  break;
                }
              }
              const p1 = segmentPath[foundIdx];
              const p2 = segmentPath[foundIdx + 1];
              if (p1 && p2) {
                const ratio = (currentTargetDist - pathDistances[foundIdx]) / (pathDistances[foundIdx + 1] - pathDistances[foundIdx]);
                const midLng = Number(p1[0]) + (Number(p2[0]) - Number(p1[0])) * ratio;
                const midLat = Number(p1[1]) + (Number(p2[1]) - Number(p1[1])) * ratio;
                const bearing = this.calcBearingDeg(p1, p2);
                const rotation = bearing - 90;
                const directionMarker = new this.AMap.Marker({
                  position: [midLng, midLat],
                  content: `
                    <div style="transform: rotate(${rotation}deg); width: 20px; height: 10px; display: flex; align-items: center; pointer-events: none; opacity: 0.85;">
                      <img src="${require('@/assets/map/direction.png')}" style="width: 100%; height: auto;" />
                    </div>
                  `,
                  offset: new this.AMap.Pixel(-10, -5),
                  zIndex: 20,
                  bubble: true
                });
                overlays.push(directionMarker);
              }
              currentTargetDist += targetSpacing;
            }
          }

          const indices = this.pickEvenlySpacedIndices(totalPoints, 6);
          for (let i = 0; i < indices.length; i++) {
            const idx = indices[i];
            const p = segmentPath[idx];
            const lng = Number(p[0]);
            const lat = Number(p[1]);
            if (Number.isNaN(lng) || Number.isNaN(lat)) continue;

            let markerType = 'normal';
            if (configName !== '干线协调') {
              if (i === 0) markerType = 'start';
              else if (i === indices.length - 1) markerType = 'end';
            }

            // 干线协调：id 用干线编号，road 用干线名称（与菜单标题一致）
            const markerId = (configName === '干线协调' && line.trunkId)
              ? `${line.trunkId}_point_${i + 1}`
              : `MOCK-${configName.charAt(0)}-${lineIdx}-${segmentIdx}-${idx}`;
            const markerRoad = (configName === '干线协调' && line.trunkName)
              ? line.trunkName
              : `${configName}路口-${lineIdx}-${segmentIdx}-${idx}`;

            const marker = this.createTrafficLightMarker([lng, lat], {
              ...config,
              id: markerId,
              road: markerRoad
            }, markerType);
            if (marker) overlays.push(marker);
          }
        } // end else

      }); // end segments.forEach

      return overlays;
    },

    /**
     * 均匀选取点的索引
     * @param {number} totalPoints - 总点数
     * @param {number} count - 要选取的点数
     * @returns {Array<number>} 索引数组
     */
    pickEvenlySpacedIndices(totalPoints, count) {
      const total = Math.max(Number(totalPoints) || 0, 0);
      const target = Math.max(Number(count) || 0, 0);
      if (total <= 0 || target <= 0) return [];
      if (target >= total) return Array.from({ length: total }, (_, i) => i);
      if (target === 1) return [0];

      return Array.from({ length: target }, (_, k) => Math.round((k * (total - 1)) / (target - 1)));
    },

    /**
     * 构建备选线路路径
     * @param {Array<number>} start - 起点坐标 [lng, lat]
     * @param {Array<number>} end - 终点坐标 [lng, lat]
     * @param {number} pointCount - 点数量
     * @returns {Array} 路径点数组
     */
    buildFallbackLinePath(start, end, pointCount) {
      const sLng = Number(start && start[0]);
      const sLat = Number(start && start[1]);
      const eLng = Number(end && end[0]);
      const eLat = Number(end && end[1]);
      const n = Math.max(Number(pointCount) || 2, 2);
      const path = [];

      if ([sLng, sLat, eLng, eLat].some(v => Number.isNaN(v))) return path;

      for (let i = 0; i < n; i += 1) {
        const t = n === 1 ? 0 : i / (n - 1);
        const lng = sLng + (eLng - sLng) * t;
        const lat = sLat + (eLat - sLat) * t;
        path.push({ lng, lat });
      }
      return path;
    },

    /**
     * 提取主要直线段
     * @param {Array} path - 路径点数组
     * @returns {Array} 直线段数组
     */
    extractMainStraightSegments(path) {
      const getCoord = (p) => {
        if (!p) return { lng: NaN, lat: NaN };
        if (Array.isArray(p)) return { lng: Number(p[0]), lat: Number(p[1]) };
        if (p.getLng) return { lng: p.getLng(), lat: p.getLat() };
        return { lng: Number(p.lng), lat: Number(p.lat) };
      };

      const points = (path || []).map(p => getCoord(p)).filter(p => !isNaN(p.lng) && !isNaN(p.lat));
      if (points.length < 2) return [];

      const thresholdDeg = 18;
      const segments = [];
      let curStart = 0;
      let curAngle = null;
      let curLen = 0;

      const pushSegment = (endIdx) => {
        if (endIdx <= curStart) return;
        segments.push({
          start: curStart,
          end: endIdx,
          len: curLen
        });
      };

      for (let i = 0; i < points.length - 1; i += 1) {
        const a = points[i];
        const b = points[i + 1];
        const len = this.calcApproxDistance(a, b);
        if (len <= 0) continue;
        const angle = this.calcBearingDeg(a, b);

        if (curAngle === null) {
          curStart = i;
          curAngle = angle;
          curLen = len;
          continue;
        }

        const diff = this.calcAngleDiffDeg(curAngle, angle);
        if (diff <= thresholdDeg) {
          curLen += len;
        } else {
          pushSegment(i);
          curStart = i;
          curAngle = angle;
          curLen = len;
        }
      }

      pushSegment(points.length - 2);

      if (segments.length === 0) return [points];

      segments.sort((s1, s2) => s2.len - s1.len);
      const maxLen = segments[0].len || 0;
      const filtered = segments.filter(s => s.len >= maxLen * 0.55).slice(0, 3);
      const finalSegments = filtered.map(s => points.slice(s.start, s.end + 2));
      return finalSegments.length > 0 ? finalSegments : [points];
    },

    /**
     * 从不同格式的点中提取经纬度数组 [lng, lat]
     * @param {Object|Array} p - 点对象或数组
     * @returns {Array<number>} 经纬度数组
     */
    _getCoords(p) {
      if (!p) return [0, 0];
      const lng = p.lng || (p.getLng ? p.getLng() : (Array.isArray(p) ? Number(p[0]) : 0));
      const lat = p.lat || (p.getLat ? p.getLat() : (Array.isArray(p) ? Number(p[1]) : 0));
      return [lng, lat];
    },

    /**
     * 计算两点之间的方位角（度）
     * @param {Object|Array} a - 起点
     * @param {Object|Array} b - 终点
     * @returns {number} 方位角
     */
    calcBearingDeg(a, b) {
      const [alng, alat] = this._getCoords(a);
      const [blng, blat] = this._getCoords(b);

      const latRad = ((alat + blat) / 2) * Math.PI / 180;
      const dx = (blng - alng) * Math.cos(latRad);
      const dy = (blat - alat);
      
      const mathAngle = Math.atan2(dy, dx) * 180 / Math.PI;
      return (90 - mathAngle + 360) % 360;
    },

    /**
     * 计算两个角度的差值
     * @param {number} a - 角度1
     * @param {number} b - 角度2
     * @returns {number} 角度差
     */
    calcAngleDiffDeg(a, b) {
      let diff = Math.abs(a - b);
      if (diff > 180) diff = 360 - diff;
      return diff;
    },

    /**
     * 计算两点之间的近似距离
     * @param {Object|Array} a - 点1
     * @param {Object|Array} b - 点2
     * @returns {number} 距离
     */
    calcApproxDistance(a, b) {
      const [alng, alat] = this._getCoords(a);
      const [blng, blat] = this._getCoords(b);

      const latRad = ((alat + blat) / 2) * Math.PI / 180;
      const dx = (blng - alng) * Math.cos(latRad);
      const dy = (blat - alat);
      return Math.sqrt(dx * dx + dy * dy);
    },

    /**
     * 根据当前缩放级别计算普通圆点的尺寸（px）
     * @returns {number} 圆点尺寸
     */
    getDotSizeByZoom() {
      if (!this.map) return 14;
      const zoom = this.map.getZoom();
      // 基准：zoom=15时是14px。每缩小一级减小3px。
      const size = 14 + (zoom - 15) * 3;
      return Math.min(Math.max(6, size), 28); // 最小值设为 6px
    },

    /**
     * 创建交通信号灯标记
     * @param {Array<number>|Object} position - 位置坐标
     * @param {Object} config - 配置对象
     * @param {string} [type='normal'] - 标记类型
     * @returns {Object|null} 标记对象
     */
    createTrafficLightMarker(position, config, type = 'normal') {
      if (!position || !config) return null;

      try {
        const lng = position.getLng ? position.getLng() : Number(position[0] !== undefined ? position[0] : position.lng);
        const lat = position.getLat ? position.getLat() : Number(position[1] !== undefined ? position[1] : position.lat);
        if (isNaN(lng) || isNaN(lat)) return null;

        let displayText = config.name ? config.name.charAt(0) : '';
        if (type === 'start') displayText = '起';
        if (type === 'end') displayText = '终';

        const isAbnormal = ["离线", "降级", "故障"].includes(config.name);
        const isRoute = ["干线协调", "勤务路线"].includes(config.name);
        const isStartEnd = type === 'start' || type === 'end';
        const isPassed = type === 'passed';

        let markerContent = '';
        
        // --- 核心优化：尺寸全部使用 var(--xxx) CSS变量接管 ---
        if (isStartEnd) {
          markerContent = `
            <div class="pure-light-node start-end-node" style="width: var(--special-size); height: calc(var(--special-size) + 6px); background: transparent; border: none; display: flex; justify-content: center; align-items: flex-end; cursor: pointer; transform-origin: bottom center;">
              <img src="${require(`@/assets/map/${type}.png`)}" style="width: 100%; height: auto; object-fit: contain; pointer-events: none;" />
            </div>
          `;
        } else if (isPassed) {
          markerContent = `
            <div class="pure-light-node" style="width: 14px; height: 14px; background: #5A5A5A; border: 1.5px solid rgba(255,255,255,0.25); box-sizing: content-box; display: flex; justify-content: center; align-items: center; color: #888; border-radius: 50%; cursor: pointer; padding: 2px; opacity: 0.55;">
              <span style="transform: scale(0.8); font-weight: bold; font-size: 12px;">勤</span>
            </div>
          `;
        } else if (isAbnormal) {
          const iconName = config.name === '离线' ? 'lixian' : config.name === '降级' ? 'jiangji' : 'guzhang';
          markerContent = `
            <div class="pure-light-node breathe" style="width: var(--special-size); height: var(--special-size); background: transparent; border: none; display: flex; justify-content: center; align-items: center; cursor: pointer; padding: 0;">
              <img src="${require(`@/assets/images/icon_${iconName}.png`)}" style="width: 100%; height: 100%; object-fit: contain;" />
            </div>
          `;
        } else {
          markerContent = `
            <div class="pure-light-node ${isRoute ? 'route-node' : ''}" style="width: var(--dot-size); height: var(--dot-size); background: ${config.color || '#999'}; box-shadow: ${isRoute ? 'none' : `0 0 8px ${config.color}`}; border: ${isRoute ? 'none' : '1.5px solid rgba(255,255,255,0.7)'}; box-sizing: border-box; display: flex; justify-content: center; align-items: center; color: #fff; border-radius: 50%; cursor: pointer; padding: var(--dot-padding);">
              <span style="display: var(--text-display); transform: scale(0.8); font-weight: bold; font-size: var(--text-size);">${displayText}</span>
            </div>
          `;
        }

        const marker = new this.AMap.Marker({
          position: [lng, lat],
          zIndex: isStartEnd ? 120 : (isAbnormal ? 110 : 100),
          content: markerContent,
          // 核心优化：高德 2.0 原生支持 anchor 属性。代替手动计算 Offset！
          anchor: isStartEnd ? 'bottom-center' : 'center', 
          extData: {
            ...config,
            position: [lng, lat],
            statusColor: config.color || '#999',
            statusLabel: config.name,
            road: config.road || '规划路口',
            timestamp: Date.now(),
            time: this.formatEventTime(Date.now())
          }
        });

        marker.on('click', (e) => {
          if (this.isComponentDestroyed) return;
          const extData = e.target.getExtData();
          if (this.$route && this.$route.path === '/home') {
            this.cancelCloseInfoWindow();
            this.openLightInfo(extData, e.lnglat);
          }
          const pixel = this.map.lngLatToContainer(e.lnglat);
          this.$emit('map-crossing-click', extData, e.lnglat, pixel);
        });

        marker.on('mouseover', (e) => {
          if (this.isComponentDestroyed) return;
          if (this.$route && this.$route.path === '/home') {
            this.cancelCloseInfoWindow();
            this.openLightInfo(e.target.getExtData(), e.lnglat);
          }
          const pixel = this.map.lngLatToContainer(e.lnglat);
          this.$emit('map-crossing-mouseover', e.target.getExtData(), e.lnglat, pixel);
        });

        marker.on('mouseout', (e) => {
          if (this.isComponentDestroyed) return;
          if (this.$route && this.$route.path === '/home') {
            this.scheduleCloseInfoWindow();
          }
          this.$emit('map-crossing-mouseout', e.target.getExtData());
        });

        return marker;
      } catch (e) {
        console.warn('创建标记时出错:', e);
        return null;
      }
    },

    /**
     * 打开信号灯信息窗口
     * @param {Object} data - 信号灯数据
     * @param {Array<number>} position - 位置坐标
     */
    openLightInfo(data, position) {
      if (!this.isMapReady()) return;

      const infoWindowId = `info-window-${Date.now()}`;
      this.activeInfoWindowId = infoWindowId;
      const isAbnormal = ["离线", "降级", "故障"].includes(data.name);
      const deviceStatusText = isAbnormal ? data.name : '正常';
      const alarmInfoText = isAbnormal ? this.getAlarmInfoText(data.name) : '';
      const eventTimeText = this.formatEventTime(data.timestamp || data.time);
      let statusDotContent = '';
      
      if (isAbnormal) {
        const iconName = data.name === '离线' ? 'lixian' : data.name === '降级' ? 'jiangji' : 'guzhang';
        statusDotContent = `<img src="${require(`@/assets/images/icon_${iconName}.png`)}" style="width: 100%; height: 100%; object-fit: contain;" />`;
      } else {
        statusDotContent = `<span>${data.name.charAt(0)}</span>`;
      }
      
      const content = `
        <div class="custom-info-card" id="${infoWindowId}">
          <div class="close-btn" data-id="${infoWindowId}">✕</div>
          <div class="card-header">
            <div class="status-dot ${isAbnormal ? 'breathe' : ''}" style="background: ${isAbnormal ? 'transparent' : data.statusColor}; border: ${isAbnormal ? 'none' : ''}">
              ${statusDotContent}
            </div>
            <span class="status-text">${data.statusLabel}</span>
          </div>
          <div class="card-body">
            ${isAbnormal
              ? `
                <div class="info-line"><span class="label">路口名称：</span><span class="value">${data.road}</span></div>
                <div class="info-line"><span class="label">设备状态：</span><span class="value digital">${deviceStatusText}</span></div>
                <div class="info-line"><span class="label">报警信息：</span><span class="value">${alarmInfoText}</span></div>
                <div class="info-line"><span class="label">发生时间：</span><span class="value digital">${eventTimeText}</span></div>
              `
              : `
                <div class="info-line"><span class="label">路口名称：</span><span class="value">${data.road}</span></div>
                <div class="info-line"><span class="label">设备状态：</span><span class="value digital">${deviceStatusText}</span></div>
              `
            }
          </div>
        </div>
      `;

      if (!this.infoWindow) {
        this.infoWindow = new this.AMap.InfoWindow({
          isCustom: true,
          offset: new this.AMap.Pixel(0, -20),
          autoMove: false
        });
      }

      this.infoWindow.setContent(content);
      this.infoWindow.open(this.map, position);

      setTimeout(() => {
        if (this.activeInfoWindowId !== infoWindowId) return;
        const closeBtn = document.querySelector(`#${infoWindowId} .close-btn`);
        if (closeBtn) {
          closeBtn.addEventListener('click', () => {
            if (this.infoWindow) this.infoWindow.close();
          });
        }

        const root = document.querySelector(`#${infoWindowId}`);
        if (root) {
          root.addEventListener('mouseenter', () => {
            if (this.activeInfoWindowId !== infoWindowId) return;
            this.isInfoWindowHovered = true;
            this.cancelCloseInfoWindow();
          });
          root.addEventListener('mouseleave', () => {
            if (this.activeInfoWindowId !== infoWindowId) return;
            this.isInfoWindowHovered = false;
            this.scheduleCloseInfoWindow();
          });
        }
      }, 100);
    },

    /**
     * 取消关闭信息窗口
     */
    cancelCloseInfoWindow() {
      if (this.infoCloseTimer) {
        clearTimeout(this.infoCloseTimer);
        this.infoCloseTimer = null;
      }
    },

    /**
     * 安排关闭信息窗口
     */
    scheduleCloseInfoWindow() {
      this.cancelCloseInfoWindow();
      this.infoCloseTimer = setTimeout(() => {
        if (this.isComponentDestroyed) return;
        if (this.isInfoWindowHovered) return;
        if (this.infoWindow) this.infoWindow.close();
        this.activeInfoWindowId = null;
      }, 160);
    },

    /**
     * 获取报警信息文本
     * @param {string} statusName - 状态名称
     * @returns {string} 报警信息
     */
    getAlarmInfoText(statusName) {
      if (statusName === '离线') return '通讯中断设备离线';
      if (statusName === '降级') return '降级定周期控制';
      if (statusName === '故障') return '东向左转信号灯红绿同亮';
      return '设备异常';
    },

    /**
     * 格式化事件时间
     * @param {Date|number|string} input - 时间输入
     * @returns {string} 格式化后的时间
     */
    formatEventTime(input) {
      let d = null;
      if (input instanceof Date) d = input;
      else if (typeof input === 'number') d = new Date(input);
      else if (typeof input === 'string') {
        const t = Date.parse(input);
        if (!Number.isNaN(t)) d = new Date(t);
      }
      if (!d || Number.isNaN(d.getTime())) d = new Date();
      const y = d.getFullYear();
      const m = d.getMonth() + 1;
      const day = d.getDate();
      const hh = String(d.getHours()).padStart(2, '0');
      const mm = String(d.getMinutes()).padStart(2, '0');
      return `${y}.${m}.${day} ${hh}:${mm}`;
    },

    /**
     * 切换所有图例的可见性
     */
    toggleAll() {
      const targetState = !this.isAllSelected;
      if (!this.isMapReady()) return;

      if (targetState) {
        this.activeLegends = this.statusConfig.map(item => item.name);
        Object.values(this.routeGroups).forEach(overlays => {
          if (overlays && overlays.length > 0) this.map.add(overlays);
        });
      } else {
        this.activeLegends = [];
        Object.values(this.routeGroups).forEach(overlays => {
          if (overlays && overlays.length > 0) this.map.remove(overlays);
        });
        if (this.infoWindow) this.infoWindow.close();
      }
    },

    /**
     * 切换指定路线的可见性
     * @param {string} name - 路线名称
     */
    toggleRouteVisible(name) {
      if (!this.isMapReady()) return;

      const overlays = this.routeGroups[name] || [];
      const index = this.activeLegends.indexOf(name);
      if (index > -1) {
        this.activeLegends.splice(index, 1);
        this.map.remove(overlays);
        if (this.infoWindow) this.infoWindow.close();
      } else {
        this.activeLegends.push(name);
        this.map.add(overlays);
      }
    },

    /**
     * 根据位置聚焦地图
     * @param {string|Array<number>} targetPos - 目标位置
     */
    focusByLocation(targetPos) {
      if (!this.isMapReady() || !targetPos) return;

      let pos = targetPos;
      if (typeof targetPos === 'string') {
        pos = targetPos.split(',').map(Number);
      }
      if (!Array.isArray(pos) || pos.length < 2) return;

      const [targetLng, targetLat] = pos;
      let bestMarker = null;
      let minDistanceSq = Infinity;

      Object.values(this.routeGroups).forEach(group => {
        if (!Array.isArray(group)) return;
        group.forEach(item => {
          if (!(item instanceof this.AMap.Marker)) return;
          const markerExt = item.getExtData();
          const markerPos = markerExt.position;
          if (!markerPos) return;

          const dx = markerPos[0] - targetLng;
          const dy = markerPos[1] - targetLat;
          const distSq = dx * dx + dy * dy;

          if (distSq < 0.000001) {
            const isAbnormal = ["离线", "降级", "故障"].includes(markerExt.name);
            const currentIsAbnormal = bestMarker ? ["离线", "降级", "故障"].includes(bestMarker.getExtData().name) : false;

            if (distSq < minDistanceSq || (isAbnormal && !currentIsAbnormal)) {
              minDistanceSq = distSq;
              bestMarker = item;
            }
          }
        });
      });

      if (bestMarker) {
        const finalPos = bestMarker.getPosition();
        this.map.setZoomAndCenter(17, finalPos, false, 500);
        setTimeout(() => {
          if (!this.isComponentDestroyed) this.openLightInfo(bestMarker.getExtData(), finalPos);
        }, 600);
      } else {
        this.map.setZoomAndCenter(17, [targetLng, targetLat], false, 500);
      }
    },

    /**
     * 通过路口编号定位到对应的标记
     * @param {string} id - 路口编号
     * @returns {Array<number>|null} 位置坐标
     */
    focusById(id) {
      if (!this.isMapReady() || !id) return null;

      let bestMarker = null;
      Object.values(this.routeGroups).forEach(group => {
        if (!Array.isArray(group) || bestMarker) return;
        group.forEach(item => {
          if (bestMarker) return;
          if (!(item instanceof this.AMap.Marker)) return;
          const ext = item.getExtData();
          if (ext.id === id || ext['路口编号'] === id) {
            bestMarker = item;
          }
        });
      });

      if (bestMarker) {
        const finalPos = bestMarker.getPosition();
        this.map.setZoomAndCenter(17, finalPos, false, 500);
        return finalPos;
      }
      return null;
    },

    /**
     * 切换图例的可见性
     */
    toggleLegend() {
      this.legendVisible = !this.legendVisible;
    },

    /**
     * 按4:4:4比例提取故障、离线、降级路口信息并存储到localStorage
     */
    storeStatusCoordsToLocalStorage() {
      const alarmTypes = [
        { status: "故障", titles: ["通讯中断", "灯组故障", "相位冲突", "绿冲突"], level: "high", type: "error" },
        { status: "离线", titles: ["信号机离线", "信号机离线", "通讯中断", "检测器异常"], level: "mid", type: "warning" },
        { status: "降级", titles: ["降级黄闪", "降级黄闪", "方案切换异常", "检测器异常"], level: "mid", type: "warning" },
      ];

      const alarmList = [];
      let id = 1;

      alarmTypes.forEach(({ status, titles, level, type }) => {
        (this.statusIntersections[status] || []).slice(0, 4).forEach((item, i) => {
          const lng = item["位置-经度"];
          const lat = item["位置-纬度"];
          const name = item["路口名称"] || "";
          if (!lng || !lat) return;
          alarmList.push({
            id: `A${String(id).padStart(3, "0")}`,
            title: titles[i] || titles[0],
            loc: name,
            level,
            type,
            description: `${name}-${titles[i] || titles[0]}`,
            position: [lng, lat],
          });
          localStorage.setItem(`pos${id}`, `${lng},${lat}`);
          id++;
        });
      });

      localStorage.setItem("alarmListFromMap", JSON.stringify(alarmList));
      console.log('状态坐标及告警数据已存储到localStorage');
    },

    /**
     * 将经纬度转换为像素坐标
     * @param {number} lng - 经度
     * @param {number} lat - 纬度
     * @returns {Object|null} 像素坐标
     */
    lngLatToPixel(lng, lat) {
        if (!this.map) return null;
        return this.map.lngLatToContainer([lng, lat]);
    }
  }
};
</script>

<style scoped>
.map-wrapper {
  width: 100%;
  height: 100vh;
  position: relative;
  background: #010813;
}

.map-container {
  width: 100%;
  height: 100%;
}

::v-deep .amap-logo,
::v-deep .amap-copyright,
::v-deep .amap-copyright-logo {
  display: none !important;
}

::v-deep .pure-light-node.breathe {
  animation: light-breathe 2s infinite ease-in-out;
}

::v-deep .pure-light-node span {
  display: flex;
  transform: scale(0.75);
  align-items: center;
}

::v-deep .pure-light-node:hover {
  transform: scale(1.4);
  filter: brightness(1.2);
}

@keyframes light-breathe {
  0% {
    transform: scale(0.9);
    opacity: 0.8;
  }

  50% {
    transform: scale(1.1);
    opacity: 1;
  }

  100% {
    transform: scale(0.9);
    opacity: 0.8;
  }
}

::v-deep .close-btn {
  position: absolute;
  top: 10px;
  right: 12px;
  color: #8da6c7;
  cursor: pointer;
  font-size: 16px;
  transition: color 0.3s;
  line-height: 1;
  z-index: 10;
}

::v-deep .close-btn:hover {
  color: #ffffff;
}

::v-deep .custom-info-card {
  position: relative;
  background: rgba(10, 15, 24, 0.95);
  border-radius: 10px;
  padding: 12px 16px;
  min-width: 200px;
  border: 1px solid rgba(255, 255, 255, 0.1);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5);
  color: #fff;
}

::v-deep .card-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

::v-deep .status-dot {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 8px;
  font-size: 14px;
  padding: 0;
  box-sizing: border-box;
}

::v-deep .status-dot.breathe {
  animation: light-breathe 2s infinite ease-in-out;
}

::v-deep .status-dot span {
  transform: scale(0.75);
}

::v-deep .status-dot img {
  width: 100%;
  height: 100%;
  object-fit: contain;
  display: block;
}

::v-deep .status-text {
  font-size: 15px;
  font-weight: bold;
}

::v-deep .info-line {
  display: flex;
  margin-bottom: 6px;
  font-size: 13px;
  align-items: center;
}

::v-deep .label {
  color: #8da6c7;
  white-space: nowrap;
}

::v-deep .value {
  color: #ffffff;
}

::v-deep .digital {
  font-family: 'Consolas', monospace;
}

.map-legend {
  position: absolute;
  bottom: 30px;
  right: 40px;
  background: rgba(5, 22, 45, 0.9);
  border: 1px solid #1e4d8e;
  padding: 15px;
  border-radius: 6px;
  z-index: 100;
  transition: all 0.3s ease-in-out;
  opacity: 1;
  max-width: 200px;
  overflow: hidden;
}

.map-legend.legend-hidden {
  opacity: 0;
  transform: translateX(calc(100% + 20px));
  pointer-events: none;
}

.legend-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  border-bottom: 1px solid #1e4d8e;
  padding-bottom: 8px;
}

.legend-close-btn {
  color: #8da6c7;
  cursor: pointer;
  font-size: 16px;
  transition: color 0.3s;
  line-height: 1;
}

.legend-close-btn:hover {
  color: #ffffff;
}

.legend-show-btn {
  position: absolute;
  bottom: 30px;
  right: 20px;
  background: rgba(5, 22, 45, 0.9);
  border: 1px solid #1e4d8e;
  width: 40px;
  height: 40px;
  border-radius: 6px 0 0 6px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  z-index: 99;
  transition: all 0.3s ease-in-out;
}

.legend-show-btn:hover {
  background: rgba(10, 30, 60, 0.9);
  border-color: #3a75c4;
}

.legend-show-icon {
  color: #8da6c7;
  font-size: 18px;
  transition: color 0.3s;
}

.legend-show-btn:hover .legend-show-icon {
  color: #ffffff;
}

.legend-title {
  color: #fff;
  font-size: 14px;
}

.legend-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  cursor: pointer;
  transition: 0.3s;
}

.legend-item.is-inactive {
  opacity: 0.2;
  filter: grayscale(1);
}

.legend-dot {
  margin-right: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.legend-dot:not(.is-status-wrapper) {
  width: 20px;
  height: 20px;
  border-radius: 50%;
}

.legend-dot span {
  display: inline-block;
  width: 20px;
  height: 20px;
  font-size: 12px;
  color: #FFF;
  text-align: center;
  transform: scale(0.75);
  line-height: 20px;
}

.legend-dot.special-route {
  position: relative;
  overflow: visible !important;
  z-index: 1;
  border: none !important;
  border-radius: 50%;
}

.legend-dot.special-route span {
  position: relative;
  z-index: 3;
  font-weight: bold;
}

.legend-dot.special-route::after {
  content: "";
  position: absolute;
  top: 50%;
  left: 50%;
  width: 150%;
  height: 3px;
  background-color: inherit;
  opacity: 0.8;
  transform: translate(-50%, -50%) rotate(-45deg);
  pointer-events: none;
  z-index: 0;
}

.legend-dot.special-route::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border-radius: 50%;
  z-index: 2;
  background-color: inherit;
  opacity: 1;
}

.legend-label {
  flex: 1;
  color: #d0d9e2;
  font-size: 13px;
}

.legend-status {
  font-size: 11px;
  color: #5b7da8;
}

.all-select {
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
  padding-bottom: 12px;
  margin-bottom: 12px !important;
}

.all-select .legend-dot {
  border-radius: 2px;
  transition: all 0.3s;
  width: 10px;
  height: 10px;
}

.legend-dot.is-status-wrapper {
  width: 28px;
  height: 28px;
  background-color: transparent !important;
  box-shadow: none !important;
  border: none !important;
  margin-right: 0;
  transform: translateX(-15%);
}

.status-icon {
  width: 100%;
  height: 100%;
  object-fit: contain;
  display: block;
}

::v-deep .pure-light-node {
  width: 16px;
  height: 16px;
  border-radius: 50%;
  border: 2px solid rgba(255, 255, 255, 0.8);
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #fff;
  pointer-events: auto;
}

::v-deep .pure-light-node.route-node {
  position: relative;
  overflow: visible;
}

::v-deep .pure-light-node.route-node::after {
  content: "";
  position: absolute;
  top: 50%;
  left: 50%;
  width: 150%;
  height: 3px;
  background-color: inherit;
  opacity: 0.8;
  transform: translate(-50%, -50%) rotate(-45deg);
  pointer-events: none;
}

::v-deep .pure-light-node.route-node span {
  position: relative;
  z-index: 1;
}

::v-deep .pure-light-node:not(.abnormal-node) {
  border: 1px solid rgba(255, 255, 255, 0.4);
}

::v-deep .duty-progress-node {
  animation: duty-pulse 1.6s infinite ease-in-out;
}

@keyframes duty-pulse {
  0%   { box-shadow: 0 0 0 3px rgba(188, 48, 29, 0.5); }
  50%  { box-shadow: 0 0 0 9px rgba(188, 48, 29, 0.08); }
  100% { box-shadow: 0 0 0 3px rgba(188, 48, 29, 0.5); }
}
</style>
