<template>
  <div class="map-wrapper">
    <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: {},
      polylines: [],
      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: {},

    };
  },
  mounted() {
    this.isComponentDestroyed = false; // 重置标识
    this.loadMapData().then(() => {
      this.classifyIntersectionsByStatus();
      this.updateMapByMode();
      this.initAMap();
    });

    if (this.$route.path === '/home') {
      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';
    },
    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 [];
    }
  },
  methods: {
    // 动态加载地图数据
    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 = [];
      }
    },

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

    // 将真实路口数据按状态类型分类
    classifyIntersectionsByStatus() {
      const remainingData = this.intersectionData;
      const normalStatusCount = 6;
      const abnormalStatusCount = 3;
      const chunkSize = Math.floor(remainingData.length / (normalStatusCount + abnormalStatusCount));
      const maxAbnormalCount = 4;

      this.statusIntersections = {
        "中心计划": remainingData.slice(0, 20),
        "干线协调": [], // 清空，改为动态生成
        "勤务路线": [], // 清空，改为动态生成
        "定周期控制": remainingData.slice(chunkSize, chunkSize * 2),
        "感应控制": remainingData.slice(chunkSize * 2, chunkSize * 3),
        "自适应控制": remainingData.slice(chunkSize * 3, chunkSize * 4),
        "手动控制": remainingData.slice(chunkSize * 4, chunkSize * 5),
        "特殊控制": remainingData.slice(chunkSize * 5, chunkSize * 6),
        "离线": remainingData.slice(chunkSize * 6, Math.min(chunkSize * 7, chunkSize * 6 + maxAbnormalCount)),
        "降级": remainingData.slice(chunkSize * 7, Math.min(chunkSize * 8, chunkSize * 7 + maxAbnormalCount)),
        "故障": remainingData.slice(chunkSize * 8, Math.min(chunkSize * 9, chunkSize * 8 + maxAbnormalCount))
      };
    },

    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);
          }
        }
      });
    },

    async initAMap() {
      if (this.isComponentDestroyed) return;

      // 确保在加载前注入
      window._AMapSecurityConfig = { securityJsCode: this.securityJsCode };

      try {
        const AMap = await AMapLoader.load({
          key: this.amapKey,
          version: "2.0",
          // 核心：确保 Driving 插件在此加载
          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();
            // 临时方案，实际项目中删除 按4:3:3比例提取故障、离线、降级坐标点并存储到localStorage
            this.storeStatusCoordsToLocalStorage();
          }
        });
      } catch (err) {
        console.error('地图加载失败:', err);
      }
    },

    // 绘制静态路线和标记
    // 对于普通状态，从 mock 数据加载路口标记
    // 对于路线类（干线协调和勤务路线），使用高德地图路线规划绘制路线和密集点位
    async drawStaticRoutes() {
      if (!this.isMapReady()) return;

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

      this.clearAllRouteOverlays();

      const realRouteConfigs = {
        "干线协调": [
          { start: [116.6421, 39.9272], end: [116.6825, 39.9272], color: "#13C373" },
          { start: [116.6426, 39.9221], end: [116.6830, 39.9221], color: "#13C373" },
          { start: [116.6432, 39.9171], end: [116.6833, 39.9171], color: "#13C373" },
          { start: [116.6438, 39.9123], end: [116.6841, 39.9123], color: "#13C373" },
          { start: [116.6445, 39.9075], end: [116.6846, 39.9075], color: "#13C373" }
        ],
        "勤务路线": [
          { start: [116.6900, 39.9225], end: [116.6900, 39.8971], color: "#BC301D" },
          { start: [116.6965, 39.9225], end: [116.6965, 39.8971], color: "#BC301D" },
          { start: [116.7021, 39.9225], end: [116.7021, 39.8971], color: "#BC301D" },
          { start: [116.7120, 39.9225], end: [116.7120, 39.8971], color: "#BC301D" },
          { start: [116.7234, 39.9225], end: [116.7234, 39.8971], color: "#BC301D" },
          { start: [116.7290, 39.9225], end: [116.7290, 39.8971], color: "#BC301D" },
          { start: [116.7350, 39.9170], end: [116.7350, 39.9000], color: "#BC301D" }
        ]
      };

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

        // 1. 处理普通非路线状态（从 mock 数据加载）
        if (!realRouteConfigs[config.name]) {
          const intersections = this.statusIntersections[config.name] || [];
          const markers = intersections.map(item =>
            this.createTrafficLightMarker([item["位置-经度"], item["位置-纬度"]], config)
          ).filter(Boolean);
          this.routeGroups[config.name] = markers;
          if (this.activeLegends.includes(config.name)) this.map.add(markers);
          continue;
        }

        // 2. 处理路线类（干线/特勤）
        this.routeGroups[config.name] = [];
        const lines = realRouteConfigs[config.name] || [];

        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 (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);
        }
      }
    },

    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 = {};
    },

    sleep(ms) {
      return new Promise(resolve => setTimeout(resolve, ms));
    },

    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');
    },

    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'));
        });
      });
    },

    withTimeout(promise, timeoutMs) {
      return Promise.race([
        promise,
        new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), timeoutMs))
      ]);
    },

    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 segments = this.extractMainStraightSegments(basePath);
      const overlays = [];

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

        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 indices = this.pickEvenlySpacedIndices(totalPoints, 8);

        // 为第一个和最后一个圆点设置特殊类型
        for (let i = 0; i < indices.length; i++) {
          const idx = indices[i];
          const p = segmentPath[idx];
          const lng = p && typeof p.lng === 'number' ? p.lng : (Array.isArray(p) ? Number(p[0]) : NaN);
          const lat = p && typeof p.lat === 'number' ? p.lat : (Array.isArray(p) ? Number(p[1]) : NaN);
          if (Number.isNaN(lng) || Number.isNaN(lat)) continue;

          // 确定圆点类型：第一个为start，最后一个为end，其余为normal
          let markerType = 'normal';
          if (i === 0) {
            markerType = 'start';
          } else if (i === indices.length - 1) {
            markerType = 'end';
          }

          const marker = this.createTrafficLightMarker([lng, lat], {
            ...config,
            id: `MOCK-${configName.charAt(0)}-${lineIdx}-${segmentIdx}-${idx}`,
            road: `${configName}路口-${lineIdx}-${segmentIdx}-${idx}`
          }, markerType);
          if (marker) overlays.push(marker);
        }
      });

      return overlays;
    },

    pickEvenlySpacedIndices(totalPoints, count) {
      const total = Math.max(Number(totalPoints) || 0, 0);
      const target = Math.max(Number(count) || 0, 0);
      if (total <= 0) return [];
      if (target <= 0) return [];
      if (target >= total) return Array.from({ length: total }, (_, i) => i);
      if (target === 1) return [0];

      const set = new Set();
      const last = total - 1;
      for (let k = 0; k < target; k += 1) {
        const idx = Math.round((k * last) / (target - 1));
        set.add(idx);
      }
      return Array.from(set).sort((a, b) => a - b);
    },

    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;
    },

    extractMainStraightSegments(path) {
      const points = (path || []).filter(p => p && typeof p.lng === 'number' && typeof p.lat === 'number');
      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];
    },

    calcBearingDeg(a, b) {
      const latRad = ((a.lat + b.lat) / 2) * Math.PI / 180;
      const dx = (b.lng - a.lng) * Math.cos(latRad);
      const dy = (b.lat - a.lat);
      let deg = Math.atan2(dy, dx) * 180 / Math.PI;
      if (deg < 0) deg += 360;
      return deg;
    },

    calcAngleDiffDeg(a, b) {
      let diff = Math.abs(a - b);
      if (diff > 180) diff = 360 - diff;
      return diff;
    },

    calcApproxDistance(a, b) {
      const latRad = ((a.lat + b.lat) / 2) * Math.PI / 180;
      const dx = (b.lng - a.lng) * Math.cos(latRad);
      const dy = (b.lat - a.lat);
      return Math.sqrt(dx * dx + dy * dy);
    },

    createTrafficLightMarker(position, config, type = 'normal') {
      if (!position || !config) return null;

      try {
        const lng = Number(position[0] || position.lng);
        const lat = Number(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 size = (type === 'start' || type === 'end') ? '22px' : (isAbnormal ? '30px' : '14px');
        const sizeNumber = parseInt(size, 10);
        const paddingNumber = (isAbnormal || type === 'start' || type === 'end') ? 0 : 2;
        const outerSizeNumber = sizeNumber + paddingNumber * 2;

        // 边框样式：起终点用实白边框
        const borderStyle = (type === 'start' || type === 'end')
          ? '2px solid #fff'
          : '1.5px solid rgba(255,255,255,0.7)';

        // 生成异常状态的图标路径
        let markerContent = '';
        if (isAbnormal) {
          const iconName = config.name === '离线' ? 'lixian' : config.name === '降级' ? 'jiangji' : 'guzhang';
          markerContent = `
            <div class="pure-light-node ${isAbnormal ? 'breathe' : ''}"
                style="
                  width: ${size};
                  height: ${size};
                  background: transparent;
                  box-shadow: none;
                  border: none;
                  box-sizing: content-box;
                  display: flex;
                  justify-content: center;
                  align-items: center;
                  cursor: pointer;
                  padding: ${paddingNumber}px;
                ">
              <img src="${require(`@/assets/images/icon_${iconName}.png`)}" style="width: 100%; height: 100%; object-fit: contain;" />
            </div>
          `;
        } else {
          markerContent = `
            <div class="pure-light-node ${isAbnormal ? 'breathe' : ''} ${isRoute ? 'route-node' : ''}"
                style="
                  width: ${size};
                  height: ${size};
                  background: ${config.color || '#999'};
                  box-shadow: ${isRoute ? 'none' : `0 0 8px ${config.color}`};
                  border: ${isRoute ? 'none' : borderStyle};
                  box-sizing: content-box;
                  display: flex;
                  justify-content: center;
                  align-items: center;
                  color: #fff;
                  border-radius: 50%;
                  cursor: pointer;
                  padding: ${paddingNumber}px;
                ">
              <span style="transform: scale(0.8); font-weight: bold; font-size: 12px;">${displayText}</span>
            </div>
          `;
        }

        const marker = new this.AMap.Marker({
          position: [lng, lat],
          // 这里的 type 已经从参数拿到了，不会报错了
          zIndex: (type === 'start' || type === 'end') ? 120 : (isAbnormal ? 110 : 100),
          content: markerContent,
          offset: new this.AMap.Pixel(-Math.round(outerSizeNumber / 2), -Math.round(outerSizeNumber / 2)),
          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.isHomePage) {
            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.isHomePage) return;
          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.isHomePage) return;
          this.scheduleCloseInfoWindow();

          // 传递路口鼠标滑出事件
          this.$emit('map-crossing-mouseout', e.target.getExtData());
        });

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

    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)
        });
      }

      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);
    },

    getAlarmInfoText(statusName) {
      if (statusName === '离线') return '通讯中断设备离线';
      if (statusName === '降级') return '降级定周期控制';
      if (statusName === '故障') return '东向左转信号灯红绿同亮';
      return '设备异常';
    },

    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();
      }
    },

    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);
      }
    },

    focusByLocation(targetPos) {
      if (!this.isMapReady() || !targetPos || targetPos.length !== 2) return;

      let foundMarker = null;
      Object.values(this.routeGroups).forEach(group => {
        const marker = group.find(item => {
          if (!(item instanceof this.AMap.Marker)) return false;
          const pos = item.getExtData().position;
          return Math.abs(pos[0] - targetPos[0]) < 0.0001 && Math.abs(pos[1] - targetPos[1]) < 0.0001;
        });
        if (marker) foundMarker = marker;
      });

      if (foundMarker) {
        const finalPos = foundMarker.getPosition();
        this.map.setZoomAndCenter(17, finalPos, false, 500);
        setTimeout(() => {
          if (!this.isComponentDestroyed) this.openLightInfo(foundMarker.getExtData(), finalPos);
        }, 600);
      }
    },

    toggleLegend() {
      this.legendVisible = !this.legendVisible;
    },

    // 按4:3:3比例提取故障、离线、降级坐标点并存储到localStorage
    storeStatusCoordsToLocalStorage() {
      // 故障、离线、降级坐标点（按4:3:3比例）
      const faultCoords = [
        [116.723317, 39.907606],
        [116.703624, 39.89801],
        [116.661252, 39.924948],
        [116.708958, 39.899609]
      ];
      
      const offlineCoords = [
        [116.677855, 39.895636],
        [116.656673, 39.856063],
        [116.656485, 39.90118]
      ];
      
      const degradedCoords = [
        [116.713356, 39.952856],
        [116.665391, 39.934546],
        [116.697784, 39.891312]
      ];

      // 组合成10个元素的数组
      const statusCoords = [...faultCoords, ...offlineCoords, ...degradedCoords];

      // 存储到localStorage
      statusCoords.forEach((coords, index) => {
        localStorage.setItem(`pos${index + 1}`, coords.join(','));
      });

      console.log('状态坐标已存储到localStorage');
    },
    // 公开方法：将经纬度转换为像素坐标
    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;
}

/* 异常状态增加稍微剧烈一点的呼吸感，但缩小范围 */
@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 .pure-light-node:not(.abnormal-node) {
  border: 1px solid rgba(255, 255, 255, 0.4);
}
</style>
