<template>
  <div style="position: relative; height: 100%" ref="vChartRef" id="mars3d-container">
    <div class="control-button-div" v-if="props.page=='miningSiteManagement'">
      <a-button style="margin-right: 10px;n" type="primary" @click="startDraw">开始绘制</a-button>
      <a-button type="error" @click="clearDraw">清除绘制</a-button>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted } from 'vue';
  import * as mars3d from 'mars3d';
  import { point, polygon as trfPolygon } from '@turf/helpers';
  import { wktToGeoJSON,geojsonToWKT  } from "@terraformer/wkt"
  const props = defineProps(['page','data'])
  const emits = defineEmits(['getAddress'])
  let map: mars3d.Map; // 地图对象
  const vChartRef = ref<HTMLElement>();
  const drawLayer = new mars3d.layer.GraphicLayer({
    isAutoEditing: true,
  });
  let graphic
  onMounted(() => {
    let options = {
      scene: {
        center: {
          lat: 35.362625,
          lng: 118.033886,
          alt: 8306.3,
          heading: 360,
          pitch: -45,
        },
        scene3DOnly: false,
        shadows: false,
        removeDblClick: true,
        sceneMode: 3,
        showSun: true,
        showMoon: true,
        showSkyBox: true,
        showSkyAtmosphere: true,
        fog: true,
        fxaa: true,
        requestRenderMode: true,
        contextOptions: {
          requestWebgl1: false,
          webgl: {
            preserveDrawingBuffer: true,
            alpha: false,
            stencil: true,
            powerPreference: 'high-performance',
          },
        },
        globe: {
          depthTestAgainstTerrain: false,
          baseColor: '#546a53',
          showGroundAtmosphere: true,
          enableLighting: false,
        },
        cameraController: {
          zoomFactor: 3,
          minimumZoomDistance: 1,
          maximumZoomDistance: 50000000,
          enableRotate: true,
          enableTranslate: true,
          enableTilt: true,
          enableZoom: true,
          enableCollisionDetection: true,
          minimumCollisionTerrainHeight: 15000,
        },
      },
      control: {
        homeButton: false,
        baseLayerPicker: false,
        sceneModePicker: false,
        vrButton: false,
        fullscreenButton: false,
        navigationHelpButton: false,
        animation: false,
        timeline: false,
        infoBox: false,
        geocoder: false,
        selectionIndicator: false,
        showRenderLoopErrors: true,
        contextmenu: {
          hasDefault: true,
        },
        mouseDownView: true,
        zoom: {
          insertIndex: 1,
        },
      },
      method: {
        templateValues: {
          dataServer: '//data.mars3d.cn',
          gltfServerUrl: '//data.mars3d.cn/gltf',
        },
      },
      // terrain: {
      //   url: '//data.mars3d.cn/terrain',
      //   show: true,
      //   clip: true,
      // },
      basemaps: [
        {
          id: 10,
          name: '地图底图',
          type: 'group',
          opacity: 1,
        },
        {
          id: 2021,
          pid: 10,
          name: '天地图影像',
          icon: 'https://data.mars3d.cn/img/thumbnail/basemap/tdt_img.png',
          type: 'group',
          layers: [
            {
              name: '底图',
              type: 'tdt',
              layer: 'img_d',
              eventParent: {
                id: 2021,
                pid: 10,
                name: '天地图影像',
                icon: 'https://data.mars3d.cn/img/thumbnail/basemap/tdt_img.png',
                type: 'group',
                layers: [
                  {
                    name: '底图',
                    type: 'tdt',
                    layer: 'img_d',
                    show: true,
                  },
                  {
                    name: '注记',
                    type: 'tdt',
                    layer: 'img_z',
                    show: true,
                  },
                ],
                show: true,
              },
              private: false,
              id: 'm-a57ecb7d-ba05-47a3-b1be-2e28411a5954',
              opacity: 1,
              pid: 2021,
              parent: {
                id: 2021,
                pid: 10,
                name: '天地图影像',
                icon: 'https://data.mars3d.cn/img/thumbnail/basemap/tdt_img.png',
                type: 'group',
                layers: [
                  {
                    name: '底图',
                    type: 'tdt',
                    layer: 'img_d',
                    show: true,
                  },
                  {
                    name: '注记',
                    type: 'tdt',
                    layer: 'img_z',
                    show: true,
                  },
                ],
                show: true,
              },
              zIndex: 1,
            },
            {
              name: '注记',
              type: 'tdt',
              layer: 'img_z',
              eventParent: {
                id: 2021,
                pid: 10,
                name: '天地图影像',
                icon: 'https://data.mars3d.cn/img/thumbnail/basemap/tdt_img.png',
                type: 'group',
                layers: [
                  {
                    name: '底图',
                    type: 'tdt',
                    layer: 'img_d',
                    show: true,
                  },
                  {
                    name: '注记',
                    type: 'tdt',
                    layer: 'img_z',
                    show: true,
                  },
                ],
                show: true,
              },
              private: false,
              id: 'm-671f9d42-dda7-45ec-9d0f-4259c915b2cb',
              opacity: 1,
              pid: 2021,
              parent: {
                id: 2021,
                pid: 10,
                name: '天地图影像',
                icon: 'https://data.mars3d.cn/img/thumbnail/basemap/tdt_img.png',
                type: 'group',
                layers: [
                  {
                    name: '底图',
                    type: 'tdt',
                    layer: 'img_d',
                    show: true,
                  },
                  {
                    name: '注记',
                    type: 'tdt',
                    layer: 'img_z',
                    show: true,
                  },
                ],
                show: true,
              },
              zIndex: 2,
            },
          ],
          show: true,
          opacity: 1,
        },
      ],
      layers: [],
    };
    initMap(options);
  });

  const isFirstLoad = ref(true);
  const idNum = ref(0);
  let graphicLayer = null;
  const pointGraphic = ref();
  const pointData = ref();
  const initMap = (newData: any) => {
    // 第一次加载
    if (isFirstLoad.value) {
      map = new mars3d.Map(vChartRef.value, newData);
    } else {
      // 之后更新
      // map.setOptions(newData);
      map.setSceneOptions(newData.scene);
    }
    isFirstLoad.value = false;
    // 初始化矢量图层
    handlerInitEntityLayer();
    // 创建一个用于存放所有点位的图层
    const pointLayer = new mars3d.layer.GraphicLayer({
      name: 'PointLayer',
      hasEdit: false,
      isAutoEditing: false,
    });
    map.addLayer(pointLayer);
    map.addLayer(drawLayer);
    if(props.page == 'parkinglot'){
      map.on(mars3d.EventType.click, async (event) => {
        const cartesian = map.camera.pickEllipsoid(
          event.position,
          map.scene.globe.ellipsoid
        );
        if (!cartesian) return;
        const point = mars3d.LngLatPoint.fromCartesian(cartesian);
        point.format();
        const { lng, lat } = point;
        const address = await getAddressByLngLat(lng, lat);
        emits('getAddress', lng, lat, address)
        pointData.value = {
          lng,
          lat,
          address
        }
        if (pointGraphic.value) {
          pointLayer.removeGraphic(pointGraphic.value);
        }
        pointGraphic.value = new mars3d.graphic.BillboardEntity({
          position: [lng, lat, 10],
          style: {
            image: '/positioning.png',
            scale: 0.6,
            disableDepthTestDistance: Number.POSITIVE_INFINITY,
            verticalOrigin: mars3d.Cesium.VerticalOrigin.BOTTOM,
          },
        });
        pointLayer.addGraphic(pointGraphic.value);
      });
    }
    if(props.page == 'miningSiteManagement'){ 
      console.log('props.data',props.data)
      console.log('props.data.geom',props.data.geom)
      if(props.data && props.data.geom){
        const geojson = wktToGeoJSON(props.data.geom);
        console.log('geojson', geojson);
        graphic = new mars3d.graphic.PolygonEntity({
          positions: geojson.coordinates[0],
          style: {
            color: "#00B569",
            opacity: 0.2,
            outline: true,
            outlineColor: "#00B569",
            outlineWidth: 2,
          },
        });
        drawLayer.addGraphic(graphic);
        drawLayer.flyTo()
      }
    }
    if(props.page == 'inspectionrecorduser'){
      const showListPointLayer = new mars3d.layer.GraphicLayer({
        name: 'showListPointLayer',
        hasEdit: false,
        isAutoEditing: false,
      });
      map.addLayer(showListPointLayer);
      props.data.forEach(item => {
        if(item.Lng && item.Lat){
          const pointGraphicData = new mars3d.graphic.BillboardEntity({
            position: [item.Lng, item.Lat, 10],
            style: {
              image: '/positioning.png',
              scale: 0.6,
              disableDepthTestDistance: Number.POSITIVE_INFINITY,
              verticalOrigin: mars3d.Cesium.VerticalOrigin.BOTTOM,
            },
          });
          showListPointLayer.addGraphic(pointGraphicData);
        }
      })
        // 获取最后一个点
      const last = props.data[props.data.length - 1];

      if (last && last.Lng && last.Lat) {
        map.flyTo({
          lng: Number(last.Lng),
          lat: Number(last.Lat),
          alt: 1500,
          duration: 2,
        });
      }
    }
  };
  async function getAddressByLngLat(lng: number, lat: number) {
    const GAODE_KEY = "6af6a87038f44c8c793aa70331f2b7ca";
    const url = `https://restapi.amap.com/v3/geocode/regeo?key=${GAODE_KEY}&location=${lng},${lat}&radius=1000&extensions=base`;

    const res = await fetch(url);
    const data = await res.json();

    if (data.status === '1') {
      return data.regeocode.formatted_address;
    }
    return '未知位置';
  }
  //  地球创建完成后默认加载矢量数据图层
  const handlerInitEntityLayer = () => {
    if (graphicLayer == null) {
      graphicLayer = new mars3d.layer.GraphicLayer({ id: 999 });
    }
  };
  const getPosition = () => {
    return pointData.value;
  };
  const startDraw = async () => {
    graphic = await drawLayer.startDraw({
      type: 'polygon',
      style: {
        color: "#00B569",
        opacity: 0.2,
        outline: true,
        outlineColor: "#00B569",
        outlineWidth: 2,
        clampToGround: true,
        height: 0
      },
    });
    console.log('graphic', graphic);
  }
  const clearDraw = async () => {
    drawLayer.clear();
  }
  const getGraphic = (addOrUpdate = 'add') => {
    if (graphic) {
      let graphicJson = graphic.toJSON();
      let coordinates = graphicJson.position || graphicJson.positions;
      // 移除 Z 坐标（保留经纬度）
      const filteredCoordinates = coordinates.map((coord: [number, number, number]) => [
        coord[0], // 经度
        coord[1], // 纬度
      // 忽略 coord[2]（Z 值）
      ]);

      let polygonData: any = [];
      let geom = '';
      filteredCoordinates.push(filteredCoordinates[0]);
      if (addOrUpdate == 'add') {
        polygonData.push(filteredCoordinates);
      } else {
        polygonData = filteredCoordinates;
      }
      geom = geojsonToWKT(trfPolygon(polygonData).geometry);
      return geom
    }
    return null;
  }
  defineExpose({
    getPosition,
    getGraphic
  });
</script>
<style lang="less" scoped>
.control-button-div{
  position: absolute;
  top: 10px;
  left: 10px;
  z-index: 2;
}
</style>
