<template>
<div ref="vChartRef" id="mars3d-container" class="mars3d-container">
    <div class="button_choose">        
      <a-button type="primary" @click="chooseWorkSpaceType">绘制</a-button>
      <a-button type="error" @click="deletePolygon">删除</a-button>
    </div>
</div>
</template>
<script lang="ts" setup>
  import { ref, watch, onMounted, defineEmits,defineProps } from 'vue';
  import { defaultIcon,locateBack } from './svg';
  import * as mars3d from 'mars3d';
  import * as Cesium from 'mars3d-cesium'; 
  // import * as turf from '@turf/turf';
  import { WktToGeojson, GeojsonToWkt } from '@/components/MapboxMaps/src/WktGeojsonTransform';
  import { useMessage } from '@/hooks/web/useMessage';
  const { createMessage } = useMessage();
  
  const props = defineProps([
    'showGeomData',
    'geomType'
  ]);
  const emits = defineEmits(['setNowShowData']);

  const vChartRef: any = ref<HTMLElement>();
  let map: mars3d.Map; // 地图对象
  let graphicLayers = new mars3d.layer.GraphicLayer({
    isAutoEditing: false,
  });
    
  onMounted(() => {    
    initMap();
  });

  const initMap = () => {
    map = new mars3d.Map(vChartRef.value, {
      scene: {
        center: {
          lat: 35.134608,
          lng: 118.29853,
          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: true,
        baseLayerPicker: false,
        sceneModePicker: true,
        vrButton: false,
        fullscreenButton: true,
        navigationHelpButton: true,
        animation: false,
        timeline: false,
        infoBox: false,
        geocoder: false,
        selectionIndicator: false,
        showRenderLoopErrors: true,
        contextmenu: {
          hasDefault: false,
        },
        mouseDownView: true,
        zoom: {
          insertIndex: 1,
        },
        compass: {
          bottom: 'toolbar',
          left: '5px',
          rotation: true,
        },
        distanceLegend: {
          left: '10px',
          bottom: '2px',
        },
        locationBar: {
          crs: 'CGCS2000_GK_Zone_3',
          crsDecimal: 0,
          template:
            "<div>经度:{lng}</div> <div>纬度:{lat}</div> <div class='hide1000'>横{crsx}  纵{crsy}</div> <div>海拔：{alt}米</div> <div class='hide700'>层级：{level}</div><div>方向：{heading}°</div> <div>俯仰角：{pitch}°</div><div class='hide700'>视高：{cameraHeight}米</div>",
          cacheTime: 50,
        },
      },
      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-770c35e7-9054-4259-b5ee-c15f108becd0',
              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-3b881368-574b-48a5-88b2-8b3c2c48fd62',
              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: [],
    });
    if (map) {
      map.addLayer(graphicLayers);
      handlerLocation([118.2958779, 35.1342553]); 
      if(props.showGeomData.geom){
        addGeomLayers(props.showGeomData)
      }
    }
  };
  
  function chooseWorkSpaceType() {
    if(props.geomType == 'point'){
      drawPoint()
    }
    if(props.geomType == 'polyline'){
      drawPolyline()
    }
    if(props.geomType == 'polygon'){
      drawPolygon()
    }
  }
    // 地图标注-绘制--------------------------------------------------------------------
  const mapDrawType: any = '';
  let layersarr: any = [];
  // 地图标注-SVG内容生成图片链接
  function svgToDataURL(svgString: any) {
    return 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svgString)));
  }
    // 地图标注-绘制-点
  async function drawPoint() {
    if(layersarr.length>0){
      layersarr.forEach((graphicLayer) => {
        graphicLayers.removeGraphic(graphicLayer);
      });
      layersarr = []
    }
    const image = new Image();
    image.crossOrigin = 'Anonymous';
    image.src = svgToDataURL(defaultIcon.replaceAll('currentColor', '#2D8CF0'));
    image.onload = () => {
      // 创建Canvas元素
      const canvas = document.createElement('canvas');
      canvas.width = 30;
      canvas.height = 40;
      // 获取Canvas绘图上下文
      const ctx = canvas.getContext('2d');
      ctx.fillStyle = '#00000000';
      ctx?.fillRect(0, 0, canvas.width, canvas.height);
      ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
      const dataURL = canvas.toDataURL('image/png');
      graphicLayers.startDraw({
        type: 'billboard',
        style: {
          image: dataURL,
          horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
          iconname: 'defaultIcon',
        },
      })
      .then((graphic) => {
        let graphicJson = graphic.toJSON();
        let coordinates = [graphicJson.position[0],graphicJson.position[1]];
        let pos = GeojsonToWkt(turf.point(coordinates).geometry)
        console.log('pos',pos)
        emits('setNowShowData', pos)
        layersarr.push(graphic) 
      });
      
    };
  }
  // 地图标注-绘制-线
  async function drawPolyline() {
    if(layersarr.length>0){
      layersarr.forEach((graphicLayer) => {
        graphicLayers.removeGraphic(graphicLayer);
      });
      layersarr = []
    }
    const graphic = await graphicLayers.startDraw({
      type: 'polyline',
      style: {
        width: 5,
        line_start_cap: 0,
        line_end_cap: 0,
        color: '#2D8CF0',
      },
    });
    let graphicJson = graphic.toJSON();
    let coordinates = graphicJson.position || graphicJson.positions.map(item => [item[0], item[1]]);
    coordinates.push(coordinates[0]);
    let polygonData: any = [];
    polygonData.push(coordinates);
    let pos = GeojsonToWkt(turf.multiLineString(polygonData).geometry)
    emits('setNowShowData', pos)
    layersarr.push(graphic)
  }
  // 地图标注-绘制-形状
  async function drawPolygon() {
    if(layersarr.length>0){
      layersarr.forEach((graphicLayer) => {
        graphicLayers.removeGraphic(graphicLayer);
      });
      layersarr = []
    }
    const graphic = await graphicLayers.startDraw({
      type: 'polygon',
      style: {
        color: '#2D8CF0',
        fill: false,
        outline: true,
        outlineColor: '#2D8CF0',
        outlineWidth: 3, 
      },   
    });
    

    let graphicJson = graphic.toJSON();
    let coordinates = graphicJson.position || graphicJson.positions.map(item => [item[0], item[1]]);
    coordinates.push(coordinates[0]);
    let polygonData: any = [];
    polygonData.push(coordinates);
    let polygonData1: any = [];
    polygonData1.push(polygonData);
    let multiPolygon = turf.multiPolygon(polygonData1).geometry
    let pos = GeojsonToWkt(multiPolygon)

    emits('setNowShowData', pos)
    layersarr.push(graphic)
  }
  async function deletePolygon() {
    if(layersarr.length>0){
      layersarr.forEach((graphicLayer) => {
        graphicLayers.removeGraphic(graphicLayer);
      });
      layersarr = []
    }
  }
  const addGeomLayers = (e) =>{
    const coordinate = ref()
    const lngLat = ref()
    if(props.geomType == 'point'){
      addPointLayers(e)
      return
    }
    if(props.geomType == 'polyline'){
      coordinate.value = WktToGeojson(e.geom).coordinates[0] 
      lngLat.value = coordinate.value[0]
    }
    if(props.geomType == 'polygon'){
      coordinate.value = WktToGeojson(e.geom).coordinates[0]
      lngLat.value = coordinate.value[0][0]
    }
    handlerLocation(lngLat.value); 
    let polygonGraphic = new mars3d.graphic.PolygonEntity({
        id: e.gid,
        positions: coordinate.value,
        style: {
          clampToGround: true,
          fill: false,
          color: '#2D8CF0',
          outline: true,
          outlineColor: '#2D8CF0',
          outlineWidth: 3,  
          label: {
            text: e.gid,
            font_size: 16,
            color: '#000000',
            outline: true,
            outlineColor: '#ffffff',
            outlineWidth: 6,
            verticalOrigin: Cesium.VerticalOrigin.CENTER,
            horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
          },      
        },
      });
      // 将 作业区-圈 添加到图层中
      graphicLayers.addGraphic(polygonGraphic);
      // 数据
      layersarr.push(polygonGraphic);
  }
  const addPointLayers = (e) =>{
    const coordinate = WktToGeojson(e.geom).coordinates
    handlerLocation(coordinate); 
    const canvas = document.createElement('canvas');
    canvas.width = 30;
    canvas.height = 40;
    const image = new Image();
    image.crossOrigin = 'Anonymous';
    image.src = svgToDataURL(defaultIcon.replaceAll('currentColor', '#2D8CF0'));
    image.onload = () => {
      // 获取Canvas绘图上下文
      const ctx = canvas.getContext('2d');
      ctx.fillStyle = '#00000000';
      ctx?.fillRect(0, 0, canvas.width, canvas.height);
      // 在Canvas上绘制图片
      ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
      // 将Canvas内容转换为图片的数据URL
      const dataURL = canvas.toDataURL('image/png');

      let pointGraphic = new mars3d.graphic.BillboardEntity({
        id: e.gid,
        position: coordinate,
        style: {
          image: dataURL,
          scale: 1,
          verticalOrigin: Cesium.VerticalOrigin.CENTER,
          horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
          iconname: 'defaultIcon',
          clampToGround: true,
          label: {
            text: `${e.gid}`,
            font_size: 20,
            color: '#000000',
            outline: true,
            outlineColor: '#ffffff',
            outlineWidth: 6,
            verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
            horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
            pixelOffset: [25, 0],
          },
        },
      });
      // 将 点对象 添加到图层中
      graphicLayers.addGraphic(pointGraphic);
      // 数据
      layersarr.push(pointGraphic);
    }
    
  }
  // 图斑定位
  const handlerLocation = (lngLat) => {
    const position = Cesium.Cartesian3.fromDegrees(lngLat[0], lngLat[1]);
    map.flyToPoint(position);
  };

  defineExpose({
    handlerLocation,
  });

  onMounted(() => {
      
  });
</script>
<style lang="less" scoped>
.mars3d-container {
  position: relative;
  width: 100%;
  height: 100%;
}

.button_choose {
  position: absolute;
  top: 10%;
  right: 1%;
  width: 100px;
  height: 100px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-around;
  z-index: 9;
}

.popoverAnnotation {
  width: 18px;
  height: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 3px;
}
  
</style>
  