<template>
    <div class="map-wrapper">
      <div id="event-container"></div>
    </div>
</template>

<script setup lang="ts">
import { onMounted, ref, defineProps, onUnmounted } from 'vue'
import {getEventMap} from '@/api/event/map'

interface EventMap  {
  id: string,
  latitude: number,
  longitude: number,
}
const props = defineProps({
  wgs84: {
    type: Object,
    default: () => ({})
  },
  selectable: {
    type: Boolean,
    default: true
  },
});

const emit = defineEmits(['location-selected']);

let map = null as any;
const selectedLocation = ref({
  lng: 0,
  lat: 0,
  address: ''
});
const marker = ref(null);
const mapList = ref<EventMap[]>([]);

// 加载天地图API
const loadTiandituAPI = () => {
  return new Promise((resolve, reject) => {
    if (window.T) {
      resolve(window.T);
      return;
    }
    
    const script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'https://api.tianditu.gov.cn/api?v=4.0&tk=15b72cbf46b07ee54b6e0ef159aa2329';
    script.onload = () => {
      resolve(window.T);
    };
    script.onerror = reject;
    document.head.appendChild(script);
  });
};

// 初始化天地图
const initTiandituMap = () => {
  // 创建地图实例
  map = new T.Map('event-container');
  
  // 设置地图中心点和缩放级别
  const centerPoint = new T.LngLat(121.4737,  31.2304);
  map?.centerAndZoom(centerPoint, 8);

  // 添加地图控件
  const ctrl = new T.Control.MapType();
  map?.addControl(ctrl);

  const zoomCtrl = new T.Control.Zoom();
  map?.addControl(zoomCtrl);

  const scaleCtrl = new T.Control.Scale();
  map?.addControl(scaleCtrl);

  if (mapList.value.length > 0) {
    mapList.value.forEach((item) => {
      addMarker(new T.LngLat(Number(item.longitude), Number(item.latitude)));
    })
  }

};

const addMarker = (lnglat) => {
  if (marker.value) {
    map?.removeOverLay(marker.value);
  }
  
  marker.value = new T.Marker(lnglat);
  map?.addOverLay(marker.value);
};


const fetchEventMaps = async()=>{
  try {
    const res = await getEventMap() || []
    mapList.value = res.data
  } catch (error) {
  }
}

onMounted(() => {
  loadTiandituAPI()
    .then( async() => {
      await fetchEventMaps()
      initTiandituMap();
    })
    .catch((e) => {
      console.error('天地图加载失败:', e);
    });
});

onUnmounted(() => {
  if (map) {
    // 天地图没有直接的destroy方法，可以清空地图容器
    const container = document.getElementById('event-container');
    if (container) {
      container.innerHTML = '';
    }
  }
});
</script>

<style lang="scss" scoped>
.map-wrapper{
  position: relative;
  width: 100%;
  height: 100vh;
}
#event-container {
  width: 100%;
  height: 100%;
  cursor: pointer;
}

.location-info {
  margin-top: 10px;
  padding: 10px;
  background-color: #f5f5f5;
  border-radius: 4px;
  position: relative;
  .edit-btn{
    position: absolute;
    top:20px;
    right: 20px;
  }
  
  p {
    margin: 5px 0;
  }
}
</style>