<template>
  <div class="vmap-container" style="width: 100%;height: 100%;"></div>
</template>

<script>
import { Map, validate } from '../index'
import events from '../constants/event_list'
export default {
  props: ['mapstyle'],
  methods: {
    init() {
      try {
        this.vMap = new Map({
          style: this.mapstyle,
          container: this.$el
        })
        // 托管场景的事件
        events.forEach(eventName => {
          this.vMap.on(eventName, e => {
            this.$emit(`on-${eventName}`, e)
          })
        })
      } catch (err) {
        this.$emit('on-error', err)
        throw err
      }
    }
  },
  mounted() {
    if (!this.mapstyle) {
      return
    }
    if (typeof this.mapstyle !== 'string') {
      let errors = validate(this.mapstyle)
      if (errors.length) {
        console.error(`样式文件错误：${errors.join(';')}`)
        return
      }
    }
    this.init()
    this.$emit('on-render')
  },
  data() {
    return {
      vMap: null
    }
  },
  watch: {
    mapstyle() {
      try {
        if (!this.mapstyle) {
          return
        }
        if (typeof this.mapstyle !== 'string') {
          let errors = validate(this.mapstyle)
          if (errors.length) {
            this.vMap && this.vMap.destroy()
            throw new Error(`样式文件错误：${errors.join(';')}`)
          }
        }
        if (!this.vMap) {
          this.init()
        } else {
          this.vMap.setStyle(this.mapstyle)
        }
        this.$emit('on-render')
      } catch (err) {
        this.$emit('on-error', err)
        throw err
      }
    }
  }
}
</script>

<style scoped></style>
