<template>
  <super-dialog v-bind="$attrs" v-model="isShowDialog" fullscreen :modal="false" @open="open" @closed="closed"
    :title="title" append-to-body>
    <div class="process-dialog">
      <div id="mapContainer" v-loading="mapLoading"></div>
      <div class="marker-result">
        <el-row>
          <el-col :span="12">
            <span>经度： {{ location.lng }}</span>
          </el-col>
          <el-col :span="12">
            <span>经度： {{ location.lat }}</span>
          </el-col>
        </el-row>
      </div>
      <div class="search-style" style="display: flex; align-items: center">
        <el-input placeholder="请输入搜索地址" style="width: 100%" id="tipinput" v-model="mapAddress" @input="searchKeyWord"
          @blur="searchKeyWord">
          <el-button slot="append" icon="el-icon-search" @change="searchKeyWord"></el-button>
        </el-input>
      </div>
      <div class="map_search" v-if="showsearchResult">
        <ul>
          <li v-if="!poiListData.length" class="li-style">暂无结果</li>
          <li v-else class="li-style" style="cursor: pointer" @click="markerResult(item)"
            v-for="(item, index) in poiListData" :key="index">
            {{ item.name }}
          </li>
        </ul>
      </div>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="isShowDialog = false">取 消</el-button>
      <el-button type="primary" @click="handleSave">确 定</el-button>
    </span>
  </super-dialog>
</template>

<script>
import { lazyAMapApiLoaderInstance } from 'vue-amap'
window._AMapSecurityConfig = {
  securityJsCode: window.context.securityJsCode, //你的秘钥
}
import SuperDialog from '@/components/SuperDialog/index.vue'
import { dictionaryEscape, getDictionaryByCode } from '@/utils/dictionary'
export default {
  name: 'MapLocationPickup',
  inheritAttrs: false,
  props: {
    isShow: {
      default: false,
      type: Boolean,
    },
    title: {
      default: '坐标拾取',
      type: String,
    },
    locationList: {
      type: Array,
      default: () => [],
    },
  },
  components: {
    SuperDialog,
  },
  data() {
    return {
      mapLoading: false,
      editorOptions: undefined,
      autoCompleteComponent: undefined,
      placeSearchComponent: undefined,
      mapAddress: '',
      showsearchResult: false,
      poiListData: [],
      map: null,
      address: '',
      location: {
        lng: undefined,
        lat: undefined,
      },
      marker: null,
    }
  },
  computed: {
    isShowDialog: {
      get() {
        return this.isShow
      },
      set(val) {
        this.$emit('update:isShow', val)
      },
    },
  },

  methods: {
    getDictionaryByCode,
    dictionaryEscape,
    // 打开弹层时触发
    open() {
      lazyAMapApiLoaderInstance.load().then((response) => {
        this.initMap()
      })
    },

    handleSave() {
      if (this.location.lng && this.location.lat) {
        this.$emit('location', this.location)
        this.isShowDialog = false
      } else {
        this.$message({
          message: '请选择坐标',
          type: 'warning',
        })
      }
    },
    /** 初始化搜索 */
    mapSearchInit() {
      let autoOptions = {
        input: 'tipInput',
        city: '重庆,四川,贵州,云南', //城市
      }
      this.autoCompleteComponent = new AMap.Autocomplete(autoOptions)
      // 注册placeSearch组件
      this.placeSearchComponent = new AMap.PlaceSearch({
        city: '重庆,四川,贵州,云南', //城市
        citylimit: false
      })
    },
    searchKeyWord() {
      if (this.mapAddress !== '') {
        this.placeSearchComponent.search(this.mapAddress, (status, result) => {
          if (status === 'complete' && result.info === 'OK') {
            this.showsearchResult = true
            this.poiListData = result.poiList.pois
          } else {
            this.showsearchResult = true
            this.poiListData = []
          }
        })
      } else {
        this.poiListData = []
        this.showsearchResult = false
        this.map.clearMap()
      }
    },
    markerResult(data) {
      this.showsearchResult = false
      this.address = data.name
      this.map.clearMap() // 清除所有覆盖物（点标志）
      this.marker = null
      this.location = {
        lng: undefined,
        lat: undefined,
      }
      this.marker = new AMap.Marker({
        draggable: true,
        position: [Number(data.location.lng), Number(data.location.lat)],
      })

      this.map.add(this.marker) // 添加点标志
      this.showInfoWindow(this.marker)
      setTimeout(() => {
        this.map.setCenter(data.location)
        this.map.setZoom(15)
      }, 50)
      this.location = {
        lng: data.location.lng,
        lat: data.location.lat,
      }
      this.marker.on('dragend', () => {
        this.mapAddress = ''
        this.showsearchResult = false
        //拖动坐标获取新坐标
        console.log('最新坐标：', this.marker.getPosition())
        const { lng, lat } = this.marker.getPosition()
        this.location = {
          lng,
          lat,
        }
        this.getPalceByLngLat(lng, lat, () => {
          this.showInfoWindow(this.marker)
        })
      })
    },
    //反查地址
    getPalceByLngLat(lng, lat, cb) {
      if (!this.geocoder) {
        AMap.plugin('AMap.Geocoder', () => {
          this.geocoder = new AMap.Geocoder()
        })
      }

      this.geocoder.getAddress([lng, lat], (status, result) => {
        if (status === 'complete' && result.info === 'OK') {
          this.address = result.regeocode.formattedAddress
          cb && cb()
        } else {
          this.address = ''
          cb && cb()
        }
      })
    },
    showInfoWindow(marker) {
      let infoWindow = new AMap.InfoWindow({
        isCustom: true, //是否自定义信息窗体
        content: `<div style="background-color: white;color:#000000; padding: 10px; border-radius: 5px;border: 1px solid #cccccc;"> 地址：${this.address}</div>`,
        closeWhenClickMap: true,
        zIndex: 999,
        offset: new AMap.Pixel(16, -35),
      })
      infoWindow.open(this.map, marker.getPosition())
    },
    //地图初始化
    initMap() {
      this.map = new AMap.Map('mapContainer', {
        center: [106.5478767, 29.5647398],
        zoom: 11,
        layers: [
          new AMap.TileLayer(), // 默认普通地图图层
        ],
      })
      this.map.on('click', (ev) => {
        this.mapAddress = ''
        const lng = ev.lnglat.getLng()
        const lat = ev.lnglat.getLat()
        this.getPalceByLngLat(lng, lat, () => {
          this.markerResult({
            name: this.address,
            location: {
              lng,
              lat,
            },
          })
        })
      })
      // 搜索
      this.mapSearchInit()
      // //editorOptions 是一个配置对象，专门用于控制地图上编辑功能的样式和行为，尤其是与 MouseTool 配合使用时，能够对绘制的图形进行编辑（例如移动标记点、修改多边形节点等）。
      this.editorOptions = {
        editMarkerOptions: {
          icon: new AMap.Icon({
            size: new AMap.Size(16, 16), // 图标大小
            image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
          }),
          offset: new AMap.Pixel(-8, -8), // 图标偏移量
        },
        // 配置可移动的标记点的样式
        moveMarkerOptions: {
          icon: new AMap.Icon({
            size: new AMap.Size(20, 20),
            image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png',
          }),
          offset: new AMap.Pixel(-10, -10),
        },
        // 配置多边形/线条中间节点的样式
        midMarkerOptions: {
          icon: new AMap.Icon({
            size: new AMap.Size(14, 14),
            image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png',
          }),
          offset: new AMap.Pixel(-7, -7),
        },
      }
    },

    // 关闭弹层触发
    closed() {
      const { orgData } = this
      // 重置data中的数据
      Object.assign(this.$data, this.$options.data.call(this), { orgData })
    },
  },
}
</script>

<style lang="scss" scoped>
@import "@/assets/css/element-variables";

::v-deep .el-dialog__body {
  height: calc(100% - 60px) !important;
  max-height: calc(100% - 60px) !important;
}

::v-deep .el-dialog__footer {
  text-align: center;
}

::v-deep .super-dialog-content {
  height: calc(100% - 50px) !important;
  //   padding: 0!important;
}

.process-dialog {
  height: 100% !important;
  background-color: #f2f2f2;
  position: relative;
}

#mapContainer {
  width: 100%;
  height: 100%;
  position: absolute;
}

.marker-result {
  position: absolute;
  top: 30px;
  left: 30px;
  z-index: 200;
  width: 300px;
  height: 40px;
  background: #114066;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
  color: #fff;
  line-height: 40px;
  font-size: 14px;

  span {
    padding: 0 10px;
  }
}

.search-style {
  position: absolute;
  top: 68px;
  left: 30px;
  z-index: 200;
  width: 300px;
  height: 40px;
}

.map_search {
  position: absolute;
  top: 108px;
  left: 30px;
  z-index: 999;
  width: 300px;
  height: 200px;
  overflow-y: scroll;
  background: #114066;
  color: #fff;
  border-radius: 5px;
}

.li-style {
  padding: 6px 15px;
}

.li-style:hover {
  background: #43a1ff;
}
</style>