<template>
  <div id="mapDiv" class="container">
    <div class="editBar" v-if="isModify">
      <div
        :class="[isAdd ? 'map-add' : 'map-stop', { 'map-grey': isGrey }]"
        :id="[isAdd ? 'add1' : 'stop1']"
        @click="drawFeature()"
      ></div>
      <div
        :class="[isEdit ? 'map-edit' : 'map-stop', { 'map-grey': isGrey }]"
        @click="editFeature()"
      ></div>
      <div
        :class="[isDel ? 'map-del' : 'map-stop', { 'map-grey': isGrey }]"
        @click="deleteFeature()"
      ></div>
    </div>
  </div>
</template>

<script>
import esriLoader from "esri-loader";
// 高德
import remoteLoad from "../tsl-map/js/remoteLoad";
import CoordsConvertUtil from "../tsl-map/js/CoordsConvert";
let toolbar, editToolbar;

export default {
  name: "TslMapPlotting",
  props: {
    districtname: {
      type: [String],
      default: "",
    },
    // 地图是否可编辑
    isModify: {
      type: Boolean,
      default: true,
    },
    mapData: {
      type: Object,
      default: null,
    },
    // 围栏坐标 默认是84坐标系
    fence: {
      type: String,
      default: "",
    },
    mapParams: {
      type: Object,
      default: null,
    },
  },
  data() {
    return {
      baseMapURL:
        "http://10.207.204.29:80/OneMapServer/rest/services/DARK_SHMAP/MapServer?token=",
      map: null,
      spatialRef: null,
      mouseTool: null,
      drawingFeatures: [],
      polyEditors: [],
      clickedFeature: null,
      exhibition: false,
      level: {
        0: "province",
        1: "city",
        2: "district",
        3: "street",
      },
      zoomLevel: {
        0: 6,
        1: 8,
        2: 9,
        3: 15,
      },
      drawingFuc: "point",
      isMultiple: true,
      isDrawing: false,
      isAdd: true,
      isEdit: true,
      isDel: true,
      isGrey: false, // 灰掉
      keyword: "设备",
      clickCount: 0,
      contextMenu: null,
      drawingListener: null,
      districtLayer: null,
      drawingLayer: null,
      globalPoly: null,
      globalPaths: [],
      globaldistrictPaths: [],
      isPointInRing: true,
      isRingInRing: true,
      districtName: "", // 区名字
    };
  },
  destroyed() {
    if (this.mapParams.mapType === "ESRI") {
      if (this.drawingLayer.graphics.length > 0) {
        this.drawingLayer.clear();
      }
      this.map.destroy();
    } else if (this.mapParams.mapType === "GD") {
      if (this.drawingFeatures > 0) {
        this.drawingFeatures.splice(0, this.drawingFeatures.length);
        this.polyEditors.splice(0, this.polyEditors.length);
        this.clickCount = 0;
      }
      this.map.clearMap();
    }
  },
  mounted() {
    let that = this;
    if (this.mapParams.mapType === "ESRI") {
      // if (this.mapParams.tokenUrl_dahoutai) {
      //   this.Http({
      //     async: true,
      //     url: this.mapParams.tokenUrl_dahoutai,
      //     success: function (data) {
      //       let GLOBAL_TOKEN = data.substr(0, data.length - 2)
      //       that.mapParams.url += GLOBAL_TOKEN
      that.initMap(function() {
        that.mapState();
        that.$emit("mapLoaded");
        // that.$bus.on("/map/setLongLatitude", () => {
        //   that.mapState();
        // });
      });
      //     },
      //     error: function (error) {
      //       console.log(error)
      //     }
      //   }, 'get')
      // }
    } else if (this.mapParams.mapType === "GD") {
      // 初始化地图
      this.initMap(function() {
        that.mapState();
        that.$emit("mapLoaded");
      });
      //   that.$bus.on("/map/setLongLatitude", () => {
      //     that.mapState();
      //   });
    }
  },
  watch: {
    districtname(newval, oldval) {
      window.AMap.plugin("AMap.DistrictSearch", function() {
        let district = new window.AMap.DistrictSearch();
        district.setLevel("district");
        district.setExtensions("all");
        district.search(newval, (status, result) => {
          if (status === "complete") {
            this.globaldistrictPaths = result.districtList[0].boundaries;
          }
        });
      });
    },
    fence(newval, oldval) {
      if (this.map != null && newval != "" && newval != null) {
        this.fenceDraw();
      }
    },
  },
  methods: {
    mapState() {
      if (this.mapParams.mapType === "ESRI") {
        esriLoader
          .loadModules([
            "esri/geometry/Point",
            "esri/graphic",
            "esri/geometry/Polygon",
            "esri/geometry/Polyline",
            "esri/symbols/SimpleLineSymbol",
            "esri/symbols/SimpleFillSymbol",
            "esri/Color",
            "esri/symbols/SimpleMarkerSymbol",
          ])
          .then(
            ([
              Point,
              Graphic,
              Polygon,
              Polyline,
              SimpleLineSymbol,
              SimpleFillSymbol,
              Color,
              SimpleMarkerSymbol,
            ]) => {
              if (this.mapData) {
                if (this.drawingLayer.graphics.length > 0) {
                  this.drawingLayer.clear();
                }
                switch (this.mapData.state) {
                  case "point":
                    this.drawingFuc = "point";
                    if (this.mapData.output) {
                      for (
                        let i = 0, len = this.mapData.output.length;
                        i < len;
                        i++
                      ) {
                        if (
                          this.mapData.output[i].center.length > 0 &&
                          (this.mapData.output[i].center[0] != null ||
                            this.mapData.output[i].center[1] != null)
                        ) {
                          let pt = new Point(
                            this.mapData.output[i].center[0],
                            this.mapData.output[i].center[1],
                            this.spatialRef
                          );
                          let symbolPoint = new SimpleMarkerSymbol()
                            .setStyle(SimpleMarkerSymbol.STYLE_SQUARE)
                            .setColor(new Color([255, 0, 0, 0.5]));
                          symbolPoint.setPath(
                            "M16,4.938c-7.732,0-14,4.701-14,10.5c0,1.981,0.741,3.833,2.016,5.414L2,25.272l5.613-1.44c2.339,1.316,5.237,2.106,8.387,2.106c7.732,0,14-4.701,14-10.5S23.732,4.938,16,4.938zM16.868,21.375h-1.969v-1.889h1.969V21.375zM16.772,18.094h-1.777l-0.176-8.083h2.113L16.772,18.094z"
                          );
                          symbolPoint.setColor(new Color("#00FF00"));
                          let marker = new Graphic(pt, symbolPoint);
                          // this.map.centerAt(pt)
                          this.map.centerAndZoom(pt, 4);
                          this.map.resize();
                          this.map.reposition();
                          this.drawingLayer.add(marker);
                        }
                      }
                    }
                    break;
                  case "line":
                    this.drawingFuc = "line";
                    if (this.mapData.output) {
                      for (
                        let i = 0, len = this.mapData.output.length;
                        i < len;
                        i++
                      ) {
                        if (this.mapData.output[i].path !== "") {
                          let paths = JSON.parse(this.mapData.output[i].path);
                          let mline = new Polyline(paths);
                          let marker = new Graphic(mline);
                          let fSymbol = new SimpleLineSymbol(
                            "solid",
                            "#3B00FF",
                            2
                          );
                          marker.setSymbol(fSymbol);

                          this.drawingLayer.add(marker);
                        }
                      }
                    }
                    break;
                  case "polygon":
                    this.drawingFuc = "polygon";
                    if (this.mapData.output) {
                      for (
                        let i = 0, len = this.mapData.output.length;
                        i < len;
                        i++
                      ) {
                        if (this.mapData.output[i].path !== "") {
                          let paths = JSON.parse(this.mapData.output[i].path);
                          let polygon = new Polygon(paths);
                          let marker = new Graphic(polygon);
                          let fSymbol = new SimpleFillSymbol(
                            SimpleFillSymbol.STYLE_SOLID,
                            new SimpleLineSymbol("solid", "#3B00FF", 2),
                            new Color([0, 0, 255, 0.15])
                          );
                          marker.setSymbol(fSymbol);
                          this.drawingLayer.add(marker);
                          let pt = new Point(
                            polygon.getCentroid().x,
                            polygon.getCentroid().y,
                            this.spatialRef
                          );
                          // this.map.centerAt(pt)
                          this.map.centerAndZoom(pt, 4);
                          this.map.resize();
                          this.map.reposition();
                        }
                      }
                    }
                    break;
                }

                // this.isMultiple = this.mapData.isMultiple
                // this.keyword = this.mapData.keyword
              }
            }
          );
      } else if (this.mapParams.mapType === "GD") {
        if (this.mapData) {
          if (this.drawingLayer.getOverlays().length > 0) {
            this.drawingLayer.clearOverlays();
            this.drawingFeatures.splice(0, this.drawingFeatures.length);
          }
          switch (this.mapData.state) {
            case "point":
              this.drawingFuc = "point";
              if (this.mapData.output) {
                for (
                  let i = 0, len = this.mapData.output.length;
                  i < len;
                  i++
                ) {
                  if (
                    this.mapData.output[i].center.length > 0 &&
                    (this.mapData.output[i].center[0] != null ||
                      this.mapData.output[i].center[1] != null)
                  ) {
                    let pos = CoordsConvertUtil.wgs84ToGaode([this.mapData.output[i].center]);
                    let marker = new window.AMap.Marker({
                      content: '<div class ="marker-point"></div>',
                      raiseOnDrag: true,
                      position: new window.AMap.LngLat(pos[0][0], pos[0][1]),
                      bubble: true,
                    });
                    if (this.mapData.isMultiple) {
                      marker.setExtData(i + 1);
                    }
                    marker.on("rightclick", (e) => {
                      if (!this.isDel) {
                        this.contextMenu.open(this.map, e.lnglat);
                        this.clickedFeature = e.target;
                      }
                    });
                    this.drawingLayer.addOverlay(marker);
                    this.drawingFeatures.push(marker);
                  }
                }
                this.map.setFitView(this.drawingFeatures);
                this.clickCount = this.mapData.output.length;
              }
              break;
            case "line":
              this.drawingFuc = "line";
              if (this.mapData.output) {
                for (
                  let i = 0, len = this.mapData.output.length;
                  i < len;
                  i++
                ) {
                  if (this.mapData.output[i].path !== "") {
                    let paths = JSON.parse(this.mapData.output[i].path);
                    paths = CoordsConvertUtil.wgs84ToGaode(paths);
                    let mline = new window.AMap.Polyline({
                      path: paths,
                      strokeColor: "#3B00FF",
                      strokeWeight: 2,
                      bubble: true,
                    });
                    mline.on("rightclick", (e) => {
                      if (!this.isDel) {
                        this.contextMenu.open(this.map, e.lnglat);
                        this.clickedFeature = e.target;
                      }
                    });
                    this.drawingLayer.addOverlay(mline);
                    this.drawingFeatures.push(mline);
                  }
                  this.clickCount = this.mapData.output.length;
                  this.map.setFitView(this.drawingFeatures);
                }
              }
              break;
            case "polygon":
              this.drawingFuc = "polygon";
              if (this.mapData.output) {
                for (
                  let i = 0, len = this.mapData.output.length;
                  i < len;
                  i++
                ) {
                  if (
                    this.mapData.output[i].path !== "" &&
                    this.mapData.output[i].path !== null
                  ) {
                    let paths = JSON.parse(this.mapData.output[i].path);
                    paths = CoordsConvertUtil.wgs84ToGaode(paths);
                    let polygon = new window.AMap.Polygon({
                      fillColor: "#FFFFFF",
                      fillOpacity: 0.5,
                      strokeColor: "#3B00FF",
                      strokeWeight: 2,
                      path: paths,
                      bubble: true,
                    });
                    polygon.on("rightclick", (e) => {
                      if (!this.isDel) {
                        this.contextMenu.open(this.map, e.lnglat);
                        this.clickedFeature = e.target;
                      }
                    });
                    this.drawingFeatures.push(polygon);
                    this.drawingLayer.addOverlay(polygon);
                  }
                }
                this.clickCount = this.mapData.output.length;
                this.map.setFitView(this.drawingFeatures);
              }
              break;
          }
          this.isMultiple = this.mapData.isMultiple;
          this.keyword = this.mapData.keyword;
          if (this.mapData.exhibition)
            this.exhibition = this.mapData.exhibition;
        }
      }
    },
    initMap(callbackEvent) {
      let that = this;
      const options = {
        url: that.mapParams.apiUrl,
      };
      if (that.mapParams.mapType === "ESRI") {
        esriLoader.loadScript(options).then(function() {
          esriLoader.loadCss(that.mapParams.apiCss);
          esriLoader
            .loadModules([
              "esri/map",
              "esri/geometry/Extent",
              "esri/toolbars/draw",
              "esri/toolbars/edit",
              "esri/layers/ArcGISTiledMapServiceLayer",
              "esri/layers/GraphicsLayer",
              "esri/graphic",
              "esri/geometry/Point",
              "esri/symbols/SimpleMarkerSymbol",
              "esri/symbols/SimpleLineSymbol",
              "esri/symbols/SimpleFillSymbol",
              "esri/SpatialReference",
              "esri/Color",
              "esri/layers/FeatureLayer",
              "esri/renderers/SimpleRenderer",
              "esri/renderers/UniqueValueRenderer",
              "esri/symbols/TextSymbol",
              "esri/symbols/Font",
              "esri/layers/LabelClass",
            ])
            .then(
              ([
                Map,
                Extent,
                Draw,
                Edit,
                ArcGISTiledMapServiceLayer,
                GraphicsLayer,
                Graphic,
                Point,
                SimpleMarkerSymbol,
                SimpleLineSymbol,
                SimpleFillSymbol,
                SpatialReference,
                Color,
                FeatureLayer,
                SimpleRenderer,
                UniqueValueRenderer,
                TextSymbol,
                Font,
                LabelClass,
              ]) => {
                that.map = new Map("mapDiv", {
                  logo: false,
                  slider: false,
                  fitExtent: true,
                  showLabels: true,
                  autoResize: true,
                  // extent: new Extent({
                  //   xmin: -13316.678500000387,
                  //   ymin: -6166.42689999938,
                  //   xmax: -3084.0087999999523,
                  //   ymax: 1161.8869000002742
                  // }),
                  // zoom: 6
                });

                that.spatialRef = new SpatialReference({ wkid: 4326 });
                let spatialRefName;
                if (that.mapParams.spatialReference) {
                  spatialRefName = that.mapParams.spatialReference.name;
                }
                switch (spatialRefName) {
                  case "sh_54":
                    that.spatialRef = new SpatialReference(
                      that.mapParams.spatialReference.content
                    );
                    break;
                }
                // that.map.centerAndZoom(new Point(-8608.602249756555, -3204.8339660667316, that.spatialRef), 3)
                that.map.resize();
                that.map.reposition();
                let baseMapLayer = new ArcGISTiledMapServiceLayer(
                  that.mapParams.url
                );
                that.map.addLayer(baseMapLayer);
                that.districtLayer = new GraphicsLayer();
                that.drawingLayer = new GraphicsLayer({ id: "drawlayer" });
                that.map.addLayer(that.districtLayer);
                that.map.addLayer(that.drawingLayer);


                toolbar = new Draw(that.map);
                toolbar.on("draw-complete", that.addToMap);
                editToolbar = new Edit(that.map);
                return Promise.resolve(that.map);
              }
            )
            .then(function(map) {
              callbackEvent(that.map);
            })
            .catch((err) => {
              console.error(err);
              callbackEvent(null);
            });
        });
      } else if (this.mapParams.mapType === "GD") {
        remoteLoad(this.mapParams.url).then(function() {
          setTimeout(() => {
            that.map = new window.AMap.Map("mapDiv", {
              resizeEnable: true,
              zoom: 13,
            });
            that.districtLayer = new window.AMap.OverlayGroup();
            that.drawingLayer = new window.AMap.OverlayGroup();
            that.map.add(that.districtLayer);
            that.map.add(that.drawingLayer);

            that.contextMenu = new window.AMap.ContextMenu();
            that.contextMenu.addItem("删除", that.deleteOne, 0);
            that.map.on("resize", function(e) {
              let oldSize = e.oldsize;
              let newSize = e.newsize;
              if (
                oldSize.width !== newSize.width &&
                oldSize.height !== newSize.height
              ) {
                if (that.districtLayer.getOverlays().length > 0) {
                  that.map.setFitView(that.districtLayer.getOverlays());
                } else {
                  that.map.setFitView(that.drawingFeatures);
                }
              }
            });
            that.map.on("click", function(e) {
              if (
                that.drawingFeatures.length >= 1 &&
                !that.isMultiple &&
                !that.isAdd
              ) {
                that.$emit(
                  "message",
                  "warning",
                  "该" + that.keyword + "坐标已添加!"
                );
                that.isDrawing = false;
                that.endDrawing();
              }
            });
            that.fenceDraw();
            if (that.districtname !== "") {
              window.AMap.plugin("AMap.DistrictSearch", function() {
                let district = new window.AMap.DistrictSearch();
                district.setLevel("district");
                district.setExtensions("all");
                district.search(that.districtname, function(status, result) {
                  if (status === "complete") {
                    that.globaldistrictPaths =
                      result.districtList[0].boundaries;
                  }
                });
              });
            }
            callbackEvent(that.map);
          }, 400);
        });
      }
    },
    fenceDraw() {
      if (this.districtLayer.getOverlays().length > 0) {
        this.districtLayer.clearOverlays();
      }
      if (this.fence !== "") {
        let paths = JSON.parse(this.fence);
        paths = CoordsConvertUtil.wgs84ToGaode(paths);
        this.globalPaths = paths;
        let poly = new window.AMap.Polyline({
          path: paths,
          strokeColor: "#0091ea",
          strokeWeight: 3,
        });
        this.districtLayer.addOverlay(poly);
        this.map.setFitView(poly);
      }
    },
    initToolbar(Draw, Point, SimpleMarkerSymbol, Graphic, Edit) {
      let that = this;
      that.map.centerAndZoom(new Point(-961, -9741, that.spatialRef), 5);
      that.map.resize();
      that.map.reposition();
      toolbar = new Draw(that.map);
      toolbar.on("draw-complete", that.addToMap);
      editToolbar = new Edit(that.map);
    },
    activateToolbar(graphic) {
      let tool = 15;
      // tool = tool | Edit.MOVE
      // tool = tool | Edit.EDIT_VERTICES
      // tool = tool | Edit.SCALE
      // tool = tool | Edit.ROTATE
      let options = {
        allowAddVertices: true,
        allowDeleteVertices: true,
        uniformScaling: true,
      };
      editToolbar.activate(tool, graphic, options);
    },
    addToMap(evt) {
      esriLoader
        .loadModules([
          "esri/layers/GraphicsLayer",
          "esri/geometry/Point",
          "esri/graphic",
          "esri/symbols/PictureMarkerSymbol",
          "esri/symbols/TextSymbol",
          "esri/symbols/SimpleLineSymbol",
          "esri/symbols/SimpleFillSymbol",
          "esri/SpatialReference",
          "esri/symbols/Font",
          "esri/Color",
          "esri/symbols/SimpleMarkerSymbol",
        ])
        .then(
          ([
            GraphicsLayer,
            Point,
            Graphic,
            PictureMarkerSymbol,
            TextSymbol,
            SimpleLineSymbol,
            SimpleFillSymbol,
            SpatialReference,
            Font,
            Color,
            SimpleMarkerSymbol,
          ]) => {
            let symbol;

            switch (evt.geometry.type) {
              case "point":
                symbol = new SimpleMarkerSymbol();
                symbol.setPath(
                  "M16,4.938c-7.732,0-14,4.701-14,10.5c0,1.981,0.741,3.833,2.016,5.414L2,25.272l5.613-1.44c2.339,1.316,5.237,2.106,8.387,2.106c7.732,0,14-4.701,14-10.5S23.732,4.938,16,4.938zM16.868,21.375h-1.969v-1.889h1.969V21.375zM16.772,18.094h-1.777l-0.176-8.083h2.113L16.772,18.094z"
                );
                symbol.setColor(new Color("#00FF00"));
                break;
              case "multipoint":
                symbol = new SimpleMarkerSymbol();
                symbol.setPath(
                  "M16,4.938c-7.732,0-14,4.701-14,10.5c0,1.981,0.741,3.833,2.016,5.414L2,25.272l5.613-1.44c2.339,1.316,5.237,2.106,8.387,2.106c7.732,0,14-4.701,14-10.5S23.732,4.938,16,4.938zM16.868,21.375h-1.969v-1.889h1.969V21.375zM16.772,18.094h-1.777l-0.176-8.083h2.113L16.772,18.094z"
                );
                symbol.setColor(new Color("#00FF00"));
                break;
              case "polyline":
                symbol = new SimpleLineSymbol();
                break;
              default:
                symbol = new SimpleFillSymbol(
                  SimpleFillSymbol.STYLE_SOLID,
                  new SimpleLineSymbol("solid", "#3B00FF", 2),
                  new Color([0, 0, 255, 0.15])
                );
                break;
            }
            let graphic = new Graphic(evt.geometry, symbol);
            this.drawingLayer.add(graphic);
          }
        );
    },
    drawFeature() {
      if (this.isAdd && this.isGrey) {
        return;
      }
      this.isAdd = !this.isAdd;
      this.isGrey = !this.isGrey;
      if (this.mapParams.mapType === "ESRI") {
        if (
          !this.isAdd &&
          !this.isMultiple &&
          this.drawingLayer.graphics.length > 0
        ) {
          this.$emit("warning", "该" + this.keyword + "坐标已添加!");
          return;
        }
        if (!this.isAdd) {
          toolbar.activate(this.drawingFuc);
        } else {
          toolbar.deactivate();
          this.formatePath();
        }
      } else if (this.mapParams.mapType === "GD") {
        if (
          !this.isAdd &&
          !this.isMultiple &&
          this.drawingFeatures.length > 0
        ) {
          this.$emit("warning", "该" + this.keyword + "坐标已添加!");
          return;
        }
        if (!this.isAdd) {
          switch (this.drawingFuc) {
            case "point":
              this.drawPoint();
              break;
            case "line":
              this.drawPolyline();
              break;
            case "polygon":
              this.drawPolygon();
              break;
          }
        } else {
          this.endDrawing();
          // if (!this.isMultiple) { this.clickCount = 0 }
          this.formatePath();
        }
      }
    },
    editFeature() {
      if (this.isPointInRing && this.isRingInRing) {
        if (this.isEdit && this.isGrey) {
          return;
        }
        this.isEdit = !this.isEdit;
        this.isGrey = !this.isGrey;
        if (this.mapParams.mapType === "ESRI") {
          esriLoader.loadModules(["dojo/_base/event"]).then(([event]) => {
            let that = this;
            if (!that.isEdit) {
              this.drawingLayer.on("click", function(evt) {
                if (!that.isEdit && that.isDel) {
                  event.stop(evt);
                  that.activateToolbar(evt.graphic);
                } else if (that.isEdit && !that.isDel) {
                  that.drawingLayer.clear();
                }
              });
            } else {
              that.map.setMapCursor("default");
              editToolbar.deactivate();
              this.formatePath();
            }
          });
        } else if (this.mapParams.mapType === "GD") {
          switch (this.drawingFuc) {
            case "point":
              this.editFeaturePoint();
              break;
            case "line":
            case "polygon":
              this.editFeaturePoly();
              break;
          }
        }
      } else {
        this.$emit("warning", "请在围栏范围内修改坐标!");
      }
    },
    deleteFeature() {
      let that = this;
      if (this.isDel && this.isGrey) {
        return;
      }
      this.isDel = !this.isDel;
      this.isGrey = !this.isGrey;
      if (!this.isDel) {
        if (this.mapParams.mapType === "ESRI") {
          this.$emit("warning", "鼠标选中删除！");
          this.drawingLayer.on("click", function(evt) {
            if (!that.isEdit && this.isDel && !this.isGrey) {
              event.stop(evt);
              that.activateToolbar(evt.graphic);
            } else if (that.isEdit && !that.isDel) {
              that.drawingLayer.clear();
            }
          });
        } else if (this.mapParams.mapType === "GD") {
          this.$emit("warning", "鼠标右键点击删除！");
        }
      } else {
        this.formatePath();
      }
    },
    endDrawing() {
      if (this.mouseTool !== null) {
        this.mouseTool.close(false);
      }
    },
    drawPolygon() {
      let that = this;
      this.$emit("message", "warning", "双击结束绘制！");
      that.isEnable = !that.isEnable;
      window.AMap.plugin("AMap.MouseTool", function() {
        if (that.mouseTool === null) {
          that.mouseTool = new window.AMap.MouseTool(that.map);
        }
        that.map.setDefaultCursor("default");
        that.mouseTool.polygon({
          fillColor: "#FFFFFF",
          strokeColor: "#3B00FF",
          fillOpacity: 0.5,
          strokeWeight: 2,
        });
        that.isDrawing = true;
        that.getdrawingFeatures();
      });
    },
    drawPolyline() {
      let that = this;
      this.$emit("message", "warning", "双击结束绘制！");
      window.AMap.plugin("AMap.MouseTool", function() {
        that.mouseTool = new window.AMap.MouseTool(that.map);
        that.map.setDefaultCursor("default");
        that.mouseTool.polyline({ strokeColor: "#3B00FF", strokeWeight: 2 });
        that.isDrawing = true;
        that.getdrawingFeatures();
      });
    },
    drawPoint() {
      let that = this;
      window.AMap.plugin("AMap.MouseTool", function() {
        that.mouseTool = new window.AMap.MouseTool(that.map);
        that.map.setDefaultCursor("default");
        let content = '<div class ="marker-point"></div>';
        if (that.isMultiple) {
          content =
            '<div class ="marker-point-multi"><p style ="font-size: 14px; color: #fff; text-align:center; font-weight:bold;">' +
            (that.clickCount + 1) +
            "</p></div>";
        }
        that.mouseTool.marker({
          content: content,
          raiseOnDrag: true,
          extData: that.clickCount + 1,
        });
        that.isDrawing = true;
        that.getdrawingFeatures();
      });
    },
    editFeaturePoly() {
      let that = this;
      if (!that.isEdit) {
        window.AMap.plugin("AMap.PolyEditor", () => {
          for (let i = 0, len = that.drawingFeatures.length; i < len; i++) {
            var pyEditor = new window.AMap.PolyEditor(
              that.map,
              that.drawingFeatures[i]
            );
            pyEditor.open();
            that.polyEditors.push(pyEditor);
            pyEditor.on("adjust", (event) => {
              // let evArray = event.target.getPath();
              // let points = [];
              // if (that.globalPaths.length !== 0) {
              //   for (let i = 0; i < evArray.length; i++) {
              //     points.push(
              //       window.AMap.GeometryUtil.isPointInRing(
              //         evArray[i],
              //         that.globalPaths
              //       )
              //     );
              //   }
              //   that.isPointInRing = points.every((item) => {
              //     return item === true;
              //   });
              // }
              // if (that.globaldistrictPaths.length !== 0) {
              //   for (let i = 0; i < evArray.length; i++) {
              //     console.log('111111')
              //     points.push(
              //       window.AMap.GeometryUtil.isPointInRing(
              //         evArray[i],
              //         that.globaldistrictPaths
              //       )
              //     );
              //   }
              //   that.isRingInRing = points.every((item) => {
              //     return item === true;
              //   });
              // }
            });
          }
        });
      } else {
        that.endEditPoly();
        that.formatePath();
      }
    },
    editFeaturePoint() {
      if (!this.isEdit) {
        let markers = this.drawingFeatures;
        let that = this;
        for (let i = 0, len = markers.length; i < len; i++) {
          markers[i].setDraggable(true);
          markers[i].on("dragstart", function(item) {
            if (!that.isMultiple) {
              markers[i].setContent(
                '<div class = "marker-point-selected"></div>'
              );
            } else {
              markers[i].setContent(
                '<div class ="marker-point-multi-selected"><p style ="font-size: 14px; color: #fff; text-align:center; font-weight:bold;">' +
                  item.target.getExtData() +
                  "</p></div>"
              );
            }
          });
          markers[i].on("dragend", function(item) {
            that.isPointInRing = window.AMap.GeometryUtil.isPointInRing(
              item.lnglat,
              that.globalPaths
            );
            if (that.isPointInRing) {
              if (!that.isMultiple) {
                markers[i].setContent('<div class = "marker-point"></div>');
              } else {
                markers[i].setContent(
                  '<div class ="marker-point-multi"><p style ="font-size: 14px; color: #fff; text-align:center; font-weight:bold;">' +
                    item.target.getExtData() +
                    "</p></div>"
                );
              }
            } else {
              that.$emit("message", "warning", "请在围栏范围内修改坐标!");
            }
          });
        }
      } else {
        this.endEditPoint();
        this.formatePath();
      }
    },
    endEditPoint() {
      let path = [];
      for (let i = 0; i < this.drawingFeatures.length; i++) {
        this.drawingFeatures[i].setDraggable(false);
        path.push(this.drawingFeatures[i].getPosition());
      }
      if (this.mouseTool != null) {
        this.mouseTool.close(false);
      }
    },
    endEditPoly() {
      this.map.setDefaultCursor("grab");
      // console.log(this.polyEditors.getPath())
      for (let i = 0; i < this.polyEditors.length; i++) {
        this.polyEditors[i].close();
        // this.polyEditors[i].on('end', (event) => {
        //   console.log(event.target.getPath())
        //   let points = []
        //   for (let i = 0; i < event.target.getPath().length; i++) {
        //     points.push(window.AMap.GeometryUtil.isPointInRing(event.target.getPath()[i], this.globalPaths))
        //   }
        //   this.isPointInRing = points.every(item => { return item === true })
        //   console.log(this.isPointInRing)
        // })
      }
      for (let i = 0; i < this.drawingFeatures.length; i++) {
        this.polyEditors[i].close();
        // this.polyEditors[i].on('end', (event) => {
        //   console.log(event.target.getPath(), 'event')
        //   // event.target 即为编辑后的折线对象
        // })
      }
    },
    deleteOne() {
      this.map.remove(this.clickedFeature);
      let index = this.drawingFeatures.indexOf(this.clickedFeature);
      if (index !== -1) {
        this.drawingFeatures.splice(index, 1);
        if (this.drawingFuc === "line" || this.drawingFuc === "polygon") {
          this.polyEditors.splice(index, 1);
        }
      }
    },
    getdrawingFeatures() {
      let that = this;
      that.drawingListener = window.AMap.event.addListener(
        this.mouseTool,
        "draw",
        function(e) {
          that.drawingFeatures.push(e.obj);
          let isPointInRing = true;
          if (that.drawingFuc === "point") {
            isPointInRing = window.AMap.GeometryUtil.isPointInRing(
              e.obj.getPosition(),
              that.globalPaths
            );
          } else {
            let points = [];
            for (let i = 0; i < e.obj.getPath().length; i++) {
              if (that.globalPaths.length !== 0) {
                points.push(
                  window.AMap.GeometryUtil.isPointInRing(
                    e.obj.getPath()[i],
                    that.globalPaths
                  )
                );
              }
            }
            isPointInRing = points.every((item) => {
              return item === true;
            });
          }
          if (isPointInRing) {
            e.obj.on("rightclick", function(e) {
              if (!that.isDel) {
                that.contextMenu.open(that.map, e.lnglat);
                that.clickedFeature = e.target;
              }
            });
            that.clickCount += 1;
            if (that.drawingFuc === "point") {
              that.mouseTool.marker({
                content:
                  '<div class ="marker-point-multi"><p style ="font-size: 14px; color: #fff; text-align:center; font-weight:bold;">' +
                  (that.clickCount + 1) +
                  "</p></div>",
                raiseOnDrag: true,
                extData: that.clickCount + 1,
              });
            }

            if (!that.isMultiple && that.drawingFeatures.length > 1) {
              that.map.remove(that.drawingFeatures[1]);
              that.drawingFeatures.splice(1, 1);
            }
          } else {
            if (that.drawingFeatures.length === 1) {
              that.map.remove(
                that.drawingFeatures[that.drawingFeatures.length - 1]
              );
              that.drawingFeatures = [];
            } else {
              that.map.remove(
                that.drawingFeatures[that.drawingFeatures.length - 1]
              );
            }
            that.$emit("message", "warning", "请在围栏范围内添加坐标!");
          }
        }
      );
    },
    formatePath() {
      let exportsLoc = [];
      if (this.mapParams.mapType === "ESRI") {
        for (let i = 0, len = this.drawingLayer.graphics.length; i < len; i++) {
          let obj = {
            center: [],
            path: "",
          };
          let paths;
          let centerX = 0;
          let centerY = 0;
          switch (this.drawingFuc) {
            case "point":
              paths = JSON.stringify([
                this.drawingLayer.graphics[i].geometry.x,
                this.drawingLayer.graphics[i].geometry.y,
              ]);
              obj.center = [
                this.drawingLayer.graphics[i].geometry.x,
                this.drawingLayer.graphics[i].geometry.y,
              ];
              break;
            case "line":
              paths = this.drawingLayer.graphics[0].geometry.paths[i];
              let linePath = paths.map(function(item) {
                return [item.lng, item.lat];
              });
              for (let i = 0, len = linePath.length; i < len; i++) {
                centerX += linePath[i][0];
                centerY += linePath[i][1];
              }
              obj.center = [
                centerX / linePath.length,
                centerY / linePath.length,
              ];
              obj.path = JSON.stringify(
                this.drawingLayer.graphics[0].geometry.paths[0]
              );
              break;
            case "polygon":
              obj.center = [
                this.drawingLayer.graphics[0].geometry.getCentroid().x,
                this.drawingLayer.graphics[0].geometry.getCentroid().y,
              ];
              obj.path = JSON.stringify(
                this.drawingLayer.graphics[0].geometry.rings[0]
              );
              break;
          }
          exportsLoc.push(obj);
        }
      } else if (this.mapParams.mapType === "GD") {
        if (this.mouseTool !== null) {
          window.AMap.event.removeListener(this.drawingListener);
          this.mouseTool.close(false);
        }
        for (let i = 0, len = this.drawingFeatures.length; i < len; i++) {
          let obj = {
            center: [],
            path: "",
          };
          let paths;
          let outPut = [];
          let centerX = 0;
          let centerY = 0;
          switch (this.drawingFuc) {
            case "point":
              paths = this.drawingFeatures[i].getPosition();
              paths = CoordsConvertUtil.gaodeToWGS84([[paths.getLng(), paths.getLat()]]);
              obj.center = paths[0];
              break;
            case "line":
              paths = this.drawingFeatures[i].getPath();
              let linePath = paths.map(function(item) {
                return [item.lng, item.lat];
              });
              linePath = CoordsConvertUtil.gaodeToWGS84(linePath);
              for (let i = 0, len = linePath.length; i < len; i++) {
                outPut.push([linePath[i][0], linePath[i][1]]);
                centerX += linePath[i][0];
                centerY += linePath[i][1];
              }
              obj.center = [
                centerX / linePath.length,
                centerY / linePath.length,
              ];
              obj.path = JSON.stringify(outPut);
              break;
            case "polygon":
              paths = this.drawingFeatures[i].getPath();
              let polyPath = paths.map(function(item) {
                return [item.lng, item.lat];
              });
              polyPath = CoordsConvertUtil.gaodeToWGS84(polyPath);
              for (let i = 0, len = polyPath.length; i < len; i++) {
                outPut.push([polyPath[i][0], polyPath[i][1]]);
                centerX += polyPath[i][0];
                centerY += polyPath[i][1];
              }
              outPut.push(outPut[0]);
              obj.center = [
                centerX / polyPath.length,
                centerY / polyPath.length,
              ];
              obj.path = JSON.stringify(outPut);
              break;
          }
          exportsLoc.push(obj);
        }
      }
      this.$emit("exportLocation", exportsLoc);
    },
  },
};
</script>

<style>
.marker-point {
  width: 25px;
  height: 32px;
  background: url("./icon/normal.png") no-repeat center center;
  cursor: pointer;
  background-size: contain;
}
.marker-point-selected {
  width: 25px;
  height: 32px;
  background: url("./icon/selected.png") no-repeat center center;
  cursor: pointer;
  background-size: contain;
}
.marker-point-multi {
  width: 25px;
  height: 32px;
  background: url("./icon/normal_multi.png") no-repeat center center;
  cursor: pointer;
  background-size: contain;
}
.marker-point-multi-selected {
  width: 25px;
  height: 32px;
  background: url("./icon/selected_multi.png") no-repeat center center;
  cursor: pointer;
  background-size: contain;
}
</style>

<style scoped>
.container {
  height: 100%;
  width: 100%;
  position: relative;
}
.editBar {
  position: absolute;
  margin: 10px;
  z-index: 1;
}
.map-add {
  width: 24px;
  height: 24px;
  margin: 3px;
  background: url("./icon/add.png") no-repeat;
  background-size: 100% 100%;
  background-position: center center;
  cursor: pointer;
}
.map-edit {
  width: 24px;
  height: 24px;
  margin: 3px;
  background: url("./icon/edit.png") no-repeat;
  background-size: 100% 100%;
  background-position: center center;
  cursor: pointer;
}
.map-stop {
  opacity: 1 !important;
  cursor: pointer !important;
  width: 24px;
  height: 24px;
  margin: 3px;
  background: url("./icon/end.png") no-repeat;
  background-size: 100% 100%;
  background-position: center center;
}
.map-del {
  width: 24px;
  height: 24px;
  margin: 3px;
  background: url("./icon/delete.png") no-repeat;
  background-size: 100% 100%;
  background-position: center center;
  cursor: pointer;
}
.map-grey {
  opacity: 0.5;
  cursor: not-allowed;
}
</style>
