<template>
  <div
    ref="map"
    class="u-relative"
  >
    <i
      v-if="center"
      class="o-place el-icon-place has-active u-pointer"
      @click="onPlace"
    />
  </div>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader'

export default {
  name: 'DeviceMap',
  props: {
    device: {
      type: Object,
      required: true
    }
  },
  computed: {
    center () {
      const { longitude, latitude } = this.device
      return longitude && latitude
        ? [Number(longitude), Number(latitude)]
        : null
    }
  },
  watch: {
    center () {
      if (this.center) {
        if (this.map) {
          this.map.setCenter(this.center)
          this.map.getAllOverlays('marker')[0].setPosition(this.center)
          this.map.setFitView()
        } else {
          this.initMap()
        }
      } else {
        this.map?.destroy()
        this.map = null
      }
    }
  },
  mounted () {
    this.center && this.initMap()
  },
  activated () {
    this.map?.setFitView(null, true)
  },
  beforeDestroy () {
    this.map?.destroy()
  },
  methods: {
    initMap () {
      AMapLoader.load({
        key: process.env.VUE_APP_GAODE_MAP_KEY,
        version: '2.0',
        plugins: ['']
      }).then(AMap => {
        this.map = new AMap.Map(this.$refs.map, {
          center: this.center
        })
        this.map.add(new AMap.Marker({
          position: this.center,
          icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png'
        }))
        this.map.setFitView()
      })
    },
    onPlace () {
      this.map?.setFitView()
    }
  }
}
</script>

<style lang="scss" scoped>
.o-place {
  display: inline-flex;
  justify-content: center;
  align-items: center;
  position: absolute;
  top: 0;
  left: 0;
  width: 48px;
  height: 48px;
  font-size: 24px;
  border-radius: 50%;
  background-color: #fff;
  z-index: 9;
}
</style>
