<template>
  <div>
    <div class="draw">

    </div>
  </div>
</template>

<script setup lang="ts">
import Draw from 'ol/interaction/Draw.js';
import { unByKey } from 'ol/Observable.js';
import { LineString, Polygon } from 'ol/geom.js';
import { getArea, getLength } from 'ol/sphere.js';
import { Vector as VectorSource } from 'ol/source.js';
import { Vector as VectorLayer } from 'ol/layer.js';
import { Circle as CircleStyle, Fill, Stroke, Style } from 'ol/style.js';
// -----------------------------------------------------------------------------------------------------------------------------------
import useMapStore from '@/store/modules/maps';
import { defineProps, watch, ref, reactive, defineExpose, getCurrentInstance } from 'vue';
// -----------------------------------------------------------------------------------------------------------------------------------
const props = defineProps(['measureEnable', 'types']);
const { proxy } = getCurrentInstance();
const useOlMap = useMapStore();
let draw: Draw; // global so we can remove it later
let sketch; //当前绘制的元素.
watch(
  () => props.measureEnable, (newValue) => {
    console.log(newValue);

    if (newValue) {
      addDrawVector();
      addInteraction();
    } else {
      removeInteraction();
    }
  },
)

const source = new VectorSource();
const vector = new VectorLayer({
  source: source,
  style: {
    'fill-color': 'rgba(255, 255, 255, 0.2)',
    'stroke-color': '#ffcc33',
    'stroke-width': 3,
    'circle-radius': 7,
    'circle-fill-color': '#ffcc33',
  },
  properties: {
    name: '测距图层'
  }
});

function addDrawVector() {
  let layerArr = useOlMap.$state.olmap?.getLayers().getArray()!;
  for (let layer of layerArr) {
    if (layer instanceof VectorLayer) {
      console.log(layer);
      if (layer.getProperties().name == '测距图层') {
        useOlMap.$state.olmap?.removeLayer(layer);
      }
    }
  }
  useOlMap.$state.olmap?.addLayer(vector);
}

const formatLength = function (line) {
  const length = getLength(line);
  let output;
  if (length > 100) {
    output = Math.round((length / 1000) * 100) / 100 + ' ' + 'km';
  } else {
    output = Math.round(length * 100) / 100 + ' ' + 'm';
  }
  return output;
};
/**
 * Format area output.
 * @param {Polygon} polygon The polygon.
 * @return {string} Formatted area.
 */
const formatArea = function (polygon) {
  const area = getArea(polygon);
  let output;
  if (area > 10000) {
    output = Math.round((area / 1000000) * 100) / 100 + ' ' + 'km<sup>2</sup>';
  } else {
    output = Math.round(area * 100) / 100 + ' ' + 'm<sup>2</sup>';
  }
  return output;
};

function addInteraction() {
  console.log('add')
  const type = props.types;
  draw = new Draw({
    source: source,
    type: type,
    style: new Style({
      fill: new Fill({
        color: 'rgba(255, 255, 255, 0.8)',
      }),
      stroke: new Stroke({
        color: 'rgba(0, 0, 0, 0.5)',
        lineDash: [10, 10],
        width: 2,
      }),
      image: new CircleStyle({
        radius: 5,
        stroke: new Stroke({
          color: 'rgba(0, 244, 255, 0.7)',
          width: 3
        }),
        fill: new Fill({
          color: 'rgba(255, 255, 255, 0.5)',
        }),
      }),
    }),
  });
  useOlMap.$state.olmap?.addInteraction(draw);
  removeInteraction();
  let listener;
  draw.on('drawstart', function (evt) {
    // set sketch
    sketch = evt.feature;
    /** @type {import("../src/ol/coordinate.js").Coordinate|undefined} */
    listener = sketch.getGeometry().on('change', function (evt) {
      const geom = evt.target;
      let output;
      if (geom instanceof Polygon) {
        output = formatArea(geom);
      } else if (geom instanceof LineString) {
        output = formatLength(geom);
      }
    });
  });
  draw.on('drawend', function () {
    // unset sketch
    sketch = null;
    // createMeasureTooltip();
    unByKey(listener);
  });

  document.onkeydown = function (event) {
    if (event.key == "Escape") {
      removeInteraction();
    }
  }
}

function removeInteraction() {
  if (draw.getActive()) {
    draw.abortDrawing();
    useOlMap.$state.olmap?.removeInteraction(draw);
    console.log('remove')
    let layerArr = useOlMap.$state.olmap?.getLayers().getArray()!;
    for (let layer of layerArr) {
      if (layer instanceof VectorLayer) {
        console.log(layer);
        if (layer.getProperties().name == '测距图层') {
          useOlMap.$state.olmap?.removeLayer(layer);
        }
      }
    }
    proxy.$emit('drawEnd')
  }

}
</script>

<style scoped>
.draw {

}
</style>