<template>
  <el-dialog
    :title="$t('common.map')"
    :visible.sync="viewMapInfo.showMap"
    width="80%"
    :before-close="closeMap"
    :close-on-click-modal="false"
    :close-on-press-escape="true"
  >
    <div class="map-container">
      <div id="qqmapcontainer" style="width: 100%; height: 500px;"></div>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: 'ViewMap',
  data() {
    return {
      viewMapInfo: {
        lat: '',
        lng: '',
        showMap: false,
        map: null
      }
    }
  },
  methods: {
    open(param) {
      this.viewMapInfo.showMap = true

      if (param.lng && param.lat) {
        const lngLat = this.wgs84togcj02(param.lng, param.lat)
        this.viewMapInfo.lat = lngLat.lat
        this.viewMapInfo.lng = lngLat.lon
      } else {
        this.viewMapInfo.lat = 36.72
        this.viewMapInfo.lng = 100.985
      }

      this.$nextTick(() => this.initMap())
    },
    initMap() {
      const container = document.getElementById('qqmapcontainer')
      if (!container) return

      this.viewMapInfo.map = new window.AMap.Map(container, {
        center: [this.viewMapInfo.lng, this.viewMapInfo.lat],
        zoom: 17.2,
        resizeEnable: true
      })

      new window.AMap.Marker({
        position: [this.viewMapInfo.lng, this.viewMapInfo.lat],
        map: this.viewMapInfo.map,
        icon: new window.AMap.Icon({
          size: new window.AMap.Size(25, 35),
          imageSize: new window.AMap.Size(25, 35),
          image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png'
        })
      })
    },
    closeMap(done) {
      if (this.viewMapInfo.map) {
        this.viewMapInfo.map.destroy()
        this.viewMapInfo.map = null
      }
      this.viewMapInfo.showMap = false
      if (typeof done === 'function') {
        done()
      }
    },
    wgs84togcj02(lng, lat) {
      return { lon: lng, lat }
    }
  }
}
</script>

<style lang="scss" scoped>
.map-container {
  width: 100%;
  height: 500px;
}
</style>
