<template>
  <div class="main_container">
    <div class="container-map" v-bind="getMapOptions" />
  </div>
</template>
<script>
import { Map, View, Feature } from 'ol'
import 'ol/ol.css'
import { Tile, Vector as VectorLayer } from 'ol/layer'
import { XYZ, Vector as VectorSource } from 'ol/source'
import { transform, fromLonLat } from 'ol/proj'
import * as control from 'ol/control'
import Point from 'ol/geom/Point'
import { Style, Icon } from 'ol/style'
import plain from '@/assets/images/plain.png'

import { reactive, computed, toRefs, onMounted } from 'vue'

export default {
  name: 'PositionMsg',
  props: {
    id: {
      type: String,
      default: 'map-track'
    },
    coordinate: {
      type: Array,
      required: true
    }
  },
  emits: {},
  setup(props, { emit }) {
    const data = reactive({

      mapData: null,
      mapView: null
    })
    const getMapOptions = computed(() => {
      return {
        id: props.id
      }
    })
    /**
     * 初始化底图
     */
    const initMap = function() {
      const layers = [
        new Tile({
          visible: true,
          source: new XYZ({
            url: 'https://tianditu.t-aaron.com/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=f82bb2fd8115c7fb576a8b2fcf738523'
          })
        })
      ]
      data.mapView = new View({
        maxZoom: 18,
        zoom: 4,
        center: transform([108.94043, 31.008173], 'EPSG:4326', 'EPSG:3857')
      })
      data.mapData = new Map({
        layers: layers,
        target: props.id,
        view: data.mapView,
        controls: control.defaults({
          attribution: false,
          rotate: false,
          zoom: false
        })
      })
      data.mapData.render()
    }

    function positionPoint(coordinate) {
      data.mapView.animate(
        { center: transform(coordinate, 'EPSG:4326', 'EPSG:3857') },
        { zoom: 18 }
      )
    }

    /**
     * 加载矢量图层
     */
    const getLayer = function(coordinate) {
      const pointFeatures = []
      const featureItem = new Feature(new Point(fromLonLat(coordinate)))
      featureItem.setStyle(new Style({
        image: new Icon({
          anchor: [0.5, 0.5],
          src: plain,
          crossOrigin: '',
          scale: [1, 1],
          rotateWithView: true
        })
      }))
      pointFeatures.push(featureItem)
      const pointSource = new VectorSource({
        wrapX: false,
        features: pointFeatures
      })
      const problemLayer = new VectorLayer({
        source: pointSource,
        zIndex: 12
      })
      positionPoint(coordinate)
      data.mapData.addLayer(problemLayer)
    }

    onMounted(() => {
      initMap()
    })

    return {
      ...toRefs(data),
      getMapOptions,
      initMap,
      getLayer,
      positionPoint

    }
  }
}
</script>
<style scoped>
.main_container {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
}
.container-map {
  width: 100%;
  height: 100%;
}
</style>
