<template>
  <div ref="mapPopupRef" class="popover">
    这是弹窗
  </div>
</template>
<script>
import Overlay from 'ol/Overlay'
import MarkerImg from './markerImage'

export default {
  props: {
    list: {
      type: Array,
      required: true
    }
  },
  data() {
    return {
      currStationInfo: {}
    }
  },
  mounted() {
    this.map = this.$parent.getMapInstance()
    this.initMapClick()
    this.initMapPopup()
    this.initMarkers()
  },
  methods: {
    // 初始化marker
    initMarkers() {
      this.list.forEach(eventItem => {
        this.map.addOverlay(this.getMarker(eventItem))
      })
    },

    // 初始化地图点击事件
    initMapClick() {
      this.map.on('click', () => {
        this.closeMapPopup()
      })
    },

    // 初始化地图弹窗
    initMapPopup() {
      this.popupOverlay = new Overlay({
        element: this.$refs.mapPopupRef,
        autoPan: true,
        autoPanAnimation: {
          duration: 250
        },
        positioning: 'bottom-center'
      })
      this.map.addOverlay(this.popupOverlay)
    },

    // 显示地图弹窗
    showMapPopup(stationInfo) {
      this.popupOverlay.setPosition([stationInfo.lon, stationInfo.lat])
      this.currStationInfo = stationInfo // 填充基本信息
    },

    //关闭地图弹窗
    closeMapPopup() {
      this.popupOverlay.setPosition(null)
    },

    // 获取marker图标
    getMarker(stationInfo) {
      const { lon, lat } = stationInfo
      const img = document.createElement('img')
      img.src =
        MarkerImg[
          ['Car', 'GroudMonitoringStation', 'ImsRnStation', 'NuclearFacility', 'Ship'][parseInt(Math.random() * 5)]
        ]
      img.style.width = '30px'
      img.style.height = '30px'
      img.style.cursor = 'pointer'
      img.addEventListener('click', () => {
        this.showMapPopup(stationInfo)
      })
      return new Overlay({
        position: [lon, lat],
        element: img,
        id: stationInfo.stationId,
        positioning: 'top-center'
      })
    },

    // 设置marker位置
    setMarkerPosition(markerId, position) {
      const overlay = this.map.getOverlayById(markerId)
      overlay.setPosition(position)
    }
  }
}
</script>
<style lang="less" scoped>
.popover {
  width: 200px;
  height: 300px;
  background-color: rgba(2, 26, 29, 0.9);
  box-shadow: 0 0 5px rgba(2, 26, 29, 0.9);
}
</style>
