<!-- 地图关键字模糊搜索位置-->
<!--
prop:
  location: '北京',

-->

<template>
  <div>
    <el-autocomplete
      v-model="key"
      :fetch-suggestions="querySearchAsync"
      placeholder="请输入内容"
      :style="{ width: '100%' }"
      @change="change"
      @select="getAddress"
    />
    <baidu-map>
      <bm-local-search
        :auto-viewport="true"
        :keyword="key"
        :location="location"
        :panel="false"
        @searchcomplete="searchcomplete"
      />
    </baidu-map>
  </div>
</template>

<script>
export default {
  props: {
    keyword: {
      type: String,
      default: '',
    },
    location: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      key: '',
      addressList: [],
      loading: false,
      selectAddress: {},
    }
  },
  watch: {
    keyword(newVal, oldVal) {
      this.key = newVal
    },
    // key(newVal, oldVal) {
    //   this.getAddress({
    //     value: newVal,
    //   })
    // },
  },
  methods: {
    searchcomplete(results) {
      if (results && results.as) {
        this.addressList = results.as
      } else {
        this.addressList = {}
      }
    },
    querySearchAsync(queryString, cb) {
      clearTimeout(this.timeout)
      this.timeout = setTimeout(() => {
        cb(this.createStateFilter())
      }, 500)
    },
    createStateFilter() {
      let addressList = this.addressList
      if (this.addressList.length > 0) {
        return addressList.map((address) => {
          return {
            value: address.address,
            lat: address.point.lat,
            lng: address.point.lng,
          }
        })
      } else {
        return []
      }
    },
    getAddress(item) {
      this.$emit('getAddress', item)
    },
    change(val) {
      this.$emit('change', val)
    },
  },
}
</script>
