<template>
  <el-dialog
    v-dialog-drag
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    :title="mapTitle"
    :visible.sync="dialogVisible"
    width="900px"
    append-to-body
    @close="handleClose"
  >
    <el-input id="tipInput" v-model="inputMap" placeholder="请输入搜索名称">
      <el-button slot="append" icon="el-icon-search" @click="handleSearch">搜索</el-button>
    </el-input>
    <div v-if="showSearchResult" class="map_search_result">
      <ul>
        <li v-for="(item,index) in poiList" :key="index" @click="markerResult(item)">{{ item.name }}</li>
      </ul>
    </div>
    <!--    <pre>{{ poiList }}</pre>-->
    <div style="margin: 20px 0;" />
    <div id="container" class="container" />
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
      <el-button @click="handleClose">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader'
import vMap from '@/components/Vctgo/vMap/index'

// 设置安全密钥
window._AMapSecurityConfig = {
  securityJsCode: '1091cb7a90c725e6873bb88e37c54f5d'
}
const init = {
  latitudeTmp: '34.34727',
  longitudeTmp: '108.94647'
}
export default {
  components: {
    vMap
  },
  data() {
    return {
      dialogVisible: false,
      mapTitle: '选择位置',
      map: null,
      inputMap: '',
      auto: null,
      placeSearch: null,
      marker: null,
      geocoder: null,
      instance: null,
      locationAddressTmp: null, // 地址信息
      latitudeLongitudeTmp: null, // 经纬度
      latitudeTmp: init.latitudeTmp,
      longitudeTmp: init.longitudeTmp,
      poiList: [],
      showSearchResult: []
    }
  },
  methods: {
    handleClose() {
      this.latitudeTmp = init.latitudeTmp
      this.longitudeTmp = init.longitudeTmp
      this.inputMap = ''
      this.locationAddressTmp = null
      this.latitudeLongitudeTmp = null
      this.dialogVisible = false
    },
    handleSubmit() {
      this.$emit('ok', {
        latitudeLongitude: this.latitudeLongitudeTmp,
        locationAddress: this.locationAddressTmp
      })
      this.handleClose()
    },
    mapSearchInit() {
      const autoOptions = {
        input: 'tipInput'
      }
      const autoCompleteComponent = new AMap.Autocomplete(autoOptions)
      this.autoCompleteComponent = autoCompleteComponent
      // 注册placeSearch组件
      this.placeSearch = new AMap.PlaceSearch()
    },
    // 初始化地图
    initMap() {
      AMapLoader.load({
        key: 'b036e144859ed142fb696276e16d22c4', // 申请好的Web端开发者Key，首次调用 load 时必填
        version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ['AMap.AutoComplete',
          'AMap.PlaceSearch',
          'AMap.Scale',
          'AMap.OverView',
          'AMap.ToolBar',
          'AMap.MapType',
          'AMap.PolyEditor',
          'AMap.CircleEditor',
          'AMap.Geolocation',
          'AMap.Marker',
          'AMap.Pixel',
          'AMap.Geocoder',
          'AMap.InfoWindow'] // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      }).then((AMap) => {
        this.instance = AMap
        this.map = new AMap.Map('container', { // 设置地图容器id
          viewMode: '2D', // 是否为3D地图模式
          zoom: 15, // 初始化地图级别
          center: [this.longitudeTmp, this.latitudeTmp], // 初始化地图中心点位置
          resizeEnable: true
        })
        // const marker = new AMap.Marker({
        //   icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
        //   position: [22, 22],
        //   offset: new AMap.Pixel(-10, -35),
        //   visible: false
        // })
        // this.marker = marker
        // this.map.add(marker)
        this.map.on('click', (e) => {
          this.setPosition(e.lnglat)
        })
        this.geocoder = new AMap.Geocoder({ extensions: 'all' })
        var autoOptions = { input: 'mapInput' }
        // this.mapSearchInit()
        // this.placeSearch = new AMap.PlaceSearch({
        //   map: this.map,
        //   panel: 'panel', // 结果列表将在此容器中进行展示。
        //   // city: "010", // 兴趣点城市
        //   autoFitView: true, // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
        //   extensions: 'base' // 返回基本地址信息
        // })
        this.placeSearch = new AMap.PlaceSearch()
        // {
        //   pageSize: 5, // 单页显示结果条数
        //     pageIndex: 1, // 页码
        //   city: '010', // 兴趣点城市
        //   citylimit: true, // 是否强制限制在设置的城市内搜索
        //   map: this.map, // 展现结果的地图实例
        //   panel: 'panel', // 结果列表将在此容器中进行展示。
        //   autoFitView: true // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
        // }
        this.auto = new AMap.AutoComplete(autoOptions)
        this.auto.on('select', this.select)// 注册监听，当选中某条记录时会触发
      }).catch(e => {
        console.log(e)
      })
    },
    setPosition(posi) {
      this.geocoder.getAddress(posi, async(status, result) => {
        if (status === 'complete' && result.info === 'OK') {
          this.latitudeLongitudeTmp = posi.lat + ',' + posi.lng
          this.locationAddressTmp = result.regeocode.formattedAddress + '(' + this.latitudeLongitudeTmp + ')'
          this.inputMap = this.locationAddressTmp
        }
      })
    },
    /** 关键词搜索 */
    handleSearch() {
      // this.placeSearch.search(this.inputMap)
      // console.log('this.placeSearch', this.placeSearch)
      const that = this
      this.placeSearch.search(that.inputMap, function(status, result) {
        console.log('search', status, result)
        if (status === 'complete' && result.info === 'OK') {
          that.showsearchResult = true
          that.poiList = result.poiList.pois
        } else {
          that.showsearchResult = false
          that.poiList = []
          that.$message({
            message: '没有查到结果',
            type: 'warning'
          })
        }
      })
      // this.placeSearch.search(this.inputMap, function(status, result) {
      //   // 查询成功时，result即对应匹配的POI信息
      //   console.log(status)
      //   console.log(result)
      //   this.event.addListener(this.placeSearch, 'markerClick', function(e) {
      //     console.log(e.data.location.lng, e.data.location.lat)
      //   })
      // })
    },

    // 选择搜索的内容
    markerResult(data) {
      this.showsearchResult = false
      this.address = data.name
      var marker = new AMap.Marker({
        position: [Number(data.location.lng), Number(data.location.lat)]
      })
      this.map.clearMap()// 清除所有覆盖物（点标志）
      this.map.add(marker)// 添加点标志
      this.showInfoWindow(marker)
      setTimeout(() => {
        this.map.setCenter(data.location)
        this.map.setZoom(15)
      }, 50)
      const thisPosition = {
        address: this.address,
        lng: data.location.lng,
        lat: data.location.lat
      }
      this.$emit('select', thisPosition)
    },
    handleOpen(latitudeTmp, longitudeTmp, inputMap) {
      this.latitudeTmp = latitudeTmp || init.latitudeTmp
      this.longitudeTmp = longitudeTmp || init.longitudeTmp
      this.inputMap = inputMap || null
      this.dialogVisible = true
      this.initMap()
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  width: 800px;
  height: 500px;
}
</style>
