jihongshun
2025-08-07 afec9f1c12683a11845b277c62e0ca9b83e1a5ca
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
<template>
  <div>
    <el-dialog
      title="新建项目"
      :visible="dialogVisible"
      append-to-body 
      fullscreen
      :before-close="handleClose">
       <el-row :gutter="6">
          <el-col :span=6>
              <el-card class="noScroll">
                <div class="chooseModel">
                  <div class="fontJust">设备列表</div>
                   <el-button @click="addDevice"> 新增</el-button>
                  <el-table
                    :data="tableData"
                    max-height = '180'
                    :row-key="getRowKeys"
                    style="width: 100%">
                    <el-table-column
                      prop="deviceName"
                      label="设备名称"
                      width="150">
                    </el-table-column>
                    <el-table-column
                      prop="mode"
                      label="模板"
                      width="120">
                    </el-table-column>
                    <el-table-column
                      fixed="right"
                      label="操作"
                      width="130">
                      <template slot-scope="scope">
                        <el-button type="text" size="small" @click="chooseModel(scope.row)">模板</el-button>
                        <el-button type="text" size="small" @click="flyToLocal(scope.row)">定位</el-button>
                        <el-button type="text" size="small" @click="deleteData(scope.row)">移除</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </el-card>
              <el-card >
                <div class="chooseModelTree">
                  <!-- <el-button type="primary" @click='chooseModel'>添加设备</el-button> -->
                  <div class="fontJust">巡检点目录</div>
                  <el-tree
                    class="filter-tree"
                    node-key="id"
                    :data="treeData"
                    :props="defaultProps"
                    default-expand-all
                    ref="tree">
                  </el-tree>
                </div>
              </el-card>
          </el-col>
          <el-col :span=18>
              <CesiumMap ></CesiumMap>
          </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="submit()" >生成航线任务</el-button>
      </span>
    </el-dialog>
     <chooseDeviceDialog v-if="showDevice" @cancel ='cancel' @dealChooseArr="dealChooseArr" ></chooseDeviceDialog>
     <chooseModelDialog v-if="showModel" @cancelModel ='cancelModel' @receiveModel="receiveModel" :deviceId="deviceId"></chooseModelDialog>
  </div>
</template>
<script>
import CesiumMap from "../../../../utils/components/cesium-map.vue";
import chooseDeviceDialog from './chooseDeviceDialog.vue';
import chooseModelDialog from './chooseModelDialog.vue';
import { obtainRealData ,buildKmz} from "@/api/system/template"
let rotationAngle = Cesium.Math.toRadians(0)
let lastConnectPolyline 
export  default{
  components: {
    CesiumMap,
    chooseDeviceDialog,
    chooseModelDialog
  },
  data(){
    return{
       dialogVisible :true,
        tableData: [],
        treeData:[],
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        showDevice:false,
        multipleSelection: [],
        showModel:false,
        deviceId:null
    }
  },
  methods:{
    handleClose(){
      this.dialogVisible = false
      this.$emit('close')
    },
    flyToLocal(row){
       const position = Cesium.Cartesian3.fromDegrees(row.longitude,row.latitude, row.deviceHeight);
      // rotationAngle  = Cesium.Math.toRadians(row.face)  ||  Cesium.Math.toRadians(0)
      rotationAngle  = Cesium.Math.toRadians(row.face)  ||  Cesium.Math.toRadians(0)
      // 设置模型方向(可选)
      const heading = Cesium.Math.toRadians(row.face); // 朝东南方向
      const pitch = 0;
      const roll = 0;
      const orientation = Cesium.Transforms.headingPitchRollQuaternion(
        position,
        new Cesium.HeadingPitchRoll(heading, pitch, roll)
      );
 
      // 加载 glTF 模型
      const entity = viewer.entities.add({
        name: row.id,
        position: position,
        orientation: orientation,
        model: {
          uri: row?.ardTowerModel.modelRoute, // 替换成你的模型路径
          scale: 1,
        },
        label: {
          show: true,
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
          horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
          font: '28px Helvetica',
          outlineColor: Cesium.Color.BLUE,
          outlineWidth: 3,
          fillColor: Cesium.Color.fromCssColorString('#FFFFFF'), //44c3cc
          text: row.deviceName,
          style: Cesium.LabelStyle.FILL_AND_OUTLINE,
          pixelOffset: new Cesium.Cartesian2(0.0, -56.0),
          scaleByDistance: new Cesium.NearFarScalar(1000, 0.6, 10000, 0.4),
          pixelOffsetScaleByDistance: new Cesium.NearFarScalar(1000, 0.4, 10000, 0.4),
          disableDepthTestDistance: 100000000
        }
      });
      console.log(entity)
      // 飞行到模型位置
      console.log(this.treeData)
      viewer.flyTo(entity)
    },
    addDevice(){
      this.showDevice = true
    },
    cancel(){
      this.showDevice = false
    },
    hasSameId(array1, array2) {
      const ids1 = new Set(array1.map(item => item.id));
      const ids2 = new Set(array2.map(item => item.id));
      return ids1.size !== [...ids1].filter(id => ids2.has(id)).length;
    },
    dealChooseArr(arr){
      if(this.tableData?.length == 0 ){
        this.tableData = arr
      }else {
        const hasSameId = arr.filter(obj1 =>
          this.tableData.some(obj2 => obj1.id === obj2.id)
        );
        if(hasSameId?.length != 0){
          return this.$message({
            message: '选择设备数据和已有数据重复',
            type: 'warning'
          })
        }
        this.tableData = this.treeData.concat(arr)
      }
      const dealTreeData =this.dealTee()
      this.treeData = dealTreeData
    },
    dealTee(){
      console.log(this.tableData)
     return  this.tableData.map(item => ({
        ...item,
        label: item.deviceName,
      }));
    },
    deleteData(row){
      console.log(row)
      // 找到 id 为 "1" 的元素索引
      const index = this.tableData.findIndex(item => item.id === row.id);
      // 如果找到了,删除该元素
      if (index !== -1) {
        this.tableData.splice(index, 1);
      }
      const indexTree = this.treeData.findIndex(item => item.id === row.id);
      // 如果找到了,删除该元素
      if (index !== -1) {
        this.treeData.splice(indexTree, 1);
      }
      if(this.treeData?.length >=2 && this.treeData[0]?.children?.length > 0 && this.treeData[1]?.children?.length > 0 ) {
          this.dealAddHeight()
      } else if(this.treeData?.length ==1) {
        this.treeData.map((device,index) => {
          // 确保设备有children数组
          if(index == 0) {
            //第一个数据
            if (device.children && Array.isArray(device.children) && device.children.length > 0) {
                // 获取最后一个空中点
                const lastChild = device.children[device.children.length - 1];
                const firstChild = device.children[0];
                // 深拷贝最后一个元素(包括嵌套的children)
                const newChildJson = JSON.parse(JSON.stringify(lastChild));
                // 深拷贝最一一个元素(包括嵌套的children)
                const firstChildJson = JSON.parse(JSON.stringify(firstChild));
 
                if(newChildJson && newChildJson.label.includes('加高')){
                  device.children?.pop(newChild);
                }else if(firstChildJson && firstChildJson.label.includes('加高')) {
                    device.children?.shift(firstChildJson);
                }
                // 添加到children数组末尾
            }
          }
        })
      }
      const entitiesToRemove = [];
      viewer.entities.values.forEach(entity => {
        if (entity.id && entity.id.includes(row.id)) {
          entitiesToRemove.push(entity.id);
        }
      });
      entitiesToRemove.forEach(id => {
        viewer.entities.removeById(id);
      });
      this.drawConnectionsWithLabels(this.treeData)
      // console.log(this.tableData)
      console.log(this.treeData)
      // const dealTreeData = this.dealTee()
      // console.log(dealTreeData)
      // this.treeData = dealTreeData
      // this.drawConnectionsWithLabels(this.treeData)
    },
    chooseModel(row){
      this.deviceId = row.id
      this.showModel = true
    },
    cancelModel(){
      this.showModel = false
    },
    receiveModel(obj){
      //deal逻辑
      let flightTemplateId =obj.modelObj.id
      let deviceId = obj.deviceId
      this.dealTableTemplate(obj)
      // let 
      obtainRealData(flightTemplateId,deviceId).then(res=>{
        console.log(res)
        let treeDealData = this.transformFlightData(res.data?.coordinateSystemVoS || [])
        console.log(treeDealData)
        this.dealTreeMerge(obj,treeDealData)
        
        this.rotateAllPoints(this.treeData || [],res.data.longitude,res.data.latitude,res.data.height)
        console.log(this.treeData)
        if(this.treeData?.length >=2 && this.treeData[0]?.children?.length > 0 && this.treeData[1]?.children?.length > 0 ) {
            this.dealAddHeight()
        }
        console.log(this.treeData)
        this.drawConnectionsWithLabels(this.treeData)
      })
      // this.dealTreeMerge(obj)
    },
    dealAddHeight(){
      let currentLength = this.treeData.filter(item=>item.children)?.length || 0
      console.log(this.treeData)
      console.log(currentLength)
      this.treeData.map((device,index) => {
          // 确保设备有children数组
          if(index == 0) {
            //第一个数据
            if (device.children && Array.isArray(device.children) && device.children.length > 0) {
                // 获取最后一个空中点
                const lastChild = device.children[device.children.length - 1];
                // 深拷贝最后一个元素(包括嵌套的children)
                const newChild = JSON.parse(JSON.stringify(lastChild));
                if(newChild.label.includes('加高')) {
 
                }else {
                  newChild.label = newChild.label + '-加高'
                  // 高度增加20
                  // newChild.height += 20;
                  //塔高 - 高度  + 往上飞多少米
                  newChild.height += (device.ardTowerModel?.modelHeight  - newChild.height +  20) ;
                  console.log('push11111111111111')
                  // 添加到children数组末尾
                  device.children.push(newChild);
                }
            }
          }
          else if(index == currentLength -1) {
            if (device.children && Array.isArray(device.children) && device.children.length > 0) {
                // 获取最后一个空中点
                const lastChild = device.children[0];
                // 深拷贝最一一个元素(包括嵌套的children)
                const newChild = JSON.parse(JSON.stringify(lastChild));
                if(newChild.label.includes('加高')) {
                }else {
                  newChild.label = newChild.label + '-加高第一个点'
                  newChild.height += (device.ardTowerModel?.modelHeight  - newChild.height +  20) ;
                  // 添加到children数组末尾
                  device.children.unshift(newChild);
                }
                
            }
          } else {
            if (device.children && Array.isArray(device.children) && device.children.length > 0) {
                // 获取最后一个空中点
                const firstChild = device.children[0];
                const lastChild = device.children[device.children.length - 1];
                // 深拷贝最一一个元素(包括嵌套的children)
                const newFirstChild = JSON.parse(JSON.stringify(firstChild));
                const newLastChildChild = JSON.parse(JSON.stringify(lastChild));
                //高度增加20
                if(newFirstChild.label.includes('加高')) {
                }else {
                    newFirstChild.label = newFirstChild.label + '-加高'
                    newFirstChild.height += (device.ardTowerModel?.modelHeight  - newFirstChild.height +  20) ;
                    device.children.unshift(firstChild);
                }
                if(newLastChildChild.label.includes('加高')) {
                }else {
                    newLastChildChild.label = newLastChildChild.label + '-加高'
                    newLastChildChild.height += (device.ardTowerModel?.modelHeight  - newLastChildChild.height +  20) ;
                    device.children.push(newLastChildChild);
                }
            }
          }
      })
    },
    //返回数据转换树结构
    transformFlightData(data) {
      console.log(data)
      const result = [];
 
      data.forEach(item => {
        // 找到第一个 groundPoint,作为代表
        const groundPoint = item.groundPointVo?.[0];
 
        // 生成 children 节点
        const children = groundPoint ? [{
          id: groundPoint.id,
          label: groundPoint.targetName,
          longitude: groundPoint.longitude,
          latitude: groundPoint.latitude,
          height: groundPoint.height
        }] : [];
 
        // 生成空中点
        result.push({
          id: item.id,
          label: item.targetName,
          longitude: item.longitude,
          latitude: item.latitude,
          height: item.altitude,
          children
        });
      });
 
      return result;
    },
    dealTableTemplate(obj){
      const targetTableData = this.tableData.find(item => item.id === obj.deviceId)
      const targetTreeData = this.treeData.find(item => item.id === obj.deviceId)
      if (targetTableData) {
        this.$set(targetTableData, 'mode', obj.modelObj.templateName) // ✅ Vue2 需要使用 $set 以确保响应式
      }
      if (targetTreeData) {
        this.$set(targetTreeData, 'mode', obj.modelObj.templateName) // ✅ Vue2 需要使用 $set 以确保响应式
      }
    },
    dealTreeMerge(obj,data){
      this.treeData.forEach(item => {
        if(item.id == obj.deviceId) {
          // 替换第一层每个节点的 children
          this.$set(item, 'children', JSON.parse(JSON.stringify(data)));
        }
      });
    },
    generateId() {
      return 'id_' + Math.random().toString(36).substring(2, 10);
    },
    drawConnectionsWithLabels(devices) {
      if(lastConnectPolyline) {
        viewer.entities.remove(lastConnectPolyline)
        lastConnectPolyline = null
      }
        // 直接操作EntityCollection(推荐)
      const entitiesToRemove = [];
      viewer.entities.values.forEach(entity => {
        if (entity.id && entity.id.includes(this.deviceId)) {
          entitiesToRemove.push(entity.id);
        }
      });
 
      entitiesToRemove.forEach(id => {
        viewer.entities.removeById(id);
      });
      const airPoints = [];
      console.log(devices)
      devices.forEach(device => {
        if (!Array.isArray(device.children)) return;
        device.children.forEach(airPoint => {
          // 空中点位置
          const airPos = Cesium.Cartesian3.fromDegrees(
            airPoint.longitude,
            airPoint.latitude,
            airPoint.height
          );
 
          // ✅ 添加空中点实体和 label
          viewer.entities.add({
            position: airPos,
            id:device.id +'airpoint' + this.generateId(),
            point: {
              pixelSize: 6,
              color: Cesium.Color.YELLOW
            },
            label: {
              text: airPoint.label || '',
              font: '14px sans-serif',
              fillColor: Cesium.Color.YELLOW,
              style: Cesium.LabelStyle.FILL_AND_OUTLINE,
              outlineColor: Cesium.Color.BLACK,
              outlineWidth: 2,
              verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
              pixelOffset: new Cesium.Cartesian2(0, -12)
            }
          });
 
          airPoints.push(airPos);
 
          // 遍历地面点(子项)
          if (Array.isArray(airPoint.children)) {
            airPoint.children.forEach(groundPoint => {
              const groundPos = Cesium.Cartesian3.fromDegrees(
                groundPoint.longitude,
                groundPoint.latitude,
                groundPoint.height
              );
 
              // ✅ 添加地面点实体和 label
              viewer.entities.add({
                id:device.id +'groundpoint' + this.generateId(),
                position: groundPos,
                point: {
                  pixelSize: 6,
                  color: Cesium.Color.BLUE
                },
                label: {
                  text: groundPoint.label || '',
                  font: '14px sans-serif',
                  fillColor: Cesium.Color.WHITE,
                  style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                  outlineColor: Cesium.Color.BLACK,
                  outlineWidth: 2,
                  verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                  pixelOffset: new Cesium.Cartesian2(0, -12)
                }
              });
 
              // ✅ 蓝色虚线连接:空中点 ➜ 地面点
              viewer.entities.add({
                id:device.id +'polyline' + this.generateId(),
                polyline: {
                  positions: [airPos, groundPos],
                  width: 2,
                  material: new Cesium.PolylineDashMaterialProperty({
                    color: Cesium.Color.BLUE,
                    dashLength: 8
                  })
                }
              });
            });
          }
        });
      });
      console.log(airPoints)
      // ✅ 黄色实线连接所有空中点
      if (airPoints.length > 1) {
        lastConnectPolyline = viewer.entities.add({
          polyline: {
            positions: airPoints,
            width: 3,
            material: Cesium.Color.YELLOW
          }
        });
      }
    },
    rotateAllPoints(dataList,towerLongitude,towerLatitude,towerhHight) {
      return dataList.map(item => {
        if(!item.isDeal) {
          const towerPoint = Cesium.Cartesian3.fromDegrees(towerLongitude, towerLatitude, towerhHight);
          const newGround = {
            ...item,
          };
          if(item.id == this.deviceId ){
            item.isDeal = true
          } 
          // 处理子空中点
          newGround.children = item.children?.map(child => {
            const airPoint = Cesium.Cartesian3.fromDegrees(child.longitude, child.latitude, child.height);
            const rotatedAirPoint = this.rotateAroundPoint( airPoint,towerPoint, rotationAngle);
            const rotatedAirCarto = Cesium.Cartographic.fromCartesian(rotatedAirPoint);
            child.longitude = Cesium.Math.toDegrees(rotatedAirCarto.longitude)
            child.latitude = Cesium.Math.toDegrees(rotatedAirCarto.latitude)
            child.height = rotatedAirCarto.height
            child.children = child.children?.map(sonChild => {
              const groundPoint = Cesium.Cartesian3.fromDegrees(sonChild.longitude, sonChild.latitude, sonChild.height);
              const newGroundPoint = this.rotateAroundPoint( groundPoint,towerPoint, rotationAngle);
              const newGroundCarto = Cesium.Cartographic.fromCartesian(newGroundPoint);
              return {
                ...sonChild,
                longitude: Cesium.Math.toDegrees(newGroundCarto.longitude),
                latitude: Cesium.Math.toDegrees(newGroundCarto.latitude),
                height: newGroundCarto.height
              };
            });
          });
          console.log(newGround.children)
          return newGround;
        }
         
      });
    },
    // 计算点A绕点B逆时针旋转指定角度后的新位置
    //  空中点或者地面点笛卡尔坐标 塔的笛卡尔坐标    塔的朝向值
    rotateAroundPoint(startPoint,pivotPoint,rotationAngle) {
      console.log(rotationAngle)
      // 创建一个从B点到本地坐标系的转换矩阵(东方向为X轴,北方向为Y轴,垂直方向为Z轴)
     const transformationMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(pivotPoint);
      // 获取世界坐标系到本地坐标系的转换矩阵
     const inverseTransformationMatrix = Cesium.Matrix4.inverse(transformationMatrix,new Cesium.Matrix4());
      // 将A点转换到局部坐标系中
     const localStartPoint = Cesium.Matrix4.multiplyByPoint(inverseTransformationMatrix, startPoint,new Cesium.Cartesian3());
      // 计算A点在局部坐标系中逆时针旋转指定角度后的新位置
     const rotatedX = localStartPoint.x * Math.cos(rotationAngle) + localStartPoint.y * Math.sin(rotationAngle);
     const rotatedY = localStartPoint.y * Math.cos(rotationAngle) - localStartPoint.x * Math.sin(rotationAngle);
     const rotatedZ = localStartPoint.z; // Z轴坐标保持不变
      // 将旋转后的局部坐标转换回世界坐标系
     return Cesium.Matrix4.multiplyByPoint(transformationMatrix, new Cesium.Cartesian3(rotatedX, rotatedY, rotatedZ), new Cesium.Cartesian3());
    },
    getRowKeys(row){
      console.log(row)
      return row.id +this.generateId()
    },
    submit(){
      console.log(this.treeData)
 
      const routePointList = [];
 
      this.treeData.forEach(device => {
        device.children.forEach((airPoint, index) => {
          routePointList.push({
            routePointIndex: routePointList.length,
            longitude: airPoint.longitude,
            latitude: airPoint.latitude,
            height: airPoint.height,
            isStartAndEndPoint: false,
            coordinatePointReq: {
                height: airPoint.children[0].height,
                latitude:airPoint.children[0].latitude,
                longitude: airPoint.children[0].longitude
              }
          });
        });
      });
 
      // 标记首尾为 true
      if (routePointList.length > 0) {
        routePointList[0].isStartAndEndPoint = true;
        routePointList[routePointList.length - 1].isStartAndEndPoint = true;
      }
 
      console.log(routePointList);
      let params  = {
        routePointList:routePointList
      }
      console.log('生成航线')
      buildKmz(params).then(res=>{
        if(res.code == 200) {
           this.$message({
              message: '生成航线成功',
              type: 'success'
            })
        }
      })
    }
  }
}
 
</script>
<style scoped>
.filter-tree{
  height: 365px;
  width: 100%;
  overflow: auto;
}
.fontJust{
  text-align: center;
}
.el-table {
  height: 180px;
}
</style>