<script setup>
import maplibregl from "maplibre-gl";
import "maplibre-gl/dist/maplibre-gl.css";
import * as turf from "@turf/turf";
import MapboxDraw from "@mapbox/mapbox-gl-draw";
import "@mapbox/mapbox-gl-draw/dist/mapbox-gl-draw.css";

const mapContainer = useTemplateRef("mapContainer");

/**
 * @type {Ref<maplibregl.Map>}
 */
const map = ref();

const { feature } = useApi();

MapboxDraw.constants.classes.CANVAS = "maplibregl-canvas";
MapboxDraw.constants.classes.CONTROL_BASE = "maplibregl-ctrl";
MapboxDraw.constants.classes.CONTROL_PREFIX = "maplibregl-ctrl-";
MapboxDraw.constants.classes.CONTROL_GROUP = "maplibregl-ctrl-group";
MapboxDraw.constants.classes.ATTRIBUTION = "maplibregl-ctrl-attrib";

MapboxDraw.lib.theme.find((x) => x.id === "gl-draw-lines").paint[
  "line-dasharray"
] = [0.2, 2];

onMounted(async () => {
  if (!mapContainer.value) return;
  map.value = new maplibregl.Map({
    container: mapContainer.value, // container id
    style: "https://demotiles.maplibre.org/style.json", // style URL
    center: [116.405285, 39.904989], // starting position [lng, lat]
    zoom: 4, // starting zoom
  });
  map.value.removeControl(map.value._controls[0]);
  const draw = new MapboxDraw({
    displayControlsDefault: false,
    controls: {
      point: true,
      line_string: true,
      polygon: true,
      trash: true,
      // combine_features: true,
      // uncombine_features: true,
    },
  });

  const updateArea = (e) => {
    const data = draw.getAll();
    console.log(data);
  };

  map.value.addControl(draw, "top-right");
  map.value.on("draw.create", updateArea);
  map.value.on("draw.delete", updateArea);
  map.value.on("draw.update", updateArea);
  map.value.on("draw.selectionchange", (e) => {
    console.log(e);
  });

  const { data, status } = await feature.list({ page: 1, size: 10 });
  if (status.value !== "success") return;
  let jsonData = turf.featureCollection(
    data.value.data.map((x) =>
      turf.feature(x.geometry, {
        id: x.id,
        name: x.name,
      })
    )
  );
  console.log(jsonData);

  map.value.addSource("data", { type: "geojson", data: jsonData });
  map.value.addLayer({
    id: "data-symbol",
    type: "symbol",
    source: "data",
    paint: {
      "text-color": "#000",
    },
    layout: {
      "text-field": ["get", "name"],
      "text-font": ["Open Sans Regular", "Arial Unicode MS Regular"],
      "text-size": 12,
    },
  });
  map.value.addLayer({
    id: "data-fill",
    type: "fill",
    source: "data",
    paint: {
      "fill-color": "#000",
      "fill-opacity": 0.5,
      "fill-outline-color": "#FF0000", // 添加边界线颜色
    },
  });
});
</script>

<template>
  <div ref="mapContainer" class="w-full h-full" />
</template>
