<template>
  <div class="n-map"></div>
</template>

<script>
import {prop, loadMap} from '@uif/next/lib/utils/tools'
import vModel from '_common/vModel'

export default {
  name: 'n-map',
  mixins: [vModel],
  props: {
    // 坐标
    value: prop.object(() => ({lng: 116.404, lat: 39.915})),
    // 缩放等级
    zoom: prop.number(12),
    // 可控制
    control: prop.boolean()
  },
  data () {
    return {
      nValue: this.value
    }
  },
  watch: {
    nValue (location) {
      if (this.marker && (this.marker.lng !== location.lng || this.marker.lat !== location.lat)) {
        this.setCenter(location)
        this.setMarker(location)
      }
    }
  },
  mounted () {
    this.mapInit()
  },
  methods: {
    // 初始化
    mapInit () {
      return loadMap().then(BMap => {
        this.BMap = BMap
        this.map = new this.BMap.Map(this.$el)
        this.map.enableScrollWheelZoom()
        this.setCenter(this.nValue)
        this.setMarker(this.nValue)
        if (this.control) {
          // 添加默认缩放平移控件
          this.map.addControl(new this.BMap.NavigationControl())
          // 添加默认缩略地图控件
          this.map.addControl(new this.BMap.OverviewMapControl())
          this.map.addEventListener('click', this.onMapClick)
        }
      })
    },
    setByAddress (address, zoom) {
      new this.BMap.Geocoder()
        .getPoint(address, location => {
          if (location) {
            this.setMarker(location)
            this.setCenter(location, zoom || 16)
          }
        })
    },
    // 地图点击事件
    onMapClick (evt) {
      this.nValue = evt.point
      this.setMarker(this.nValue)
      this.$emit('u-change', this.nValue)
    },
    // 设置居中
    setCenter (location, zoom) {
      const point = new this.BMap.Point(location.lng, location.lat)
      this.map.centerAndZoom(point, zoom || this.zoom)
    },
    // 设置标记
    setMarker (location) {
      this.marker = location
      const point = new this.BMap.Point(this.marker.lng, this.marker.lat)
      const marker = new this.BMap.Marker(point)
      this.map.clearOverlays()
      this.map.addOverlay(marker)
    }
  }
}
</script>
