<template>
  <el-drawer
    :show-close="false"
    :title="'定位'"
    :wrapper-closable="false"
    :close-on-press-escape="false"
    :visible.sync="isShow"
    size="900px"
    custom-class="xl-drawer"
    direction="rtl"
    >
    <el-form :model="pointObj" class="lib-edit" :is-inline="false" label-width="50px" disabled>
      <el-form-item label="经度" style="width:50%">
        <el-input v-model="pointObj.longitude" />
      </el-form-item>
      <el-form-item label="纬度" style="width:50%">
        <el-input v-model="pointObj.latitude" />
      </el-form-item>
      <el-form-item label="地址">
        <el-input v-model="pointObj.address" />
      </el-form-item>
    </el-form>
    <div class="container">
      <div class="search-box">
        <input id="search" v-model="searchKey">
        <button class="search-handle" @click="searchHandle">搜索</button>
        <div id="searchTip" class="tip-box" />
      </div>
      <!-- 地图 -->
      <el-amap
        class="amap-box"
        :amap-manager="amapManager"
        :vid="'amap-vue'"
        :zoom="zoom"
        :plugin="plugin"
        :center="center"
        :events="events"
      >
        <!-- 标记 -->
        <el-amap-marker v-for="(marker, index) in markers" :key="index" :position="marker" />
      </el-amap>
    </div>
    <div class="handle-btn xl-form">
      <el-button class="xl-form-btn t2" @click="close">关 闭</el-button>
      <el-button class="xl-form-btn t1" @click="close('confirm')">确 定</el-button>
    </div>
  </el-drawer>
</template>
<script>
import { AMapManager, lazyAMapApiLoaderInstance } from 'vue-amap'
const amapManager = new AMapManager()
export default {
  name: 'Map',
  mixins,
  props: {
    isShow: Boolean
  },
  data() {
    const _this = this
    return {
      loading: true,
      formData: [],
      searchKey: '',
      amapManager,
      markers: [],
      searchOption: {
        city: '全国',
        citylimit: true
      },
      // center: [114.13245, 22.649001],
      center: [115.852386, 28.684076],
      zoom: 17,
      loaded: false,
      pointObj: {},
      events: {
        init() {
          lazyAMapApiLoaderInstance.load().then(() => {
            _this.initSearch()
          })
        },
        // 点击获取地址的数据
        click(e) {
          _this.markers = []
          const { lng, lat } = e.lnglat
          _this.center = [lng, lat]
          _this.markers.push([lng, lat])
          // 这里通过高德 SDK 完成。
          const geocoder = new AMap.Geocoder({
            radius: 1000,
            extensions: 'all'
          })
          geocoder.getAddress([lng, lat], function(status, result) {
            if (status === 'complete' && result.info === 'OK') {
              if (result && result.regeocode) {
                const address = result.regeocode.formattedAddress
                _this.searchKey = address
                _this.pointObj = {
                  longitude: lng,
                  latitude: lat,
                  address
                }
                _this.$nextTick()
              }
            }
          })
        }
      },
      // 工具插件
      plugin: [
        {
          // 定位
          pName: 'Geolocation',
          events: {
            init(o) {
              if (!_this.pointObj.latitude || !_this.pointObj.longitude) {
                // console.log(1)
                // o是高德地图定位插件实例
                o.getCurrentPosition((status, result) => {
                  if (result && result.position) {
                    const { lng, lat } = result.position // 经纬度
                    _this.center = [lng, lat]
                    _this.pointObj = {
                      longitude: lng,
                      latitude: lat,
                      address: result.formattedAddress
                    }
                    _this.searchKey = result.formattedAddress
                    _this.markers.push([lng, lat])
                    _this.loaded = true
                    // 页面渲染好后
                    _this.$nextTick()
                  }
                })
              }
            },
            click(e) {
              console.log(e)
            }
          }
        },
        {
          // 工具栏
          pName: 'ToolBar',
          position: 'RT',
          events: {
            init(instance) {
            }
          }
        },
        {
          // 搜索
          pName: 'PlaceSearch',
          events: {
            init(instance) {
            }
          }
        }
      ]
    }
  },
  watch: {
    isShow(val) {
      if (val) {
        if (this.pointObj.longitude && this.pointObj.latitude) {
          this.center = [this.pointObj.longitude, this.pointObj.latitude]
        }
        this.searchKey = !this.pointObj.latitude || !this.pointObj.longitude ? '' : this.pointObj.address
        this.markers.push(!this.pointObj.latitude || !this.pointObj.longitude ? [] : [this.pointObj.longitude, this.pointObj.latitude])
      }
    }
  },
  created() {
    this.$root.$on('handleMap', (pointObj) => {
      // console.log('pointObj', pointObj)
      pointObj.address = !pointObj.latitude || !pointObj.longitude ? '' : pointObj.address
      this.pointObj = pointObj
    })
  },
  methods: {
    initSearch() {
      const _this = this
      const map = this.amapManager.getMap()
      AMapUI.loadUI(['misc/PoiPicker'], function(PoiPicker) {
        var poiPicker = new PoiPicker({
          input: 'search',
          placeSearchOptions: {
            map: map,
            pageSize: 10
          },
          suggestContainer: 'searchTip',
          searchResultsContainer: 'searchTip'
        })
        _this.poiPicker = poiPicker
        // 监听poi选中信息
        poiPicker.on('poiPicked', function(poiResult) {
          const source = poiResult.source
          const poi = poiResult.item
          if (source !== 'search') {
            poiPicker.searchByKeyword(poi.name)
          } else {
            poiPicker.clearSearchResults()
            _this.markers = []
            const { lng, lat } = poi.location
            const address = poi.cityname + poi.adname + poi.name
            _this.center = [lng, lat]
            _this.pointObj = {
              longitude: lng,
              latitude: lat,
              address
            }
            _this.markers.push([lng, lat])
            _this.searchKey = address
          }
        })
      })
    },
    searchHandle() {
      if (this.searchKey !== '') {
        this.poiPicker.searchByKeyword(this.searchKey)
      }
    },
    close(str) {
      // this.amapManager.destroy()
      if (str === 'confirm') {
        this.searchKey = ''
        this.$emit('close', this.pointObj)
      } else {
        this.$emit('close')
      }
    }
  }
}
</script>
<style scoped lang="scss">
@import "../../styles/libEdit.scss";
.lib-edit {
  padding-top: 0;
  width:100%;
  ::v-deep .el-form-item {
    margin-bottom: 10px;
  }
  ::v-deep .el-date-editor.el-input {
    width: 100%;
  }
}
.handle-btn {
  text-align: center;
  margin: 20px 0;
}
.container {
  width: 850px;
  height: 500px;
  border: 1px solid #ddd;
  .search-box {
    position: absolute;
    z-index: 5;
    width: 300px;
    height: 30px;
    input {
      float: left;
      width: 80%;
      height: 100%;
      border: 1px solid #30ccc1;
      padding: 0 8px;
      outline: none;
    }
    button {
      float: left;
      width: 20%;
      height: 100%;
      background: #30ccc1;
      border: 1px solid #30ccc1;
      color: #fff;
      outline: none;
      &:hover{
        background: rgba($color: #59d2c9, $alpha: 1.0);
        cursor: pointer;
      }
    }
    .tip-box {
      width: 100%;
      max-height: 260px;
      position: absolute;
      top: 30px;
      overflow-y: auto;
      background-color: #fff;
    }
  }
}
</style>
