<template>
  <div class="map-container">
    <mars-map @mapLoad="mapLoad" :options="options"></mars-map>
    <div class="multiple">
      <div
        @click="toggleSelection(item)"
        :class="{ checkbox: true, checked: isSelected(item) }"
        v-for="(item, index) in multipleList"
        :key="index"
      >
        <img
          :src="require(`../assets/images/${item}.png`)"
          alt=""
          class="btn-icon"
        />
        {{ item }}
      </div>
    </div>
  </div>
</template>

<script>
import MarsMap from "@/components/mars-map";
import { getAreaData } from "@/api/yunkun/index.js";

export default {
  data() {
    const basePathUrl = window.basePathUrl || "";
    return {
      map: null,
      options: {
        scene: {
          center: {
            lat: 29.689932,
            lng: 120.127589,
            alt: 146960.4,
            heading: 9.5,
            pitch: -46.2,
          },
        },
        control: {
          contextmenu: { preventDefault: false, hasDefault: false },
        },
        terrain: {
          show: false,
        },
        basemaps: [
          {
            name: "影像地图",
            type: "xyz",
            url: process.env.VUE_APP_BASE_API2 + "/{z}/{y}/{x}.png",
            minimumLevel: 1,
            maximumLevel: 16,
            show: true,
          },
          // {
          //   name: "mapbox影像图",
          //   icon: "img/basemaps/mapboxSatellite.png",
          //   type: "mapbox",
          //   username: "sharealex",
          //   styleId: "cly5i21fn00e901prgq643t4r",
          //   token:
          //     "pk.eyJ1Ijoic2hhcmVhbGV4IiwiYSI6ImNsaXNhZmRjbTFhbnczZmxib3h1OW05YXYifQ.PhlKv60ar3K359d8x2yBPw",
          //   tilesize: 256,
          //   scaleFactor: false,
          //   show: true,
          // },
        ],
      },
      mapLayer: {},
      rongheUrl: basePathUrl + "lib/ronghe.json",
      suzhouUrl: basePathUrl + "lib/suzhou.json",
      rimCityUrl: basePathUrl + "lib/nearbyCity.json",
      list: [],
      multipleList: ["线路总数", "营业网点", "上门收款点", "ATM机"],
      selectedItems: [],
      currentIndex: null,
      layerzIndex: {
        相城区: 60,
        姑苏区: 60,
        虎丘区: 60,
        工业园区: 40,
        吴中区: 60,
        吴江区: 40,
      },
    };
  },
  components: {
    MarsMap,
  },
  created() {
    this.getAreaData();
  },
  methods: {
    toggleSelection(item) {
      // 切换选中状态
      if (this.isSelected(item)) {
        this.selectedItems = this.selectedItems.filter(
          (selectedItem) => selectedItem !== item
        );
      } else {
        this.selectedItems.push(item);
      }
      if (this.currentIndex == null) return;
      const markerItme = document
        .getElementById(`marker${this.currentIndex}`)
        .getElementsByClassName("row-item");

      for (let i = 0; i < this.multipleList.length; i++) {
        markerItme[i].style.display = "block";
      }
      this.handlerhidle(markerItme);
    },
    //处理数据的每一项的显示与隐藏
    handlerhidle(cell) {
      this.selectedItems.forEach((item) => {
        let itemIndex = this.multipleList.findIndex((it) => it == item);
        if (itemIndex > -1) {
          cell[itemIndex].style.display = "none";
        }
      });
    },
    isSelected(item) {
      // 检查某个项是否被选中
      return this.selectedItems.includes(item);
    },
    async getAreaData() {
      let res = await getAreaData();
      this.list = res.data;
    },
    mapLoad(map) {
      this.map = map;
      if (process.env.NODE_ENV === "production") {
        map.setSceneOptions({
          cameraController: {
            enableZoom: false,
            enableTranslate: false,
            enableRotate: false,
            enableTilt: false,
          },
        });
      }
      //创建地图图层
      this.createMapLayer();
      //六区
      this.addAreaLayer();
      //苏州融合图层
      this.addRonghe();
      this.addScale();
      //周边
      this.initRimcity();
    },
    createMapLayer() {
      //苏州周边图层
      this.mapLayer.rim = new mars3d.layer.GraphicLayer();
      this.map.addLayer(this.mapLayer.area);

      //图标图层
      this.mapLayer.marker = new mars3d.layer.GraphicLayer();
      this.map.addLayer(this.mapLayer.marker);

      // 苏州六区图层
      this.mapLayer.area = new mars3d.layer.GraphicLayer();
      this.map.addLayer(this.mapLayer.area);
    },
    async addRonghe() {
      // 创建苏州六区边界
      let mapData = await mars3d.Util.fetchJson({ url: this.rongheUrl });
      const arr = mars3d.Util.geoJsonToGraphics(mapData);
      const polygonEntity = new mars3d.graphic.PolygonEntity({
        positions: arr[0].positions,
        style: {
          fill: true,
          materialType: "Image",
          materialOptions: {
            image: require("../assets/images/map-bg.jpg"),
          },
          outline: true,
          outlineWidth: 4,
          outlineColor: "#00D1FF",
        },
      });
      this.mapLayer.area.addGraphic(polygonEntity);
      //三维立体墙
      const wall = new mars3d.graphic.WallPrimitive({
        positions: arr[0].positions,
        style: {
          setHeight: -20000,
          diffHeight: 20000, // 墙高
          width: 10,
          materialType: mars3d.MaterialType.Image2,
          materialOptions: {
            image: require("../assets/images/fence-top.png"),
            color: "#0071F8",
          },
        },
      });
      this.mapLayer.area.addGraphic(wall);
    },
    async addAreaLayer() {
      let mapData = await mars3d.Util.fetchJson({ url: this.suzhouUrl });
      const arr = mars3d.Util.geoJsonToGraphics(mapData);
      for (let i = 0; i < arr.length; i++) {
        const item = arr[i];
        const index = i + 1;

        const polygonEntity = new mars3d.graphic.PolygonEntity({
          id: index,
          positions: item.positions,
          style: {
            fill: true,
            color: "#001C54",
            opacity: 0.5,
            outline: true,
            outlineWidth: 2,
            outlineColor: "#00BEFF",
            highlight: {
              type: "click",
              color: "#003EFF",
              opacity: 0.6,
              outlineColor: "#00B0FF",
            },
          },
          attr: item.attr,
        });
        this.addMarker(item.attr.x, item.attr.y, item.attr.name, index);
        //高亮后;
        polygonEntity.on(mars3d.EventType.highlightOpen, (e) => {
          this.handlerMarkerHighlight(true, e.target.id);
          const circleItem = this.mapLayer.marker.getGraphicById(
            `circle${e.target.id}`
          );
          circleItem.openHighlight({
            radius: 6200,
            materialOptions: {
              color: "#FD873F",
            },
          });

          this.currentIndex = e.target.id;
        });
        //关闭高亮后
        polygonEntity.on(mars3d.EventType.highlightClose, (e) => {
          this.handlerMarkerHighlight(false, e.target.id);
          const circleItem = this.mapLayer.marker.getGraphicById(
            `circle${e.target.id}`
          );
          circleItem.closeHighlight();
          this.currentIndex = null;
        });

        this.mapLayer.area.addGraphic(polygonEntity);
      }
    },
    addMarker(lng, lat, name, id) {
      let areaItem = this.list.filter((item) => item.area == name);
      console.log(areaItem);
      if (areaItem.length <= 0) return;
      // 水波动态效果
      const circleGraphic = new mars3d.graphic.CircleEntity({
        position: new mars3d.LngLatPoint(lng, lat),
        id: `circle${id}`,
        style: {
          radius: 4200,
          materialType: mars3d.MaterialType.CircleWave,
          materialOptions: {
            color: "#5CD2E6",
            count: 2,
            speed: 10,
          },
        },
        allowDrillPick: true, //是否允许鼠标穿透拾取
      });
      this.mapLayer.marker.addGraphic(circleGraphic);
      let html = `<div class="mars-four-color">
        <div class="four-color_name">${areaItem[0].area}</div>
        <div class="screen-list">
                  <div class="row-item">
                  <div class="lable-value">
                    <div class="lable-data">线路总数</div>
                    <div class="value-data">${areaItem[0].lineTotalNum} <span>条</span></div>
                    </div>
                    </div>
                     <div class="row-item">
                  <div class="lable-value">
                     <div class="lable-data">营业网点</div>
                     <div class="value-data">${areaItem[0].outletsTotalNum} <span>个</span></div>
                    </div>
                     </div>
                      <div class="row-item">
                  <div class="lable-value">
                     <div class="lable-data">上门收款点</div>
                     <div class="value-data">${areaItem[0].paymentPointNum} <span>个</span></div>
                    </div>
                      </div>
                       <div class="row-item">
                  <div class="lable-value">
                     <div class="lable-data">ATM机</div>
                <div class="value-data">${areaItem[0].atmTotalNum} <span>台</span></div>
                    </div>
                    </div>
                  </div>
        </div>`;
      const divGraphic = new mars3d.graphic.DivGraphic({
        id: `marker${id}`,
        position: new mars3d.LngLatPoint(lng, lat),
        zIndex: this.layerzIndex[areaItem[0].area],
        style: {
          html: html,
          horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
          verticalOrigin: Cesium.VerticalOrigin.CENTER,
          clampToGround: true,
          scaleByDistance: true,
        },
        show: true,
      });
      this.mapLayer.marker.addGraphic(divGraphic);
    },
    //处理marker高亮与清除高亮
    handlerMarkerHighlight(boole, id) {
      const markerItme = document.getElementById(`marker${id}`);
      const bg = markerItme.getElementsByClassName("four-color_name")[0];
      const cell = markerItme.getElementsByClassName("row-item");
      if (boole) {
        bg.style.color = "#612500";
        bg.style.background = `url( ${require("@/assets/images/areaName_active.png")})`;
        bg.style.backgroundSize = "100% 100%";
        for (let i = 0; i < this.multipleList.length; i++) {
          cell[i].style.display = "block";
        }
        this.handlerhidle(cell);
      } else {
        bg.style.color = "#fff250";
        bg.style.background = `url( ${require("@/assets/images/areaName.png")})`;
        bg.style.backgroundSize = "100% 100%";
        for (let i = 0; i < this.multipleList.length; i++) {
          cell[i].style.display = "none";
        }
      }
    },
    //周边城市
    initRimcity() {
      mars3d.Util.fetchJson({ url: this.rimCityUrl }).then((res) => {
        const arr = mars3d.Util.geoJsonToGraphics(res);
        arr.map((item, index) => {
          const polygonEntity = new mars3d.graphic.PolygonEntity({
            positions: item.positions,
            style: {
              fill: true,
              color: "#101A2E",
              opacity: 0.5,
              outline: true,
              outlineWidth: 2,
              outlineColor: "#28334A",
              clampToGround: true,
              // hasShadows: true,
              label: {
                text: item.attr.name,
                position: "center",
                font_size: 18,
                color: "#283F61",
                // font_family: "楷体",
                outline: true,
                outlineColor: "black",
                outlineWidth: 1,
                // 视距的设置
                scaleByDistance: true,
                scaleByDistance_far: 20000000,
                scaleByDistance_farValue: 0.1,
                scaleByDistance_near: 1000,
                scaleByDistance_nearValue: 1,
              },
            },
          });

          this.mapLayer.area.addGraphic(polygonEntity);
        });
      });
    },
    addScale() {
      const graphic = new mars3d.graphic.RectanglePrimitive({
        positions: [
          [119.924698, 31.029796, 13.9],
          [120.305187, 30.567241, -7.4],
          [120.862246, 30.817488, -27.2],
        ],
        style: {
          materialType: mars3d.MaterialType.Image2,
          materialOptions: {
            image: require("../assets/images/mapScale.png"),
            opacity: 1,
          },
          flat: true,
        },
      });
      this.mapLayer.area.addGraphic(graphic);
    },
  },
};
</script>

<style lang="scss" scoped>
.map-container {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
  .multiple {
    position: absolute;
    bottom: 20px;
    left: 50%;
    transform: translateX(-50%);
    z-index: 100;
    width: 880px;
    height: 80px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background: url("../assets/images/multipleList.png");
    background-size: 100% 100%;
    padding: 0 180px;
    .checkbox {
      cursor: pointer;
      width: 112px;
      height: 32px;
      line-height: 32px;
      text-align: center;
      font-size: 14px;
      color: #ffffff;
      background: linear-gradient(180deg, #072853 0%, #0079ff 100%);
      border: 1px solid #0084ff;
      border-radius: 16px;
      display: flex;
      align-items: center;
      justify-content: center;
      opacity: 1;
    }
    .checked {
      opacity: 0.5;
    }
    .btn-icon {
      width: 15px;
      height: 16px;
      margin-right: 10px;
    }
  }
}
</style>
