<template>
  <div 
    class="floating-map-container"
    :style="{
      width: `${width}px`,
      height: `${height}px`,
      left: `${position.x}px`,
      top: `${position.y}px`,
      zIndex: zIndex
    }"
   
  >
    <div class="map-header" 
    @mousedown="startDrag"
    @touchstart="startDrag">
      <span>实时位置</span>
      <div class="controls">
        <!-- <el-icon @click="toggleSize"><Expand /></el-icon> -->
        <el-icon @click="close"><Close /></el-icon>
      </div>
    </div>
    <div 
      id="float-container" 
      class="map-body"
      @mousedown.stop
    ></div>
    <div 
      class="resize-handle"
      @mousedown="startResize"
      @touchstart="startResize"
    ></div>
  </div>
</template>

<script setup>
import { ref, onMounted,watch ,onUnmounted  } from 'vue'
import { Expand, Close } from '@element-plus/icons-vue'

const props = defineProps({
  // 初始位置
  initialPosition: {
    type: Object,
    default: () => ({ x: window.innerWidth - 320, y: window.innerHeight - 240 })
  },
  // 初始尺寸
  initialSize: {
    type: Object,
    default: () => ({ width: 500, height: 350 })
  },
  // 飞机位置数据
  planePosition: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(['close'])

const position = ref({ ...props.initialPosition })
const width = ref(props.initialSize.width)
const height = ref(props.initialSize.height)
const zIndex = ref(100)
const isDragging = ref(false)
const isResizing = ref(false)
const startPos = ref({ x: 0, y: 0 })
const map = ref(null)
const marker = ref(null)

// 加载天地图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.value = new T.Map('float-container');
  console.log("")
  // 设置地图中心点和缩放级别
  const centerPoint = new T.LngLat(116.397428, 39.90923);
  map.value.centerAndZoom(centerPoint, 11);



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

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



// 更新飞机位置
const updatePlanePosition = () => {
  if (map.value && marker.value) {
    const newPos = new T.LngLat(props.planePosition.lng, props.planePosition.lat)
    marker.value.setLngLat(newPos)
    map.value.panTo(newPos)
  }
}

// 开始拖动
const startDrag = (e) => {
  e.preventDefault()
  isDragging.value = true
  zIndex.value = 1000 // 确保拖动时在最上层
  
  const clientX = e.clientX || e.touches[0].clientX
  const clientY = e.clientY || e.touches[0].clientY
  
  startPos.value = {
    x: clientX - position.value.x,
    y: clientY - position.value.y
  }
  
  document.addEventListener('mousemove', handleDrag)
  document.addEventListener('touchmove', handleDrag, { passive: false })
  document.addEventListener('mouseup', stopDrag)
  document.addEventListener('touchend', stopDrag)
}

// 处理拖动
const handleDrag = (e) => {
  if (!isDragging.value) return
  e.preventDefault()
  
  const clientX = e.clientX || e.touches[0].clientX
  const clientY = e.clientY || e.touches[0].clientY
  
  position.value = {
    x: clientX - startPos.value.x,
    y: clientY - startPos.value.y
  }
}

// 停止拖动
const stopDrag = () => {
  isDragging.value = false
  document.removeEventListener('mousemove', handleDrag)
  document.removeEventListener('touchmove', handleDrag)
  document.removeEventListener('mouseup', stopDrag)
  document.removeEventListener('touchend', stopDrag)
}

// 开始调整大小
const startResize = (e) => {
  e.preventDefault()
  e.stopPropagation()
  isResizing.value = true
  
  const clientX = e.clientX || e.touches[0].clientX
  const clientY = e.clientY || e.touches[0].clientY
  
  startPos.value = {
    x: clientX,
    y: clientY
  }
  
  document.addEventListener('mousemove', handleResize)
  document.addEventListener('touchmove', handleResize, { passive: false })
  document.addEventListener('mouseup', stopResize)
  document.addEventListener('touchend', stopResize)
}

// 处理调整大小
const handleResize = (e) => {
  if (!isResizing.value) return
  e.preventDefault()
  
  const clientX = e.clientX || e.touches[0].clientX
  const clientY = e.clientY || e.touches[0].clientY
  
  const deltaX = clientX - startPos.value.x
  const deltaY = clientY - startPos.value.y
  
  width.value = Math.max(200, width.value + deltaX)
  height.value = Math.max(150, height.value + deltaY)
  
  startPos.value = { x: clientX, y: clientY }
  
  // 地图尺寸变化后需要重新调整
  if (map.value) {
    setTimeout(() => {
      map.value.checkResize()
    }, 0)
  }
}

// 停止调整大小
const stopResize = () => {
  isResizing.value = false
  document.removeEventListener('mousemove', handleResize)
  document.removeEventListener('touchmove', handleResize)
  document.removeEventListener('mouseup', stopResize)
  document.removeEventListener('touchend', stopResize)
}

// 切换大小
const toggleSize = () => {
  if (width.value === 300) {
    width.value = 500
    height.value = 350
  } else {
    width.value = 300
    height.value = 200
  }
  
  // 地图尺寸变化后需要重新调整
  if (map.value) {
    setTimeout(() => {
      map.value.checkResize()
    }, 0)
  }
}

// 关闭浮窗
const close = () => {
  emit('close')
}

// 监听飞机位置变化
watch(() => props.planePosition, () => {
  updatePlanePosition()
}, { deep: true })

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

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

<style scoped>
.floating-map-container {
  position: fixed;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
  display: flex;
  flex-direction: column;
  cursor: move;
  user-select: none;
  transition: all 0.3s ease;
}

.map-header {
  padding: 8px 12px;
  background-color: #165DFF;
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: move;
}

.map-header span {
  font-size: 14px;
  font-weight: bold;
}

.controls {
  display: flex;
  gap: 8px;
}

.controls .el-icon {
  cursor: pointer;
  padding: 2px;
  border-radius: 4px;
}

.controls .el-icon:hover {
  background-color: rgba(255, 255, 255, 0.2);
}

.map-body {
  flex: 1;
  min-height: 0;
}

.resize-handle {
  position: absolute;
  right: 0;
  bottom: 0;
  width: 16px;
  height: 16px;
  background-color: #165DFF;
  z-index: 10;
}
</style>