<template>
  <el-dialog title="选择位置" :visible.sync="selectAddressMapVisible" width="60%">
    <div class="map-cpn-container">
      <div class="buiness-search-conrainer" style="display: flex; align-items: center; margin: 0 0 20px 0;">
        <el-select style="width: 100%;" @change="handleSelectChange" v-model="searchAddress" filterable remote
          reserve-keyword placeholder="请输入您的位置" :remote-method="handleSearchNearbyAddress" :loading="isLoading">
          <el-option v-for="(item, index) in addressList" :key="index" :label="item.name" :value="item.name + item.tel">
          </el-option>
        </el-select>
      </div>
      <div v-if="currentSelectLngLat.length">当前选中的位置：<el-tag>{{ currentSelectLngLat[0] }} </el-tag> - <el-tag>{{
        currentSelectLngLat[1] }}</el-tag></div>
      <el-divider></el-divider>
      <div id="map-container"></div>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="selectAddressMapVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader'
import { MessageBox } from 'element-ui'

export default {
  data() {
    return {
      selectAddressMapVisible: false,
      map: null,
      prevPoint: null,
      searchAddress: "",
      currentAddressPoint: [113.08272, 22.87655],
      isLoading: false,
      addressList: [],
      currentSelectLngLat: []
    }
  },

  methods: {
    show() {
      this.selectAddressMapVisible = true
      !this.map && this.initMap()
    },

    initMap() {
      window._AMapSecurityConfig = {
        securityJsCode: 'ad9587997f413d1089653ea4560a91d0'
      }

      AMapLoader.load({
        key: "3b84da70f85b1024deb934d8835b03ad",
        version: "2.0",
        plugins: ['AMap.HawkEye', 'AMap.AutoComplete', 'AMap.Marker', 'AMap.PlaceSearch'],
      }).then((AMap) => {
        this.map = new AMap.Map("map-container", {
          zoom: 16,
          center: this.currentAddressPoint,
        });

        this.map.on('click', this.getClickAddress)

      }).catch(e => {
        console.log(e);
      })
    },

    setSelectPoint() {

    },

    getClickAddress(e) {
      const { lnglat } = e
      const { lat, lng } = lnglat
      this.searchAddress = ''
      this.prevPoint && this.map.remove(this.prevPoint)
      this.currentAddressPoint = [lng, lat]
      this.currentSelectLngLat = [lng, lat]
      this.map.setZoomAndCenter(18, [lng, lat])
      this.prevPoint = new AMap.Marker({
        position: this.currentAddressPoint,
      });
      this.prevPoint.setMap(this.map);
    },

    /**
     * 搜索地址
     */
    handleSearchNearbyAddress(queryString) {
      if (queryString) {
        const _this = this
        this.isLoading = true
        let placeSearch = new AMap.PlaceSearch({
          pageSize: 50,
          pageIndex: 1,
          extensions: 'all',
        })
        placeSearch.searchNearBy(queryString, this.currentAddressPoint, 50000, function (status, result) {
          if (result && typeof result === 'object' && result.info === 'OK') {
            _this.addressList = result.poiList.pois
          }
          _this.isLoading = false
        })
      }
    },

    handleSelectChange(e) {
      const detailInfo = this.addressList.find(item => {
        return item.name + item.tel === e
      })

      if (detailInfo) {
        const location = detailInfo.location
        this.currentSelectLngLat = [location.lng, location.lat]
        this.map.setZoomAndCenter(18, this.currentSelectLngLat)
        this.prevPoint = new AMap.Marker({
          position: this.currentSelectLngLat,
        });
        this.prevPoint.setMap(this.map);
      }
    },

    // 点击确定
    handleSubmit() {
      if (!this.currentSelectLngLat.length) {
        MessageBox.confirm('您还没选择门店经纬度，确认关闭？', '提示').then(res => {
          this.selectAddressMapVisible = false
        }).catch(() => {
          console.log("取消了");
        })
      } else {
        this.$emit('select', this.currentSelectLngLat)
        this.selectAddressMapVisible = false
      }
    }
  },
}
</script>

<style lang="scss" scoped>
#map-container {
  width: 100%;
  height: 500px;
}
</style>