<template>
  <div style="width: 100%" @click="show()">
    <slot></slot>

    <BasicModal
      width="1000px"
      @register="registerModal"
      @ok="submit"
      @cancel="handleCancel"
      destroy-on-close
      :title="t('选择地址')"
    >
      <div class="mb-2">
        <Input id="tipinput" v-model:value="val" :placeholder="t('请填写详细地址')" />
      </div>
      <div id="container" ref="wrapRef" style="width: 100%; height: 500px"></div>
    </BasicModal>
  </div>
</template>

<script setup lang="ts">
  import { nextTick, ref, unref } from 'vue';
  import { BasicModal, useModal } from '/@/components/Modal';
  import { Input, message } from 'ant-design-vue';
  import { useScript } from '/@/hooks/web/useScript';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();
  const emits = defineEmits(['success', 'cancel']);
  const A_MAP_URL = 'https://webapi.amap.com/maps?v=2.0&key=4b3856cde2cd0421211ccc386669b33a';
  const props = defineProps({
    value: String,
  });
  const val = ref<string>();

  const wrapRef = ref<HTMLDivElement | null>(null);
  const AMap = ref<any>();
  const map = ref<any>();
  const geocoder = ref<any>();
  const mapMarker = ref<any>();
  const placeSearch = ref<any>();
  const auto = ref<any>();
  const { toPromise } = useScript({ src: A_MAP_URL });
  //输入提示
  var autoOptions = {
    input: 'tipinput',
  };
  const lnglat = ref<string[]>([]);
  const [registerModal, { closeModal, openModal }] = useModal();

  async function initMap() {
    await toPromise();
    await nextTick();
    const wrapEl = unref(wrapRef);

    if (!wrapEl) return;
    AMap.value = (window as any).AMap;
    map.value = new AMap.value.Map('container', {
      resizeEnable: true,
    });

    map.value.on('click', showInfoClick);
    markerByAddress();
    geocoder.value = new AMap.value.Geocoder({
      city: '010', //城市设为北京，默认：“全国”
      radius: 1000, //范围，默认：500
    });
    mapMarker.value = new AMap.value.Marker();

    // AMap.value.plugin('AMap.Geolocation', function () {
    //   var geolocation = new AMap.value.Geolocation({
    //     enableHighAccuracy: true, // 是否使用高精度定位，默认：true
    //     timeout: 10000, // 设置定位超时时间，默认：无穷大
    //     offset: [10, 20], // 定位按钮的停靠位置的偏移量
    //     zoomToAccuracy: true, //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
    //     position: 'RB', //  定位按钮的排放位置,  RB表示右下
    //   });

    //   geolocation.getCurrentPosition(function (status, result) {
    //     if (status == 'complete') {
    //       onComplete(result);
    //     } else {
    //       onError(result);
    //     }
    //   });

    //   function onComplete(data) {
    //     // data是具体的定位信息
    //     console.log(data, 'onComplete');
    //   }

    //   function onError(data) {
    //     // 定位出错
    //     console.log(data);
    //   }
    // });
  }

  function showInfoClick(e) {
    lnglat.value = [e.lnglat.getLng(), e.lnglat.getLat()];
    map.value.add(mapMarker.value);
    mapMarker.value.setPosition(lnglat.value);
    geocoderAddr();
  }
  function showMarkerClick(e) {
    lnglat.value = [e.lnglat.getLng(), e.lnglat.getLat()];
    geocoderAddr();
  }
  function geocoderAddr() {
    geocoder.value.getAddress(lnglat.value, function (status, result) {
      if (status === 'complete' && result.regeocode) {
        val.value = result.regeocode.formattedAddress;
      } else {
        message.error(t('根据经纬度查询地址失败'));
      }
    });
  }
  function markerByAddress() {
    AMap.value.plugin(
      ['AMap.PlaceSearch', 'AMap.AutoComplete', 'AMap.Geolocation', 'AMap.Geocoder'],
      function () {
        auto.value = new AMap.value.AutoComplete(autoOptions);
        placeSearch.value = new AMap.value.PlaceSearch({
          map: map.value,
        }); //构造地点查询类
        if (val.value) serachVal(val.value);
        auto.value.on('select', select); //注册监听，当选中某条记录时会触发
        function select(e) {
          placeSearch.value.setCity(e.poi.adcode);
          val.value = e.poi.name;
          serachVal(e.poi.name);
        }
      },
    );
  }

  function serachVal(name) {
    placeSearch.value.search(name, function (status, result) {
      // 查询成功时，result即对应匹配的POI信息

      if (status == 'complete') {
        map.value.getAllOverlays('marker').forEach((o) => {
          map.value.remove(o);
        });
        var pois = result.poiList.pois;
        for (var i = 0; i < pois.length; i++) {
          var poi = pois[i];
          var marker: any = [];
          marker[i] = new AMap.value.Marker({
            position: poi.location, // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
            title: poi.name,
          });
          // 将创建的点标记添加到已有的地图实例：
          map.value.add(marker[i]);
          marker[i].on('click', showMarkerClick);
        }
        map.value.setFitView();
      } else {
        message.warning(t('未匹配到POI信息'));
      }
    }); //关键字查询查询
  }
  function show() {
    openModal();
    val.value = props.value;
    if (!props.value) {
      //预览页面 重置
      val.value = '';
    }
    initMap();
  }
  function submit() {
    emits('success', { lnglat: lnglat.value, address: val.value });

    closeModal();
  }
  function handleCancel() {
    emits('cancel');

    closeModal();
  }
</script>
<style>
  .amap-sug-result {
    border: 0;
  }
</style>
