<template>
  <div class="map full">
    <div class="map-container full"></div>
  </div>
</template>

<script>
import mapboxgl from 'mapbox-gl'
import _ from 'lodash'
import style from './map'
import elementResizeDetectorMaker from 'element-resize-detector'

mapboxgl.accessToken =
  'pk.eyJ1Ijoid2FueWFueWFuIiwiYSI6Im1uNVZnTncifQ.90XY40_yjpItUHO8HnbbpA'

export default {
  props: {
    list: {
      type: Array,
      default: []
    }
  },
  methods: {
    jump2project(item) {
      this.$emit('on-click', item)
    },
    updateMarkers() {
      this.removeAllmarkers()
      this.markers = []
      let bounds = [180, 90, -180, -90]
      this.list.forEach(item => {
        let {project_id, bbox, name} = item
        if (!bbox) {
          return
        }
        let center = [(bbox[0]+bbox[2])/2, (bbox[1]+bbox[3])/2]
        let el = document.createElement('div')
        el.className = 'project-marker cursor'
        let nameEl = document.createElement('div')
        nameEl.className = 'marker-name'
        nameEl.innerText = name
        el.appendChild(nameEl)
        let imgEl = document.createElement('div')
        imgEl.className = 'marker-img'
        el.appendChild(imgEl)
        el.onclick = e => {
          this.jump2project(item)
        }
        let marker = new mapboxgl.Marker({element: el}).setLngLat(center).addTo(this.map)
        marker.id = project_id
        this.markers.push(marker)
        bounds[0] = Math.min(bbox[0], bounds[0])
        bounds[1] = Math.min(bbox[1], bounds[1])
        bounds[2] = Math.max(bbox[2], bounds[2])
        bounds[3] = Math.max(bbox[3], bounds[3])
      })
      console.log(bounds)
      this.map.fitBounds(bounds, {
        padding: 50,
        duration: 1000
      })
    },
    removeAllmarkers() {
      if (!this.markers?.length) {
        return
      }
      this.markers.forEach(marker => {
        marker.remove()
      })
      this.markers = []
    }
  },
  mounted() {
    this.map = new mapboxgl.Map({
      container: this.$el.querySelector('.map-container'),
      style,
      bearing: 0,
      pitch: 0,
      center: [110.9, 32.79],
      zoom: 4.2,
      doubleClickZoom: false,
      dragRotate: false,
      pitchWithRotate: false
    })
    var erd = elementResizeDetectorMaker();
    erd.listenTo(this.$el, element => {
      this.map.resize()
    });
    this.updateMarkers()
  },
  data() {
    return {
      dlgShow: false,
      projectName: ''
    }
  },
  watch: {
    list: {
      deep: true,
      handler() {
        this.updateMarkers()
      }
    }
  }
}
</script>