<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref, watchEffect } from 'vue';
import { useScriptTag } from '@vueuse/core';
import { AMAP_SDK_URL } from '@/constants/map-sdk';

// eslint-disable-next-line no-underscore-dangle
window._AMapSecurityConfig = {
  securityJsCode: '3625f15d14e8a930436da886419363ff'
};

defineOptions({
  name: 'MapGaode'
});

const { value } = defineProps<{
  value: [number, number] | [string, string] | string | null;
}>();

// 可得到地址信息
const address = defineModel<string>('address', { default: '' });

const { load } = useScriptTag(AMAP_SDK_URL);

const domRef = ref<HTMLDivElement>();
const map = ref<AMap.Map | null>(null);
const marker = ref<AMap.Marker | null>(null);
const circle = ref<AMap.Circle | null>(null);
const geocoder = ref<any>(null);

// eslint-disable-next-line vue/return-in-computed-property
const loglat = computed<[number, number]>(() => {
  // 转换成[number, number]格式
  if (Array.isArray(value)) {
    if (Object.prototype.toString.call(value[0]) === '[object String]') return value.map(item => Number(item));
    return value;
  } else if (Object.prototype.toString.call(value) === '[object String]') {
    return value!.split(',').map(item => Number(item));
  }
});

async function renderMap() {
  await load(true);
  if (!domRef.value || !loglat.value) return;
  map.value = new AMap.Map(domRef.value, {
    zoom: 20,
    center: loglat.value,
    viewMode: '3D'
  });

  // eslint-disable-next-line no-new
  marker.value = new AMap.Marker({
    position: new AMap.LngLat(...loglat.value)
  });
  map.value.add(marker.value);

  loadPlugin();

  map.value.getCenter();
}

// 需要加载的插件有经纬度和电子转换，POI 搜索插件，输入提示插件
function loadPlugin() {
  AMap.plugin(['AMap.Geocoder'], () => {
    // 开发依赖有一个map的ts检测包，但是不包括插件相关的
    geocoder.value = new AMap.Geocoder();
  });
}

watchEffect(() => {
  if (value && geocoder.value) {
    geocoder.value.getAddress(loglat.value, (status: string, result: any) => {
      if (status === 'complete' && result.regeocode) {
        address.value = result.regeocode.formattedAddress;
        console.log('地址解析成功:', result.regeocode.formattedAddress);
      } else {
        address.value = '';
        console.error('地址解析失败:', status, result); // 增加详细错误日志
      }
    });
  }
});

onMounted(() => {
  renderMap();
});

onBeforeUnmount(() => {
  map.value?.destroy();
  map.value = null;
  marker.value = null;
  circle.value = null;
  geocoder.value = null;
});
</script>

<template>
  <div ref="domRef" class="h-full w-full"></div>
</template>

<style scoped></style>
