<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 legendConfig" class="legend-item" @click="toggleRouteVisible(item.name)" :key="item.name"
          :class="{ 'is-inactive': !activeLegends.includes(item.name) }"
          v-if="!mode || (mode === '路口' && !['干线协调', '勤务路线'].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">
      <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: ["中心计划", "干线协调", "勤务路线", "定周期控制", "感应控制", "自适应控制", "手动控制", "特殊控制", "离线", "降级", "故障"],
      // 核心修正：增加生命周期标识，防止组件销毁后异步回调继续执行
      _isDestroyed: false,
      legendConfig: [
        { name: "中心计划", start: [116.6350, 39.9105], end: [116.6910, 39.9115], color: "#004CDE" },
        { name: "干线协调", start: [116.6355, 39.9025], end: [116.6915, 39.9035], color: "#13C373" },
        { name: "勤务路线", start: [116.6360, 39.8945], end: [116.6920, 39.8955], color: "#BC301D" },
        { name: "定周期控制", start: [116.6521, 39.9200], end: [116.6531, 39.8800], color: "#3296FA" },
        { name: "感应控制", start: [116.6611, 39.9205], end: [116.6615, 39.8805], color: "#FF864C" },
        { name: "自适应控制", start: [116.6711, 39.9210], end: [116.6720, 39.8810], color: "#9F6EFE" },
        { name: "手动控制", start: [116.6300, 39.9150], end: [116.6310, 39.8850], color: "#EB9F36" },
        { name: "特殊控制", start: [116.6820, 39.9215], end: [116.6825, 39.8815], color: "#A26218" },
        { name: "离线", start: [116.6415, 39.9235], end: [116.6850, 39.9240], color: "#7A7A7A" },
        { name: "降级", start: [116.6365, 39.8850], end: [116.6800, 39.8860], color: "#D9C13B" },
        { name: "故障", start: [116.6950, 39.9150], end: [116.6955, 39.885], color: "#FF3938" }
      ]
    };
  },
  mounted() {
    this._isDestroyed = false; // 重置标识
    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._isDestroyed = true;

    // 2. 清理全局回调
    window.closeMapInfoWindow = null;

    // 3. 关闭弹窗
    if (this.infoWindow) {
      this.infoWindow.close();
      this.infoWindow = null;
    }

    // 4. 清理覆盖物引用
    Object.values(this.routeGroups).forEach(overlays => {
      if (Array.isArray(overlays)) {
        overlays.forEach(o => o.setMap && o.setMap(null));
      }
    });
    this.routeGroups = {};

    // 5. 销毁地图实例并清空引用
    if (this.map) {
      this.map.destroy();
      this.map = null;
    }
  },
  computed: {
    isAllSelected() {
      return this.activeLegends.length === this.legendConfig.length;
    }
  },
  methods: {
    // 检查地图环境是否安全可用
    isMapReady() {
      return !this._isDestroyed && this.map && typeof this.map.add === 'function';
    },

    updateMapByMode() {
      switch (this.mode) {
        case '路口':
          this.activeLegends = ["中心计划", "定周期控制", "感应控制", "自适应控制", "手动控制", "特殊控制", "离线", "降级", "故障"];
          break;
        case '干线':
          this.activeLegends = ["干线协调"];
          break;
        case '特勤':
          this.activeLegends = ["勤务路线"];
          break;
        default:
          this.activeLegends = this.legendConfig.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() {
      window._AMapSecurityConfig = { securityJsCode: this.securityJsCode };
      try {
        const AMap = await AMapLoader.load({
          key: this.amapKey,
          version: "2.0",
          plugins: ['AMap.Driving']
        });

        // 异步回来后，首先检查组件是否还在
        if (this._isDestroyed) return;

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

        this.map.on('complete', () => {
          if (!this._isDestroyed) this.drawStaticRoutes();
        });
      } catch (err) {
        console.error('地图加载失败:', err);
      }
    },



    // ... 其他代码保持不变
    isMapReady() {
      return !this._isDestroyed && this.map && typeof this.map.add === 'function';
    },

    drawStaticRoutes() {
      if (!this.isMapReady()) return;

      this.legendConfig.forEach((config, index) => {
        // 使用箭头函数保持 this 指向 Vue 实例
        setTimeout(() => {
          if (!this.isMapReady()) return;

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

          // 这里必须用箭头函数 (status, result) => { ... }
          driving.search(config.start, config.end, (status, result) => {
            // 这里的 this 才能访问到 isMapReady
            if (!this.isMapReady()) return;

            let path = [];
            if (status === 'complete' && result.routes[0]) {
              result.routes[0].steps.forEach(step => { path = path.concat(step.path); });
            } else {
              path = [config.start, config.end];
            }

            const markers = [];
            let polyline = null;

            // 路线逻辑
            if (["干线协调", "勤务路线"].includes(config.name)) {
              polyline = new this.AMap.Polyline({
                path: path,
                strokeColor: config.color,
                strokeWeight: 6,
                strokeOpacity: 0.6,
                zIndex: 15
              });
            }

            // --- 稀疏化逻辑 ---
            const isAbnormalStatus = ["离线", "降级", "故障"].includes(config.name);
            // 异常状态（离线等）每 40 个点取一个，普通状态每 15 个点取一个
            const stepSize = isAbnormalStatus ? 40 : 15;

            for (let i = 0; i < path.length; i += stepSize) {
              markers.push(this.createTrafficLightMarker(path[i], config));
            }

            const overlays = [...markers, polyline].filter(Boolean);
            this.routeGroups[config.name] = overlays;

            if (this.isMapReady() && this.activeLegends.includes(config.name)) {
              this.map.add(overlays);
            }
          });
        }, index * 200);
      });
    },

    createTrafficLightMarker(position, config) {
      const isAbnormal = ["离线", "降级", "故障"].includes(config.name);
      const lng = Number(position[0] || position.lng);
      const lat = Number(position[1] || position.lat);

      // 3. 【视觉优化】调整 Marker 大小比例
      // 异常状态图标略大（为了警示），普通点位略小且半透明
      const size = isAbnormal ? '18px' : '14px';
      const opacity = isAbnormal ? '1' : '0.85';
      const shadow = isAbnormal ? `0 0 10px ${config.color}` : `0 0 5px ${config.color}`;

      const marker = new this.AMap.Marker({
        position: [lng, lat],
        zIndex: isAbnormal ? 110 : 100, // 异常图标显示在更上层
        content: `
          <div class="pure-light-node ${isAbnormal ? 'breathe abnormal-node' : ''}" 
              style="
                width: ${size}; 
                height: ${size}; 
                background: ${config.color}; 
                box-shadow: ${shadow}; 
                opacity: ${opacity};
                border: 1.5px solid rgba(255,255,255,0.7);
                font-size: 12px;
                display: flex;
                justify-content: center;
                align-items: center;
                color: #fff;
                padding: 8px;
              ">
            <span style="transform: scale(0.7); font-weight: bold;">${config.name.charAt(0)}</span>
          </div>
        `,
        offset: new this.AMap.Pixel(-8, -8),
        extData: {
          ...config,
          position: [lng, lat],
          statusColor: config.color,
          statusLabel: isAbnormal ? config.name : "正常运行",
          road: '北京路与南京路',
          time: '2026.1.23.12:00'
        }
      });

      marker.on('click', (e) => {
        this.openLightInfo(e.target.getExtData(), e.lnglat);
        this.$emit('map-crossing-click', e.target.getExtData(), e.lnglat);
      });

      return marker;
    },

    openLightInfo(data, position) {
      if (!this.isMapReady()) return;

      const content = `
        <div class="custom-info-card">
          <div class="close-btn" onclick="window.closeMapInfoWindow()">✕</div>
          <div class="card-header">
            <div class="status-dot" style="background: ${data.statusColor}">
              <span>${data.name.charAt(0)}</span>
            </div>
            <span class="status-text">${data.statusLabel}</span>
          </div>
          <div class="card-body">
            <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">${data.time}</span></div>
          </div>
        </div>
      `;

      window.closeMapInfoWindow = () => {
        if (this.infoWindow) this.infoWindow.close();
      };

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

    toggleAll() {
      const targetState = !this.isAllSelected;
      if (!this.isMapReady()) return;

      if (targetState) {
        this.activeLegends = this.legendConfig.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._isDestroyed) this.openLightInfo(foundMarker.getExtData(), finalPos);
        }, 600);
      }
    },

    toggleLegend() {
      this.legendVisible = !this.legendVisible;
    }
  }
};
</script>

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

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

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

::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%,
  100% {
    opacity: 0.7;
    transform: scale(1);
  }

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

::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: 18px;
  height: 18px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 8px;
  font-size: 12px;
  padding: 12px;
  box-sizing: border-box;
}

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

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

.map-legend.legend-hidden {
  opacity: 0;
  transform: translateX(100%);
  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 {
  border-radius: 50%;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #fff;
  pointer-events: auto;
  /* 确保能点击 */
}

/* 异常状态增加稍微剧烈一点的呼吸感，但缩小范围 */
@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>
