GuLiMmo
2024-03-19 aec00ecc093be803860c8675cbe1c4c776a7cb4e
src/pages/page-web/projects/components/route-edit/index.vue
@@ -1,23 +1,34 @@
<template>
  <div class="route-edit-box">
    <div class="btn-group">
      <a-button type="text" @click="backPage">
        <template #icon>
          <ArrowLeftOutlined />
      <a-popover
        :visible="modfiyPopupShow"
        overlayClassName="popup-container"
        placement="leftBottom"
        :getPopupContainer="(triggerNode: any) => triggerNode.parentNode">
        <template #content>
          <div class="popup-text">返回将退出航线编辑器,您要保存吗?如果不保存,您更改的内容将会丢失。</div>
          <div class="btn-tool">
            <a-button size="small" class="btn-cancel" @click="modfiyPopupShow = false">取消</a-button>
            <a-button size="small" class="btn-cancel" @click="handleModfiySave(false)">不保存</a-button>
            <a-button size="small" type="primary" @click="handleModfiySave(true)">保存</a-button>
          </div>
        </template>
        返回
      </a-button>
      <div class="save-button">
        <a-button type="text" @click="backPage">
          <template #icon>
            <ArrowLeftOutlined />
          </template>
          返回
        </a-button>
      </a-popover>
      <div class="save-button" @click="saveWaylineFile">
        <SaveOutlined />
      </div>
      <setting>
      <setting v-model:loadCompleted="loadCompleted">
        <template #show>
          <a-button type="text" class="setting-btn">
            <div class="router-setting">
              <img
                class="wayline-icon"
                :src="getResource('wayline.png')"
                alt="icon" />
              <img class="wayline-icon" :src="getResource('wayline.png')" alt="icon" />
              <span class="text">航线设置</span>
              <CaretDownOutlined />
            </div>
@@ -26,10 +37,7 @@
      </setting>
    </div>
    <div class="wayline-info">
      <div
        class="info-box"
        v-for="(item, index) in waylineDetails"
        :key="index">
      <div class="info-box" v-for="(item, index) in waylineDetails" :key="index">
        <div class="title">{{ item.title }}</div>
        <div class="info">{{ item.value }}</div>
      </div>
@@ -40,23 +48,27 @@
        :key="index"
        :class="{ 'active-point': index == selectPointIndex }"
        @click="pointSelect(item, index)">
        <div class="graph">
          <div class="left"></div>
          <div class="right">{{ index + 1 }}</div>
        </div>
        <div class="graph-right">
          <div
            v-for="(event, index) in item.eventList"
            :key="index"
            class="s-event-icon">
            <a-tooltip placement="top">
              <template #title>
                {{ event.name }}
              </template>
              <img :src="event.icon" alt="icon" />
            </a-tooltip>
        <a-tooltip placement="top">
          <template #title>
            <span>{{ item.isUseGlobalHeight ? '跟随全局' : '不跟随全局' }}</span>
          </template>
          <div class="graph">
            <div class="left" :style="{ borderTopColor: item.isUseGlobalHeight ? '#61d396' : '#409eff' }"></div>
            <div class="right">{{ index + 1 }}</div>
          </div>
        </div>
        </a-tooltip>
        <contextMenu :menu="[{ title: '删除航点', value: { index, item } }]">
          <div class="graph-right">
            <div v-for="(event, index) in item.eventList" :key="index" class="s-event-icon">
              <a-tooltip placement="top">
                <template #title>
                  {{ event.name }}
                </template>
                <img :src="event.icon" alt="icon" />
              </a-tooltip>
            </div>
          </div>
        </contextMenu>
      </li>
    </ul>
  </div>
@@ -66,23 +78,21 @@
import _ from 'lodash'
import * as Cesium from 'cesium'
import setting from './components/setting.vue'
import { ref, reactive, defineEmits, defineProps, watch, onMounted } from 'vue'
import useKmzTsa, { kmlStr, template as xmlTemplate } from '/@/utils/cesium/use-kmz-tsa'
import { ref, defineEmits, defineProps, watch, onMounted } from 'vue'
import { ArrowLeftOutlined, CaretDownOutlined, SaveOutlined } from '@ant-design/icons-vue'
import { cesiumOperation } from '/@/hooks/use-cesium-tsa'
import { useMyStore } from '/@/store'
import ImageTrailMaterial from '/@/utils/cesium/ImageTrailMaterial'
import useMapDraw from '/@/utils/cesium/use-map-draw'
import useMapDraw, { kmlEntities as globalEntities, selectPointIndex as pointIdx } from '/@/utils/cesium/use-map-draw'
import contextMenu from './components/content-menu.vue'
const store = useMyStore()
const { appContext }: any = getCurrentInstance()
const global = appContext.config.globalProperties
const {
  removeAllPoint,
  getEntityById,
  addPolyline,
  addRightClick,
  removeRightClickEvent,
} = cesiumOperation()
const kmzUtils = useKmzTsa()
const { removeAllPoint, getEntityById, addPolyline, removeAllDataSource, addRightClick, removeRightClickEvent } =
  cesiumOperation()
interface waylineDetails {
  title: string
@@ -97,6 +107,7 @@
interface tragetPoint {
  position: Cesium.Cartesian3
  isUseGlobalHeight: boolean
  eventList: eventParmas[]
}
@@ -115,20 +126,20 @@
const tragetPointArr = ref<tragetPoint[]>([])
let kmlDataSource:
  | { entities: { values: { _children: any }[] }; show: boolean }
  | null
  | any = null
let kmlDataSource: { entities: { values: { _children: any }[] }; show: boolean } | null | any = null
let mouseRightClickEvent: any = null
// 绘制地图上的东西
let mapDraw = null
let mapDraw: any = null
// 航线详情
const waylineDetails = ref<waylineDetails[]>([])
// 样式
const kmlEntities = ref<Cesium.Entity[]>([])
const loadCompleted = ref<boolean>(false)
// 编辑时初始化
const initDrawRoute = () => {
  const options = {
    camera: global.$viewer.scene.camera,
@@ -138,30 +149,46 @@
  if (kmlDataSource) {
    global.$viewer.dataSources.remove(kmlDataSource)
  }
  global.$viewer.dataSources
    .add(Cesium.KmlDataSource.load(filePath.value, options))
    .then((res: any) => {
      kmlDataSource = res
      mapDraw = useMapDraw(kmlDataSource, [], filePath.value, global)
      const {
        drawWayline,
        waylineDetails: details,
        waylinePointsEvent,
        kmlEntities: entities,
      } = mapDraw
      drawWayline()
      waylineDetails.value = details
      tragetPointArr.value = waylinePointsEvent.value
      kmlEntities.value = entities.value
      if (!mouseRightClickEvent) {
        // 添加右键事件
        addMapPointEvent()
      }
  global.$viewer.dataSources.add(Cesium.KmlDataSource.load(filePath.value, options)).then((res: any) => {
    kmlDataSource = res
    mapDraw = useMapDraw(kmlDataSource, [], filePath.value, global)
    const {
      drawWayline,
      waylineDetails: details,
      waylinePointsEvent,
      kmlEntities: entities,
      clearWaylineData,
    } = mapDraw
    clearWaylineData()
    drawWayline()
    kmzUtils.init(filePath.value).then((kmlRes) => {
      loadCompleted.value = true
    })
}
    waylineDetails.value = details
    tragetPointArr.value = waylinePointsEvent.value
    watch(
      () => waylinePointsEvent.value,
      (val) => {
        tragetPointArr.value = val
      },
      {
        deep: true,
      },
    )
// const createPointOrPolyline = () => {}
    kmlEntities.value = entities.value
    if (!mouseRightClickEvent) {
      // 添加右键事件
      addMapPointEvent()
    }
  })
}
// 新建航线初始化
const initCreateRoute = () => {
  mapDraw = useMapDraw('', [], '', global)
  const xml = kmzUtils.generateXML(xmlTemplate.value)
  mapDraw.drawWayline([], xml)
}
// 创建广告牌
const createBillboard = (title: string | number, color: string) => {
@@ -195,8 +222,10 @@
    global.$viewer.entities.remove(nextPointEntity)
    kmlEntities.value.forEach((entity: Cesium.Entity | any, i: number) => {
      entity.billboard.image = createBillboard(i + 1, '#61d396')
      entity.label.show = false
    })
    selectPointIndex.value = null
    pointIdx.value = null
    return
  }
  if (prevPointEntity) {
@@ -212,12 +241,7 @@
  const nextPoint = points[index + 1]?.position
  if (prevPoint) {
    // 获取中心点
    const centerPoint = Cesium.Cartesian3.lerp(
      currentPoint,
      prevPoint,
      0.5,
      new Cesium.Cartesian3(),
    )
    const centerPoint = Cesium.Cartesian3.lerp(currentPoint, prevPoint, 0.5, new Cesium.Cartesian3())
    // 获取两个点之间的距离
    let distance = Cesium.Cartesian3.distance(currentPoint, prevPoint)
    distance = Math.round(distance)
@@ -225,12 +249,7 @@
  }
  if (nextPoint) {
    // 获取中心点
    const centerPoint = Cesium.Cartesian3.lerp(
      currentPoint,
      nextPoint,
      0.5,
      new Cesium.Cartesian3(),
    )
    const centerPoint = Cesium.Cartesian3.lerp(currentPoint, nextPoint, 0.5, new Cesium.Cartesian3())
    // 获取两个点之间的距离
    let distance = Cesium.Cartesian3.distance(currentPoint, nextPoint)
    distance = Math.round(distance)
@@ -240,11 +259,22 @@
  kmlEntities.value.forEach((entity: Cesium.Entity | any, i: number) => {
    if (i === index) {
      entity.billboard.image = createBillboard(index + 1, '#f3be4f')
      const dashLineEntity: Cesium.Entity | any = getEntityById(`dashLine${i}`)
      dashLineEntity.polyline.material = new Cesium.PolylineDashMaterialProperty({
        color: Cesium.Color.fromBytes(235, 192, 99),
      })
      entity.label.show = true
    } else {
      entity.billboard.image = createBillboard(i + 1, '#61d396')
      const dashLineEntity: Cesium.Entity | any = getEntityById(`dashLine${i}`)
      dashLineEntity.polyline.material = new Cesium.PolylineDashMaterialProperty({
        color: Cesium.Color.WHITE,
      })
      entity.label.show = false
    }
  })
  selectPointIndex.value = index
  pointIdx.value = index
}
// 添加右键事件,弹出窗口
@@ -264,16 +294,11 @@
      },
      {
        class: 'add-next-point',
        title: `在${Number(selectPointIndex.value) + 1}号航点前插入`,
        title: `在${Number(selectPointIndex.value) + 1}号航点后插入`,
      },
    ]
    const defaultEvents = [
      { class: 'finally-point', title: '在最后航点新增航点' },
    ]
    const events =
      selectPointIndex.value !== null
        ? [...defaultEvents, ...pointEvents]
        : defaultEvents
    const defaultEvents = [{ class: 'finally-point', title: '在最后航点新增航点' }]
    const events = selectPointIndex.value !== null ? [...defaultEvents, ...pointEvents] : defaultEvents
    popupDom = createPointPopupDom(events)
    global.$viewer.container.appendChild(popupDom)
    popupDom.style.transform = `translate3d(${x}px, ${y}px, 0)`
@@ -323,87 +348,90 @@
  `
  return pointPopup
}
// 给DOM添加点击事件
const addMenuEvent = (dom: HTMLElement, position: Cesium.Cartesian2) => {
  dom.addEventListener('click', (e: any) => {
    removeCesiumChildDom(popupDom)
    const className = e.target.className
    const c3Position = global.$viewer.scene.globe.pick(
      global.$viewer.camera.getPickRay(position),
      global.$viewer.scene,
    )
    const c3Position = global.$viewer.scene.globe.pick(global.$viewer.camera.getPickRay(position), global.$viewer.scene)
    const c2Postion = ellipsoid.cartesianToCartographic(c3Position)
    const longitude = Cesium.Math.toDegrees(c2Postion.longitude)
    const latitude = Cesium.Math.toDegrees(c2Postion.latitude)
    const height = 70
    const createPointPosition = Cesium.Cartesian3.fromDegrees(
      longitude,
      latitude,
      height,
    )
    let entity: Cesium.Entity | any = null
    // 获取全局高度
    const globalHeight: string = xmlTemplate.value.Folder.globalHeight['#text']
    const height = Number(globalHeight)
    // 右键点击的位置
    const createPointPosition = Cesium.Cartesian3.fromDegrees(longitude, latitude, height)
    const entity: Cesium.Entity = global.$viewer.entities.add({
      position: createPointPosition,
    })
    // 起飞点海拔
    const takeOffRefPointAGLHeight = xmlTemplate.value.missionConfig.takeOffRefPointAGLHeight
    const posterHeight = Number(takeOffRefPointAGLHeight['#text'])
    // 当前点位个数
    const points = xmlTemplate.value.Folder.Placemark
    // 加入到解析的JSON对象中
    const setting = {
      Point: {
        coordinates: { '#text': `${longitude},${latitude}` },
      },
      index: { '#text': points.length },
      ellipsoidHeight: { '#text': height - posterHeight },
      height: { '#text': height },
      useGlobalHeadingParam: { '#text': 1 },
      useGlobalHeight: { '#text': 1 },
      useGlobalSpeed: { '#text': 1 },
      useGlobalTurnParam: { '#text': 1 },
      useStraightLine: { '#text': 1 },
      waypointHeadingParam: {
        waypointHeadingAngle: { '#text': 0 },
        waypointHeadingMode: { '#text': 'followWayline' },
        waypointHeadingPathMode: { '#text': 'followBadArc' },
        waypointHeadingPoiIndex: { '#text': 0 },
        waypointPoiPoint: { '#text': '0.000000,0.000000,0.000000' },
      },
      waypointSpeed: { '#text': 10 },
      waypointTurnParam: {
        waypointTurnDampingDist: { '#text': 0.2 },
        waypointTurnMode: { '#text': 'toPointAndStopWithDiscontinuityCurvature' },
      },
      isRisky: { '#text': 0 },
    }
    if (className === 'finally-point') {
      entity = global.$viewer.entities.add({
        position: createPointPosition,
        label: {
          text: 'ASL:70m',
          font: '13px monospace',
          showBackground: true,
          horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
          disableDepthTestDistance: Number.POSITIVE_INFINITY,
          pixelOffset: new Cesium.Cartesian2(0, -40),
        },
        billboard: {
          image: createBillboard(tragetPointArr.value.length + 1, '#61d396'),
          pixelOffset: new Cesium.Cartesian2(0, -20),
        },
        point: {
          pixelSize: 20,
          color: Cesium.Color.GHOSTWHITE,
          outlineColor: Cesium.Color.BLACK,
        },
      })
      const prePostion =
        tragetPointArr.value[tragetPointArr.value.length - 1].position
      const polylinePositions = [prePostion, createPointPosition]
      addPolyline({
        polyline: {
          positions: polylinePositions,
          width: 7,
          material: new ImageTrailMaterial({
            backgroundColor: Cesium.Color.fromBytes(96, 210, 149),
            image: getResource('arrow-right.png'),
            imageW: 7,
            duration: 0,
            animation: false,
          }),
          clampToGround: false, // 关闭贴地效果,保留高度
        },
      })
      addPolyline({
        polyline: {
          positions: Cesium.Cartesian3.fromDegreesArrayHeights([
            longitude,
            latitude,
            height,
            longitude,
            latitude,
            0,
          ]),
          width: 1,
          material: new Cesium.PolylineDashMaterialProperty({
            color: Cesium.Color.WHITE,
          }),
        },
      })
      globalEntities.value.push(entity)
      xmlTemplate.value.Folder.Placemark.push(setting)
      tragetPointArr.value.push({
        position: createPointPosition,
        eventList: [],
        isUseGlobalHeight: Boolean(setting.useGlobalHeight['#text']),
      })
    }
    // clearCesiumMap()
    // createMapMarker(undefined, [...kmlEntities.value, entity])
    if (className === 'add-prev-point') {
      globalEntities.value.splice(selectPointIndex.value, 0, entity)
      xmlTemplate.value.Folder.Placemark.splice(selectPointIndex.value, 0, setting)
      tragetPointArr.value.splice(selectPointIndex.value, 0, {
        position: createPointPosition,
        eventList: [],
        isUseGlobalHeight: Boolean(setting.useGlobalHeight['#text']),
      })
    }
    if (className === 'add-next-point') {
      const index = _.cloneDeep(selectPointIndex.value + 1)
      globalEntities.value.splice(index, 0, entity)
      xmlTemplate.value.Folder.Placemark.splice(index, 0, setting)
      tragetPointArr.value.splice(index, 0, {
        position: createPointPosition,
        eventList: [],
        isUseGlobalHeight: Boolean(setting.useGlobalHeight['#text']),
      })
    }
    // 更新点位序号
    xmlTemplate.value.Folder.Placemark.forEach((placemark: { index: { [x: string]: number } }, index: number) => {
      placemark.index['#text'] = index
    })
    const xmlStr = kmzUtils.generateXML(xmlTemplate.value)
    mapDraw.drawWayline(globalEntities.value, xmlStr)
  })
}
@@ -415,8 +443,25 @@
  }
}
const modfiyPopupShow = ref<boolean>(false)
const backPage = () => {
  emits('backFn')
  if (isModify.value) {
    modfiyPopupShow.value = true
  } else {
    mapDraw.clearWaylineData()
    kmlStr.value = ''
    emits('backFn')
  }
}
const handleModfiySave = (isSave: boolean) => {
  if (isSave) {
    saveWaylineFile()
    modfiyPopupShow.value = false
  } else {
    mapDraw.clearWaylineData()
    kmlStr.value = ''
    emits('backFn')
  }
}
// 清空画布
const clearCesiumMap = () => {
@@ -430,10 +475,35 @@
  }
}
// 保存文件
const saveWaylineFile = () => {
  kmzUtils.save()
  mapDraw.clearWaylineData()
  kmlStr.value = ''
  emits('backFn')
}
// 判断当前文件是否被修改
const isModify = ref<boolean>(false)
watch(
  () => kmlStr.value,
  (val) => {
    isModify.value = true
  },
  {
    deep: true,
  },
)
onMounted(() => {
  // 清空画布
  clearCesiumMap()
  initDrawRoute()
  console.log(!!filePath.value)
  if (filePath.value) {
    initDrawRoute()
  } else {
    initCreateRoute()
  }
})
onUnmounted(() => {
@@ -459,17 +529,48 @@
    align-items: center;
    justify-content: flex-start;
    :deep() {
      .popup-container {
        .ant-popover-content {
          .ant-popover-arrow,
          .ant-popover-inner {
            border-color: #282828;
            background-color: #282828;
            box-shadow: 0 1px 4px rgba(0, 0, 0, 0.5);
            .popup-text {
              color: #fff;
              width: 400px;
            }
            .btn-tool {
              margin-top: 10px;
              display: flex;
              justify-content: flex-end;
              .ant-btn {
                border: 0;
              }
              .btn-cancel {
                background-color: #3c3c3c;
                margin-right: 5px;
              }
            }
          }
        }
      }
    }
    .ant-btn {
      color: #fff;
    }
    .save-button {
      font-size: 20px;
      margin: 0 10px 0 auto;
      cursor: pointer;
      &:hover {
        color: #409eff;
      }
    }
    .setting-btn {
      background-color: #3c3c3c;
      margin-right: 10px;
@@ -521,6 +622,7 @@
    padding: 0;
    height: calc(100vh - 180px);
    overflow: auto;
    li {
      cursor: pointer;
      padding: 10px 0;
@@ -546,7 +648,7 @@
      }
      .graph-right {
        width: calc(100% - 40px);
        width: 100%;
        height: 30px;
        border-bottom: 1px solid #4f4f4f;
        display: flex;
@@ -571,8 +673,10 @@
    }
  }
}
.active-point {
  background-color: #3c3c3c;
  .graph {
    .left {
      border-top-color: #f3bf4e !important;