<template>
  <div class="map-info">
       <input type="text" readonly :value="xyText" />
    <input type="text" readonly :value="wgs84Text" /> 
    <!-- <input type="text" readonly :value="pixelText" /> -->
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue';
import { transform } from 'ol/proj';

const props = defineProps({
  map: Object
});

const xyText = ref('XY坐标: --');
const wgs84Text = ref('WGS84: --');
// const pixelText = ref('像素: --');

function handleMouseMove(event) {
  if (!props.map) {
    console.warn('地图实例未传递到OpenLayersMapInfo组件');
    return;
  }
  
  try {
    // 1. 获取像素坐标
    const pixel = [event.offsetX, event.offsetY];
    // console.log('鼠标像素坐标:', pixel);
    
    // 2. 获取投影坐标
    const coordinate = props.map.getCoordinateFromPixel(pixel);
    // console.log('投影坐标:', coordinate);
    
    if (coordinate) {
      xyText.value = `XY坐标: X=${coordinate[0].toFixed(6)}, Y=${coordinate[1].toFixed(6)}`;
      
      // 3. 转换为WGS84
      try {
        const [lng, lat] = transform(coordinate, 'EPSG:4528', 'EPSG:4326');
      //  console.log('WGS84坐标:', lng, lat);
        wgs84Text.value = `WGS84: 经度=${lng.toFixed(6)}°, 纬度=${lat.toFixed(6)}°`;
      } catch (error) {
       // console.error('坐标转换失败:', error);
        wgs84Text.value = 'WGS84: 转换错误';
      }
    } else {
      xyText.value = 'XY坐标: --';
      wgs84Text.value = 'WGS84: --';
    }
  } catch (error) {
    console.error('处理鼠标移动事件时出错:', error);
    xyText.value = 'XY坐标: 错误';
    wgs84Text.value = 'WGS84: 错误';
  }
}

function setupListener() {
  if (!props.map) return;
  const mapElement = props.map.getTargetElement();
  if (mapElement) {
    mapElement.addEventListener('mousemove', handleMouseMove);
  }
}
function cleanupListener() {
  if (!props.map) return;
  const mapElement = props.map.getTargetElement();
  if (mapElement) {
    mapElement.removeEventListener('mousemove', handleMouseMove);
  }
}

onMounted(setupListener);
onUnmounted(cleanupListener);
watch(() => props.map, (newMap, oldMap) => {
  cleanupListener();
  setupListener();
});
</script>

<style scoped>
.map-info {
  position: absolute;
  bottom: 10px;
  right: 25px;
  z-index: 3000;
  display: flex;
  flex-direction: column;
  gap: 1px;
  pointer-events: none;
  padding: 5px;
  border-radius: 4px;
  background-color: rgba(255, 255, 255, 0.6);
}
.map-info input {
  padding: 4px;
  background: rgba(255, 255, 255, 0.8);
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 12px;
  color: #333;
  width: 350px;
  margin-bottom: 2px;
  pointer-events: none;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .map-info {
    bottom: 10px;
    right: 10px;
  }
  
  .map-info input {
    width: 250px;
    font-size: 11px;
  }
}
</style> 