<template>
  <div class="xiaoqu-map">
    <mars-map @mapLoad="mapLoad" :options="options"></mars-map>
  </div>
</template>

<script>
import configJson from "./map-config.json";
import { mapGetters } from "vuex";
import garden from "./garden.json";
import MarsMap from "@/components/mars-map";

export default {
  props: {
    xiaoquId: {
      type: Number,
      default: 0,
    },
  },
  computed: {
    ...mapGetters(["mapParmas"]),
  },
  data() {
    const basePathUrl = window.basePathUrl || "";
    return {
      map: null,
      mapLayer: {},
      config: {},
      options: {
        scene: {
          showSun: false, //太阳
          showMoon: false, //月亮
          showSkyAtmosphere: false, //是否显示地球大气层外光圈
          globe: {
            showGroundAtmosphere: false, // 关闭大气（球表面白蒙蒙的效果）
            depthTestAgainstTerrain: false,
            baseColor: "#546a53",
          },
        },
        basemaps: [
          {
            name: "ArcGIS影像",
            icon: "img/basemaps/esriWorldImagery.png",
            type: "arcgis",
            layer: "img_d", // 使用layer时会自动用内部固定url "https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer"
            enablePickFeatures: false,
            show: true,
          },
        ],
      },
      configUrl: basePathUrl,
      geoJsonLayerDTH: null,
    };
  },
  components: {
    MarsMap,
  },
  watch: {
    mapParmas: {
      handler(newValue, oldValue) {
        this.add3DXiaoqu(newValue.sd);
        this.addNetworkLayer(newValue.networkName);
        if (this.geoJsonLayerDTH && this.geoJsonLayerDTH.length > 0)
          this.map.getLayerById("dth").clear(); //清除单体化
      },
      deep: true, // Deeply watch all nested properties
    },
  },
  created() {
    this.config = configJson[JSON.parse(this.xiaoquId)];
  },
  methods: {
    mapLoad(map) {
      let _this = this;
      this.map = map;

      map.centerAt(this.config.viewHome, {
        complete: function () {
          //加载图层数据
          _this.addMapLayer();
        },
      });
      map.on(mars3d.EventType.click, function (e) {
        if (!e.id) {
          if (_this.geoJsonLayerDTH && _this.geoJsonLayerDTH.length > 0)
            map.getLayerById("dth").clear(); //清除单体化
          _this.$store.commit("CHANGE_QUERY", {
            buildingId: undefined,
            // deptId: undefined,
          }); //存储全局参数
        }
      });
    },
    //图层组
    mapGraphicLayer() {
      this.mapLayer.garden = new mars3d.layer.GraphicLayer();
      this.map.addLayer(this.mapLayer.garden);

      this.mapLayer.plane = new mars3d.layer.GraphicLayer();
      this.map.addLayer(this.mapLayer.plane);

      this.mapLayer.planePoint = new mars3d.layer.GraphicLayer();
      this.map.addLayer(this.mapLayer.planePoint);

      this.mapLayer.network = new mars3d.layer.GraphicLayer({ show: true });
      this.map.addLayer(this.mapLayer.network);
    },
    addMapLayer() {
      this.mapGraphicLayer();
      if (this.xiaoquId == 267) {
        this.addshop();
      }
      if (
        this.xiaoquId === 202 ||
        this.xiaoquId === 245 ||
        this.xiaoquId === 215 ||
        this.xiaoquId === 248
      ) {
        this.addGardenLayer();
      }

      this.addbuildingLayer();
    },
    //商铺面
    addshop() {
      this.mapLayer.shopLayer = new mars3d.layer.GraphicLayer();
      this.map.addLayer(this.mapLayer.shopLayer);
      mars3d.Util.fetchJson({
        url: this.configUrl + `lib/geoJson/xiaoqu/shop${this.xiaoquId}.json`,
      }).then((res) => {
        const arr = mars3d.Util.geoJsonToGraphics(res);
        arr.map((item, index) => {
          const polygon = new mars3d.graphic.PolygonEntity({
            positions: item.positions,
            style: {
              color: "#062F63",
              opacity: 0.6,
              outline: true,
              outlineWidth: 2,

              highlight: {
                type: "click",
                color: "#FD873F",
                label: {
                  color: "black",
                },
              },
              label: {
                text: item.attr.TextString,
                color: "#fff",
                font_size: 12,
                outline: false,
                scaleByDistance: true,
                scaleByDistance_far: 20000000,
                scaleByDistance_farValue: 0.1,
                scaleByDistance_near: 1000,
                scaleByDistance_nearValue: 1,
              },
            },
            attr: item.attr,
          });
          polygon.bindPopup(function (event) {
            const item = event.graphic?.attr;
            if (!item || item.TextString == " ") {
              return false;
            }
            const inthtml = `
                <div class="shop-dialog">
                  <div class="shop-item">
                      <div class="shop-lable">楼号:</div>
                      <div class="shop-value">${item["楼号"]}</div>
                    </div>
                     <div class="shop-item">
                      <div class="shop-lable">门牌号:</div>
                      <div class="shop-value">${item.TextString}</div>
                    </div>
                     <div class="shop-item">
                      <div class="shop-lable">房间号:</div>
                      <div class="shop-value">${item["房间号"]}</div>
                    </div>
                     <div class="shop-item">
                      <div class="shop-lable">招牌名称:</div>
                      <div class="shop-value">${item["招牌名称"]}</div>
                    </div>
                     <div class="shop-item">
                      <div class="shop-lable">商铺面积:</div>
                      <div class="shop-value">${item["商铺面积"]}㎡</div>
                    </div>
                     <div class="shop-item">
                      <div class="shop-lable">负责人姓名:</div>
                      <div class="shop-value">${item["负责人姓名"]}</div>
                    </div>
                     <div class="shop-item">
                      <div class="shop-lable">电话:</div>
                      <div class="shop-value">${item["联系电话"]}</div>
                    </div>
                     <div class="shop-item">
                      <div class="shop-lable">经营类别:</div>
                      <div class="shop-value">${item["经营类别"]}</div>
                    </div>
                     <div class="shop-item">
                      <div class="shop-lable">经营状态:</div>
                      <div class="shop-value">${item["经营状态"]}</div>
                    </div>
                    <div class="shop-item">
                      <div class="shop-lable">备注:</div>
                      <div class="shop-value">${item["备注"]}</div>
                    </div>
                    <div class="shop-item">
                      <div class="shop-lable">企业营业执照名称:</div>
                      <div class="shop-value">${item["企业营业执"]}</div>
                    </div>
                </div>`;
            return inthtml;
          });
          this.mapLayer.shopLayer.addGraphic(polygon);
        });
      });
    },
    //苑图层
    addGardenLayer() {
      const data = garden[this.xiaoquId];
      Object.keys(data).map((key, index) => {
        const item = data[key];
        const graphic = new mars3d.graphic.BillboardEntity({
          position: new mars3d.LngLatPoint(item.x, item.y, item.height),
          style: {
            image:
              "http://www.jichuanglanhai.com/demo/taicang-file/images/" +
              item.icon +
              ".png",
            scale: 1,
            width: 70,
            height: 45,
            clampToGround: false,

            label: {
              text: key,
              font_size: 14,
              font_family: "黑体",
              color: "#ffffff",
              visibleDepth: false,
              pixelOffsetY: -5,
              background: true,
              backgroundColor: "#000000",
              backgroundOpacity: 1,
              backgroundPadding: new Cesium.Cartesian2(4, 3),
            },
          },
        });
        this.mapLayer.garden.addGraphic(graphic);
      });
    },
    extractNumbersAndDashes(str) {
      // 正则表达式匹配数字和可能的 - 号
      const regex = /(?:\d+-?)+/g;
      // 查找所有匹配的子字符串
      const matches = str.match(regex);
      // 如果有匹配的结果，将其合并为一个字符串并返回
      return matches ? matches.join("") : "";
    },
    pointFilter(attr) {
      let data = garden[this.xiaoquId];
      let yuanName = "";
      let buildingNumber = this.extractNumbersAndDashes(attr["幢号"]);
      let image = "";
      let buildingColor = "";
      const match = attr["幢号"].match(/^(.*?)(\d+)/);
      if (match) {
        //  215是景瑞
        yuanName =
          this.xiaoquId == 215
            ? attr["网格名"]
            : this.xiaoquId == 248
            ? attr["别称"]
            : match[1];
      }
      if (
        this.xiaoquId == 245 ||
        this.xiaoquId == 202 ||
        this.xiaoquId == 215 ||
        this.xiaoquId == 248
      ) {
        buildingColor = data[yuanName].color;
        image =
          "//122.193.93.182:19002/profile/3DDATA/images/" +
          data[yuanName].id +
          ".png";
      } else {
        buildingColor = "#19FA63";
        image = "//122.193.93.182:19002/profile/3DDATA/images/6.png";
      }

      return { yuanName, buildingNumber, buildingColor, image };
    },
    //平面 + 图标
    async addbuildingLayer() {
      let _this = this;
      let res = await mars3d.Util.fetchJson({
        url:
          this.configUrl + `lib/geoJson/xiaoqu/building${this.xiaoquId}.json`,
      });
      const arr = mars3d.Util.geoJsonToGraphics(res);
      arr.map((item, index) => {
        const { yuanName, buildingNumber, buildingColor, image } =
          this.pointFilter(item.attr);
        const polygon = new mars3d.graphic.PolygonEntity({
          id: item.attr["幢号"],
          positions: item.positions,
          style: {
            color: "transparent",
            opacity: 0,
            outline: false,
            outlineColor: "transparent",
            outlineWidth: 0,
          },
        });
        this.mapLayer.plane.addGraphic(polygon);

        const point = new mars3d.graphic.BillboardEntity({
          id: item.attr["幢号"],
          position: polygon.centerPoint,
          style: {
            image: image,
            scale: 1,
            width: 46,
            height: 42,
            visibleDepth: false,
            clampToGround: true, //贴地
            label: {
              clampToGround: true, //贴地
              pixelOffsetY: -3,
              scale: 1,
              text: buildingNumber,
              height: 0,
              opacity: 1,
              font_size: 12,
              font_weight: "bold",
              color: buildingColor,
              font_family: "微软雅黑",
              outline: true,
              outlineColor: "#0C212C",
              outlineWidth: 2,
              outlineOpacity: 1,
              visibleDepth: false,
            },
          },
          attr: {
            id: index,
            yuanName: yuanName,
            buildingNumber: buildingNumber,
            floorNum: item.attr["层数"],
          },
        });
        point.on(mars3d.EventType.click, function (e) {
          let buildingItem = _this.mapLayer.plane.getGraphicByAttr(e.id);
          if (_this.mapLayer.tiles3dLayer && _this.mapLayer.tiles3dLayer.show) {
            const geojson = buildingItem.toGeoJSON();
            _this.map.getLayerById("dth").loadGeoJSON(geojson, { clear: true });
          } else {
            buildingItem.openHighlight({
              color: "#FFA200",
              opacity: 0.3,
              outline: true,
              outlineColor: "#F5DC02",
              outlineWidth: 2,
            });
          }
          _this.$store.dispatch("GetBuildingId", {
            deptName: e.target.attr.yuanName,
            name: e.target.attr.buildingNumber + "幢",
          });
        });
        this.mapLayer.planePoint.addGraphic(point);
      });
    },

    //小区网格面
    async addNetworkLayer(show) {
      if (show && this.mapLayer.network.length == 0) {
        let res = await mars3d.Util.fetchJson({
          url:
            this.configUrl + `lib/geoJson/xiaoqu/network${this.xiaoquId}.json`,
        });
        const arr = mars3d.Util.geoJsonToGraphics(res);
        arr.map((item, index) => {
          let polygon = new mars3d.graphic.PolygonEntity({
            id: item.attr["名称"],
            positions: item.positions,
            style: {
              color: "#005AFF",
              opacity: 0.2,
              clampToGround: true,
              classification: true,
              buffer: 1,
              outline: true,
              outlineWidth: 3,
              outlineColor: "#32FF85",
            },
          });
          this.mapLayer.network.addGraphic(polygon);
        });
      }

      this.$nextTick(() => {
        if (show && this.mapLayer.network.length > 0) {
          this.mapLayer.network.show = true;
          let networkItem = this.mapLayer.network.getGraphicById(show);
          networkItem.openHighlight({
            color: "#FF3992",
            opacity: 0.5,
            outline: true,
            outlineColor: "#FF129D",
            outlineWidth: 5,
          });
        }
        if (!show && this.mapLayer.network.length > 0)
          this.mapLayer.network.show = false;
      });
    },

    //3D小区模型
    add3DXiaoqu(show) {
      if (show && this.mapLayer.tiles3dLayer == undefined) {
        //2D显存 - 集显
        let maximumMemoryUsage =
          process.env.NODE_ENV === "production" ? (1024 * 2) / 2 : 1024 / 2;
        // 倾斜模型
        this.mapLayer.tiles3dLayer = new mars3d.layer.TilesetLayer({
          show: false,
          name: "太仓测试",
          url: this.config.qingxie.url,
          maximumScreenSpaceError: 16,
          maximumMemoryUsage: maximumMemoryUsage,
          dynamicScreenSpaceError: false,
          skipLevelOfDetail: true,
          preferLeaves: true,
          flyTo: false,
          center: this.config.viewHome,
        });
        this.map.addLayer(this.mapLayer.tiles3dLayer);
        this.addDTH();
      }
      if (show && this.mapLayer.tiles3dLayer) {
        this.handle3dPoint("3d");
        this.mapLayer.tiles3dLayer.show = true;
      }

      if (!show && this.mapLayer.tiles3dLayer) {
        this.handle3dPoint("2d");
        this.mapLayer.tiles3dLayer.show = false;
      }
    },
    //2D - 3D点处理
    handle3dPoint(type) {
      this.mapLayer.planePoint.eachGraphic((graphic) => {
        var centerPoint = graphic.centerPoint;
        if (type == "3d") {
          let attr = graphic.attr;
          centerPoint.alt = Number(attr.floorNum) * 3 + 10;
        }
        graphic.setOptions({
          position: centerPoint,
          style: {
            width: type == "3d" ? 30 : 46,
            height: type == "3d" ? 30 : 42,
            clampToGround: type == "3d" ? false : true,
            label: {
              clampToGround: type == "3d" ? false : true,
              height: centerPoint.alt,
            },
          },
        });
      });
    },
    //单体化
    addDTH() {
      this.geoJsonLayerDTH = new mars3d.layer.GeoJsonLayer({
        id: "dth",
        show: true,
        name: "太仓-楼栋",
        symbol: {
          type: "polygonP",
          styleOptions: {
            color: "#FFA200",
            opacity: 0.3,
            outline: true,
            outlineColor: "#F5DC02",
            outlineWidth: 8,
            outlineOpacity: 0.3,
            clampToGround: true,
            classification: true,
            buffer: 1,
          },
        },
      });
      this.map.addLayer(this.geoJsonLayerDTH);
    },

    // handlezs() {
    //   // this.mapLayer.zhengsheLayer.show = true;
    //   this.addZhengsheLayer();
    // },
    // //正射图层
    // addZhengsheLayer() {
    //   if (!window.zhengsheLayer) {
    //     // 加载正射影像
    //     window.zhengsheLayer = new mars3d.layer.WmsLayer({
    //       show: false,
    //       url: this.config.zhengshe.url,
    //       layers: this.config.zhengshe.layers,
    //       parameters: {
    //         transparent: true,
    //         format: "image/png",
    //       },
    //       // bbox: [
    //       //   608648.6336036972, 3481287.392025131, 609648.8066657612,
    //       //   3482195.491969689,
    //       // ],
    //       // srs: "EPSG:4549",
    //       // brightness: 0.9,
    //       // contrast: 0.9, // 对比度
    //       // saturation: 0.9,
    //       // gamma: 0.9,
    //       // tileWidth: 64,
    //       // tileHeight: 64,
    //     });
    //     this.map.addLayer(window.zhengsheLayer);

    //     window.zhengsheLayer.show = true;
    //   }
    // },
  },
};
</script>

<style lang="scss" scoped>
.xiaoqu-map {
  position: absolute;
  z-index: 10;
  height: 100%;
  width: 100%;
}
</style>
