<template>
  <div class="container">
    <!-- 内容区域 -->
    <div class="main-content">
      <!-- 地图缩略图 -->
      <div class="map-thumbnail">
        <div id="mars2dContainerSSS" class="mars2d-container"></div>
      </div>
    </div>
  </div>
</template>

<script>
import 'mars2d/mars2d.css';
import * as mars2d from 'mars2d';

export default {
  components: {},
  data() {
    const basePathUrl = window.basePathUrl || "";
    return {
      configUrl: basePathUrl + "config/config.json",
      mapOptions: {
        copyright: false, // 不显示厂商logo
        basemaps: [
          {
            "id": 2021,
            "pid": 10,
            "name": "高德电子",
            "icon": "img/basemaps/gaode_vec.png",
            "type": "gaode",
            "layer": "vec",
            "show": true
          },
          {
            "pid": 10,
            "name": "高德卫星",
            "icon": "img/basemaps/gaode_img.png",
            "type": "group",
            "layers": [
              {
                "name": "底图",
                "type": "gaode",
                "layer": "img_d"
              },
              {
                "name": "注记",
                "type": "gaode",
                "layer": "img_z"
              }
            ]
          },
        ],
        center: { lat: 31.324918, lng: 120.618391 },
        zoom: 10,
        zoomControl: true,
      },
      map: null, // 地图实例
      markerIcon: require('@/assets/images/detailsicon/icon-定位@2x.png'), // 坐标图icon
    };
  },
  methods: {
    // 初始化地图
    initMap() {
      this.map = new mars2d.Map('mars2dContainerSSS', this.mapOptions);
      this.map.on('load', this.onload);
    },
    // 地图加载完成后的回调
    onload() {
      this.addDistrictsLayer();
    },
    // 添加各区图层
    addDistrictsLayer() {
      const geoJsonLayer = new mars2d.layer.GeoJsonLayer({
        name: "苏州市各区",
        url: "https://geo.datav.aliyun.com/areas_v3/bound/320500_full.json",
        symbol: {
          type: "polygon",
          styleOptions: {
            fill: true,
            fillColor: "white",
            fillOpacity: 0.7,
            outline: true,
            outlineWidth: 2,
            outlineOpacity: 1,
            outlineColor: "white"
          }
        },
        tooltip: "{name}<br/>项目数量:{num}个",
        flyTo: true
      });
      this.map.addLayer(geoJsonLayer);

      // 绑定事件
      geoJsonLayer.on(mars2d.EventType.load, (event) => {
        console.log("数据加载完成", event);

        const arrdata = [
          { name: "姑苏区", Y: 31.318468, X: 120.618391, value: 15, id: 0 },
          { name: "吴中区", Y: 31.285618, X: 120.641166, value: 10, id: 1 },
          { name: "相城区", Y: 31.385618, X: 120.581166, value: 8, id: 2 },
          { name: "吴江区", Y: 31.165618, X: 120.641166, value: 12, id: 3 },
          { name: "工业园区", Y: 31.305618, X: 120.741166, value: 7, id: 4 },
          { name: "高新区", Y: 31.325618, X: 120.541166, value: 5, id: 5 },
          { name: "虎丘区", Y: 31.335618, X: 120.561166, value: 3, id: 6 },
          { name: "常熟市", Y: 31.655618, X: 120.751166, value: 6, id: 7 },
          { name: "张家港市", Y: 31.865618, X: 120.551166, value: 4, id: 8 },
          { name: "昆山市", Y: 31.385618, X: 120.961166, value: 9, id: 9 },
          { name: "太仓市", Y: 31.555618, X: 121.121166, value: 2, id: 10 },
        ];
        this.bindYewuData(event.graphics, arrdata);
      });

      // 绑定事件
      geoJsonLayer.on(mars2d.EventType.click, (event) => {
        const graphic = event.graphic;
        if (graphic) {
          this.map.fitBounds(graphic.getBounds());
        } else {
          console.error("Graphic is undefined in click event");
        }
      });

      geoJsonLayer.on(mars2d.EventType.mouseover, (event) => {
        console.log("Mouseover event:", event); // 添加日志输出
        const graphic = event.graphic;
        if (graphic) {
          graphic.setStyle({
            outlineColor: "#666",
            outlineWidth: 3,
            fillOpacity: 0.7
          });
          graphic.bringToFront();
        } else {
          console.error("Graphic is undefined in mouseover event");
        }
      });

      geoJsonLayer.on(mars2d.EventType.mouseout, (event) => {
        console.log("Mouseout event:", event); // 添加日志输出
        const graphic = event.graphic;
        if (graphic) {
          graphic.setStyle({
            outlineColor: "white",
            outlineWidth: 2,
            fillOpacity: 0.5
          });
        } else {
          console.error("Graphic is undefined in mouseout event");
        }
      });
    },
    // 绑定业务数据
    bindYewuData(graphics, arrdata) {
      for (let i = 0; i < graphics.length; i++) {
        const graphic = graphics[i];
        graphic.attr.num = 0;
        for (let j = 0; j < arrdata.length; j++) {
          const fname = graphic.attr.name;
          if (arrdata[j].name.indexOf(fname) !== -1) {
            graphic.attr.num = arrdata[j].value;
            break;
          }
        }
        graphic.setStyle({ fillColor: this.getColor(graphic.attr.num) });
      }
    },
    // 获取颜色
    getColor(num) {
      const arrSpan = [1, 5, 10, 15, 20];
      const arrColor = ["#FFEDA0", "#FEB24C", "#FD8D3C", "#FC4E2A", "#E31A1C", "#BD0026", "#800026"];
      let length = arrSpan.length;
      if (length > arrColor.length) {
        length = arrColor.length;
      }

      for (let k = 0; k < length; k++) {
        if (num < arrSpan[k]) {
          return arrColor[k];
        }
      }
      return arrColor[length - 1];
    },
    // 添加图例
    addLegend() {
      let strHtml = "<div class='legend-title'>项目数量(个)</div>";

      const arrSpan = [1, 5, 10, 15, 20];
      const arrColor = ["#FFEDA0", "#FEB24C", "#FD8D3C", "#FC4E2A", "#E31A1C", "#BD0026", "#800026"];
      let length = arrSpan.length;
      if (length > arrColor.length) {
        length = arrColor.length;
      }

      for (let i = 0; i <= length; i++) {
        let label = arrSpan[i];

        if (i === 0) {
          label = "小于" + arrSpan[i];
        } else if (i === length) {
          label = "大于" + arrSpan[i - 1];
        } else {
          label = arrSpan[i - 1] + "-" + arrSpan[i];
        }

        strHtml +=
          "<div class='legend-item'><span class='legend-color' style='background:" +
          arrColor[i] +
          "'></span><span class='legend-des'>" +
          label +
          "</span></div>";
      }
      eventTarget.fire("initHtml", {
        html: strHtml
      });
    }
  },
  mounted() {
    this.initMap();
    console.log('Initializing map with options:', this.mapOptions);
    this.addLegend(); // 在 mounted 生命周期钩子中调用 addLegend
  },
  beforeDestroy() {
    if (this.map) {
      this.map.destroy();
    }
  }
};

// 事件对象，用于抛出事件给vue
export const eventTarget = new mars2d.BaseClass()
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  width: 100%;
  background-color: #FFFFFF;
  box-shadow: 0rem 0.13rem 0.63rem 0rem rgba(177, 177, 177, 0.1);
  border-radius: 0.5rem 0.5rem 0.5rem 0.5rem;
  gap: 1rem;
  overflow: auto;
}

.main-content {
  display: flex;
  gap: 2rem;
  padding: 1rem;
}

.map-thumbnail {
  width: 100%;
  height: 25rem;
  position: relative;
}

.mars2d-container {
  width: 100%;
  height: 100%;
}

.classify {
  width: 2.81rem;
  height: 1.38rem;
  background-color: rgba(43, 98, 241, 0.8);
  border-radius: 0.69rem 0.69rem 0.69rem 0.69rem;
  color: white;
  position: absolute;
  bottom: .5rem;
  left: .5rem;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: .7rem;
  z-index: 999;
}

.legend-title {
  font-size: 1rem;
  font-weight: bold;
  margin-bottom: 0.5rem;
}

.legend-item {
  display: flex;
  align-items: center;
  margin-bottom: 0.3rem;
}

.legend-color {
  width: 1rem;
  height: 1rem;
  margin-right: 0.5rem;
  display: inline-block;
}

.legend-des {
  font-size: 0.9rem;
}
</style>