<template>
  <div class="map-container">
    <div id="map" class="map"></div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      map: null,
      currentLayer: null,
      cars: [],  // 存储多个小车的数组
      carIcon: null,
      pointIcon: null,
    };
  },
  mounted() {
    this.initMap();
    for (let i = 0; i < document.getElementsByClassName("tdt-iconLayers-layer").length; i++) {
      //document.getElementsByClassName("tdt-iconLayers-layer")[i].style.display = "none"
    }
    setTimeout(function () {
      let a = document.getElementsByName('[data-layerid="128"]');
      // console.log(a)
    }, 2000)
  },
  methods: {
    initMap() {
      // 初始化天地图
      const center = new T.LngLat(116.40769, 39.89945); // 设置中心点为北京
      let imageURL = 'http://t0.tianditu.gov.cn/vec_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img' +
        '&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=1eb44fae5b9dc454442b322e9a41d233';
      let imageUrl2 = 'http://t0.tianditu.gov.cn/cia_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img' +
        '&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=1eb44fae5b9dc454442b322e9a41d233'
      this.currentLayer = new T.TileLayer(imageURL, {minZoom: 1, maxZoom: 18}); // 矢量底图
      this.map = new T.Map('map', {layers: [this.currentLayer]});

      this.map.centerAndZoom(center, 18);

      var ctrl = new T.Control.MapType();
      //��加控件
      this.map.addControl(ctrl);


      // 小车图标的自定义图标
      this.carIcon = new T.Icon({
        iconUrl: require('@/assets/xc.png'),  // 替换为你的小车图标路径
        iconSize: new T.Point(40, 40)
      });

      // 小点的图标
      this.pointIcon = new T.DivIcon({
        html: '<div class="point-icon"></div>',
        iconSize: new T.Point(10, 10)
      });

      // 初始化多个小车
      const initialPositions = [
        { x: 116.40769, y: 39.89945 },
        { x: 116.40779, y: 39.89955 },
        { x: 116.40789, y: 39.89965 },
      ];

      initialPositions.forEach((pos, index) => {
        this.cars.push({
          id: index,
          marker: null,
          lastPoint: null,
          x: pos.x,
          y: pos.y,
        });
        const point = new T.LngLat(pos.x, pos.y);
        this.addCarAtPoint(index, point);
      });

      // 监听地图缩放事件
      this.map.addEventListener("zoomend", this.updateAllCarsDisplay);

      // 模拟多个小车移动
      setInterval(() => {
        this.cars.forEach(car => {
          const newPoint = new T.LngLat(car.x += 0.00001, car.y += 0.00001);
          this.addCarAtPoint(car.id, newPoint);
        });
      }, 200);
    },

    addCarAtPoint(carId, currentPoint) {
      const car = this.cars[carId];
      if (car.lastPoint) {
        const angle = this.calculateAngle(car.lastPoint, currentPoint);
        this.updateCarPosition(carId, currentPoint, angle);
      } else {
        const zoomLevel = this.map.getZoom();
        let markerIcon = this.createMarkerIcon(zoomLevel, 0);
        car.marker = new T.Marker(currentPoint, {icon: markerIcon});
        this.map.addOverLay(car.marker);
      }

      car.marker.addEventListener('click', () => {
        alert(`小车${carId}当前坐标：经度: ${currentPoint.lng}, 纬度: ${currentPoint.lat}`);
      });

      car.lastPoint = currentPoint;
    },

    // 计算两个坐标点之间的角度
    calculateAngle(point1, point2) {
      const deltaX = point2.lng - point1.lng;
      const deltaY = point2.lat - point1.lat;
      const angle = Math.atan2(deltaY, deltaX) * (180 / Math.PI); // 弧度转角度
      return angle;
    },

    updateCarPosition(carId, point, angle) {
      const car = this.cars[carId];
      if (car.marker) {
        this.map.removeOverLay(car.marker);
      }

      const zoomLevel = this.map.getZoom();
      let markerIcon = this.createMarkerIcon(zoomLevel, angle);

      car.marker = new T.Marker(point, {icon: markerIcon});
      this.map.addOverLay(car.marker);

      car.marker.addEventListener('click', () => {
        alert(`小车${carId}当前坐标：经度: ${point.lng}, 纬度: ${point.lat}`);
      });
    },

    createMarkerIcon(zoomLevel, angle) {
      if (zoomLevel >= 18) {
        return new T.DivIcon({
          html: `<div class="car-icon" style="transform: rotate(${angle}deg); width: 30px; height: 30px; background-color: transparent;">
                    <img src="${require('@/assets/xc.png')}" style="width: 100%; height: 100%; object-fit: contain;" />
                 </div>`,
          iconSize: new T.Point(30, 30),
          iconAnchor: new T.Point(15, 15)
        });
      } else {
        return new T.DivIcon({
          html: '<div class="point-icon" style="width: 10px; height: 10px; background-color: #007bff; border-radius: 50%;"></div>',
          iconSize: new T.Point(10, 10),
          iconAnchor: new T.Point(5, 5)
        });
      }
    },

    updateAllCarsDisplay() {
      this.cars.forEach(car => {
        if (car.lastPoint) {
          const angle = this.calculateAngle(car.lastPoint, car.lastPoint);
          this.updateCarPosition(car.id, car.lastPoint, angle);
        }
      });
    }
  },
};
</script>

<style scoped>
.map-container {
  position: relative;
  width: 100%;
  height: 100vh;
}

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

.basemap-switcher {
  position: absolute;
  top: 10px;
  left: 10px;
  background-color: white;
  padding: 10px;
  border-radius: 5px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

button {
  margin: 5px;
  padding: 8px 16px;
  cursor: pointer;
}


:global(.custom-div-icon) {
  background: none !important;
  border: none !important;
}

.car-icon {
  width: 30px;
  height: 30px;
  background-color: transparent;
}

.car-icon img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.point-icon {
  width: 10px;
  height: 10px;
  background-color: #007bff;
  border-radius: 50%;
}
</style>
