无人机管理后台前端(已迁走)
chenyao
2025-05-23 23aa4b64192290656bd0594846a68264e01f8a3e
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
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
<template>
    <div id="taskMap">
        <div class="new-task-region" v-show="isShowSearch">
            <div class="searchInput">
                <el-select
                    :disabled="disabled"
                    :teleported="false"
                    class="ztzf-select"
                    v-model="optionsValue"
                    placeholder="请选择查询"
                >
                    <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
 
                <el-input v-model="searchKey" @input="handlerInput" placeholder="请输入搜索关键字"></el-input>
            </div>
        </div>
        <div class="select-down-list" ref="selectDownRef" v-show="isSelectDown">
            <div class="item" v-for="item in downList" @click="selectedValue(item)">{{ item.nickname || item.name }}</div>
        </div>
    </div>
</template>
<script setup>
import _ from 'lodash'
import * as Cesium from 'cesium'
import { Cartesian3, Math as CesiumMath, Terrain, Viewer } from 'cesium'
import AmapMercatorTilingScheme from '@/utils/cesium/AmapMercatorTilingScheme'
import { analyzeKmzFile, removeTextKey, XMLToJSON } from '@/utils/cesium/kmz'
import uavImg from '@/assets/images/home/useUavHome/uavImg.png'
import { getLnglatAltitude } from '@/utils/cesium/mapUtil'
import { getWaylineByArea } from '@/api/job/task'
import { useStore } from 'vuex'
import { searchByKeyword } from '@/api/home/common'
// 新图片
import addressArea from '@/assets/images/addressArea.png'
import newStartPoint from '@/assets/images/newStartPoint.png'
import newEndPointImg from '@/assets/images/newEndPointicon.png'
import newlineImg from '@/assets/images/newarrow-right.png'
import { PublicCesium } from '@/utils/cesium/publicCesium'
import { gcj02ToWgs84 } from '@/utils/coordinateTransformation'
import { ElMessage } from 'element-plus'
const store = useStore()
const userAreaPosition = computed(() => store.state.home.userAreaPosition)
// const selectedAreaCode = computed(() => store.state.user.selectedAreaCode)
// const userAreaCode = computed(() => store.state.user.userInfo.detail.areaCode)
const loginUserInfo = computed(() => store.state.user.userInfo.detail)
const areaValue = ref(loginUserInfo.value.areaName)
 
// 声明事件
const emit = defineEmits(['clickPosition', 'saveWayline'])
 
const props = defineProps({
    wayLineFile: {
        type: String,
        default: '',
    },
    waylineModel: {
        type: String,
        default: '',
    },
    checkedTableData: {
        type: Array,
        default: () => [],
    },
    waylineTypeTest: {
        type: Number,
        default: 3,
    },
})
 
const searchKey = ref('')
const optionsValue = ref('2')
const disabled = ref(true)
let options = [
    {
        value: '1',
        label: '机巢',
    },
    {
        value: '2',
        label: '地址',
    },
]
const isShowSearch = ref(false)
const isSelectDown = ref(false)
// 地址搜索结果
const downList = ref([])
// 获取地址搜索结果
const getAddressList = async () => {
    const res = await searchByKeyword(encodeURIComponent(`${areaValue.value}+${searchKey.value}`))
    if (res.data.code !== 0) return
    downList.value = res?.data?.data.tips || []
    if (downList.value.length > 0) {
        isSelectDown.value = true
    } else {
        isSelectDown.value = false
    }
}
// input对应下拉数据初始化
const inputSelect = () => {
    if (optionsValue.value === '2' && searchKey.value !== '') {
        getAddressList()
    }
}
 
// 输入框input事件
const handlerInput = _.debounce(inputSelect, 1000)
const addressPointEntity = ref(null)
const position = ref({})
 
const imageryProvider_ammapSL = new Cesium.UrlTemplateImageryProvider({
    url: 'https://webrd02.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}',
    layer: 'tdtVecBasicLayer',
    style: 'default',
    format: 'image/png',
    tileMatrixSetID: 'GoogleMapsCompatible',
    subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'],
    maximumLevel: 18,
    tilingScheme: new AmapMercatorTilingScheme(),
    credit: 'amap_SL',
})
 
let viewer = null
let currentEntity = null
let connectLines = [] // 存储连接线实体
let polygonPoints = [] // 存储多边形的点
let polygonEntity = null // 存储多边形实体
let existingEntity = null // 后端返回数据生成得面状线
// 添加变量跟踪当前菜单
let currentMenu = null
// 存储选择航线第一个点的位置
let firstPosition = null
let machineNestPositionLine = null
 
const init = () => {
    viewer = new PublicCesium({ dom: 'taskMap' }).getViewer()
    //设置默认点
    const { longitude = 115.763819, latitude = 28.787374, height = 10 } = userAreaPosition.value || {}
    viewer.camera.setView({
        destination: Cartesian3.fromDegrees(longitude, latitude, height),
        orientation: {
            heading: 0, // east, default value is 0.0 (north)
            pitch: Cesium.Math.toRadians(-90), // default value (looking down)
            roll: 0.0, // default value
        },
    })
}
// 机巢下拉获取值
const selectedValue = item => {
    searchKey.value = item.nickname || item.name
    const [lng, lat] = item.location.split(',').map(Number)
    const [longitude, latitude] = gcj02ToWgs84(lng, lat)
    position.value = { longitude, latitude }
 
    // 添加标注点
    const cartesian3 = Cesium.Cartesian3.fromDegrees(Number(position.value.longitude), Number(position.value.latitude), 0)
    // 清除之前的实体
    if (addressPointEntity.value) {
        viewer.entities.remove(addressPointEntity.value)
    }
    addressPointEntity.value = viewer.entities.add({
        id: 'address_point',
        position: cartesian3,
        billboard: {
            image: addressArea,
            pixelOffset: new Cesium.Cartesian2(0, -13),
            outlineWidth: 0,
            width: 30,
            height: 30,
            scale: 1.0,
        },
        label: {
            text: searchKey.value,
            font: '12px monospace',
            showBackground: true,
            horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
            verticalOrigin: Cesium.VerticalOrigin.TOP,
            disableDepthTestDistance: Number.POSITIVE_INFINITY,
            pixelOffset: new Cesium.Cartesian2(0, -50),
        },
    })
    flyToPoints([[Number(position.value.longitude), Number(position.value.latitude)]])
    isSelectDown.value = false
}
 
// 单点左键点击事件
const singlePointLeftClick = () => {
    viewer.screenSpaceEventHandler.setInputAction(click => {
        if (props.waylineTypeTest !== 1) return
        const cartesian = viewer.camera.pickEllipsoid(click.position, viewer.scene.globe.ellipsoid)
        if (cartesian) {
            // 清除之前的实体
            viewer.entities.removeAll()
 
            // 添加新点
            const point = viewer.entities.add({
                position: cartesian,
                point: {
                    pixelSize: 10,
                    color: Cesium.Color.fromCssColorString('#1FFF69'),
                },
            })
 
            // 转换坐标
            const cartographic = Cesium.Cartographic.fromCartesian(cartesian)
            const longitude = Cesium.Math.toDegrees(cartographic.longitude)
            const latitude = Cesium.Math.toDegrees(cartographic.latitude)
 
            // 更新当前实体引用
            currentEntity = point
 
            // 发送坐标
            emit('clickPosition', { longitude, latitude })
        }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
}
 
// 智能规划航线
const intelligentPlanning = () => {
    // 添加点击事件监听
    viewer.screenSpaceEventHandler.setInputAction(click => {
        if (props.waylineTypeTest !== 2) return
        const cartesian = viewer.camera.pickEllipsoid(click.position, viewer.scene.globe.ellipsoid)
 
        if (cartesian) {
            // 添加新点
            const point = viewer.entities.add({
                position: cartesian,
                point: {
                    pixelSize: 10,
                    color: Cesium.Color.fromCssColorString('#1FFF69'),
                },
            })
 
            // 存储点位
            polygonPoints.push(cartesian)
 
            // 当点击超过2个点时绘制多边形
            if (polygonPoints.length > 2) {
                // 移除旧的多边形
                if (polygonEntity) {
                    viewer.entities.remove(polygonEntity)
                }
 
                // 创建新的多边形
                polygonEntity = viewer.entities.add({
                    polygon: {
                        hierarchy: new Cesium.PolygonHierarchy(polygonPoints),
                        // material: new Cesium.Color.fromBytes(212, 46, 32, 100),
                        material: new Cesium.Color(0, 0.5, 1, 0.3), // 蓝色
                        outline: true,
                        // outlineColor: new Cesium.Color.fromBytes(212, 46, 32, 255),
                        outlineColor: new Cesium.Color(0, 0.5, 1, 1), // 蓝
                        outlineWidth: 2,
                        height: 0, // Set explicit height
                        heightReference: Cesium.HeightReference.NONE, // Disable terrain clamping
                    },
                })
            }
 
            // 转换坐标并发送
            const cartographic = Cesium.Cartographic.fromCartesian(cartesian)
            const longitude = Cesium.Math.toDegrees(cartographic.longitude)
            const latitude = Cesium.Math.toDegrees(cartographic.latitude)
            // emit('clickPosition', cartographic);
        }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
    // 修改右键点击事件,添加菜单
    viewer.screenSpaceEventHandler.setInputAction(movement => {
        if (props.waylineTypeTest !== 2) return
        if (polygonPoints.length > 2) {
            // 清除之前的菜单
            if (currentMenu) {
                document.body.querySelectorAll('.context-menu').forEach(menu => menu.remove())
            }
 
            const menuContainer = document.createElement('div')
            menuContainer.className = 'context-menu'
 
            // 获取地图容器
            const mapContainer = document.getElementById('taskMap')
            // 使用鼠标右键点击的实际位置
            menuContainer.style.position = 'absolute'
            menuContainer.style.left = `${movement.position.x}px`
            menuContainer.style.top = `${movement.position.y}px`
            menuContainer.style.zIndex = '1000'
 
            menuContainer.innerHTML = `
                <div class="menu-item" id="saveWayline">保存航线</div>
                <div class="menu-item" id="cancelDraw">取消绘制</div>
            `
 
            mapContainer.appendChild(menuContainer)
            currentMenu = menuContainer
 
            // 添加全局点击事件监听
            const handleClickOutside = e => {
                if (!menuContainer) return
                const isClickInside = menuContainer.contains(e.target)
                if (!isClickInside) {
                    menuContainer.remove()
                    document.removeEventListener('mousedown', handleClickOutside)
                }
            }
 
            // 延迟添加事件监听,避免右键点击立即触发
            setTimeout(() => {
                document.addEventListener('mousedown', handleClickOutside)
            }, 100)
 
            // 菜单按钮点击事件
            document.getElementById('saveWayline').onclick = () => {
                const coordinates = polygonPoints.map(point => {
                    const cartographic = Cesium.Cartographic.fromCartesian(point)
                    return {
                        longitude: Cesium.Math.toDegrees(cartographic.longitude),
                        latitude: Cesium.Math.toDegrees(cartographic.latitude),
                    }
                })
                emit('saveWayline', coordinates)
                saveWaylineByArea(coordinates)
                mapContainer.removeChild(menuContainer)
            }
 
            document.getElementById('cancelDraw').onclick = () => {
                polygonPoints = []
                viewer.entities.removeAll()
                mapContainer.removeChild(menuContainer)
            }
        }
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK)
}
 
// 保存航线并且获取线
const saveWaylineByArea = dataValue => {
    const polygonArray = dataValue.map(point => [point.longitude, point.latitude])
    getWaylineByArea({ type: 2, polygon: polygonArray }).then(res => {
        if (res.data.code !== 0) retrun
        drawResultWayline(res.data.data)
    })
}
 
// 绘制后端生成得面状线
const drawResultWayline = dataValue => {
    // 先检查并删除已存在的航线
    existingEntity = viewer.entities.getById('result_wayline')
    if (existingEntity) {
        viewer.entities.remove(existingEntity)
    }
    const cartesian3List = ref([])
    dataValue.forEach(lnglat => {
        const cartesian3 = Cesium.Cartesian3.fromDegrees(
            Number(lnglat.x),
            Number(lnglat.y),
            Number(100) // 默认100
        )
        cartesian3List.value.push(cartesian3)
    })
    const setting = {
        id: 'result_wayline',
        polyline: {
            width: 2,
            positions: cartesian3List.value,
            material: Cesium.Color.CHARTREUSE,
        },
    }
    existingEntity = viewer?.entities.add({
        polyline: setting.polyline,
        id: setting.id,
    })
}
 
// 选中航线时调用 渲染线和点 type = 0
const renderingLine = lineObj => {
    const positions = lineObj.Placemark.map(item => {
        const [lon, lat] = item.Point.coordinates.split(',')
        return Cartesian3.fromDegrees(Number(lon), Number(lat))
    })
    // 存储第一个点的位置
    firstPosition = positions[0]
 
    viewer.entities.add({
        polyline: {
            width: 5,
            positions: positions,
            material: new Cesium.PolylineGlowMaterialProperty({
                image: newlineImg,
            }),
            clampToGround: false,
        },
    })
 
    positions.forEach((point, index) => {
        let setting = {}
        if (index === positions.length - 1) {
            setting = {
                position: point,
                id: `point_${index}`,
                billboard: {
                    image: newEndPointImg,
                    outlineWidth: 0,
                    width: 20,
                    height: 20,
                    scale: 1.0,
                },
            }
        } else {
            setting = {
                position: point,
                id: `point_${index}`,
                label: {
                    text: `${index + 1}`,
                    font: 'bold 14px serif',
                    fillColor: Cesium.Color.WHITE,
                    // style: Cesium.LabelStyle.FILL,
                    // verticalOrigin: Cesium.VerticalOrigin.CENTER, // 垂直居中
                    // horizontalOrigin: Cesium.HorizontalOrigin.CENTER, // 水平居中
                    pixelOffset: new Cesium.Cartesian2(1, 0), // 根据需要调整偏移量
                    eyeOffset: new Cesium.Cartesian3(0, 0, -10), // 使标签在点的上方
                },
                billboard: {
                    image: new Cesium.ConstantProperty(newStartPoint),
                    width: 70,
                    height: 70,
                },
                offset: new Cesium.Cartesian2(10, 30),
            }
        }
        viewer.entities.add(setting)
    })
}
 
// 飞到中心点
function flyToPoints(lngLatArr) {
    if (!Array.isArray(lngLatArr) || lngLatArr.length === 0) return
    const positions = lngLatArr.map(([lon, lat]) => Cesium.Cartesian3.fromDegrees(Number(lon), Number(lat)))
    // 计算包围盒 BoundingSphere(所有点的外接球)
    const boundingSphere = Cesium.BoundingSphere.fromPoints(positions)
    viewer.camera.flyToBoundingSphere(boundingSphere, {
        duration: 0,
        offset: new Cesium.HeadingPitchRange(0, -90, boundingSphere.radius * 2),
    })
}
 
// 异步解析kmz文件
const analysis = async url => {
    return new Promise(async resolve => {
        const res = await analyzeKmzFile(`${url}?_t=${new Date().getTime()}`)
        const templateXML = await res.fileInfoObj['wpmz/template.kml']
        const waylinesXML = await res.fileInfoObj['wpmz/waylines.wpml']
        const templateXMLJSON = XMLToJSON(templateXML)?.['Document']
        const templateXMLObj = removeTextKey(templateXMLJSON.Folder)
        const waylinesXMLJSON = XMLToJSON(waylinesXML)?.['Document']
        resolve({ templateXMLObj, waylinesXMLJSON })
    })
}
 
// 绘制线和飞行
const drawLine = async () => {
    let prexUrl = ref(import.meta.env.VITE_APP_AIRLINE_URL + props.wayLineFile)
    const { templateXMLObj, waylinesXMLJSON } = await analysis(prexUrl.value)
    if (props.waylineModel === 'planar') {
        drawPlanarWayline(templateXMLObj, waylinesXMLJSON)
    } else {
        if (!templateXMLObj.Placemark.length) return
        renderingLine(templateXMLObj)
        const points = templateXMLObj.Placemark.map(item => item.Point.coordinates.split(','))
        flyToPoints(points)
    }
}
 
// 生成面状航线
const drawPlanarWayline = async (templateXMLObj, waylinesXMLJSON) => {
    let coordArr = null
    // 取出点位
    let coordinates =
        templateXMLObj.Placemark.Polygon?.outerBoundaryIs.LinearRing.coordinates?.['#text']?.split('\n') || []
 
    // 数组转换
    coordArr = coordinates.map(coordinate =>
        coordinate
            .replace(/\s+/g, '')
            .split(',')
            .map(v => Number(v))
    )
    // 获取当前经纬度海拔高度
    const newCoordArr = []
    // 面状点位
    for (let [index, coord] of coordArr.entries()) {
        const [lng, lat] = coord
        const { height: hAltitude } = await getLnglatAltitude(Number(lng), Number(lat), global.$viewer)
        newCoordArr.push([lng, lat, hAltitude])
    }
    // 航线点位
    let coordinateTest = []
    const waylinePoints = waylinesXMLJSON.Folder.Placemark
    if (!waylinePoints.length) return ElMessage.error('没有航线点位')
    const waylinePointLnglats = waylinePoints.map(json => {
        const executeHeight = Number(json.executeHeight['#text'])
        const coordinate = json.Point.coordinates['#text'].split(',').map(lnglat => Number(lnglat))
        coordinateTest.push(coordinate)
        coordinates.push()
        return Cesium.Cartesian3.fromDegrees(coordinate[0], coordinate[1], executeHeight)
    })
    // 绘制面状航线--------------------
    // waylinePointLnglats.unshift(
    //     Cesium.Cartesian3.fromDegrees(
    //         Number(this.droneCoordinates.longitude),
    //         Number(this.droneCoordinates.latitude),
    //         Number(this.droneCoordinates.height)
    //     )
    // )
    // 判断是2D还是3D
    // if (!this.clampToGroundshow) {
    //     let cartesian = this.addTurnPoint(waylinePointLnglats[0], waylinePointLnglats[1])
    //     waylinePointLnglats.splice(1, 0, cartesian)
    // }
 
    existingEntity = viewer.entities.getById('result_wayline')
    if (existingEntity) {
        viewer.entities.remove(existingEntity)
    }
 
    existingEntity = viewer.entities.add({
        id: 'result_wayline',
        polyline: {
            width: 3,
            positions: waylinePointLnglats,
            material: Cesium.Color.CHARTREUSE,
            zIndex: 1,
            clampToGround: false,
        },
    })
    // 传给后端 ,取列表数据
    const cartesianlengthArr = waylinePointLnglats.map(point => {
        const cartographic = Cesium.Cartographic.fromCartesian(point)
        return {
            longitude: Cesium.Math.toDegrees(cartographic.longitude),
            latitude: Cesium.Math.toDegrees(cartographic.latitude),
        }
    })
    emit('saveWayline', cartesianlengthArr)
    // let cartesianlengthArr = waylinePointLnglats.map(cartesian => {
    //     return [cartesian3Convert(cartesian, viewer).longitude, cartesian3Convert(cartesian, viewer).latitude]
    // })
    // const centerpoint = getCenterPoint(cartesianlengthArr)
    // let maxlength = 0
    // cartesianlengthArr.forEach((item, index) => {
    //     let banseTwoPoints = getLnglatDist(item[0], item[1], centerpoint.lng, centerpoint.lat)
    //     if (banseTwoPoints > maxlength) {
    //         maxlength = banseTwoPoints
    //     }
    // })
 
    flyToPoints(coordinateTest)
}
 
// 单个点生成选择多个机巢生成航线和选择航线连线
const singlePointLines = newVal => {
    // 清除之前的连接线
    connectLines.forEach(line => viewer.entities.remove(line))
    connectLines = []
    if (currentEntity || props.waylineTypeTest === 0) {
        // 获取当前点的位置
        let currentPosition = null
        if (props.waylineTypeTest === 0) {
            currentPosition = firstPosition
        } else {
            currentPosition = currentEntity.position.getValue()
        }
 
        // 为每个选中的机巢创建点和连接线
        newVal.forEach(item => {
            // 创建机巢点
            const nestPosition = Cartesian3.fromDegrees(Number(item.longitude), Number(item.latitude))
            viewer.entities.add({
                position: nestPosition,
                billboard: {
                    image: new Cesium.ConstantProperty(uavImg),
                    width: 24,
                    height: 24,
                },
            })
 
            // 创建连接线
            machineNestPositionLine = viewer.entities.add({
                polyline: {
                    positions: [currentPosition, nestPosition],
                    width: 5,
                    material: new Cesium.PolylineGlowMaterialProperty({
                        image: newlineImg,
                    }),
                },
            })
            connectLines.push(machineNestPositionLine)
        })
 
        // 飞到所有点的中心位置
        const lngLatArr = newVal.map(item => [item.longitude, item.latitude])
        flyToPoints(lngLatArr)
    }
}
 
// 智慧规划航线-面状航线
const planarPointsLines = newVal => {
    // 如果存在面状航线
    if (existingEntity) {
        const waylinePositions = existingEntity.polyline.positions.getValue()
 
        newVal.forEach(item => {
            // 创建机巢点
            const nestPosition = Cartesian3.fromDegrees(Number(item.longitude), Number(item.latitude))
 
            // 添加机巢图标
            viewer.entities.add({
                position: nestPosition,
                billboard: {
                    image: new Cesium.ConstantProperty(uavImg),
                    width: 24,
                    height: 24,
                },
            })
 
            // 找到最近的航线点并连线
            let minDistance = Number.MAX_VALUE
            let closestPosition = null
 
            waylinePositions.forEach(waylinePos => {
                const distance = Cartesian3.distance(nestPosition, waylinePos)
                if (distance < minDistance) {
                    minDistance = distance
                    closestPosition = waylinePos
                }
            })
 
            // 创建连接线
            if (closestPosition) {
                machineNestPositionLine = viewer.entities.add({
                    polyline: {
                        positions: [nestPosition, closestPosition],
                        width: 2,
                        material: new Cesium.PolylineDashMaterialProperty({
                            color: Cesium.Color.CHARTREUSE,
                            dashLength: 8.0,
                        }),
                    },
                })
                connectLines.push(machineNestPositionLine)
            }
        })
 
        // 飞到所有点的中心位置
        const lngLatArr = newVal.map(item => [item.longitude, item.latitude])
        flyToPoints(lngLatArr)
    }
}
 
// 监听选择航线文件事件
watch(
    () => props.wayLineFile,
    async newVal => {
        await removeMap()
        if (newVal) await drawLine()
    },
    { deep: true }
)
 
// 监听表格选中数据变化
watch(
    () => props.checkedTableData,
    newVal => {
        if (!newVal.length) {
            // 清除连接线
            viewer.entities.remove(machineNestPositionLine)
            return
        }
        if (newVal.length > 0 && props.waylineModel === 'point') {
            singlePointLines(newVal)
        } else if (newVal.length > 0 && props.waylineModel === 'planar') {
            planarPointsLines(newVal)
        }
    },
    { deep: true }
)
 
watch(
    () => props.waylineTypeTest,
    async newVal => {
        if (newVal === 0) {
            isShowSearch.value = false
        } else {
            isShowSearch.value = true
        }
        await removeMap()
        if (newVal === 1) await singlePointLeftClick()
        else if (newVal === 2) await intelligentPlanning()
    },
    { deep: true }
)
 
const removeEvent = () => {
    // 清除事件监听器
    viewer.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK)
    viewer.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.RIGHT_CLICK)
}
 
const removeMap = () => {
    // 清除所有实体
    if (viewer) {
        // 清除连接线
        viewer.entities.remove(machineNestPositionLine)
        machineNestPositionLine = null
        connectLines.forEach(line => viewer.entities.remove(line))
        connectLines = []
 
        // 清除多边形点和实体
        polygonPoints = []
        if (polygonEntity) {
            viewer.entities.remove(polygonEntity)
        }
 
        // 清除当前实体和面状航线
        if (currentEntity) {
            viewer.entities.remove(currentEntity)
        }
        if (existingEntity) {
            viewer.entities.remove(existingEntity)
        }
        if (addressPointEntity) {
            viewer.entities.remove(addressPointEntity)
        }
 
        viewer.entities.removeAll()
 
        // 重置所有变量
        currentEntity = null
        polygonEntity = null
        existingEntity = null
        addressPointEntity.value = null
    }
}
 
onBeforeUnmount(() => {
    removeMap()
    removeEvent()
    // 移除所有实体并销毁viewer
    viewer.destroy()
    viewer = null
})
 
onMounted(() => {
    inputSelect()
    nextTick(() => {
        init()
    })
})
</script>
<style scoped lang="scss">
#taskMap {
    position: relative;
    height: 100%;
    .select-down-list {
        position: absolute;
        top: 50px;
        left: 42%;
        transform: translateX(-40%);
        width: 230px;
        height: 256px;
        overflow-y: auto;
        background: linear-gradient(180deg, #0d3556 0%, #012350 100%);
        border-radius: 0px 0px 8px 8px;
        border: 1px solid;
        border-image: linear-gradient(180deg, rgba(255, 255, 255, 0), rgba(115, 192, 255, 1)) 1 1;
        font-size: 14px;
        color: #ffffff;
        // opacity: 0.8;
        &::-webkit-scrollbar {
            width: 0;
            display: none;
        }
        -ms-overflow-style: none; /* IE and Edge */
        scrollbar-width: none; /* Firefox */
        .item {
            color: #ffffff;
            height: 32px;
            line-height: 32px;
            text-align: center;
            cursor: pointer;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            &:hover {
                background: linear-gradient(
                    90deg,
                    rgba(0, 122, 255, 0) 0%,
                    rgba(0, 98, 204, 0.6) 50%,
                    rgba(0, 73, 153, 0) 100%
                );
                border: 1px solid;
                border-image: linear-gradient(90deg, rgba(0, 199, 190, 0), rgba(48, 176, 199, 1), rgba(0, 199, 190, 0)) 1 1;
            }
        }
    }
    .new-task-region {
        width: 350px;
        height: 43px;
        position: absolute;
        top: 10px;
        left: 50%;
        transform: translateX(-50%);
        display: flex;
        .el-select {
            width: 100px;
            height: 100%;
 
            :deep() {
                .el-select__wrapper {
                    background: transparent;
                    border: none;
                    box-shadow: none;
                    height: 100%;
                    padding-left: 20px;
                }
 
                .el-select__suffix {
                    display: none;
                }
 
                .el-select__selected-item {
                    font-family: Source Han Sans CN, Source Han Sans CN, serif;
                    font-weight: 400;
                    font-size: 14px;
                    color: #ffffff;
                    line-height: 18px;
                }
            }
        }
        .searchInput {
            width: 243px;
            height: 100%;
            background: url('@/assets/images/home/searchBox/searchBg1.png') no-repeat center / 100% 100%;
            display: flex;
 
            .el-input {
                height: 100%;
 
                :deep() {
                    .el-input__wrapper {
                        background: transparent;
                        border: none;
                        box-shadow: none;
                        height: 100%;
                    }
 
                    .el-input__inner {
                        font-family: Source Han Sans CN, Source Han Sans CN, serif;
                        font-weight: 400;
                        font-size: 14px;
                        color: #ffffff;
                        line-height: 18px;
                        white-space: nowrap; /* 禁止换行 */
                        overflow: hidden; /* 隐藏溢出内容 */
                        text-overflow: ellipsis; /* 使用省略号显示 */
                    }
                }
            }
        }
    }
    :deep() {
        .cesium-viewer {
            height: 100%;
            overflow: hidden;
 
            .cesium-viewer-cesiumWidgetContainer {
                width: 100%;
                height: 100%;
 
                .cesium-widget {
                    width: 100%;
                    height: 100%;
 
                    canvas {
                        width: 100%;
                        height: 100%;
                    }
                }
            }
        }
 
        .cesium-viewer-bottom {
            display: none;
        }
    }
 
    :deep(.context-menu) {
        position: absolute;
        background: rgba(0, 21, 41, 0.9);
        border-radius: 4px;
        padding: 8px 0;
        min-width: 120px;
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.3);
 
        .menu-item {
            padding: 8px 16px;
            color: #fff;
            cursor: pointer;
            transition: all 0.3s;
            font-size: 14px;
 
            &:hover {
                background: rgba(255, 255, 255, 0.1);
            }
        }
    }
}
</style>