<template>
  <div class="MapViewer" ref="map"></div>
</template>
<script>
import publicFun from "@/utils/publicFunction.js";
export default {
  name: "Map",
  data() {
    return {
      map: "",
      layers: "",
      polygon: [],
      measureTool: ""
    };
  },
  mounted() {
    //地图初始化
    this.$nextTick(() => {
      this.mapInit();
      let that = this;
      this.map.on("move", e => {
        if (that.index == that.mouseIndex) {
          let center = that.map.getCenter();
          let zoom = that.map.getZoom();
          this.$emit("changeCenterZoom", {
            center: [center.lat, center.lng],
            zoom: zoom,
            index: that.index
          });
        }
      });
      // this.initDraw();
    });
  },
  props: ["mapUrl", "index", "centerZoom", "mouseIndex", "centerZoomInit"],
  destroy() {
    this.stopLabelCase();
  },
  methods: {
    // 初始化地图标记事件
    initDraw() {
      var defaultData = {
        action: "add",
        position: "topleft",
        offset: [0, 0],
        background: "#fff",
        color: "#000",
        font_size: "14px",
        closeButton: true
      };
      // 引入疑点标记绘制方法
      this.map.on("draw2-result", data => {
        let geoType = null;
        // 纬经度
        if (data && data.points.length >= 1) {
          // 类型: 0 点；1 线；2 面；3 矩形；4 圆形；5 其他；
          if (data.points.length === 1 && data.area === 0) {
            geoType = 0;
          }
          if (data.points.length === 2 && data.distance > 0) {
            geoType = 4;
          }
          if (data.points.length > 2 && data.area === 0) {
            geoType = 1;
          }
          if (data.points.length > 2 && data.area != 0 && data.area != "") {
            geoType = 2;
          }
        }
        // 首先保存数据，然后删除底图上的标记
        let coordinates = [data.points];
        let polygon = L.polygon(coordinates, {
          color: "red",
          weight: 3,
          fillColor: "red",
          opacity: 1,
          fillOpacity: 0
        }).addTo(this.map);

        polygon.on("click", e => {
          // polygon.setStyle({
          //   fillOpacity: 0.35
          // });
          // if (geometry.geometry && geometry.geometry.properties) {
          //   this.$store.state.mapMarkInfo = geometry.geometry.properties;
          // }
        });
        this.measureTool._measureGroup && this.measureTool._measureGroup.remove();
        // mousemove2Status = false;
        // this.map.doubleClickZoom.disable();
        // this.map.off("click");
        // if (this.measureTool.moveMarker) {
        //   this.map.removeLayer(this.measureTool.moveMarker);
        //   this.measureTool.moveMarker = null;
        // }
      });
      if (this.index == 0) {
        this.measureTool = new LControlDraw({
          position: defaultData.position,
          offset: defaultData.offset,
          background: defaultData.background,
          color: defaultData.color,
          font_size: defaultData.font_size,
          closeButton: defaultData.closeButton,
          iconUrl: "/static/plugins/draw-plugin/images/marker-icon.png"
        }).addTo(this.map);
      }
    },
    // 开始标记疑点事件
    startLabelCase() {
      this.measureTool.start();
    },
    // 停止标记疑点事件
    stopLabelCase() {
      this.map.off("draw2-result");
      if (this.measureTool) {
        // 移除绘制的图形
        this.measureTool._measureGroup && this.measureTool._measureGroup.remove();
        mousemove2Status = false;
        this.map.doubleClickZoom.disable();
        this.map.off("click");
        if (this.measureTool.moveMarker) {
          this.map.removeLayer(this.measureTool.moveMarker);
          this.measureTool.moveMarker = null;
        }
        this.measureTool.remove();
        this.measureTool = null;
      }
    },
    addSinglePolygon(state) {
      this.$nextTick(() => {
        if (!state && this.polygon) {
          this.polygon.forEach(item => {
            this.map.removeLayer(item);
          });
          this.addSinglePolygon(true);
        } else if (this.$store.state.selectSelectDataMap && this.$store.state.selectSelectDataMap.singlePolygon) {
          for (let item in this.$store.state.selectSelectDataMap.singlePolygon) {
            // 如果是叠置分析的图层处理方式this.$store.state.selectSelectDataMap.singlePolygon
            if (this.$store.state.selectSelectDataMap.singlePolygon[item][0].uniqueId.indexOf("overlay") > -1) {
              let uniqueId = this.$store.state.selectSelectDataMap.singlePolygon[item][0].uniqueId;
              let color = this.$store.state.selectSelectDataMap.singlePolygon[item][0].color;
              let statesArr = this.$store.state.selectSelectDataMap.singlePolygon[item].map(v => {
                return JSON.parse(v.geometry);
              });
              this.readGeojson(statesArr, color);
            } else {
              // 非叠置分析图层的处理方式
              let index = 0;
              this.$store.state.selectSelectDataMap.singlePolygon[item].forEach(v => {
                index++;
                let cid = v.cid + "_tpdb_" + index;
                let geometry = v.geometry;
                let coord = JSON.parse(geometry).geometry.coordinates;
                // 经纬度顺序转换
                let coordinates = publicFun.latLngsToReverse(coord);
                let polygon = L.polygon(coordinates, {
                  color: v.color,
                  weight: 3,
                  fillColor: v.color,
                  opacity: 1,
                  fillOpacity: 0
                }).addTo(this.map);
                polygon.on("click", e => {
                  // 鼠标点击图版高亮提示逻辑,暂时不用，如果需要的话就要
                  // this.polygonClick();
                  // if (
                  //   this.$store.state.map2DViewerPolygonsCid.newCid &&
                  //   this.polygon[this.$store.state.map2DViewerPolygonsCid.newCid]
                  // ) {
                  //   this.polygon[this.$store.state.map2DViewerPolygonsCid.newCid].setStyle({
                  //     color: this.$store.state.map2DViewerPolygonsCid.oldColor,
                  //     fillOpacity: 0
                  //   });
                  // }
                  // // 判断是否是重复点击，不是的话高亮，是的话不操作。
                  // if (cid != this.$store.state.map2DViewerPolygonsCid.newCid) {
                  //   this.$store.state.map2DViewerPolygonsCid = { newCid: cid, oldColor: v.color };
                  //   polygon.setStyle({
                  //     color: "red",
                  //     fillColor: "red",
                  //     fillOpacity: 0.35
                  //   });
                  // } else {
                  //   this.$store.state.map2DViewerPolygonsCid = { newCid: null, oldColor: null };
                  // }
                  if (v.geometry && JSON.parse(v.geometry).properties) {
                    this.$store.state.mapMarkInfo = JSON.parse(v.geometry).properties;
                  }
                });
                this.polygon[cid] = polygon;
              });
            }
          }
        }
      });
    },
    polygonClick() {},
    //geojson直接读取的坐标顺序是经纬度
    // 明天测试一下对不对
    readGeojson(geojsonArr, color) {
      let geojsonData = L.geoJSON(geojsonArr, {
        style: function (feature) {
          return { color: color };
        }
      }).addTo(this.map);
      this.polygon.push(geojsonData);
    },
    mapInit() {
      var crs = new L.Proj.CRS(
        "EPSG:0986",
        "+proj=tmerc +lat_0=0 +lon_0=121.2751921 +k=1 +x_0=0 +y_0=-3457147.81 +ellps=krass +units=m +no_defs",
        {
          resolutions: [
            132.2919312505292, 52.91677250021167, 26.458386250105836, 13.229193125052918, 5.291677250021167, 2.6458386250105836,
            1.3229193125052918, 0.5291677250021167, 0.26458386250105836, 0.13229193125052918, 0.0529167725002, 0.0264583862501,
            0.0132291931251, 0.00529167725, 0.002645838625, 0.0013229193125
          ],
          origin: [-66000, 75000],
          bounds: L.bounds([-65000, -76000], [75000, 72000])
        }
      );
      this.map = L.map(this.$refs.map, {
        crs: crs,
        zoom: 1,
        minZoom: 0,
        maxZoom: 14,
        attributionControl: false,
        zoomControl: false
      }).setView(map2DViewer.map.getCenter(), map2DViewer.map.getZoom());

      //添加默认图层
      let layer = this.$store.state.mapMethodsCollection.get("RENDER").addTiledMapLayer(this.mapUrl);
      this.layers = layer;
    },
    setView: function (coord, zoom) {
      this.$nextTick(() => {
        let center = L.latLng(coord[0], coord[1]);
        this.map.setView(center, zoom);
      });
    },
    // 更改地图渲染个数
    changeMapSize() {
      this.$nextTick(() => {
        if (this.map) {
          this.map.removeLayer(this.layers);
          let layer = this.$store.state.mapMethodsCollection.get("RENDER").addTiledMapLayer(this.mapUrl).addTo(this.map);
          this.layers = layer;
          this.map.invalidateSize(true);
        }
      });
    }
  },
  watch: {
    centerZoom: {
      handler(newValue, oldValue) {
        if (newValue.center && newValue.zoom && newValue.index != this.index) {
          this.setView(newValue.center, newValue.zoom);
        }
      },
      deep: true
    },
    centerZoomInit: {
      handler(newValue, oldValue) {
        if (newValue.lat && newValue.lng && newValue.zoom) {
          let center = L.latLng(newValue.lat, newValue.lng);
          this.map.setView(center, newValue.zoom);
        }
      },
      deep: true
    }
  }
};
</script>
<style scoped>
.MapViewer {
  width: 100%;
  height: 100%;
  background-color: #003452;
}
</style>
