<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"
  >
    <!--    <pre>{{ inputMap }}</pre>-->
    <!--    <pre>longitudeTmp 经度 {{ longitudeTmp }}</pre>-->
    <!--    <pre>latitudeTmp 维度{{ latitudeTmp }}</pre>-->
    <div style="width: 100%">
      <div class="search_box">
        <div class="label">关键字搜索</div>
        <el-input id="tipinput" v-model="inputMap" placeholder="请输入内容">
          <el-button slot="append" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        </el-input>
      </div>
      <div id="container" ref="container" />
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button v-if="!isDetail" type="primary" @click="handleSubmit()">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
import AMapLoader from '@amap/amap-jsapi-loader' // 引入AMapLoader
window._AMapSecurityConfig = {
  // 设置安全密钥
  securityJsCode: '1091cb7a90c725e6873bb88e37c54f5d'
  // securityJsCode: '8600cd917e047e113dcaae8b9aa49071'
  // securityJsCode: 'cde17a9e91459a9afcda0a7fc0ead2b7' // 金恩润泽幼儿园管理
}

const init = {
  latitudeTmp: '34.34727',
  longitudeTmp: '108.94647'
}
export default {
  components: {},
  props: [],
  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,
      lnglat: [], // 经纬度
      poiList: [],
      showSearchResult: [],
      loading: false,
      visible: false,
      isDetail: false,
      dataForm: {
        kqName: undefined,
        kqLocation: undefined,
        kqLongitude: undefined,
        kqLatitude: undefined,
        kqWorkUnit: undefined,
        cronkqAccredit: [],
        kqValidCardRange: undefined
      },
      rules: {},
      input: '',
      markers: [],
      position: {}
    }
  },
  computed: {},
  watch: {},
  created() { },
  mounted() { },
  methods: {
    getAddress() {
      const that = this
      this.geocoder.getAddress([this.longitudeTmp, this.latitudeTmp], function(status, result) {
        if (status === 'complete' && result.info === 'OK') {
          that.inputMap = `${result.regeocode.formattedAddress}(${that.latitudeTmp},${that.longitudeTmp})`
        }
      })
    },
    // 地图初始化
    initMap() {
      AMapLoader.load({
        key: 'b036e144859ed142fb696276e16d22c4', // 申请好的Web端开发者Key，首次调用 load 时必填
        // key: '71a217d98a2f5ca90eea9c7ce5ad21a7', // 申请好的Web端开发者Key，首次调用 load 时必填
        // key: 'a28fef7625af82d237ec36a4b2b35b0b', // 申请好的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.AdvancedInfoWindow' // 高级信息窗体，整合了周边搜索、路线规划功能
        ]
      }).then((AMap) => {
        this.map = new AMap.Map('container', {
          // 设置地图容器id
          viewMode: '3D', //  是否为3D地图模式
          zoom: 15, // 初始化地图级别
          center: [this.longitudeTmp, this.latitudeTmp], // 中心点坐标
          resizeEnable: true
        })
        this.geocoder = new AMap.Geocoder({})
        this.setMarker([this.longitudeTmp, this.latitudeTmp])
        // 关键字查询
        this.searchMap(AMap)
        // 监听鼠标点击事件
        this.map.on('click', this.clickMapHandler)
      }).catch((e) => { })
    },
    // 关键字查询
    searchMap(AMap) {
      console.log('searchMap')
      // 搜索框自动完成类
      this.auto = new AMap.AutoComplete({
        input: 'tipinput' // 使用联想输入的input的id
      })
      // 构造地点查询类
      this.placeSearch = new AMap.PlaceSearch({
        map: this.map
      })
      // 当选中某条搜索记录时触发
      this.auto.on('select', this.selectSite)
    },
    // 选中查询出的记录
    selectSite(e) {
      console.log('selectSite ', e)
      if (e.poi.location) {
        // const lnglat = [e.poi.location.lng, e.poi.location.lat]
        this.latitudeTmp = e.poi.location.lat
        this.longitudeTmp = e.poi.location.lng
        console.log('查询值 选中下拉框 getAddress')
        this.getAddress()
      } else {
        this.$message.error('查询地址失败，请重新输入地址')
      }
    },
    // 点击地图事件获取经纬度，并添加标记
    clickMapHandler(e) {
      this.longitudeTmp = e.lnglat.getLng()
      this.latitudeTmp = e.lnglat.getLat()
      // this.lnglat = [e.lnglat.getLng(), e.lnglat.getLat()]
      console.log('click map this.lnglat', this.lnglat, e)
      this.setMarker()
      this.getAddress()
    },
    onClickMarker(e) {
      console.log('click marker', e)
      this.longitudeTmp = e.lnglat.lng
      this.latitudeTmp = e.lnglat.lat
      this.getAddress()
    },
    //  添加标记
    setMarker() {
      const that = this
      this.removeMarker()
      const marker = new AMap.Marker({
        position: [this.longitudeTmp, this.latitudeTmp]
      })
      marker.setMap(this.map)
      // this.markers.push(marker)
      marker.on('click', (e) => {
        console.log('marker click', e)
        that.map.setCenter([e.lnglat.lng, e.lnglat.lat])
        that.onClickMarker(e)
      })
    },
    // 删除之前后的标记点
    removeMarker() {
      if (this.markers) {
        this.map.remove(this.markers)
      }
    },
    handleSearch() {
      const that = this
      this.placeSearch.search(this.inputMap)
    },
    handleOpen(latitudeTmp, longitudeTmp, inputMap) {
      this.latitudeTmp = latitudeTmp || init.latitudeTmp
      this.longitudeTmp = longitudeTmp || init.longitudeTmp
      this.inputMap = inputMap
      this.dialogVisible = true
      this.initMap()
    },
    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.latitudeTmp + ',' + this.longitudeTmp,
        locationAddress: this.inputMap
      })
      this.handleClose()
    }
  }
}
</script>

<style lang="scss">
.search_box {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  height: 50px;

  .label {
    color: #000;
    width: 100px;
  }
}

.content {
  position: relative;
}

#panel {
  position: absolute;
  top: 50px;
  right: 20px;
}

#container {
  overflow: hidden;
  width: 100%;
  height: 540px;
  margin: 0;
}

.amap-sug-result {
  z-index: 2999 !important;
}
</style>
