<template>
  <div id="map2DViewer">
    <CaseAuditPopup v-show="auditPopupShow" ref="auditRef" />
    <LabelCasePopup v-show="labelDetailsPopupShow" ref="labelRef" />
    <BasemapChange />
  </div>
</template>
<script>
import publicFun from "@/utils/publicFunction.js";
import { get } from "@/utils/request";
import CaseAuditPopup from "@/components/popup/CaseAuditPopup.vue";
import LabelCasePopup from "@/components/popup/LabelCasePopup.vue";
import BasemapChange from "@/components/map/BasemapChange.vue";
export default {
  name: "MapHolder",
  components: { CaseAuditPopup, LabelCasePopup, BasemapChange },
  data() {
    return {
      // 卷帘对比开关
      JLControlShowStatus: false,

      town: "祝桥镇,南汇新城镇,川沙新镇,老港镇,惠南镇,航头镇,泥城镇,书院镇,新场镇,大团镇,唐镇,曹路镇,宣桥镇,张江镇,合庆镇,周浦镇,康桥镇,三林镇,高桥镇,高东镇,金桥镇,北蔡镇,万祥镇,高行镇",
      auditPopupShow: false,
      labelDetailsPopupShow: false,
      auditPopupStatus: "normal",
      popup: null,
      labelPopup: null,
      // 疑点审计
      currentCid: null,
      currentHtml: null,
      // 标记疑点
      currentLabelCid: null,
      currentLabelHtml: null
    };
  },
  mounted() {
    // 监听全局事件总线中的卷帘对比事件（JLControl）
    this.$bus.$on("JLControl", () => {
      this.JLControl();
    });
    this.$bus.$on("caseAuditEvent", () => {
      this.caseAuditEvent();
    });

    //地图初始化
    this.mapInit();

    this.$store.state.mapMethodsCollection.set("RENDER", {
      addPolygonLayer: this.addPolygonLayer,
      setView: this.setView,
      deletePolygonLayer: this.deletePolygonLayer
    });
  },
  beforeDestroyed() {
    // 当容器销毁时，需要停止监听该事件
    this.$bus.$off("JLControl");
    // 疑点审计
    this.$bus.$off("caseAuditEvent");
  },
  computed: {
    // 监听底部菜单栏的状态
    getLabelCaseBtnStatus() {
      //疑点审计 1,0
      let _index = this.$store.state.bottomMenuIndexs.index;
      let _subIndex = this.$store.state.bottomMenuIndexs.subIndex;
      return { index: _index, subIndex: _subIndex };
    },
    // 监听当前菜单
    getCurrentMenu() {
      return this.$store.state.navSelect;
    }
  },
  watch: {
    getLabelCaseBtnStatus(val) {
      console.log(val, "标记疑点");
      if (val.index === 1 && val.subIndex === 1) {
        console.log("激活标记疑点弹窗");
        this.initDraw();
      } else {
        console.log("移除疑点标记事件");
        this.stopLabelCase();
      }
    },
    "$store.state.navSelect": {
      handler(val) {
        console.log(val, "currentMenu -- test");
        if (val.index !== "3") {
          if (this.JLControlShowStatus) {
            this.JLControl();
          }
          this.stopLabelCase();
          this.$store.state.bottomMenuIndexs.index = -1;
          this.$store.state.bottomMenuIndexs.subIndex = -1;
        }
        // 切换页面时判断是否需要显示区域图
        this.$nextTick(() => {
          this.getJSonData();
        });
      },
      immediate: true
    }
  },
  methods: {
    // 开始标记疑点事件
    startLabelCase() {
      map2DViewer.setDrawTool({ action: "start" });
    },
    // 停止标记疑点事件
    stopLabelCase() {
      try {
        map2DViewer.setDrawTool({
          action: "remove"
        });
      } catch (e) {
        console.log("MapHolder.vue 停止标记疑点事件 error");
      }
    },
    // 常规图层弹窗
    createAuditDiv(str) {
      // 相关属性数据
      // 表格里的数据
      let popuppef = this.$refs.auditRef;
      let tableArr = popuppef.tableArr;
      // console.log(tableArr, "shuju");
      // 根据ref获取组件的dom元素
      this.currentHtml = this.$refs.auditRef.$el.innerHTML;
      console.log($(`#${str}_id`), "8888");
      if (this.currentHtml) {
        let div = document.createElement("div");
        div.id = str + "_id";
        div.className = "case-audit";
        // 动态创建div后赋值模板样式
        div.innerHTML = this.currentHtml;
        $(() => {
          // 法律法规点击事件
          if ($(`#${str}_id a`)) {
            $(`#${str}_id a`).click(e => {
              console.log(e, "显示疑点相关的弹窗");
              this.$store.state.lawPopupShow = true;
            });
          }
          // input添加点击事件
          if ($(`#${str}_id input`)[1]) {
            $(`#${str}_id input`).click(e => {
              switch (e.target.defaultValue) {
                case "修改":
                  this.modifyBtnEvent();
                  break;
                case "确认":
                  this.confirmBtnEvent();
                  break;
              }
            });
          }
        });
        return div;
      }
    },
    /**
     * 标记疑点完成时保存描述信息的弹窗
     * @str -- id
     * @coord -- 坐标信息
     * @data -- 其余数据
     */
    createLabelDiv(str, coord, data) {
      console.log(str, "label - str");
      this.currentLabelHtml = this.$refs.labelRef.$el.innerHTML;
      if (this.currentLabelHtml) {
        let div = document.createElement("div");
        div.id = `${str}_id`;
        div.className = "label-case";
        // 动态创建div后赋值模板样式
        div.innerHTML = this.currentLabelHtml;
        $(() => {
          console.log($(`#${str}_id textarea`).val(), "textarea");
          $(`#${str}_id`).css("height", "100%");
          $(`#${str}_id input`).click(e => {
            console.log(e.target.defaultValue);
            switch (e.target.defaultValue) {
              case "删除":
                this.deleteBtnEvent(str);
                break;
              case "保存":
                this.saveBtnEvent(str, coord, data);
                break;
            }
          });
        });
        return div;
      }
    },
    modifyBtnEvent() {
      console.log("用户点击了地图中的修改按钮！");
    },
    confirmBtnEvent() {
      console.log("用户点击地图中的确认按钮");
    },
    deleteBtnEvent() {
      console.log("delete btn");
    },

    // 点击保存事件时保存点数据
    saveBtnEvent(str, coord, data) {
      console.log("save btn");
      let type = $(`#${str}_id select`).val();
      let des = $(`#${str}_id textarea`).val();
      let _oldMyLabelPointsArr = this.$store.state.myLabelPointsArr;
      let _myLabelPointsArrMap = {
        id: publicFun.buildGuid("myLabel"),
        coord: coord,
        type: type,
        des: des,
        data: data
      };
      _oldMyLabelPointsArr.push(_myLabelPointsArrMap);
      this.$store.commit("changeMyLabelData", _oldMyLabelPointsArr);
      map2DViewer.map.closePopup();
    },
    // 卷帘对比
    JLControl() {
      this.JLControlShowStatus = !this.JLControlShowStatus;
      if (this.JLControlShowStatus) {
        map2DViewer.jlMap = L.tileLayer(
          "http://t0.tianditu.gov.cn/DataServer?T=img_w&X={x}&Y={y}&L={z}&tk=f331ba0b9ab96fb21c56d91de868935d"
        ).addTo(map2DViewer.map);
        map2DViewer.jlControl = L.control.sideBySide(map2DViewer.map, map2DViewer.jlMap).addTo(map2DViewer.map);
      } else {
        map2DViewer.map.removeControl(map2DViewer.jlControl);
        map2DViewer.map.removeLayer(map2DViewer.jlMap);
        delete map2DViewer.jlMap;
        map2DViewer.jlControl = null;
      }
    },
    // 疑点审计
    caseAuditEvent() {
      // console.log("case audit");
      // 每次点击按钮后重绘弹窗
      if (this.currentHtml && this.currentCid) {
        setTimeout(() => {
          this.popup.setContent(this.createAuditDiv(this.currentCid)).openOn(map2DViewer.map);
        }, 300);
      }
    },
    // 初始化引入绘制工具
    initDraw() {
      // 引入疑点标记绘制方法
      map2DViewer.drawToolFire = data => {
        try {
          // 纬经度
          if (data && data.points.length >= 1) {
            console.log(data.points[data.points.length - 1], "绘制的图形");
            let coord = data.points[data.points.length - 1];
            if (coord && coord.length >= 2) {
              let newCoord = { lat: coord[0], lng: coord[1] };
              this.labelDetailsPopupShow = true;
              this.labelPopup = L.popup({ maxWidth: 700, maxHeight: 600 })
                .setLatLng(newCoord)
                .setContent(this.createLabelDiv("label", coord, data))
                .openOn(map2DViewer.map);
              this.labelDetailsPopupShow = false;
            }
          }
        } catch (e) {
          console.log("引入疑点标记绘制方法 error");
        }
      };
      map2DViewer.setDrawTool({
        action: "add",
        offset: [150, 50],
        background: "#fff",
        color: "red",
        font_size: "14px",
        closeButton: true,
        iconUrl: "../../static/plugins/draw-plugin/images/marker-icon.png"
      });
    },

    mapInit: function () {
      // var crs = new L.Proj.CRS(
      //   "EPSG:2401",
      //   "+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: [
      //       529.1666666666666, 264.5833333333333, 132.29166666666666, 52.916666666666664, 26.458333333333332,
      //       13.229166666666666, 5.291666666666666, 2.645833333333333, 1.3229166666666665, 0.5291666666666666,
      //       0.2645833333333333, 0.13229166666666664
      //     ],
      //     origin: [-66000, 75000],
      //     bounds: L.bounds([-65000, -76000], [75000, 72000])
      //   }
      // );

      map2DViewer.map = L.map("map2DViewer", {
        // crs: crs,
        // center: [31.074472887639914, 121.72521988031804],
        // zoom: 1,
        // minZoom: 1,
        // maxZoom: 12
        attributionControl: false,
        zoomControl: false,
        minZoom: 10,
        maxZoom: 16
      }).setView(systemConfig.mapViewer.center, systemConfig.mapViewer.zoom);

      //添加默认图层
      let guid = publicFun.buildGuid("baseLayer");
      let layer = L.esri
        .tiledMapLayer({
          url: systemConfig.mapService + "?servertype=Street_Purplish_Blue&token=" + systemConfig.token
          // url: "http://aimap.pudong.sh:5236/maps/rest/services/basemap-shanghai-gem-blue-sh2000/mapserver",
          // tileSize: 512
        })
        .addTo(map2DViewer.map);
      // layer.setStyle({opacity:0,fillOpacity:0})
      map2DViewer.layers["darkmap"] = layer;

      // 加载天地图
      let imageryLayer = L.tileLayer(systemConfig.imageryLayer);
      map2DViewer.layers["imagery"] = imageryLayer;
    },
    // 传入街道参数，重新渲染区域图层
    getJSonDataToStreet(url, param) {
      // 先删除历史图层
      if (map2DViewer.map.hasLayer(map2DViewer.groups["district_polygon"])) {
        map2DViewer.groups["district_label"].remove();
        map2DViewer.groups["district_polygon"].remove();
      }
      // 请求并渲染新的区域图层
      get("./static/json/pdgeojson.json", "").then(geoJson => {
        map2DViewer.groups["district_polygon"] = L.featureGroup();
        map2DViewer.groups["district_label"] = L.featureGroup();
        // console.log(map2DViewer.groups["district_polygon"], "district_polygon group");
        map2DViewer.groups["district_polygon"].addTo(map2DViewer.map);
        map2DViewer.groups["district_label"].addTo(map2DViewer.map);
        geoJson.features.map(feature => {
          if (this.town.indexOf(feature.properties.NAME.replace("镇", "")) > -1) {
            let center = turf.center(feature.geometry);
            this.renderPolygon(feature);
          }
        });
      });
    },
    getJSonData() {
      if (!map2DViewer.map) {
        this.mapInit();
      } else if (
        // 切换到首页和疑点筛查页且图层不存在时重新渲染区域图
        (this.$ifMenu("1", "") || this.$ifMenu("2", "")) &&
        !map2DViewer.map.hasLayer(map2DViewer.groups["district_polygon"])
      ) {
        this.getJSonDataToStreet("", "");
      } else if (
        !(this.$ifMenu("1", "") || this.$ifMenu("2", "")) &&
        map2DViewer.map.hasLayer(map2DViewer.groups["district_polygon"])
      ) {
        // 当前页不是首页和疑点筛查页时移除区域图且图层存在时
        map2DViewer.groups["district_label"].remove();
        map2DViewer.groups["district_polygon"].remove();
      }
    },
    setView: function (coord, zoom) {
      // console.log(coord, "位置");
      let center = L.latLng(coord[0], coord[1]);
      map2DViewer.map.setView(center, zoom);
    },
    renderPolygon: function (feature) {
      let center = turf.center(feature.geometry);
      let itemvalue = JSON.parse((Math.random() * 1000).toFixed(0));
      let polygonData = JSON.parse(JSON.stringify(feature));
      let coordinates = polygonData.geometry.coordinates[0];
      let polygon = L.polygon(this.latLngsToReverse(coordinates), {
        color: "#87d8fd",
        weight: 3,
        fillColor: this.getColor(itemvalue),
        opacity: 1,
        fillOpacity: 0.4
      }).addTo(map2DViewer.groups["district_polygon"]);
      center = JSON.parse(JSON.stringify(center)).geometry.coordinates;
      center.reverse();
      let wmarker = L.circleMarker(center, {
        radius: 10,
        weight: 1,
        fillOpacity: 0,
        color: "#e6d273"
      });
      wmarker.bindLabel(feature.properties.NAME, {
        noHide: true,
        clickable: true,
        offset: [-25, 10]
      });
      wmarker.addTo(map2DViewer.groups["district_label"]);
      L.circleMarker(center, {
        radius: 8,
        weight: 1,
        fillOpacity: 0,
        color: "#e6d273"
      }).addTo(map2DViewer.groups["district_polygon"]);
      L.circleMarker(center, {
        radius: 5,
        weight: 1,
        fillOpacity: 1,
        color: "#e6d273"
      }).addTo(map2DViewer.groups["district_polygon"]);
    },
    latLngsToReverse: function (latlngsAry) {
      var tempLatlngsAry = JSON.parse(JSON.stringify(latlngsAry));
      if (typeof tempLatlngsAry[0] != "object") {
        return tempLatlngsAry.reverse();
      } else {
        for (var i = 0, l = tempLatlngsAry.length; i < l; i++) {
          tempLatlngsAry[i] = this.latLngsToReverse(tempLatlngsAry[i]);
        }
      }
      return tempLatlngsAry;
    },
    getColor: function (val) {
      var that = this;
      if (val < 350) {
        return "#e565ff";
      } else if (val < 700 && val >= 350) {
        return "#0055ff";
      } else {
        return "#00ffd5";
      }
    },
    // 综合分析 - 图层绘制面
    addPolygonLayer(data, cid, color) {
      // cid -- 'yongjiu'
      // console.log(data, cid, color);
      data.map(feature => {
        let polygonData = JSON.parse(JSON.stringify(feature));
        let coordinates = polygonData.geometry.coordinates[0];
        let infos = polygonData.properties;
        let polygon = L.polygon(coordinates, {
          color: color,
          weight: 3,
          fillColor: color,
          opacity: 1,
          fillOpacity: 0.4
        }).addTo(map2DViewer.map);
        map2DViewer.polygons[`${cid}_layer`].push(polygon);
        polygon.infos = infos;
        polygon.on("click", e => {
          // console.log(e, "polygon");
          this.auditPopupShow = true;
          console.log(e.latlng, "获取当前弹窗坐标111");

          this.popup = L.popup({ maxWidth: 700, maxHeight: 600 }).setLatLng(e.latlng).setContent(this.createAuditDiv("cid"));
          // .openOn(map2DViewer.map);
          this.auditPopupShow = false;
          this.popup.openOn(map2DViewer.map);
          this.currentCid = cid;
        });
      });
    },

    //综合分析 - 标记疑点 - 删除面
    deletePolygonLayer(layer) {
      map2DViewer.polygons[layer].forEach(polygon => {
        map2DViewer.map.removeLayer(polygon);
      });
    }
  }
};
</script>
<style scoped>
#map2DViewer {
  position: absolute;
  width: 100%;
  height: calc(100% - 60px);
  background-color: #003452;
  z-index: 1;
  top: 60px;
  left: 0px;
}
</style>
