<template>
  <div class="container">
    <div id="map" style="width: 100%; height: 500px;"></div>
  </div>
</template>

<script>

import { getDataByRedis } from "@/api/car/ListManager";

export default {
  data() {
    return {
      map: null,
      polyline: null,
      carMarker: null,
      carVin: this.$route.query.carVin || null ,
      intervalId: null,
      data: {}, // 数据存储变量
    };
  },
  created() {
    // 创建定时器，每隔一定时间间隔调用fetchData方法

  },
  methods: {
    async fetchData() {
      try {
        const res = await getDataByRedis(this.carVin);
        this.data = res.data;

        // 更新车辆位置
        this.updateCarMarker();
      } catch (error) {
        console.error("Error fetching vehicle data:", error);
      }
    },
    initMap() {
      this.map = new AMap.Map('map', {
        center: [116.397428, 39.90923], // 初始化地图中心点
        zoom: 20, // 地图缩放级别
      });
      this.polyline = new AMap.Polyline({
        map: this.map,
        path: [], // 初始为空
        strokeColor: '#3366FF',
        strokeWeight: 5,
      });

      // 初始化车辆模型标记
      this.carMarker = new AMap.Marker({
        map: this.map,
        position: [116.397428, 39.90923], // 初始位置
        icon: 'https://webapi.amap.com/images/car.png',
        offset: new AMap.Pixel(-26, -13),
        autoRotation: true,
      });
    },
    updateCarMarker() {
      if (this.data.longitude && this.data.latitude) {
        const newPoint = [this.data.longitude, this.data.latitude];

        // 更新车辆模型位置
        this.carMarker.setPosition(newPoint);

        // 更新路径线条坐标
        const path = this.polyline.getPath();
        path.push(new AMap.LngLat(this.data.longitude, this.data.latitude));
        this.polyline.setPath(path);

        // 调整地图视野
        this.map.setCenter(newPoint);
      }
    },
  },
  mounted() {
    this.$store.dispatch('app/toggleSideBarHide',true);
    document.querySelector('.navbar').style.display = 'none';
    document.querySelector('.tags-view-container').style.display = 'none';


    const script = document.createElement('script');
    script.src = 'https://webapi.amap.com/maps?v=1.4.15&key=7df1851ffb059e1e75c31b9bcd892b6b';
    script.onload = () => {
      this.initMap();
    };
    document.head.appendChild(script);
    this.initMap();


  },

};

</script>
