<template>
  <div>
    <van-field
        :value="value && value.detail" type="textarea"
        :label="label" :rules="requireRule(required, label, type)" is-link readonly
        :placeholder="`请选择${label}`" :clearable="clearable" :disabled="disabled" :required="required" :maxlength="100"
        @click="showMap"/>
    <van-overlay :show="visible">
        <div id="container"></div>
        <input v-model="keyword" id="tipinput" autocomplete="off" placeholder="请输入关键字">
        <van-button id="btn" type="primary" @click="visible=false" native-type="button">确定</van-button>
    </van-overlay>
  </div>
</template>

<script>
import mixin from './mixin'

/**
 * 地图选择组件
 */
export default {
  mixins: [mixin],
  model: {
    prop: 'value',
    event: 'change'
  },
  props: {
    type: {
      type: String
    },
    maxlength: {
      type: Number,
      default: 20
    }
  },
  data() {
      return {
          visible: false
      }
  },
  methods: {
      showMap(){
          this.visible = true
          this.$nextTick(this.initMap)
      },
      initMap(){
        if (this.map) {
            return
        }
        const map = new AMap.Map("container", {
            resizeEnable: true,
            zoom: 10
        })
        this.map = map
        AMap.plugin(['AMap.Scale', 'AMap.PlaceSearch','AMap.AutoComplete'], () => {
            map.addControl(new AMap.Scale())
            const auto = new AMap.AutoComplete({input: 'tipinput'})
            const placeSearch = new AMap.PlaceSearch({map: map})
            auto.on('select', e => {
                placeSearch.setCity(e.poi.adcode)
                placeSearch.search(e.poi.name)
            })
        })

        AMapUI.loadUI(['misc/PositionPicker'], PositionPicker => {
            const positionPicker = new PositionPicker({
                mode: 'dragMap',
                map: map
            })
            this.positionPicker = positionPicker
            positionPicker.on('success', ({address, position: {lat, lng}}) => {
                this.keyword = address
                this.$emit('change', {
                    detail: address,
                    latitude: lat,
                    longitude: lng
                })
            })
            positionPicker.start(map.getCenter())
        })
    }

  }
}
</script>

<style>
#container {
  width: 100%;
  height: 100%;
}
#tipinput {
    position: absolute;
    top: 0;
    width: 80%;
    height: 42px;
    border: none;
    color: #08080a;
    text-indent: 1em;
}
#btn {
    position: absolute;
    top: 0;
    right: 0;
    width: 20%;
}
.amap-sug-result{
    z-index: 99999;
}
</style>