<template>
  <div ref="mapContainer" class="ol-map-wrapper">
    <div class="ol-map" ref="olMap"></div>
    <button class="fullscreen-btn" @click="toggleFullScreen">
      {{ isFullscreen ? '退出全屏' : '全屏显示' }}
    </button>
  </div>
</template>



<script setup>
import { ref, onMounted, onBeforeUnmount, defineProps, watch } from 'vue';
import 'ol/ol.css';
import { Map, View } from 'ol';
import TileLayer from 'ol/layer/Tile';
import XYZ from 'ol/source/XYZ';
import { Feature } from 'ol';
import Point from 'ol/geom/Point';
import VectorSource from 'ol/source/Vector';
import VectorLayer from 'ol/layer/Vector';
import { Icon, Style, Text, Fill, Stroke } from 'ol/style';
import { fromLonLat } from 'ol/proj';
import pinIcon from '../assets/图钉.png';
import { boundingExtent } from 'ol/extent';

const props = defineProps({
  dataListMap: {
    type: Array,
    default: () => []
  }
});

const mapContainer = ref(null);
const olMap = ref(null)
const map = ref(null);
const vectorLayer = ref(null);
const isMapReady = ref(false);
const isFullscreen = ref(false);


const initializeMap = () => {
  const center = fromLonLat([116.255535, 40.204654]);

  const view = new View({
    center,
    zoom: 14
  });

  const tiandituKey = 'a155b662f47ceee8d82a67bfbb3a0825';

  const tileLayers = [
    new TileLayer({
      source: new XYZ({
        url: `http://t{0-7}.tianditu.gov.cn/DataServer/wmts?T=img_w&x={x}&y={y}&l={z}&tk=${tiandituKey}`
      }),
      isBaseLayer: true
    }),
    new TileLayer({
      source: new XYZ({
        url: `http://t{0-7}.tianditu.gov.cn/DataServer/wmts?T=cia_w&x={x}&y={y}&l={z}&tk=${tiandituKey}`
      }),
      isBaseLayer: true
    })
  ];

  const vectorSource = new VectorSource();
  vectorLayer.value = new VectorLayer({
    source: vectorSource
  });

  map.value = new Map({
    target: olMap.value,
    layers: [...tileLayers, vectorLayer.value],
    view
  });

  isMapReady.value = true;
};

const getRandomCoordinateInBeijing = () => {
  const minLon = 115.7;
  const maxLon = 117.4;
  const minLat = 40.2;
  const maxLat = 40.5;

  const lon = Math.random() * (maxLon - minLon) + minLon;
  const lat = Math.random() * (maxLat - minLat) + minLat;

  return {
    longitude: parseFloat(lon.toFixed(6)),
    latitude: parseFloat(lat.toFixed(6))
  };
};

const handleTagging = (data) => {
  if (!isMapReady.value || !Array.isArray(data)) return;

  const features = [];
  const coords = [];

  data.forEach(item => {
    const { longitude, latitude } = getRandomCoordinateInBeijing(); // 模拟
    if (longitude && latitude) {
      const feature = new Feature({
        geometry: new Point(fromLonLat([longitude, latitude])),
        name: item.environmentData.fileName || ''
      });

      feature.setStyle(
        new Style({
          image: new Icon({
            src: pinIcon,
            anchor: [0.5, 1],
            scale: 1
          }),
          text: new Text({
            text: item.environmentData.fileName || '',
            offsetY: 14,
            font: '300 14px sans-serif',
            fill: new Fill({
              color: '#fff'
            }),
            stroke: new Stroke({
              color: '#fff',
              width: 0
            }),
            textAlign: 'center',
            backgroundFill: new Fill({
              color: 'rgba(0, 0, 0, 0.5)'
            }),
            backgroundStroke: new Stroke({
              color: 'rgba(0, 0, 0, 0.5)',
              width: 0
            }),
            padding: [1, 10, 1, 10],
            radius: 4
          })
        })
      );

      features.push(feature);
      coords.push(fromLonLat([longitude, latitude]));
    }
  });

  if (features.length > 0) {
    vectorLayer.value.getSource().clear();
    vectorLayer.value.getSource().addFeatures(features);

    const extent = boundingExtent(coords);
    map.value.getView().fit(extent, {
      padding: [50, 50, 50, 50],
      maxZoom: 16,
      duration: 1000
    });
  }
};


const toggleFullScreen = () => {
  const container = mapContainer.value;

  if (!document.fullscreenElement) {
    container?.requestFullscreen?.();
  } else {
    document.exitFullscreen?.();
  }
};

const fullscreenChangeHandler = () => {
  isFullscreen.value = !!document.fullscreenElement;
};

// 新增：清空地图矢量图层的方法
const clearMap = () => {
  if (vectorLayer.value && vectorLayer.value.getSource()) {
    vectorLayer.value.getSource().clear();
  }
};

watch(
  () => props.dataListMap,
  (newVal) => {
    // 当传入空数组或非法数据时，清空图层中的点
    if (!Array.isArray(newVal) || newVal.length === 0) {
      clearMap();
      return;
    }

    const tryAdd = () => {
      if (isMapReady.value) {
        handleTagging(newVal);
      } else {
        setTimeout(tryAdd, 100);
      }
    };

    tryAdd();
  },
  { deep: true, immediate: true }
);



onMounted(() => {
  try {
    initializeMap();
  } catch (error) {
    alert('初始化地图出错,', error)
  }
  document.addEventListener('fullscreenchange', fullscreenChangeHandler);
});

onBeforeUnmount(() => {
  document.removeEventListener('fullscreenchange', fullscreenChangeHandler);
});

// 对外暴露清空方法，供父组件调用
defineExpose({
  clearMap
});
</script>

<style scoped>
.ol-map-wrapper {
  position: relative;
  width: 100%;
  height: 100%;
}

.ol-map {
  width: 100%;
  height: 100%;
}

.fullscreen-btn {
  position: absolute;
  top: 10px;
  right: 10px;
  z-index: 1000;
  padding: 6px 12px;
  font-size: 14px;
  background-color: rgba(0, 0, 0, 0.5);
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  user-select: none;
}
</style>
