<template>
  <div
    style="position: relative; height: 100%"
    ref="vChartRef"
    :id="'mars3d-container-' + name"
  ></div>
  <EditModal @register="editModal" @success="editSuccess" />
</template>

<script setup lang="ts">
  import { ref, onMounted, watch } from 'vue';
  import { isArray } from '@/utils';
  import * as mars3d from 'mars3d';
  import { EditModal } from './index';
  import { useModal } from '@/components/Modal';
  import { EventBus } from '@/utils/eventBus';
  import { getPointUserOnLine } from '@/api/firegrid/firemanagement';
  import axios from 'axios';

  const [editModal, { openModal: openEidtModal }] = useModal();

  let map: mars3d.Map; // 地图对象
  const trajectoryTimePointGeoJson = ref({
    type: 'FeatureCollection',
    features: [],
  });
  const vChartRef = ref<HTMLElement>();
  const trajectoryLayerGeoJson = ref<any>(null);
  const props = defineProps({
    name: {
      type: String,
      default: '',
    },
    mapData: {
      type: Object,
      default: () => {},
    },
    routerLine: {
      type: Array,
      default: () => [],
    },
  });
  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);
    getPointInfo(props.mapData);
    loadAllRangeLayer('费县');
    // 定位到某个经纬度
    EventBus.on('inspectionMoldeMap', (data: any) => {
      map.flyToPoint(data, {
        radius: 5000, // 距离目标点的距离
        duration: 4,
      });
    });
  });
  watch(
    () => props.mapData,
    (newData) => {
      getPointInfo(newData);
      loadAllRangeLayer(newData.townname);
    },
  );
  watch(
    () => props.routerLine,
    (e) => {
      if (e.length > 0) {
        handlerTimePoint(e);
        map.flyToPoint([parseFloat(e[0].points[0].lng), parseFloat(e[0].points[0].lat)], {
          radius: 5000, // 距离目标点的距离
          duration: 4,
        });
        let data = e;
        trajectoryLayerGeoJson.value = handleRouterTeamData(e);
        console.log('trajectoryLayerGeoJson', trajectoryLayerGeoJson.value);
      }
    },
  );
  const handleRouterTeamData = (pointsArray) => {
    let geojson = {
      type: 'FeatureCollection',
      features: [],
      crs: {
        type: 'name',
        properties: {},
      },
    };

    pointsArray.forEach((points, idx) => {
      let der = 0;
      let feature = {
        type: 'Feature',
        geometry: {
          type: 'MultiLineString',
          coordinates: [[]],
        },
        properties: {
          id: 1,
          creater_id: 1,
        },
      };
      let data = points.points;
      data.forEach((item, index) => {
        // 如果是第一条数据
        if (index == 0) {
          der = item.intype;
          feature = {
            type: 'Feature',
            geometry: {
              type: 'MultiLineString',
              coordinates: [[]],
            },
            properties: {
              intype: item.intype,
            },
          };
        }
        if (der == item.intype) {
          feature.geometry.coordinates[0].push([parseFloat(item.lng), parseFloat(item.lat)]);
        } else {
          geojson.features.push(feature);
          feature = {
            type: 'Feature',
            geometry: {
              type: 'MultiLineString',
              coordinates: [[[parseFloat(data[index - 1].lng), parseFloat(data[index - 1].lat)]]],
            },
            properties: {
              intype: item.intype,
            },
          };

          der = item.intype;
        }

        if (feature.geometry.coordinates[0].length > 0) {
          geojson.features.push(feature);
        }
      });
    });
    return geojson;
  };
  const handlerTimePoint = (data) => {
    trajectoryTimePointGeoJson.value.features = [];
    data.forEach((item, index) => {
      if (item.points.length > 2) {
        let featureStart = {
          type: 'Feature',
          geometry: {
            type: 'Point',
            coordinates: [item.points[0].lng, item.points[0].lat],
          },
          properties: item.points[0],
        };
        let featureEnd = {
          type: 'Feature',
          geometry: {
            type: 'Point',
            coordinates: [
              item.points[item.points.length - 1].lng,
              item.points[item.points.length - 1].lat,
            ],
          },
          properties: item.points[item.points.length - 1],
        };
        trajectoryTimePointGeoJson.value.features.push(featureStart);
        trajectoryTimePointGeoJson.value.features.push(featureEnd);
      }
    });
  };

  const isFirstLoad = ref(true);
  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 mapContextmenuItems = [
      {
        text: '在此处添加打卡点',
        callback: (e) => {
          const mpt = mars3d.LngLatPoint.fromCartesian(e.cartesian);
          openEidtModal(true, {
            isUpdate: false,
            lat: mpt.lat,
            lng: mpt.lng,
          });
        },
      },
    ];
    map.bindContextMenu(mapContextmenuItems);
  };
  const loadAllRangeLayer = (currentStreet) => {
    // 获取所有管护范围
    let filter_options =
      currentStreet != '费县' ? '&cql_filter=xzq%20like%20%27%25' + currentStreet + '%25%27' : '';
    let url = '';
    if (currentStreet != '费县') {
      url =
        'http://221.2.83.254:9007/geoserver/ksp/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=ksp%3Ahulinyuanguanhufanwei' +
        filter_options +
        '&maxFeatures=5000&outputFormat=application%2Fjson';
    } else {
      url =
        'http://221.2.83.254:9007/geoserver/ksp/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=ksp%3Ahulinyuanguanhufanwei&maxFeatures=50000&outputFormat=application%2Fjson';
    }
    axios({
      method: 'get',
      url: url,
    }).then((res) => {
      let geojson = res.data;
      const graphicLayer = new mars3d.layer.GeoJsonLayer({
        data: geojson,
        symbol: {
          styleOptions: {
            fill: true,
            opacity: 0.3,
            outline: true,
            color: '#7CD00F',
            outlineStyle: {
              color: '#F4CC39',
              width: 3,
              opacity: 1,
            },
            label: {
              show: true,
              // 面中心点，显示文字的配置
              text: '{hulinyuan}', // 对应的属性名称
              opacity: 1,
              font_size: 16,
              color: '#ffffff',

              font_family: '楷体',
              outline: true,
              outlineColor: '#000000',
              outlineWidth: 3,

              background: false,
              backgroundColor: '#000000',
              backgroundOpacity: 0.1,

              font_weight: 'normal',
              font_style: 'normal',

              scaleByDistance: true,
              scaleByDistance_far: 20000000,
              scaleByDistance_farValue: 0.1,
              scaleByDistance_near: 1000,
              scaleByDistance_nearValue: 1,

              distanceDisplayCondition: false,
              distanceDisplayCondition_far: 10000,
              distanceDisplayCondition_near: 0,
              visibleDepth: false,
            },
          },
        },
        popup: '{hulinyuan}',
        flyTo: true,
      });
      map.addLayer(graphicLayer);
    });
  };
  const getPointInfo = (data: any) => {
    getPointUserOnLine(data).then((res) => {
      mapKindergarten(res.items.userinfo);
    });
  };
  const mapKindergarten = (arr) => {
    // 初始化地图
    // 创建一个用于存放所有点位的图层
    const pointLayer = new mars3d.layer.GraphicLayer({
      name: 'PointLayer',
      hasEdit: false,
      isAutoEditing: false,
    });

    // 将图层添加到地图
    map.addLayer(pointLayer);
    // 遍历数组，为每个点位数据创建图形点
    arr.forEach((pointData: any) => {
      // 解析点位的坐标
      const coordinates = [pointData.lng, pointData.lat];
      // 创建自定义图标点
      // 创建 Mars3D 中的点对象(默认点位样式)
      const pointGraphic = new mars3d.graphic.BillboardEntity({
        position: coordinates,
        attr: pointData,
        style: {
          label: {
            text: pointData.name,
            scale: 1,
            color: '#ffffff',
            pixelOffsetX: 0,
            pixelOffsetY: -20,
            font_size: 20,
          },
          pixelSize: 100,
          scale: 0.5,
          image: '/user.png',
        },
      });

      // 添加点位点击事件
      pointGraphic.on(mars3d.EventType.click, function (event: any) {
        var data = event.graphic.options.attr;
        console.log('点击了点位', data);
      });
      // 将点对象添加到图层
      pointLayer.addGraphic(pointGraphic);
    });
  };

  let graphicLayer = null;
  //  地球创建完成后默认加载矢量数据图层
  const handlerInitEntityLayer = () => {
    if (graphicLayer == null) {
      graphicLayer = new mars3d.layer.GraphicLayer({ id: 999 });
    }
  };
</script>
<style lang="less" scoped></style>
