<template>
  <div
    :id="mapId"
    :style="`position: ${position}; top: 0px; left: 0px; width: ${width}; height: ${height}; z-index: ${zIndex} `"
  ></div>
</template>

<script setup lang="ts">
  import { defineProps, ref, onMounted, onUnmounted, defineEmits, computed } from 'vue';
  import { v4 as uuidv4 } from 'uuid';
  import mapboxgl, { Map } from 'mapbox-gl';
  import { MapboxConfig, MapboxDefaultStyle } from '@/components/MapboxMaps/src/config';
  import { getAppEnvConfig } from '@/utils/env';
  import axios from 'axios';

  const { VITE_GLOB_YINGXIANG_SERVER, VITE_GLOB_YAOGANYINGXIANG_SERVER } = getAppEnvConfig();
  const { VITE_GLOB_API_URL, VITE_GLOB_LAN_API_URL } = getAppEnvConfig();

  const props = defineProps(['width', 'height', 'zIndex', 'position', 'centerAndZoom']);
  const emits = defineEmits(['getMap']);
  const width = computed(() => {
    return props.width;
  });
  const height = computed(() => {
    return props.height;
  });
  const zIndex = computed(() => {
    return props.zIndex;
  });
  const position = computed(() => {
    return props.position;
  });

  const mapId = `modal-map-${uuidv4()}`;
  const networkType = ref('WAN');
  let map: Map;
  onMounted(() => {
    mapboxgl.accessToken = MapboxConfig.ACCESS_TOKEN;
    // 获取网络环境后加载地图
    // loadMapInfo();
    map = initMap();
    map.on('load', () => {
      emits('getMap', map);
    });
  });

  async function loadMapInfo() {
    try {
      await axios.get(VITE_GLOB_LAN_API_URL + '/api/DroneCloudQuery/IsPublic').then((res) => {
        if (res.data.result) {
          networkType.value = 'WAN';
        } else {
          networkType.value = 'LAN';
        }
      });
    } catch (e) {
      networkType.value = 'WAN';
    } finally {
      map = initMap();
      map.on('load', () => {
        emits('getMap', map);
      });
    }
  }

  const initMap = () => {
    let mapDataSources: any =
      networkType.value == 'LAN'
        ? {
            'raster-tiles': {
              type: 'raster',
              tiles: [
                `http://t0.tianditu.gov.cn/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=${MapboxConfig.TDT_TOKEN}`,
              ],
              tileSize: 256,
              minzoom: 1,
              maxzoom: 17,
            },
            'raster-tiles-font': {
              type: 'raster',
              tiles: [
                `https://t0.tianditu.gov.cn/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=${MapboxConfig.TDT_TOKEN}`,
              ],
              tileSize: 256,
            },
            yaogan: {
              type: 'raster',
              tiles: [VITE_GLOB_YAOGANYINGXIANG_SERVER],
              tileSize: 256,
              minzoom: 16,
              maxzoom: 24,
            },
            yingxiang: {
              type: 'raster',
              tiles: [VITE_GLOB_YINGXIANG_SERVER],
              tileSize: 256,
              minzoom: 16,
              maxzoom: 24,
            },
          }
        : {
            'raster-tiles': {
              type: 'raster',
              tiles: [
                `http://t0.tianditu.gov.cn/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=${MapboxConfig.TDT_TOKEN}`,
              ],
              tileSize: 256,
              minzoom: 1,
              maxzoom: 17,
            },
            'raster-tiles-font': {
              type: 'raster',
              tiles: [
                `https://t0.tianditu.gov.cn/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=${MapboxConfig.TDT_TOKEN}`,
              ],
              tileSize: 256,
            },
          };

    let mapDataLayers: any =
      networkType.value == 'LAN'
        ? [
            {
              id: 'tdt-vec-tiles',
              type: 'raster',
              source: 'raster-tiles-font',
            },
            {
              id: 'tdt-img-tiles',
              type: 'raster',
              source: 'raster-tiles',
            },
            {
              id: 'yaogan',
              type: 'raster',
              source: 'yaogan',
              minzoom: 9,
              maxzoom: 15,
            },
            {
              id: 'yingxiang',
              type: 'raster',
              source: 'yingxiang',
              minzoom: 13,
              maxzoom: 24,
            },
          ]
        : [
            {
              id: 'tdt-vec-tiles',
              type: 'raster',
              source: 'raster-tiles-font',
            },
            {
              id: 'tdt-img-tiles',
              type: 'raster',
              source: 'raster-tiles',
            },
          ];

    return new mapboxgl.Map({
      container: mapId,
      language: 'zh-cmn',
      projection: 'equirectangular', // wgs84参考系
      style: {
        glyphs: 'mapbox://fonts/mapbox/{fontstack}/{range}.pbf',
        version: 8,
        sources: mapDataSources,
        layers: mapDataLayers,
      },
      maxZoom: 22,
      minZoom: 8,
      pitch: 0,
      zoom: props.centerAndZoom
        ? calculateZoom(JSON.parse(`[${props.centerAndZoom[0]?.fourpoint}]`))
        : 14,
      center: props.centerAndZoom
        ? getCenter(JSON.parse(`[${props.centerAndZoom[0]?.fourpoint}]`))
        : [117.984425, 35.270654],
    });
  };

  // 移动位置
  function getCenter(fourpoint) {
    let x = 0;
    let y = 0;
    let length = fourpoint.length;
    for (let i = 0; i < fourpoint.length; i++) {
      x = x + fourpoint[i][0];
      y = y + fourpoint[i][1];
    }
    x = x / length;
    y = y / length;
    return [x, y];
  }

  function calculateZoom(points) {
    // 计算边界框
    const nw = points[0];
    const ne = points[1];
    const se = points[2];
    const sw = points[3];
    const latRange = Math.abs(nw[1] - se[1]);
    const lngRange = Math.abs(nw[0] - ne[0]);
    // 计算缩放级别
    const zoomLat = Math.log2(360 / latRange) - 1;
    const zoomLng = Math.log2(360 / lngRange) - 1;
    // 返回最小的缩放级别，并保留小数后两位
    return Math.min(zoomLat * 1.05, zoomLng * 1.05).toFixed(2);
  }

  onUnmounted(() => {
    map && map.remove();
  });
</script>

<style lang="scss" scoped></style>
