<template>
  <div id="map"></div>
</template>

<script>
import L from "leaflet";
import "leaflet-draw";

export default {
  data() {
    return {
      map: null,
      polyline: null,
      polygon: null,
      markers: [],
      points: [],
      isPolygonClosed: false, // 是否闭合
      mapLayer: {},
    };
  },
  mounted() {
    this.initMap();
  },
  methods: {
    initMap() {
      this.map = L.map("map", {
        center: [31.478296, 121.089856], // 地图中心[纬度，经度]
        zoom: 15, // 地图层级

        zoomControl: false, // 放大缩小按钮
        attributionControl: false, // 右下角leaflet图标
      });
      this.mapLayer.picture = L.tileLayer(
        "https://server.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}",
        {
          maxZoom: 19,
          minZoom: 9,
          subdomains: ["0", "1", "2", "3", "4", "5", "6", "7"],
        }
      ).addTo(this.map);

      // 设置地图点击事件
      this.map.on("click", this.onMapClick);
    },
    onMapClick(e) {
      if (this.isPolygonClosed) {
        // 多边形已闭合时，点击地图切换编辑模式
        this.toggleEditing();
      } else {
        // 未闭合时继续添加点
        this.addPoint(e);
      }
    },
    addPoint(e) {
      const latlng = e.latlng;
      const marker = L.circleMarker(latlng, {
        radius: 5,
        color: "red",
        fillColor: "#f03",
        fillOpacity: 0.5,
      }).addTo(this.map);

      this.markers.push(marker);
      this.points.push(latlng);
      this.updateShape();
    },
    updateShape() {
      if (this.polyline) {
        this.map.removeLayer(this.polyline);
      }

      if (this.points.length > 2 && this.isShapeClosed()) {
        this.isPolygonClosed = true;

        this.markers.forEach((marker) => this.map.removeLayer(marker));
        this.polygon = L.polygon(this.points, { color: "blue" }).addTo(
          this.map
        );

        // 初始化多边形编辑工具
        this.initEditing();
      } else {
        this.polyline = L.polyline(this.points, { color: "blue" }).addTo(
          this.map
        );
      }
    },
    isShapeClosed() {
      const start = this.points[0];
      const end = this.points[this.points.length - 1];
      return start.distanceTo(end) < 10;
    },
    initEditing() {
      // 创建并绑定编辑控制器
      this.drawControl = new L.Control.Draw({
        edit: {
          featureGroup: L.featureGroup([this.polygon]),
          remove: false,
          marker: false,
        },
        draw: false,
      });
      this.map.addControl(this.drawControl);
    },
    toggleEditing() {
      if (this.polygon.editing && this.polygon.editing.enabled()) {
        // 关闭编辑模式并保存更新后的坐标
        this.polygon.editing.disable();
        const polygonData = this.saveEditedPoints();
        console.log("Polygon data:", polygonData); // 打印多边形数据
        // 可以在这里返回或处理多边形数据
      } else {
        // 启用编辑模式
        this.polygon.editing.enable();
      }
    },
    saveEditedPoints() {
      // 获取编辑后的多边形坐标并保存
      this.points = this.polygon.getLatLngs()[0];
      return {
        type: "Polygon",
        coordinates: this.points.map((latlng) => [latlng.lng, latlng.lat]), // 转换为 [lng, lat] 格式
      };
    },
  },
};
</script>

<style>
#map {
  height: 100%;
  width: 100%;
}
.leaflet-draw {
  display: none;
}
</style>
