<template>
  <div class="model2D">
    <div :id="mapId" class="map">
      <!-- 全屏 -->
      <div class="expandButton" @click="clickExpandButton">
        <ExpandOutlined v-if="!fullscreenFlag" style="color: #3c3c3c; font-size: 25px" />
        <CompressOutlined v-if="fullscreenFlag" style="color: #3c3c3c; font-size: 25px" />
      </div>
      <div class="angleViewButton">
        <div class="button_child" @click="lookTopView">
          <span style="color: #3c3c3c; font-size: 16px">顶视</span>
        </div>
        <div class="button_child" @click="lookDownView">
          <span style="color: #3c3c3c; font-size: 16px">俯视</span>
        </div>
      </div>
      <div class="plusAndMinusButton">
        <div class="button_child" @click="clickPlusButton">
          <PlusOutlined style="color: #3c3c3c; font-size: 25px" />
        </div>
        <div class="button_child" @click="clickMinusButton">
          <MinusOutlined style="color: #3c3c3c; font-size: 25px" />
        </div>
      </div>
    </div>
    <div class="info">
      <div class="left">键盘</div>
      <div class="right4">123</div>
      <div class="right3"> ASL: {{ asl }}m</div>
      <div class="right2"> HAE: {{ hae }}m</div>
      <div class="right1">
        <HeatMapOutlined style="margin-right: 15px; font-size: 20px" />
        WGS 84
      </div>
    </div>
  </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 axios from 'axios';
  import {
    ExpandOutlined,
    CompressOutlined,
    PlusOutlined,
    MinusOutlined,
    HeatMapOutlined,
  } from '@ant-design/icons-vue';

  const props = defineProps(['nowPreviewRecord']);
  const emits = defineEmits(['getMap']);

  const mapId = `modal-map-${uuidv4()}`;
  const networkType = ref('WAN');
  let map: Map;

  const initMap = () => {
    // let mapDataSources: any = {
    //   '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 = [
    //   {
    //     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,
      //   },
      style: {
        version: 8,
        sources: {},
        layers: [
          {
            id: 'background',
            type: 'background',
            paint: {
              'background-color': '#000', // 黑色背景
            },
          },
        ],
      },
      maxZoom: 22,
      minZoom: 8,
      pitch: 0,
      zoom: 18,
      center: props.nowPreviewRecord.boundary
        ? [
            (props.nowPreviewRecord.boundary.start_lng + props.nowPreviewRecord.boundary.end_lng) /
              2,
            (props.nowPreviewRecord.boundary.start_lat + props.nowPreviewRecord.boundary.end_lat) /
              2,
          ]
        : [117.984425, 35.270654],
    });
  };

  // 示例函数：生成网格线的 GeoJSON 数据
  function createGridFeatures() {
    const features: any = [];
    const gridSize = 10; // 每隔 10 度画一条线
    for (let lat = -90; lat <= 90; lat += gridSize) {
      features.push({
        type: 'Feature',
        geometry: {
          type: 'LineString',
          coordinates: [
            [-180, lat],
            [180, lat],
          ],
        },
      });
    }
    for (let lng = -180; lng <= 180; lng += gridSize) {
      features.push({
        type: 'Feature',
        geometry: {
          type: 'LineString',
          coordinates: [
            [lng, -90],
            [lng, 90],
          ],
        },
      });
    }
    return { type: 'FeatureCollection', features: features };
  }

  onMounted(() => {
    mapboxgl.accessToken = MapboxConfig.ACCESS_TOKEN;
    // 获取网络环境后加载地图
    // loadMapInfo();
    map = initMap();
    map.on('load', () => {
      setImage(props.nowPreviewRecord.boundary);
      move();
      emits('getMap', map);
    });
  });

  function setImage(boundary) {
    let fourpoint: any = [
      [parseFloat(boundary.start_lng), parseFloat(boundary.end_lat)],
      [parseFloat(boundary.end_lng), parseFloat(boundary.end_lat)],
      [parseFloat(boundary.end_lng), parseFloat(boundary.start_lat)],
      [parseFloat(boundary.start_lng), parseFloat(boundary.start_lat)],
    ];
    // 图片预加载
    let image = new Image();
    image.crossOrigin = 'anonymous';
    image.src = props.nowPreviewRecord.url;
    image.onload = () => {
      // 创建Canvas元素
      const canvas = document.createElement('canvas');
      canvas.width = image.width;
      canvas.height = image.height;
      // 获取Canvas绘图上下文
      const ctx = canvas.getContext('2d');
      // 在Canvas上绘制图片
      ctx.drawImage(image, 0, 0, image.width, image.height);
      // 将Canvas内容转换为图片的数据URL
      const dataURL = canvas.toDataURL('image/png');
      // 移除旧的图层和源
      if (map) {
        if (map.getLayer('radar-layer')) {
          map.removeLayer('radar-layer');
        }
        if (map.getSource('radar')) {
          map.removeSource('radar');
        }
      }
      // 添加新的源和图层
      map.addSource('radar', {
        type: 'image',
        url: dataURL,
        coordinates: fourpoint,
      });
      map.addLayer({
        id: 'radar-layer',
        type: 'raster',
        source: 'radar',
      });
    };
  }

  // 全屏
  const fullscreenFlag = ref(false);
  function clickExpandButton() {
    const mapContainer = document.getElementById(mapId);
    if (mapContainer) {
      if (!document.fullscreenElement) {
        mapContainer.requestFullscreen();
        fullscreenFlag.value = true;
      } else {
        document.exitFullscreen();
        fullscreenFlag.value = false;
      }
    }
  }
  // 顶视角
  function lookTopView() {
    map.setPitch(0);
    map.setBearing(0);
    map.setZoom(18);
    map.setCenter([
      (parseFloat(props.nowPreviewRecord.boundary.start_lng) +
        parseFloat(props.nowPreviewRecord.boundary.end_lng)) /
        2,
      (parseFloat(props.nowPreviewRecord.boundary.start_lat) +
        parseFloat(props.nowPreviewRecord.boundary.end_lat)) /
        2,
    ]);
  }
  // 俯视角
  function lookDownView() {
    map.setPitch(60);
    map.setBearing(0);
    map.setZoom(18);
    map.setCenter([
      (parseFloat(props.nowPreviewRecord.boundary.start_lng) +
        parseFloat(props.nowPreviewRecord.boundary.end_lng)) /
        2,
      (parseFloat(props.nowPreviewRecord.boundary.start_lat) +
        parseFloat(props.nowPreviewRecord.boundary.end_lat)) /
        2,
    ]);
  }
  // 放大
  function clickPlusButton() {
    map.setZoom(map.getZoom() + 0.2);
  }
  // 缩小
  function clickMinusButton() {
    map.setZoom(map.getZoom() - 0.2);
  }

  const asl = ref(0);
  const hae = ref(0);

  function move() {
    map.on('mousemove', (e) => {
      const lngLat = e.lngLat;
      asl.value = map.queryTerrainElevation(lngLat, { exaggerated: false }) || 0;
      const geoidSeparation = 3.5;
      hae.value = asl.value ? asl.value + geoidSeparation : 0;
    });
  }

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

<style lang="scss" scoped>
  .model2D {
    position: relative;
    width: 100%;
    height: 100%;

    .map {
      position: relative;
      width: 100%;
      height: 100%;

      // 全屏
      .expandButton {
        position: absolute;
        right: 20px;
        bottom: 29%;
        z-index: 500;
        background: #ffffff;
        border-radius: 5px;
        width: 40px;
        height: 40px;

        display: flex;
        align-items: center;
        justify-content: center;
      }
      // 视角
      .angleViewButton {
        z-index: 500;
        position: absolute;
        right: 20px;
        bottom: 18%;
        background: #ffffff;
        border-radius: 5px;
        width: 40px;
        height: 80px;

        display: block;
        align-items: center;
        justify-content: center;
      }
      // 放大、缩小
      .plusAndMinusButton {
        z-index: 500;
        position: absolute;
        right: 20px;
        bottom: 7%;
        background: #ffffff;
        border-radius: 5px;
        width: 40px;
        height: 80px;

        display: block;
        align-items: center;
        justify-content: center;
      }
    }

    .info {
      // 页面不能被选中
      -webkit-user-select: none; /* Safari */
      -moz-user-select: none; /* Firefox */
      -ms-user-select: none; /* IE/Edge */
      user-select: none;

      position: absolute;
      width: 100%;
      height: 4%;
      bottom: 0px;
      left: 0px;
      display: flex;

      .left {
        position: absolute;
        top: 0px;
        left: 0px;
        width: 150px;
        color: #ffffff;

        display: flex;
        align-items: center;
        justify-content: center;
      }
      .right4 {
        position: absolute;
        top: 0px;
        right: 360px;
        width: 120px;
        color: #ffffff;

        display: flex;
        align-items: center;
        justify-content: center;
      }
      .right3 {
        position: absolute;
        top: 0px;
        right: 240px;
        width: 120px;
        color: #ffffff;

        display: flex;
        align-items: center;
        justify-content: center;
      }
      .right2 {
        position: absolute;
        top: 0px;
        right: 120px;
        width: 120px;
        color: #ffffff;

        display: flex;
        align-items: center;
        justify-content: center;
      }
      .right1 {
        position: absolute;
        top: 0px;
        right: 0px;
        width: 120px;
        color: #ffffff;

        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }

  .button_child {
    width: 40px;
    height: 40px;

    display: flex;
    align-items: center;
    justify-content: center;
  }

  ::v-deep .mapboxgl-ctrl {
    display: none !important;
  }
</style>
