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

<script>
import geojsonExtent from '@mapbox/geojson-extent'
import util from '../../libs/util'
import {tableDataLoad} from '../../libs/request'
import mapboxgl from 'mapbox-gl'
import style from '../../constants/map_style'
mapboxgl.accessToken = "pk.eyJ1Ijoid2FueWFueWFuIiwiYSI6Im1uNVZnTncifQ.90XY40_yjpItUHO8HnbbpA";
export default {
  props: {
    selectedItem: {
      type: Object,
      default: null
    }
  },
  methods: {
    initMap() {
      let tileUrl = `${util.getAPI('tables')}/${this.selectedItem.owner}/${this.selectedItem.resId}/data?format=pbf&x={x}&y={y}&z={z}`
      let styleStr = JSON.stringify(style)
      styleStr = styleStr.replace(/\{\{tiles\}\}/g, tileUrl).replace(/\{\{resId\}\}/g, this.selectedItem.resId)
      let mapStyle = JSON.parse(styleStr)
      window.map = this.map = new mapboxgl.Map({
        container: this.$el.querySelector('.map-container'),
        attributionControl: false,
        style: mapStyle,
      })
      this.map.on('mousemove', this.mapMouseMove)
      this.map.on('click', this.mapClick)
      this.popup = new mapboxgl.Popup({
        closeButton: false,
        closeOnClick: false,
      })
      // 以下为临时解决方案，从后台请求geojson来获取数据的经纬度范围
      tableDataLoad(this.selectedItem.owner, this.selectedItem.resId, {
        format: 'geojson'
      }).then(res => {
        let extent = geojsonExtent(res.data)
        this.map.fitBounds(extent)
      })
    },
    mapMouseMove(e) {
      const features = this.map.queryRenderedFeatures(e.point) || []
      this.map.getCanvas().style.cursor = features.length ? 'pointer' : ''
    },
    mapClick(e) {
      const features = this.map.queryRenderedFeatures(e.point) || []
      if (!features.length) {
        this.popup.remove()
        if (this.clickedLayerId) {
          this.map.setFilter(this.clickedLayerId + '_highlight', [
            'in',
            'ogc_fid',
            -1,
          ])
        }
        return
      }
      this.clickedLayerId = features[0].layer.id.replace('_highlight', '')
      this.map.setFilter(this.clickedLayerId + '_highlight', [
        'in',
        'ogc_fid',
        features[0].properties.ogc_fid,
      ])
      this.popup
        .setLngLat(e.lngLat)
        .setHTML(this.renderPopup(features))
        .addTo(this.map)
    },
    renderPopup(features) {
      return `
        <div class="popup">
          ${features
            .map(
              (feature) => `
            <div id="feature">${this.renderFeature(feature)}</div>
          `
            )
            .join('')}
        </div>
      `
    },
    renderFeature(feature) {
      const sourceLayer = feature.layer['source-layer'] || feature.layer.source
      const properties = []
      if (feature.id) properties.push(['$id', feature.id])
      properties.push(['$type', feature.geometry.type])
      Object.keys(feature.properties).forEach((key) => {
        properties.push([key, feature.properties[key]])
      })

      return `
        <div class="layer">${sourceLayer}</div>
        ${properties
          .map(
            (property) => `
          <div class="property">
            <div class="property-key">${property[0]}</div>
            <div class="property-value" title="${property[1]}">${property[1]}</div>
          </div>
          `
          )
          .join('')}
      `
    }
  },
  mounted() {
    this.initMap()
  },
  beforeDestroy() {
    this.map.remove()
    this.map = {}
  },
  data() {
    return {
      map: {},
      popup: {},
      clickedLayerId: ''
    }
  }
}
</script>
