<template lang="pug">
.location
  el-popover(width='400', trigger='focus' :value="initShow")
    .block
      amap(:center.sync="data" :zoom="15" :animateEnable="false")
        amap-marker(:position.sync="data")
    el-select(slot='reference' v-model='data' remote filterable :remote-method="changeLocation")
      template(#prefix)
        i.el-icon-location
      el-option(v-for='option in locationOptions', :key='option.value | hash', :label='option.label' :value='option.value')
</template>
<script>

const md5 = require('md5')

export default {
  name: 'SmartLocation',
  components: {},
  props: {
    value: {
      type: [String, Boolean, Array, Number, Object, Error],
    },
  },
  states: [],
  data () {
    return {
      initShow: true,
      locationOptions: [{
        label: '默认',
        value: [116.473778, 39.990661],
      }],
      data: [116.473778, 39.990661],
    }
  },
  watch: {
  },
  created () {
  },
  computed: {
  },
  filters: {
    hash (data) {
      if (typeof data === 'object') data = JSON.stringify(data)
      return md5(data || Math.random())
    },
  },
  mounted () {
    setTimeout(() => {
      const AMap = window.AMap
      this.ac = new AMap.AutoComplete()
      this.initShow = false
    }, 100)
  },
  methods: {
    changeLocation (kw) {
      this.ac.search(kw, (status, result) => {
        if (status === 'complete' && result.tips) {
          this.locationOptions = result.tips.map(item => ({
            label: item.name,
            value: [item.location.lng, item.location.lat],
          }))
        }
      })
    },
  },
}
</script>
<style lang="stylus" rel="stylesheet/stylus" scoped>
.block {
  height 400px
}
</style>
