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

    <div class="map-legend" :style="privateStyle.legend">
      <div class="legend-title">图例</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) }">

          <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>
</template>

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

export default {
  name: "TrafficMap",
  props: {
    amapKey: { type: String, default: '您的Key' },
    securityJsCode: { type: String, default: '您的安全密钥' }
  },
  data() {
    return {
      AMap: null,
      map: null,
      infoWindow: null,
      routeGroups: {},
      polylines: [],
      privateStyle: {
        legend: {}
      },
      activeLegends: ["中心计划", "干线协调", "勤务路线", "定周期控制", "感应控制", "自适应控制", "手动控制", "特殊控制", "离线", "降级", "故障"],
      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.initAMap();

    // 自定义首页地图搜索和图例位置样式
    if (this.$route.path === '/home') {
      this.privateStyle.legend = { right: "25%" };
    }
  },
  beforeDestroy() {
    if (this.infoWindow) this.infoWindow.close();

    // 1. 清理普通的 polylines 数组
    this.polylines.forEach(p => {
      if (p && typeof p.setMap === 'function') p.setMap(null);
    });

    // 2. 核心修改：清理 routeGroups
    Object.values(this.routeGroups).forEach(g => {
      if (!g) return;

      if (Array.isArray(g)) {
        // 如果是数组（当前的逻辑），遍历每个成员销毁
        g.forEach(overlay => {
          if (overlay && typeof overlay.setMap === 'function') {
            overlay.setMap(null);
          }
        });
      } else if (typeof g.setMap === 'function') {
        // 如果是旧版的 OverlayGroup 或单个覆盖物
        g.setMap(null);
      }
    });

    if (this.map) {
      this.map.destroy();
    }
  },
  computed: {
    // 判断是否所有图例都在激活列表中
    isAllSelected() {
      return this.activeLegends.length === this.legendConfig.length;
    }
  },
  methods: {
    // 修改后的 initAMap
    async initAMap() {
      window._AMapSecurityConfig = { securityJsCode: this.securityJsCode };
      try {
        this.AMap = await AMapLoader.load({
          key: this.amapKey,
          version: "2.0",
          plugins: ['AMap.Driving', 'AMap.GeometryUtil']
        });

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

        this.map.on('complete', () => this.drawStaticRoutes());
      } catch (err) { console.error('地图初始化失败', err); }
    },

    drawStaticRoutes() {
      const AMap = this.AMap;

      this.legendConfig.forEach((config, index) => {
        setTimeout(() => {
          const driving = new AMap.Driving({
            map: null,
            hideMarkers: true,
            autoFitView: false
          });

          driving.search(config.start, config.end, (status, result) => {
            let markers = [];
            let path = [];

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

            let polyline = null;
            const needRouteLine = ["干线协调", "勤务路线"].includes(config.name);

            if (needRouteLine) {
              polyline = new AMap.Polyline({
                path: path,
                strokeColor: config.color,
                strokeWeight: 8,
                strokeOpacity: 0.8,
                showDir: false,
                lineJoin: 'round',
                zIndex: 15,
                map: null
              });
            }

            const points = [];
            const step = 10; // 步长越大，点越稀疏
            for (let i = 0; i < path.length; i += step) {
              points.push(path[i]);
            }

            // 确保终点也被加上
            if ((path.length - 1) % step !== 0) {
              points.push(path[path.length - 1]);
            }

            points.forEach((pos, idx) => {
              // 临时逻辑，有真实接口后可以删除
              const posMap = {
                8: 'pos1',
                9: 'pos2',
                10: 'pos3'
              };

              if (idx === 0 && posMap[index]) {
                localStorage.setItem(posMap[index], pos);
              }
              // 临时逻辑，有真实接口后可以删除

              markers.push(this.createTrafficLightMarker(pos, config));
            });

            // 3. 【关键修改】：overlays 数组只存放 markers，不再存放 polyline
            const overlays = [...markers, polyline].filter(Boolean);
            this.routeGroups[config.name] = overlays;

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

    createTrafficLightMarker(position, config) {
      // 根据业务需求：离线、降级、故障需要闪烁，其他保持静止
      const needsFlash = ["离线", "降级", "故障"].includes(config.name);
      const displayStatus = needsFlash ? config.name : "正常运行";
      const lng = Number(position[0] || position.lng);
      const lat = Number(position[1] || position.lat);

      const marker = new this.AMap.Marker({
        position: [lng, lat],
        zIndex: 100,
        content: `
          <div class="pure-light-node ${needsFlash ? 'breathe' : ''}" 
              style="background: ${config.color}; box-shadow: 0 0 15px ${config.color}; font-size: 12px; display: flex; justify-content: center; align-items: center; color: #fff; padding: 8px;">
            <span>${config.name.charAt(0)}</span>
          </div>
        `,
        offset: new this.AMap.Pixel(-10, -10),
        extData: {
          ...config,
          position: [lng, lat],
          statusColor: config.color, // 统一弹窗小圆点颜色
          statusLabel: displayStatus, // 统一弹窗状态文字
          road: '北京路与南京路',
          time: '2026.1.23.12:00'
        }
      });

      marker.on('click', (e) => this.openLightInfo(e.target.getExtData(), e.lnglat));
      return marker;
    },

    openLightInfo(data, position) {
      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>
      `;

      // 定义全局关闭方法（因为 isCustom:true 下 Vue 事件会失效）
      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; // 获取点击后的目标状态（true为全选，false为全不选）

      if (targetState) {
        // --- 情况 1：执行“全选” ---
        // 1. 更新激活列表
        this.activeLegends = this.legendConfig.map(item => item.name);

        // 2. 遍历所有已经生成的路线数组，将其全部添加到地图上
        Object.keys(this.routeGroups).forEach(name => {
          const overlays = this.routeGroups[name]; // 此时 routeGroups 存储的是数组
          if (overlays && overlays.length > 0) {
            this.map.add(overlays);
          }
        });
      } else {
        // --- 情况 2：执行“全不选” ---
        // 1. 清空激活列表
        this.activeLegends = [];

        // 2. 遍历所有路线数组，从地图上移除
        Object.keys(this.routeGroups).forEach(name => {
          const overlays = this.routeGroups[name];
          if (overlays && overlays.length > 0) {
            this.map.remove(overlays);
          }
        });

        // 3. 关闭当前可能打开的弹窗
        if (this.infoWindow) this.infoWindow.close();
      }
    },

    toggleRouteVisible(name) {
      const overlays = this.routeGroups[name] || []; // 获取的是数组
      const index = this.activeLegends.indexOf(name);
      if (index > -1) {
        this.activeLegends.splice(index, 1);
        this.map.remove(overlays); // 改用 remove
        if (this.infoWindow) this.infoWindow.close();
      } else {
        this.activeLegends.push(name);
        this.map.add(overlays); // 改用 add
      }
    },

    // 其他组件点击定位到地图指定的点
    focusByLocation(targetPos) {
      if (!targetPos || targetPos.length !== 2) return;

      let foundMarker = null;

      // 1. 遍历所有路线组
      Object.values(this.routeGroups).forEach(group => {
        // 2. 在组内寻找 Marker
        const marker = group.find(item => {
          if (!(item instanceof this.AMap.Marker)) return false;
          const pos = item.getExtData().position;
          // 3. 坐标比对（考虑到浮点数精度，建议使用 AMap 自带的几何工具或简单比对）
          return pos[0] === targetPos[0] && pos[1] === targetPos[1];
        });
        if (marker) foundMarker = marker;
      });

      if (foundMarker) {
        // 4. 定位并打开弹窗
        const finalPos = foundMarker.getPosition();
        this.map.setZoomAndCenter(17, finalPos, false, 500); // 17级视角，平滑移动

        setTimeout(() => {
          this.openLightInfo(foundMarker.getExtData(), finalPos);
        }, 600);
      } else {
        console.warn("未在地图上找到该坐标对应的点位:", targetPos);
      }
    }
  }
};
</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;
}

.legend-title {
  color: #fff;
  font-size: 14px;
  margin-bottom: 12px;
  border-bottom: 1px solid #1e4d8e;
  padding-bottom: 8px;
}

.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;
}
</style>
