<template>
  <div class="map">
    <el-row v-show="showTool">
      <el-col :span="17">
        <el-input v-model="search" @keyup.enter.native="seachPlace" placeholder="请输入搜索关键词"></el-input>
      </el-col>
      <el-col :span="6" style="margin-left: 14px;">
        <el-button type="primary" @click="seachPlace">查找</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-col>
    </el-row>
    <div id="container"></div>
    <div id="panel" v-show="showMarker"></div>
    <el-row class="res" v-show="current">
      <el-col :span="20">
        <div class="address">
          <span>{{ current && current.address }}</span>
        </div>
      </el-col>
      <el-col :span="3" style="margin-left: 14px;">
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { isEmpty, notEmpty } from '@/utils/tool'

export default {
  name: 'PlaceMap',
  data () {
    return {
      search: null,
      map: null,
      /**
       * address: 地址
       * lat: 经度
       * lon: 纬度
       * name: 名称
       * province: 省
       * city: 市
       * distinct: 区
       */
      current: null,
      showMarker: false,
      markerList: null,
      lat: '',
      lng: '',
      geocoder: null,
      marker: null
    }
  },
  props: {
    address: {
      type: String,
      default: () => ''
    },
    showTool:{
      type: Boolean,
      default: true
    }
  },
  mounted () {
    this.initMap()
  },
  methods: {
    initMap () {
      let that = this
      //创建地图
      // eslint-disable-next-line no-undef
      const map = new AMap.Map('container', {
        resizeEnable: true,
        zoom: 16
      })
      this.map = map

      // eslint-disable-next-line no-undef
      this.marker = new AMap.Marker({
        map: this.map,
        icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
      })

      //定位
      if (this.address) {
        this.search = this.address
        // eslint-disable-next-line no-undef
        AMap.plugin('AMap.PlaceSearch', () => {
          // eslint-disable-next-line no-undef
          let placeSearch = new AMap.PlaceSearch({
            pageSize: 1, // 单页显示结果条数
            pageIndex: 1, // 页码
            extensions: 'all',
          })
          placeSearch.search(this.search, (status, result) => {
            if (status === 'complete' && result.poiList.pois && result.poiList.pois.length > 0) {
              let l = result.poiList.pois[0].location
              // eslint-disable-next-line no-undef
              that.marker.setPosition(new AMap.LngLat(l.lng, l.lat))
              // eslint-disable-next-line no-undef
              that.map.setCenter(new AMap.LngLat(l.lng, l.lat))
            }
          })
        })
      }
      else {
        this.currentLocation()
      }

      map.on('click', (e) => {
        that.getAddress(e.lnglat)
        // eslint-disable-next-line no-undef
        that.marker.setPosition(new AMap.LngLat(e.lnglat.lng, e.lnglat.lat))
        // eslint-disable-next-line no-undef
        that.map.setCenter(new AMap.LngLat(e.lnglat.lng, e.lnglat.lat))
      })

      // eslint-disable-next-line no-undef
      AMap.plugin('AMap.Geocoder', function () {
        // eslint-disable-next-line no-undef
        that.geocoder = new AMap.Geocoder({
          // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
          city: '全国'
        })
      })

      // eslint-disable-next-line no-undef
      // this.geocoder = new AMap.Geocoder({
      //     // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
      //     city: '重庆'
      // })

      // 默认的图标样式
      const defaultIconStyle = function (index) {
        return 'red-' + (index + 1)
      }
      //鼠标hover时的样式
      const hoverIconStyle = function (index) {
        return 'blue-' + (index + 1)
      }
      //选中时的图标样式
      const selectedIconStyle = function (index) {
        return 'blue-' + (index + 1)
      }

      const vm = this
      // eslint-disable-next-line no-undef
      AMapUI.loadUI(['misc/PositionPicker', 'control/BasicControl', 'misc/MarkerList', 'overlay/SimpleMarker', 'overlay/SimpleInfoWindow'], function (PositionPicker, BasicControl, MarkerList, SimpleMarker, SimpleInfoWindow) {
        map.addControl(new BasicControl.Zoom({
          position: 'lt',
        }))

        const markerList = new MarkerList({
          map: map,
          listContainer: 'panel',
          //从数据中读取位置, 返回lngLat
          getPosition: function (item) {
            return item.location
          },
          //数据ID，如果不提供，默认使用数组索引，即index
          getDataId: function (item, index) {
            return item.id
          },
          getInfoWindow: function (data, context, recycledInfoWindow) {
            if (recycledInfoWindow) {
              recycledInfoWindow.setInfoTitle(data.name)
              recycledInfoWindow.setInfoBody(data.address)
              return recycledInfoWindow
            }

            return new SimpleInfoWindow({
              infoTitle: data.name,
              infoBody: data.address,
              // eslint-disable-next-line no-undef
              offset: new AMap.Pixel(0, -32)
            })
          },
          //构造marker用的options对象, content和title支持模板，也可以是函数，返回marker实例，或者返回options对象
          getMarker: function (data, context, recycledMarker) {
            if (recycledMarker) {
              recycledMarker.setIconStyle(defaultIconStyle(context.index))
              return
            }
            return new SimpleMarker({
              iconTheme: 'numv1',
              containerClassNames: 'my-marker',
              iconStyle: defaultIconStyle(context.index),
            })
          },
          //构造列表元素，与getMarker类似，可以是函数，返回一个dom元素，或者模板 html string
          getListElement: function (data, context, recycledListElement) {
            const label = '' + (context.index + 1)
            //使用模板创建
            const innerHTML = MarkerList.utils.template(
              '<% if(data.photos && data.photos[0]) { %>' +
              '<div class="poi-imgbox">' +
              '    <span class="poi-img" style="background-image:url(<%- data.photos[0].url %>)"></span>' +
              '</div>' +
              '<% } %>' +
              '<div class="poi-info-left">' +
              '    <h3 class="poi-title">' +
              '        <%- label %>. <%- data.name %>' +
              '    </h3>' +
              '    <div class="poi-info">' +
              '        <p class="poi-addr">地址：<%- data.address %></p>' +
              '<% if(data.tel ){ %>' +
              '        <p class="poi-addr">电话：<%- data.tel %></p>' +
              '<% } %>' +
              '    </div>' +
              '</div>' +
              '<div class="clear"></div>', {
                data: data,
                label: label
              })

            if (recycledListElement) {
              recycledListElement.innerHTML = innerHTML
              return recycledListElement
            }

            return '<li class="poibox">' + innerHTML + '</li>'
          },
          //列表节点上监听的事件
          listElementEvents: ['click'],
          //marker上监听的事件
          markerEvents: ['click'],
          //makeSelectedEvents:false,
          selectedClassNames: 'selected',
          autoSetFitView: true
        })
        vm.markerList = markerList

        markerList.on('selectedChanged', function (event, info) {
          if (info.selected) {
            const { data, marker } = info.selected
            if (marker) {
              //更新为选中样式
              info.selected.marker.setIconStyle(selectedIconStyle(info.selected.index))
            }

            if (data && data.location) {
              map.setZoomAndCenter(18, [data.location.lng, data.location.lat])

              vm.current = {
                address: data.address,
                lat: data.location.lat,
                lon: data.location.lng,
                name: data.name,
                province: data.pname,
                city: data.cityname,
                distinct: data.adname
              }
            }
          }

          if (info.unSelected && info.unSelected.marker) {
            //更新为默认样式
            info.unSelected.marker.setIconStyle(defaultIconStyle(info.unSelected.index))
          }
        })

        //vm.currentLocation()
      })
    },
    getAddress (lnglat) {
      if (this.lat === lnglat.lat && this.lng === lnglat.lng) {
        return false
      }
      this.lat = lnglat.lat
      this.lng = lnglat.lng
      this.geocoder.getAddress(lnglat, (status, result) => {
        if (status === 'complete' && result.info === 'OK') {
          // result为对应的地理位置详细信息
          this.search = result.regeocode.formattedAddress
        }
      })
    },
    currentLocation () {
      const vm = this
      // eslint-disable-next-line no-undef
      AMap.plugin('AMap.Geolocation', function () {
        // eslint-disable-next-line no-undef
        var geolocation = new AMap.Geolocation({
          // 是否使用高精度定位，默认：true
          enableHighAccuracy: true,
          // eslint-disable-next-line no-undef
          buttonOffset: new AMap.Pixel(10, 20),
          zoomToAccuracy: true,
          buttonPosition: 'LB'
        })
        vm.map.addControl(geolocation)
        geolocation.getCurrentPosition()
        // eslint-disable-next-line no-undef
        AMap.event.addListener(geolocation, 'complete', onComplete)

        function onComplete (res) {
          if (res) {
            vm.current = {
              address: res.formattedAddress,
              lat: res.position.lat,
              lon: res.position.lng,
              name: res.formattedAddress,
              province: res.province,
              city: res.city,
              distinct: res.district
            }
          }
        }
      })
    },
    resetSearch () {
      this.search = ''
      this.showMarker = false
    },
    seachPlace () {
      if (isEmpty(this.search)) {
        return
      }
      const vm = this
      // eslint-disable-next-line no-undef
      AMap.service(['AMap.PlaceSearch'], function () {
        //构造地点查询类
        // eslint-disable-next-line no-undef
        var placeSearch = new AMap.PlaceSearch({
          pageSize: 5, // 单页显示结果条数
          pageIndex: 1, // 页码
          extensions: 'all',
        })
        //关键字查询
        placeSearch.search(vm.search, function (status, result) {
          if (status === 'complete' && result.poiList.pois && result.poiList.pois.length > 0) {
            vm.markerList.render(result.poiList.pois)
            vm.showMarker = true
          }
        })
      })
    },
    handleConfirm () {
      if (this.current && notEmpty(this.current.address)) {
        this.$emit('changePlace', this.current)
      } else {
        this.$message.warning('请选择单位地址')
      }
    }
  },
  destroyed () {
    this.map && this.map.destroy()
  }
}
</script>

<style>
  li.poibox {
    border-bottom: 1px solid #eaeaea;
    border-left: 2px solid rgba(0, 0, 0, 0);
    padding: 10px 3px;
    cursor: pointer;
  }

  li.poibox.selected {
    border-left-color: #f00;
    background: #f6f6f6;
  }

  li.poibox:hover {
    background: #f6f6f6;
  }

  li.poibox:last-child {
    border-bottom: none;
  }

  h3.poi-title {
    margin: 3px 0;
    font-size: 13px;
  }

  .poibox .poi-info-left {
    padding-left: 8px;
  }

  .poi-addr {
    margin: 7px 0 0;
  }

  .poibox .poi-imgbox {
    width: 100px;
    height: 74px;
    vertical-align: top;
    float: right;
    margin: 0 8px;
    overflow: hidden;
  }

  .poibox .poi-img {
    display: inline-block;
    width: 100%;
    height: 100%;
    background-size: cover;
    background-position: 50% 50%;
  }
</style>

<style lang="scss" scoped>
  .map {
    position: relative;
  }

  #container {
    margin-top: 14px;
    width: 100%;
    height: 400px;
  }

  ul, li {
    padding: 0;
    margin: 0;
    list-style: none;
  }

  #panel {
    position: absolute;
    top: 50px;
    bottom: 0;
    right: 0;
    height: 400px;
    overflow: auto;
    width: 240px;
    z-index: 999;
    border: 1px solid #eaeaea;
    background: #fff;
  }

  .res {
    margin-top: 15px;
    display: flex;
    align-items: center;
  }
</style>