<template>
  <div>
    <div class="positionBox">
      <!-- <div>单位地址：<a-input
        style="width: 300px; "
        v-model="positionVal"
        placeholder="点击选择单位地址"
        @focus="handleOpen"
      ></a-input></div> -->

      <div class="wrapper">
        <div class="mapcontainer">
          <div class="el-dialog__header" style="margin-bottom: 15px">
            <!-- <button type="button" aria-label="Close" class="el-dialog__headerbtn" @click="handleClose">
              <i class="el-dialog__close el-icon el-icon-close" style="font-size: 25px"></i>
            </button> -->
          </div>
          <div class="mapContent">
            <div id="all" style="height: 100%">
              <div class="posInput" style="width: 700px;">
                <a-input
                  style="width: 45%; margin-left: 30px"
                  id="tipinput"
                  class="form-control input-style"
                  type="text"
                  autocomplete='off'
                  placeholder="请输入搜索地址"
                  v-model="MapAdress"
                  @focus="handleOpen"
                  @change="changeInput"
                >
                </a-input>
                <a-button type="primary" style="margin-left: 10px" @click="insureMapAdress">确定</a-button>
                <span style="margin-left: 10px;display: inline-block;margin-top: 5px;color: rgb(226, 85, 85);">注：选择地址后请点击确定提交地址</span>
              </div>

              <div id="allmap"></div>
              <!-- <div class="posSubmit">
              <el-form ref="form" label-width="100px">
                <div class="btn_box">
                  <el-form-item label="地址坐标:" style="width:45%">
                    <el-input disabled type="text" v-model="insureAdress" >
                    </el-input>
                  </el-form-item>
                  <el-form-item label="经纬度:" style="width:45%">
                    <el-input disabled type="text" v-model="insureAdress2" >
                    </el-input>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" size="large" style="margin-left: 10px" @click="insureMapAdress">确定</el-button>
                  </el-form-item>
                </div>
              </el-form>
            </div> -->
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import AMapLoader from '@amap/amap-jsapi-loader'
export default {
  name: 'app',
  props: {
    open: {
      type: Boolean,
    },
  },
  watch: {
    open: {
      handler(val) {
        if (val == false) {
          this.MapAdress = ''
        }
      },
      immediate: true,
      deep: true,
    },
  },
  data() {
    return {
    //   dialogVisible: true,
      positionVal: '',
      map: null,
      marker: null,
      geocoder: null, // 地理编码与逆地理编码类，用于地址描述与坐标之间的转换
      startAutoComplete: null,
      startPlaceSearch: null,
      positionPicker: null,
      startSeacrh: [],
      stratInfo: {},

      thisPosition: {
        location: '',
        lng: '',
        lat: '',
      },
      mapinitCode: 0, //地理编码:1;地理逆编码:2
      MapAdress: '',
      insureAdress: '',
      insureAdress2: '',
    }
  },
  mounted() {
    this.loadmap();//因为使用的弹窗加载，所以这里不用执行了，在打开弹窗时候在调用此方法
  },
  methods: {
    loadmap() {
      const that = this
      return new Promise((reslove, reject) => {
        AMapLoader.load({
          key: 'a09220a9ab56352435dd123abf0c37f6', // 申请好的Web端开发者Key，首次调用 load 时必填
          // version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
          plugins: ['AMap.ToolBar', 'AMap.Scale', 'AMap.Geocoder'], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
          AMapUI: {
            // 是否加载 AMapUI，缺省不加载
            version: '1.1', // AMapUI 缺省 1.1
            plugins: [], // 需要加载的 AMapUI ui插件
          },
        })
          .then((AMap) => {
            that.map = new AMap.Map('allmap', {
              resizeEnable: true,
              zoom: 10,
              center: [116.397428, 39.90923], //中心点坐标
            })
            // 地图点击事件
            // that.map.on("click", (e) =>{
            //   let lnglatXY = [e.lnglat.getLng(), e.lnglat.getLat()];
            //   console.log(lnglatXY)//当前经纬度
            // })

            //地图控件
            that.map.addControl(new AMap.Scale())
            that.map.addControl(new AMap.ToolBar())
            // that.map.setMapStyle("amap://styles/blue")
            // that.map.setMapStyle("amap://styles/darkblue")
            // 地理编码与逆地理编码类，用于地址描述与坐标之间的转换
            that.geocoder = new AMap.Geocoder()
            //地点查询
            AMap.plugin(['AMap.PlaceSearch', 'AMap.Autocomplete'], function () {
              let autoOptions1 = {
                input: 'tipinput',
                city: '全国',
              }
              that.startAutoComplete = new AMap.Autocomplete(autoOptions1)
              that.startPlaceSearch = new AMap.PlaceSearch({
                map: that.map,
              })
              that.startAutoComplete.on('select', that.handleStartSelect) //注册监听，当选中某条记录时会触发
            })
            that.handlePositionPickerEvent() //实现地图拖拽选址功能

            that.map.setZoom(14) //设置缩放大小

            reslove()
          })
          .catch((e) => {
            console.log(e, '高德地图加载失败')
            reject(e)
          })
      })
    },
    handlePositionPickerEvent() {
      let that = this
      AMapUI.loadUI(['misc/PositionPicker'], (PositionPicker) => {
        console.log('拖拽加载成功')
        that.positionPicker = new PositionPicker({
          // mode: 'dragMap',//拖拽地图
          mode: 'dragMarker', //拖拽图标
          map: that.map,
        })

        that.positionPicker.on('success', (positionResult) => {
          console.log(positionResult, '拖拽信息')
          console.log(positionResult.position, '拖拽经纬度')

          if (positionResult.address) {
            this.insureAdress = positionResult.address
            this.insureAdress2 = '[' + positionResult.position + ']'
          } else {
            this.insureAdress = ''
            this.insureAdress2 = ''
          }
        })
        that.positionPicker.on('fail', (positionResult) => {
          // 海上或海外无法获得地址信息
        })
      })
    },
    handleStartSelect(event) {
      console.log(event, '起点经纬度 [lng,lat]')
      if (event.poi.location == '') {
        this.$message({
          type: 'warning',
          message: '该地点无经纬度数据，请输入具体一点的地点!',
          duration: 5 * 1000,
        })
        return
      }
      if (this.marker) {
        this.map.remove(this.marker)
        this.marker = null
      }
      this.startSeacrh = []
      this.stratInfo = {}
      this.startSeacrh = [event.poi.location.lng, event.poi.location.lat]
      this.stratInfo = {
        district: event.poi.district,
        address: event.poi.address,
        name: event.poi.name,
      }
      this.insureAdress = event.poi.district + event.poi.address + event.poi.name
      this.insureAdress2 = '[' + event.poi.location.lng + ',' + event.poi.location.lat + ']'
      this.MapAdress=event.poi.address
      this.thisPosition.lat=event.poi.location.lat
      this.thisPosition.lng=event.poi.location.lng
      this.thisPosition.location=event.poi.address
      // marker添加地图上
      // this.marker = new AMap.Marker({
      //   position: this.startSeacrh, //位置
      // });
      // this.map.add(this.marker); //添加到地图

      // 传入经纬度，设置地图中心点
      this.map.setCenter(this.startSeacrh)
      this.positionPicker.start(this.startSeacrh) //启动这句控制 地图出现一个maker点，可以移动
      // this.positionPicker.stop();   //取消移动的maker
      this.map.setZoom(15)

      // 添加自定义弹窗
      // this.addDialog(this.insureAdress);
    },
    addDialog(address) {
      this.map.setCenter(this.startSeacrh)
      this.marker.content = address
      this.marker.on('click', this.markerClick)
      this.marker.emit('click', { target: this.marker })
    },
    markerClick(e) {
      let infoWindow = new AMap.InfoWindow({ offset: new AMap.Pixel(0, -30) })
      infoWindow.setContent(e.target.content)
      infoWindow.open(this.map, e.target.getPosition())
    },
    insureMapAdress() {
      //确定地址
      this.positionVal = this.insureAdress
    //   this.dialogVisible = true
    //   this.MapAdress = ''
    //   this.insureAdress = ''
    //   this.insureAdress2 = ''
      this.positionPicker.stop() //取消移动的maker
      this.$emit('MapAdressName',this.thisPosition)
    },

    maplocal(address) {
      //地理逆编码
      this.geocoder.getLocation(address, (status, result) => {
        console.log(address)
        if (status === 'complete' && result.geocodes.length) {
          console.log(result)
          const lnglat = result.geocodes[0].location

          const lat = lnglat.lat
          const lng = lnglat.lng
          that.mapinit(lat, lng) //tips：使用地理逆编码，此时解析出的经纬度位置也应逆换
        } else {
          console.log(result)
        }
      })
    },
    handleOpen() {
    //   this.dialogVisible = true
      this.loadmap()
    },
    handleClose() {
    //   this.dialogVisible = true
      this.MapAdress = ''
      this.insureAdress = ''
      this.insureAdress2 = ''
      this.positionPicker.stop() //取消移动的maker
    },
    changeInput(ev){
        this.thisPosition.location=ev.target.value
    }
  },
}
</script>
<style scoped>
.mapContent {
  /* position: absolute;
  left:0;
  top:0;
  width:100%; */
  height: 450px;
  /* width: 600px; */
}
#all {
  position: relative;
}
#allmap {
  width: 100%;
  /* height: calc(100% - 50px); */
  height: 400px;
  font-family: '微软雅黑';
}
.posInput {
  width: 50%;
  margin-bottom: 20px;
  display: flex;
}
::v-deep .el-form-item {
  margin-bottom: 0 !important;
}
.btn_box {
  display: flex;
}
/* 去除高德水印 */
::v-deep .amap-logo {
  display: none;
  opacity: 0 !important;
}
::v-deep .amap-copyright {
  opacity: 0;
}
/* .wrapper {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background: rgb(0 0 0 / 30%);
} */
/* .mapcontainer {
  position: absolute;
  left: 50%;
  top: 50%;
  width: 80%;
  transform: translate(-50%, -50%);
  background: #fff;
  padding: 50px;
} */
</style>
