<template>
  <div>
    <div class="map-wrapper">
      <div v-if="!isEdit" class="map-mask" @click="isEdit = !isEdit"></div>
      <div id="container"></div>
    </div>
    <div v-if="selectedLocation" class="location-info">
      <el-button class="edit-btn" size="small" @click="isEdit = !isEdit">{{ isEdit ? '保存' : '编辑'}}</el-button>
      <p>经度: {{ selectedLocation.lng }}</p>
      <p>纬度: {{ selectedLocation.lat }}</p>
      <p>地址: {{ selectedLocation.address || '正在获取...' }}</p>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, defineProps, onUnmounted } from 'vue'

const props = defineProps({
  wgs84: {
    type: Object,
    default: () => ({})
  },
  selectable: {
    type: Boolean,
    default: true
  },
});

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

let map = null;
const selectedLocation = ref({
  lng: 0,
  lat: 0,
  address: ''
});
const marker = ref(null);
const isEdit = ref(false);

// 加载天地图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('container');
  
  // 设置地图中心点和缩放级别
  const centerPoint = new T.LngLat(Number(props.wgs84.x) || 116.397428, Number(props.wgs84.y) || 39.90923);
  map.centerAndZoom(centerPoint, 11);

  // 添加地图控件
  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 (props.wgs84.x && props.wgs84.y) {
    addMarker(new T.LngLat(Number(props.wgs84.x), Number(props.wgs84.y)));
    reverseGeocode(new T.LngLat(Number(props.wgs84.x), Number(props.wgs84.y)));
  }

  // 添加地图点击事件
  if (props.selectable) {
    map.addEventListener('click', handleMapClick);
  }
};

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

const reverseGeocode = (lnglat) => {
  const geocoder = new T.Geocoder();
  
  geocoder.getLocation(lnglat, (result) => {
    console.log("选中地址result",result);
    if (result&&result.status==0) {
      const address = result.formatted_address;
      selectedLocation.value = {
        lng: lnglat.getLng(),
        lat: lnglat.getLat(),
        address: address
      };
      emit('location-selected', selectedLocation.value);
    }
  });
};

const handleMapClick = (e) => {
  if (!props.selectable) return;
  
  if (e && e.lnglat) {
    const lnglat = new T.LngLat(e.lnglat.getLng(), e.lnglat.getLat());
    addMarker(lnglat);
    reverseGeocode(lnglat);
  }
};

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

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

<style lang="scss" scoped>
.map-wrapper{
  position: relative;
  width: 100%;
  height: 400px;
  .map-mask{
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    // background-color: rgba(255, 255, 255, 0.5);
    z-index: 999;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
#container {
  width: 100%;
  height: 400px;
  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>