<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: [120.147376, 30.272934], // starting position [lng, lat]
    zoom: 7, // 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);
  });

  map.value.on("load", () => {
    handleData();
  });
});

onUnmounted(() => {
  if (map.value) map.value.remove();
});

const featureResult = await feature.list({ page: 1, size: 10 });

const handleData = () => {
  if (featureResult.status.value !== "success") return;
  let jsonData = turf.featureCollection(
    featureResult.data.value.data.map((x) =>
      turf.feature(x.geometry, {
        id: x.id,
        name: x.name,
      })
    )
  );

  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", // 添加边界线颜色
  //   },
  // });

  map.value.addSource("world_cities", {
    type: "vector",
    // scheme: "xyz",
    url: "/api/v1/mbtiles/world_cities",
    // url: 'http://localhost:3000/world_cities',
    // bounds: [-123.12359, -37.818085, 174.763027, 59.352706],
    // maxzoom: 6,
    // minzoom: 0,
    // tiles: ["http://localhost:3001/api/v1/mbtiles/world_cities/{z}/{x}/{y}"],
  });
  map.value.addLayer({
    id: "world_cities",
    type: "symbol",
    minzoom: 0,
    maxzoom: 6,
    source: "world_cities",
    "source-layer": "cities",
    layout: {
      "text-field": "{name}",
      // "text-font": ["Open Sans Regular", "Arial Unicode MS Regular"],
      "text-size": 12,
    },
    paint: {
      "text-color": "rgb(255,0,0)",
    },
  });

  map.value.addSource("china-shortbread", {
    type: "vector",
    // url: "/api/v1/mbtiles/china-shortbread",
    bounds: [73.41788, 14.27437, 134.8036, 53.65559],
    maxzoom: 14,
    minzoom: 0,
    tiles: [
      "http://localhost:8888/api/v1/mbtiles/china-shortbread/{z}/{x}/{y}",
    ],
  });

  // map.value.addLayer({
  //   id: "china-shortbread",
  //   type: "symbol",
  //   bounds: [73.41788, 14.27437, 134.8036, 53.65559],
  //   maxzoom: 14,
  //   minzoom: 0,
  //   source: "china-shortbread",
  //   "source-layer": "place_labels",
  //   layout: {
  //     "text-field": "hello",
  //     // "text-font": ["Open Sans Regular", "Arial Unicode MS Regular"],
  //     "text-size": 12,
  //   },
  //   paint: {
  //     "text-color": "#000",
  //   },
  // });

  setTimeout(() => {
    let source = map.value.getSource("world_cities");
    console.log(source);

    let chinashortbread = map.value.getSource("china-shortbread");
    console.log(chinashortbread);

    let maplibresource = map.value.getSource("maplibre");
    console.log(maplibresource);
  }, 1000);
};
</script>

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