<template>
  <div :id="id" :style="mapStyle">
    <slot v-if="map"></slot>
  </div>
</template>

<script>
import { mapState } from "vuex";
import { nanoid } from "nanoid";
import AMapLoader from "@amap/amap-jsapi-loader";
import { getConfig } from "@/utils";
import { place } from "@/api/amap";
import _ from "lodash";

export default {
  name: "AMap",
  provide() {
    return {
      map: this,
    };
  },
  props: {
    // map container element id
    id: {
      type: String,
      default: `map-${nanoid()}`,
    },
    // map container width
    width: {
      type: [String, Number],
      default: "100%",
    },
    // map container height
    height: {
      type: [String, Number],
      default: "100%",
    },
    // see complete options documentation https://lbs.amap.com/api/javascript-api-v2/guide/abc/load
    loadOptions: {
      type: Object,
    },
    // see complete options documentation https://lbs.amap.com/api/javascript-api-v2/documentation#map
    mapOptions: {
      type: Object,
    },
    // collection for markers. one marker options complete documentation https://lbs.amap.com/api/javascript-api-v2/documentation#marker
    markers: {
      type: Array,
      default() {
        return [];
      },
    },
    cluster: Object, // {dataOptions[],MarkerClusterOptions{}}
    // see complete options documentation https://lbs.amap.com/api/javascript-api-v2/documentation#overlaygroup
    overlayGroupOptions: {
      type: Object,
    },
    layers: {
      type: Array,
      default() {
        return [];
      },
    },
    // see all plugin https://lbs.amap.com/api/javascript-api-v2/guide/abc/plugins-list
    plugin: {
      type: Array,
    },
    moveStartIndex: {
      type: Number,
      default: 0,
    },
    moveAlong: {
      // https://developer.amap.com/api/jsapi-v2/documentation#markermovealong -- opts
      type: Object,
      default() {
        return {};
      },
    },
    moveMarker: {
      // https://lbs.amap.com/api/javascript-api-v2/documentation#marker
      type: Object,
      default() {
        return {};
      },
    },
    speedRatio: {
      type: Number,
      default: 1,
    },
    toolbar: {
      type: Object,
      default() {
        return {
          position: {
            bottom: "120px",
            left: "40px",
          },
          offset: [0, 0],
        };
      },
    },
    scale: {
      type: Object,
    },
    controlBar: {
      type: Object,
      default() {
        return {
          position: {
            bottom: "20px",
            left: "10px",
          },
          offset: [0, 0],
        };
      },
    },
  },
  data() {
    return {
      AMap: null,
      map: null,
      city: "",
      overlayGroup: null,
      infoWindow: null,
      layersList: {},
      plugins: {
        CitySearch: null,
        MouseTool: null,
        PlaceSearch: null,
      },
      drawPolygonEdit: null,
      polygonEditor: null,
      drawCircleEdit: null,
      circleEditor: null,
      rectangleEditor: null,
      rectangle: null,
      railCircle: null,
      moveAnimationMarker: null,
      movePath: [],
      currentIndex: 0,
      roadPolyline: null,
      trackMarker: null,
      timer: null,
      drawType: "",
      trafficLayer: null,
      trafficLayerVisible: false,
      currentLocation: null,
      clusterTarget: null,
    };
  },
  computed: {
    ...mapState({
      placeKeywords: (state) => state.placeKeywords,
      appLoadingMask: (state) => state.appLoadingMask,
    }),
    mapStyle() {
      return {
        width: typeof this.width === "string" ? this.width : this.width.toString() + "px",
        height: typeof this.height === "string" ? this.height : this.height.toString() + "px",
      };
    },
  },
  watch: {
    markers: {
      handler() {
        // this.map.clearMap();
        if (this.clusterTarget) this.map.remove(this.clusterTarget);
        if (this.overlayGroup) {
          this.overlayGroup.clearOverlays();
        }
        if (this.markers && this.markers.length > 0) {
          const markers = this.markers.map((marker) => {
            return new this.AMap.Marker({
              ...marker,
              icon: this.setIcon(marker.icon),
            });
          });
          // 创建覆盖物群组，传入覆盖物组成的数组
          this.overlayGroup = new this.AMap.OverlayGroup(markers);

          // 对此覆盖物群组设置同一属性
          if (this.overlayGroupOptions) this.overlayGroup.setOptions(this.overlayGroupOptions);

          // this.overlayGroup.on("click", this.overlayGroupClickHandler);

          // 统一添加到地图实例上
          this.map.add(this.overlayGroup);

          this.overlayGroup.on("click", this.overlayGroupClickHandler);
          // this.infoWindow = new AMap.InfoWindow({
          //   ...this.infoWindowOptions,
          //   content: this.$refs.windowInfo,
          // });
        }
      },
      deep: true,
      immediate: false,
    },
    "cluster.dataOptions": {
      handler(value = []) {
        console.log("cluster.dataOptions", this.clusterTarget);
        console.log("cluster.dataOptions", value);
        if (this.clusterTarget) {
          this.clusterTarget.setMap(null);
          this.map.plugin(["AMap.MarkerCluster"], () => {
            this.clusterTarget = new this.AMap.MarkerCluster(this.map, value, this.cluster.MarkerClusterOptions);
            this.clusterTarget.on("click", (data) => this.$emit("clickCluster", data, this.map));
          });
        } else {
          this.map.plugin(["AMap.MarkerCluster"], () => {
            this.clusterTarget = new this.AMap.MarkerCluster(this.map, value, this.cluster.MarkerClusterOptions);
            this.clusterTarget.on("click", (data) => this.$emit("clickCluster", data, this.map));
          });
        }
      },
      deep: true,
      immediate: false,
    },
    layers: {
      handler(value) {
        if (value && value.length > 0) {
          this.map.getLayers().forEach((layer) => {
            this.map.removeLayer(layer);
          });
          this.map.setLayers(this.setLayers(this.AMap));
        }
      },
      deep: true,
      immediate: false,
    },
    placeKeywords(value) {
      this.placeSearch(value);
    },
  },
  methods: {
    getLayers() {
      return this.layersList;
    },
    setLayers(AMap) {
      this.layersList = {};
      if (this.layers.length > 0) {
        this.layers.forEach((layer) => {
          switch (layer.type) {
            case "Satellite":
              this.layersList["Satellite"] = new AMap.TileLayer.Satellite(layer?.opts);
              break;
            case "RoadNet":
              this.layersList["RoadNet"] = new AMap.TileLayer.RoadNet(layer?.opts);
              break;
            default:
              this.layersList["default"] = new AMap.TileLayer(layer?.opts);
              break;
          }
        });
        console.log(this.layersList);
        return _.values(this.layersList);
      } else {
        this.layersList["default"] = new AMap.TileLayer();
        return [new AMap.TileLayer()];
      }
    },
    async initMap() {
      const { mapConfig } = await getConfig();
      const { load, map } = mapConfig;
      // load AMap api
      AMapLoader.load({
        ...this.loadOptions,
        ...load,
      })
        .then((AMap) => {
          this.AMap = AMap;
          // generate map object

          this.map = new AMap.Map(this.id, {
            ...this.mapOptions,
            ...map,
            layers: this.setLayers(AMap),
          });
          // 楼块图层
          const buildingLayer = new this.AMap.Buildings({
            zooms: [16, 20],
          });
          this.map.addLayer(buildingLayer);

          this.$emit("emitMap", this.map, AMap);
          // bind events
          this.map.on("click", this.clickHandler);

          // set overlayGroup
          if (this.markers && this.markers.length > 0) {
            const markers = this.markers.map((marker) => {
              return new AMap.Marker({
                ...marker,
                icon: this.setIcon(marker.icon),
              });
            });
            // 创建覆盖物群组，传入覆盖物组成的数组
            this.overlayGroup = new AMap.OverlayGroup(markers);

            // 对此覆盖物群组设置同一属性
            if (this.overlayGroupOptions) this.overlayGroup.setOptions(this.overlayGroupOptions);

            this.overlayGroup.on("click", this.overlayGroupClickHandler);

            // 统一添加到地图实例上
            this.map.add(this.overlayGroup);
          }
          // 根据IP获取当前城市
          AMap.plugin("AMap.CitySearch", () => {
            this.plugins.CitySearch = new AMap.CitySearch();
            this.plugins.CitySearch.getLocalCity((status, result) => {
              if (status === "complete" && result.info === "OK") {
                // 查询成功，result即为当前所在城市信息
                const { city } = result;
                this.city = city;
                // set plugins
                if (this.plugin && this.plugin.length > 0) {
                  this.map.plugin(this.plugin, () => {
                    this.plugin.forEach((plugin) => {
                      this.setPlugin(plugin);
                    });
                  });
                }
              }
            });
          });
          // if(process.env.VUE_APP_ENV === "development") {
          this.map.on("complete", () => {
            this.$emit("complete");
          });
          // }else {
          // AMap.plugin("AMap.Geolocation", () => {
          //   const geolocation = new AMap.Geolocation({
          //     enableHighAccuracy: true, //是否使用高精度定位，默认:true
          //     timeout: 30000, //超过10秒后停止定位，默认：5s
          //     showButton: false,
          //     zoomToAccuracy: false, //定位成功后是否自动调整地图视野到定位点
          //   });
          //   this.map.addControl(geolocation);
          //   geolocation.getCurrentPosition((status, result) => {
          //     console.log("on get current position complete", result, this.map);
          //     if (status === "complete") {
          //       this.currentLocation = result;
          //       this.$emit("complete");
          //     } else {
          //       // onError(result)
          //       this.$message.error("获取浏览器定位失败");
          //     }
          //   });
          // });
          // }

          this.setControl();
          this.trafficLayer = new this.AMap.TileLayer.Traffic({
            zIndex: 10,
            // zooms: [7, 22],
            visible: this.trafficLayerVisible,
          });
          this.trafficLayer.setMap(this.map);
        })
        .catch((e) => {
          console.log(e);
        });
    },
    setControl() {
      if (this.scale) {
        this.map.plugin(["AMap.Scale"], () => {
          const control = new this.AMap.Scale(this.scale);
          this.map.addControl(control);
        });
      }
      if (this.controlBar) {
        this.map.plugin(["AMap.ControlBar"], () => {
          const control = new this.AMap.ControlBar(this.controlBar);
          this.map.addControl(control);
        });
      }
      if (this.toolbar) {
        this.map.plugin(["AMap.ToolBar"], () => {
          const control = new this.AMap.ToolBar(this.toolbar);
          this.map.addControl(control);
        });
      }
    },
    setIcon(icon) {
      if (!icon || typeof icon === "string") {
        return icon;
      } else {
        return new this.AMap.Icon(icon);
      }
    },
    /**
     * @注册插件 https://lbs.amap.com/api/javascript-api-v2/guide/abc/plugins
     * @param {String} plugin
     */
    setPlugin(plugin) {
      const pluginName = plugin.split(".")[1];
      switch (plugin) {
        case "AMap.MouseTool": // https://developer.amap.com/api/jsapi-v2/documentation#mousetool
          this.plugins[pluginName] = new this.AMap[pluginName](this.map);
          this.plugins[pluginName].on("draw", (event) => {
            // event.obj 为绘制出来的覆盖物对象
            // console.log(event)
            const params = {
              drawType: this.drawType,
              ...event,
            };
            this.$emit("draw", params);
          });
          break;
        case "AMap.PlaceSearch": // https://developer.amap.com/api/jsapi-v2/documentation#mousetool
          console.log(this.city);
          this.plugins[pluginName] = new this.AMap[pluginName]({
            city: this.city,
            extensions: "all",
          });
          break;
      }
      console.log(this.plugins);
    },
    /**
     * @ 地图点击事件 https://developer.amap.com/api/jsapi-v2/documentation#mapeventclick
     * @param {*} e https://developer.amap.com/api/jsapi-v2/documentation#mapsevent
     */
    clickHandler(e) {
      this.$emit("clickMap", e);
    },
    /**
     * @要素集合图层点击事件
     * @param {*} e https://developer.amap.com/api/jsapi-v2/documentation#mapsevent
     */
    overlayGroupClickHandler(e) {
      this.$emit("clickMarker", e);
    },
    //工具栏选择图形
    circle(type) {
      // 先判断组件是否注册
      if (this.plugin && this.plugin.length > 0 && this.plugin.includes("AMap.MouseTool")) {
        switch (type) {
          case "circle": {
            this.drawType = type;
            this.plugins.MouseTool.circle();
            break;
          }
        }
      } else {
        this.$message.error("未注册MouseTool");
      }
    },
    //工具栏选择图形
    square(type) {
      // 先判断组件是否注册
      if (this.plugin && this.plugin.length > 0 && this.plugin.includes("AMap.MouseTool")) {
        switch (type) {
          case "square": {
            this.drawType = type;
            this.plugins.MouseTool.rectangle();
            break;
          }
        }
      } else {
        this.$message.error("未注册MouseTool");
      }
    },
    //工具栏选择图形
    polygon(type) {
      // 先判断组件是否注册
      if (this.plugin && this.plugin.length > 0 && this.plugin.includes("AMap.MouseTool")) {
        switch (type) {
          case "polygon": {
            this.drawType = type;
            this.plugins.MouseTool.polygon();
            break;
          }
        }
      } else {
        this.$message.error("未注册MouseTool");
      }
    },
    /**
     * @测量
     * @param {String} type
     */
    measure(type) {
      // 先判断组件是否注册
      if (this.plugin && this.plugin.length > 0 && this.plugin.includes("AMap.MouseTool")) {
        switch (type) {
          case "rule": {
            this.plugins.MouseTool.rule();
            break;
          }
          case "measureArea": {
            this.plugins.MouseTool.measureArea();
            break;
          }
        }
      } else {
        this.$message.error("未注册MouseTool");
      }
    },
    /**
     * @清除测量
     */
    clearMeasure() {
      // 先判断组件是否注册
      if (this.plugin && this.plugin.length > 0 && this.plugin.includes("AMap.MouseTool")) {
        this.drawType = "";
        this.plugins.MouseTool.close(true); //关闭，并清除覆盖物
      } else {
        this.$message.error("未注册MouseTool");
      }
    },
    setCenter(center, immediately, duration) {
      this.map.setCenter(center, immediately, duration);
    },
    setZoomAndCenter(zoom, center, immediately, duration) {
      this.map.setZoomAndCenter(zoom, center, immediately, duration);
    },
    setZoom(zoom) {
      this.map.setZoom(zoom);
    },
    getFitZoomAndCenterByOverlays(overlays, avoid, maxZoom) {
      return this.map.getFitZoomAndCenterByOverlays(overlays, avoid, maxZoom);
    },
    getAllOverlays(type) {
      return this.map.getAllOverlays(type);
    },
    getOverlays() {
      return this.overlayGroup.getOverlays();
    },
    placeSearch(keywords) {
      place({
        keywords: keywords,
        offset: 10,
        city: this.city,
      })
        .then((res) => {
          let list = [];
          const { status, data } = res;
          if (status === 200) {
            console.log("poidata", data);
            list = data.tips;
          }
          this.$emit("placeSearch", list);
          this.$store.commit("SET_POI_LIST", list);
        })
        .catch((err) => {
          console.log(err);
        });

      // console.log(keywords);
      // this.plugins.PlaceSearch.search(keywords, (status, result) => {
      //   console.log(result);
      //   let list = [];
      //   // 查询成功时，result即对应匹配的POI信息
      //   if (status === "complete" && result.info === "OK") {
      //     // 查询成功，result即为当前所在城市信息
      //     const { poiList } = result;
      //     list = poiList.pois;
      //   }
      //   this.$emit("placeSearch", list);
      //   this.$store.commit("SET_POI_LIST", list);
      // });
    },
    setPolygonEditor(path, autoPan = true) {
      let that = this;
      if (!path || path.length <= 0) return false;
      return new Promise((resolve) => {
        that.drawPolygonEdit = new this.AMap.Polygon({
          path,
          strokeColor: "#E6A23C",
          strokeWeight: 6,
          strokeOpacity: 1,
          fillOpacity: 0.2,
          fillColor: "#E6A23C",
          zIndex: 50,
          bubble: true,
        });
        this.map.add([that.drawPolygonEdit]);
        if (autoPan) this.map.setFitView([that.drawPolygonEdit]);
        this.map.plugin(["AMap.PolyEditor"], () => {
          this.polygonEditor = new this.AMap.PolyEditor(this.map, that.drawPolygonEdit);

          this.polygonEditor.on("move", (event) => {
            // log.info('触发事件：move')
            this.$emit("polygonEditorChange", event);
          });

          this.polygonEditor.on("adjust", (event) => {
            // log.info('触发事件：adjust')
            this.$emit("polygonEditorChange", event);
          });
          resolve({ figure: that.drawPolygonEdit, editor: that.polygonEditor });
        });
        // resolve(this.drawPolygonEdit);
        // this.polygonEditor = new this.AMap.PolyEditor(this.map, polygon);
      });

      // this.polyEditor.open();
      // return this.polyEditor
    },
    getPolygonEditor() {
      return this.polygonEditor?.getTarget();
    },
    openPolygonEditor() {
      if (this.polygonEditor) this.polygonEditor.open();
    },
    closePolygonEditor() {
      if (this.polygonEditor) this.polygonEditor.close();
    },
    async setCircleEditor({ center, radius }, autoPan = true) {
      let that = this;
      return new Promise((resolve) => {
        that.drawCircleEdit = new this.AMap.Circle({
          center,
          radius, //半径
          borderWeight: 3,
          strokeColor: "#E6A23C",
          // strokeOpacity: 1,
          strokeWeight: 6,
          strokeOpacity: 1,
          fillOpacity: 0.2,
          //strokeStyle: 'dashed',
          //strokeDasharray: [10, 10],
          // 线样式还支持 'dashed'
          fillColor: "#E6A23C",
          zIndex: 50,
        });
        this.map.add(that.drawCircleEdit);
        // 缩放地图到合适的视野级别
        if (autoPan) this.map.setFitView([that.drawCircleEdit]);
        this.map.plugin(["AMap.CircleEditor"], () => {
          // 实例化多边形编辑器，传入地图实例和要进行编辑的多边形实例
          this.circleEditor = new this.AMap.CircleEditor(this.map, that.drawCircleEdit);
          this.circleEditor.on("move", (event) => {
            // log.info('触发事件：move')
            this.$emit("circleEditorChange", event);
          });

          this.circleEditor.on("adjust", (event) => {
            // log.info('触发事件：adjust')
            this.$emit("circleEditorChange", event);
          });
          console.log("resolve之前", that.circleEditor);
          resolve({ figure: that.drawCircleEdit, editor: that.circleEditor });
        });
      });
    },
    getCircleEditor() {
      return this.circleEditor?.getTarget();
    },
    openCircleEditor() {
      if (this.circleEditor) this.circleEditor.open();
    },
    closeCircleEditor() {
      if (this.circleEditor) this.circleEditor.close();
    },
    setRectangleEditor({ northEast, southWest }, autoPan = true) {
      let that = this;
      let northEastTrans = new this.AMap.LngLat(northEast[0], northEast[1]);
      let southWestTrans = new this.AMap.LngLat(southWest[0], southWest[1]);
      let bounds = new this.AMap.Bounds(southWestTrans, northEastTrans);
      return new Promise((resolve) => {
        that.rectangle = new this.AMap.Rectangle({
          bounds: bounds, //半径
          borderWeight: 3,
          strokeColor: "#E6A23C",
          // strokeOpacity: 1,
          strokeWeight: 6,
          strokeOpacity: 1,
          fillOpacity: 0.2,
          //strokeStyle: 'dashed',
          //strokeDasharray: [10, 10],
          // 线样式还支持 'dashed'
          fillColor: "#E6A23C",
          zIndex: 50,
        });
        this.map.add(that.rectangle);
        // 缩放地图到合适的视野级别
        if (autoPan) this.map.setFitView([that.rectangle]);
        this.map.plugin(["AMap.RectangleEditor"], () => {
          // 实例化多边形编辑器，传入地图实例和要进行编辑的多边形实例
          this.rectangleEditor = new this.AMap.RectangleEditor(this.map, that.rectangle);
          this.rectangleEditor.on("move", (event) => {
            // log.info('触发事件：move')
            this.$emit("rectangleEditorChange", event);
          });

          this.rectangleEditor.on("adjust", (event) => {
            // log.info('触发事件：adjust')
            this.$emit("rectangleEditorChange", event);
          });
          console.log("resolve之前", that.rectangleEditor);
          resolve({ figure: that.rectangle, editor: that.rectangleEditor });
        });
        // resolve(that.rectangle);
      });
    },
    getRectangleEditor() {
      return this.rectangleEditor?.getTarget();
    },
    openRectangleEditor() {},
    closeRectangleEditor() {
      if (this.rectangleEditor) this.rectangleEditor.close();
    },
    //周边调度画圈
    drawCircle(center, radius) {
      if (this.railCircle) {
        this.map.remove(this.railCircle);
      }

      this.railCircle = new this.AMap.Circle({
        center,
        radius, //半径
        borderWeight: 3,
        strokeColor: "#0E70FF",
        // strokeOpacity: 1,
        strokeWeight: 3,
        strokeOpacity: 1,
        fillOpacity: 0.2,
        strokeStyle: "dashed",
        strokeDasharray: [10, 10],
        // 线样式还支持 'dashed'
        fillColor: "#0E70FF",
        // zIndex: 50,
      });

      //圆形 Circle 对象添加到 Map
      this.railCircle.setMap(this.map);
      this.setZoom(14);
    },
    setMoveAnimation(movePath) {
      // this.map.clearMap();
      this.currentIndex = 0;
      if (this.timer) clearTimeout(this.timer);
      if (this.roadPolyline) {
        this.map.remove(this.roadPolyline);
      }
      if (this.moveAnimationMarker) {
        this.map.remove(this.moveAnimationMarker);
      }

      this.movePath = movePath;
      console.log(this.movePath);
      const lineArr = this.movePath.map((x) => {
        return x.position;
      });
      console.log(lineArr);
      this.trackMarker = {
        map: this.map,
        position: lineArr[this.moveStartIndex],
        anchor: "bottom-center",
        icon: require("@/assets/images/map/icons/红点轨迹.png"),
        // ...this.moveMarker,
        // ...{
        //   icon: this.setIcon(this.moveMarker.icon),
        // }
      };
      this.AMap.plugin("AMap.MoveAnimation", () => {
        this.moveAnimationMarker = new this.AMap.Marker(this.trackMarker);
        console.log(" this.moveAnimationMarker", this.moveAnimationMarker);
        this.roadPolyline = new this.AMap.Polyline({
          // map: this.map,
          path: lineArr,
          showDir: true,
          strokeColor: "#28F", //线颜色
          // strokeOpacity: 1,     //线透明度
          strokeWeight: 6, //线宽
          // strokeStyle: "solid"  //线样式
        });
        this.roadPolyline.setMap(this.map);

        // const passedPolyline = new this.AMap.Polyline({
        //   map: this.map,
        //   strokeColor: "#AF5", //线颜色
        //   strokeWeight: 6, //线宽
        // });
        this.moveAnimationMarker.on("moving", (e) => {
          console.log("this.moveAnimationMarker.on", e);
          // this.currentIndex = e.index;
          // passedPolyline.setPath(e.passedPath);
          // this.$emit("move", e);
          this.$emit("move", { index: this.currentIndex });
          // this.map.setCenter(e.target.getPosition(),true)
        });
        // this.moveAnimationMarker.on("moveend", (e) => {
        //   console.log(e);
        //   //this.currentIndex = e.index;
        //   this.$emit("moveend", {index: this.currentIndex});
        //   // this.map.setCenter(e.target.getPosition(),true)
        // });
        this.map.setFitView();
        // this.moveAnimationMarker.moveAlong(this.movePath, {
        //   autoRotation: true,
        //   // ...this.moveAlong
        // });
      });
    },
    moveStart() {
      const duration = 10000 / this.speedRatio;
      const movePath = this.movePath.map((x) => {
        return {
          ...x,
          duration: x.duration / Number(this.speedRatio),
        };
      });
      this.moveAnimationMarker.moveTo(movePath[this.currentIndex].position, {
        duration: 500,
        // delay: 500,
        autoRotation: false,
      });
      if (this.timer) clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        if (this.currentIndex > movePath.length - 1) {
          clearTimeout(this.timer);
        } else {
          this.currentIndex++;
          this.moveStart();
        }
      }, duration);
      // movePath.forEach(item=>{
      //   this.moveAnimationMarker.moveTo(item.position,{
      //     duration: 500,
      //     // autoRotation: true,
      //     ...this.moveAlong
      //   })
      // })
      // this.moveAnimationMarker.moveAlong(movePath, this.moveAlong);
    },
    pauseMove() {
      // this.moveAnimationMarker.pauseMove();
      if (this.timer) clearTimeout(this.timer);
    },
    resumeMove() {
      // this.moveAnimationMarker.resumeMove();
      this.moveStart();
    },
    stopMove() {
      // this.moveAnimationMarker.stopMove();
      this.currentIndex = 0;
      if (this.timer) clearTimeout(this.timer);
    },
    backStep() {
      if (this.currentIndex <= 0) return false;
      this.currentIndex--;
      // const position = this.movePath[this.currentIndex]?.position;
      clearTimeout(this.timer);
      this.moveStart();
    },
    nextStep() {
      if (this.currentIndex >= this.movePath.length) return false;
      clearTimeout(this.timer);
      this.currentIndex++;
      this.moveStart();
    },
    toggleTraffic() {
      this.trafficLayerVisible = !this.trafficLayerVisible;
      if (this.trafficLayerVisible) {
        this.trafficLayer.show();
      } else {
        this.trafficLayer.hide();
      }
    },
    locationInContain(lng, lat) {
      const myLngLat = this.currentLocation.position; // 浏览器定位
      const circle = new this.AMap.Circle({
        center: new this.AMap.LngLat(lng, lat), // 圆心位置--企业经纬度
        radius: 500, // 圆半径，单位:米
      });
      if (circle.contains(myLngLat)) {
        this.appLoadingMask.close();
      } else {
        this.$message.error("您已超出调度范围，请在设定位置500米范围内进行调度");
      }
    },
  },
  mounted() {
    //init map after DOM rendered
    this.initMap();
  },
  destroyed() {
    this.map.destroy();
  },
};
</script>

<style scoped></style>
