吉安感知网项目-前端
shuishen
2026-02-03 89380e6260a75d1d3b94de687ebcc2f50d50659d
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
<template>
    <el-dialog class="command-page-map-view-dialog" v-model="visible" :show-close="false" :close-on-click-modal="false">
        <div class="dialog-container">
            <div class="left-container">
                <CommonCesiumMap
                    ref="mapRef"
                    class="leftMap command-cesium"
                    :active="visible"
                    :flat-mode="false"
                    :terrain="true"
                    :layer-mode="4"
                    :boundary="false"
                    :zoom-to-boundary="dialogMode === 'add'"
                />
            </div>
            <div class="right-container">
                <div class="header">
                    <span>{{ titleEnum[dialogMode] }}</span>
 
                    <el-icon class="close-btn" @click.stop="visible = false"><Close /></el-icon>
                </div>
 
                <div class="content" v-if="readonly">
                    <div class="detail-title">场景管理详情</div>
                    <el-row>
                        <el-col :span="24">
                            <div class="label">场景名称</div>
                            <div class="val">{{ formData.sceneName }}</div>
                        </el-col>
                        <el-col :span="24">
                            <div class="label">负责人</div>
                            <div class="val">{{ formData.defenseLeader }}</div>
                        </el-col>
                        <el-col :span="24">
                            <div class="label">负责人电话</div>
                            <div class="val">{{ formData.leaderPhone }}</div>
                        </el-col>
                        <el-col :span="24">
                            <div class="label">有效时间</div>
                            <div class="val">{{ formatEffectiveDate(formData) }}</div>
                        </el-col>
                        <el-col :span="24">
                            <div class="label">指挥点位置</div>
                            <div class="val">{{ formatLocation(formData) }}</div>
                        </el-col>
                        <el-col :span="24">
                            <div class="label">关联场景配置</div>
                            <div class="val">{{ getSceneConfigName(formData.defenseSceneId) }}</div>
                        </el-col>
                    </el-row>
                </div>
 
                <el-form
                    class="dialog-form"
                    v-else
                    ref="formRef"
                    :model="formData"
                    :rules="rules"
                    :disabled="readonly"
                    label-width="110px"
                >
                    <el-form-item label="场景名称" prop="sceneName">
                        <el-input
                            class="command-input"
                            v-model="formData.sceneName"
                            maxlength="50"
                            placeholder="请输入"
                            clearable
                        />
                    </el-form-item>
                    <el-form-item label="关联场景配置" prop="defenseSceneId">
                        <el-select
                            class="command-select"
                            popper-class="command-select-popper"
                            v-model="formData.defenseSceneId"
                            placeholder="请选择"
                            clearable
                        >
                            <el-option v-for="item in sceneConfigList" :key="item.id" :label="item.sceneName" :value="item.id" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="负责人" prop="defenseLeader">
                        <el-input
                            class="command-input"
                            v-model="formData.defenseLeader"
                            maxlength="50"
                            placeholder="请输入"
                            clearable
                        />
                    </el-form-item>
                    <el-form-item label="负责人电话" prop="leaderPhone">
                        <el-input
                            class="command-input"
                            v-model="formData.leaderPhone"
                            maxlength="50"
                            placeholder="请输入"
                            clearable
                        />
                    </el-form-item>
                    <el-form-item label="有效时间范围" prop="effectiveDateStart">
                        <el-date-picker
                            class="command-date-picker"
                            popper-class="command-date-picker-popper"
                            v-model="effectiveDateRange"
                            type="datetimerange"
                            range-separator="至"
                            start-placeholder="开始时间"
                            end-placeholder="结束时间"
                            value-format="YYYY-MM-DD HH:mm:ss"
                            :disabled-date="disablePastDate"
                            clearable
                        />
                    </el-form-item>
                    <el-form-item label="指挥点位置" prop="longitude">
                        <el-input class="command-input" :model-value="commandPointText" disabled placeholder="请选择指挥点位置">
                            <template #suffix>
                                <span class="suffix-action">地图选点</span>
                            </template>
                        </el-input>
                    </el-form-item>
                </el-form>
                <div class="footer">
                    <el-button v-if="dialogMode != 'view'" color="#2B2B4C" @click="handleCancel">
                        {{ readonly ? '关闭' : '取消' }}
                    </el-button>
                    <el-button
                        color="#284FE3"
                        v-if="!readonly"
                        type="primary"
                        :loading="submitting"
                        :disabled="submitting"
                        @click="handleSubmit"
                    >
                        确定
                    </el-button>
                </div>
            </div>
        </div>
    </el-dialog>
</template>
 
<script setup>
import { Close } from '@element-plus/icons-vue'
 
import { computed, nextTick, onMounted, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { fwDefenseSceneManageDetailApi, fwDefenseSceneManageSubmitApi } from './sceneManageApi'
import { fwDefenseSceneListApi } from '../sceneConfig/sceneConfigApi'
import { fieldRules } from '@ztzf/utils'
import CommonCesiumMap from '@/components/map-container/common-cesium-map.vue'
import * as Cesium from 'cesium'
import commandPost from '@/assets/images/dataCockpit/legend/command-post.png'
import { saveOperationLog } from '@ztzf/apis'
import { useRoute } from 'vue-router'
import { fwAreaDivideDetailApi, fwAreaDivideListApi } from '../partition/partitionApi'
import {
    addBufferRadiusLabelEntity,
    buildEllipsePositions,
} from '@/utils/cesium/shapeTools'
import { cartesian3Convert } from '@/utils/cesium/mapUtil'
import { AREA_TYPE_STYLE_MAP, BUFFER_LEVEL_STYLES, DEFAULT_AREA_STYLE } from '@ztzf/constants'
import { MapTooltip } from '@ztzf/utils'
 
// 初始化表单数据
const initForm = () => ({
    sceneName: '', // 场景名称
    defenseLeader: '', // 防控负责人
    leaderPhone: '', // 防控负责人电话
    effectiveDateStart: '', // 有效时间-开始
    effectiveDateEnd: '', // 有效时间-结束
    longitude: null, // 指挥点经度
    latitude: null, // 指挥点纬度
    defenseSceneId: '', // 关联场景配置ID
})
 
const commandPointText = computed(() => {
    // 你也可以改成 `${lng}, ${lat}`
    if (!formData.value.longitude) {
        return ''
    }
    return `${formData.value.longitude}, ${formData.value.latitude}`
})
 
const emit = defineEmits(['success'])
const formRef = ref(null) // 表单实例
const formData = ref(initForm()) // 表单数据
const visible = defineModel() // 弹框显隐
const dialogMode = ref() // 弹框模式
const submitting = ref(false) // 提交中
const readonly = computed(() => dialogMode.value === 'view')
const titleEnum = ref({ edit: '编辑', view: '查看', add: '新增' })
const effectiveDateRange = ref([]) // 有效时间范围
const sceneConfigList = ref([]) // 场景配置列表
const areaList = ref([]) // ????
const mapRef = ref(null)
const route = useRoute()
let viewer
let redPointEntity
let areaDisplaySource
let leftClickBound = false
let mouseMoveBound = false
let mapTooltip
let publicCesium
const tooltipEventKey = 'scene-manage-point-tip'
const disablePastDate = date => {
    if (!date) return false
    const todayStart = new Date()
    todayStart.setHours(0, 0, 0, 0)
    return date.getTime() < todayStart.getTime()
}
 
// 表单验证规则
const rules = {
    sceneName: fieldRules(true, 50),
    defenseLeader: fieldRules(true, 50),
    leaderPhone: fieldRules(true, 50),
    effectiveDateStart: fieldRules(true),
    longitude: fieldRules(true),
    defenseSceneId: fieldRules(true),
}
 
// 关闭弹框
function handleCancel() {
    visible.value = false
}
 
// 提交新增/编辑
async function handleSubmit() {
    const isValid = await formRef.value?.validate().catch(() => false)
    if (!isValid) return
    submitting.value = true
    try {
        await fwDefenseSceneManageSubmitApi(formData.value)
        saveOperationLog({
            requestUri: route.path,
            title: `${route.name || '场景管理'}-${dialogMode.value === 'add' ? '新增' : '编辑'}`,
            type: 1,
        })
        ElMessage.success(dialogMode.value === 'add' ? '新增成功' : '更新成功')
        visible.value = false
        emit('success')
    } finally {
        submitting.value = false
    }
}
 
// 监听有效时间范围变化,同步到表单数据
watch(
    () => effectiveDateRange.value,
    () => {
        formData.value.effectiveDateStart = effectiveDateRange.value?.[0] || ''
        formData.value.effectiveDateEnd = effectiveDateRange.value?.[1] || ''
    }
)
 
// 加载详情
async function loadDetail() {
    if (!formData.value.id) return
    const res = await fwDefenseSceneManageDetailApi({ id: formData.value.id })
    formData.value = res?.data?.data ?? initForm()
    // 同步有效时间范围
    effectiveDateRange.value = [formData.value.effectiveDateStart, formData.value.effectiveDateEnd].filter(Boolean)
}
 
// 获取场景配置列表
// ?????
function ensureAreaDisplaySource() {
    if (!viewer) return null
    if (!areaDisplaySource) {
        areaDisplaySource = new Cesium.CustomDataSource('scene-manage-area-display')
        viewer.dataSources.add(areaDisplaySource)
    }
    return areaDisplaySource
}
 
function clearAreaDisplay() {
    if (!areaDisplaySource) return
    areaDisplaySource.entities.removeAll()
}
 
function normalizeShapePoint(point) {
    if (!point) return null
    const lng = point?.lng ?? point?.longitude
    const lat = point?.lat ?? point?.latitude
    const height = Number.isFinite(Number(point?.height)) ? Number(point.height) : 0
    if (!Number.isFinite(Number(lng)) || !Number.isFinite(Number(lat))) return null
    return { lng: Number(lng), lat: Number(lat), height }
}
 
function buildShapePositions(points = []) {
    const normalized = points.map(normalizeShapePoint).filter(Boolean)
    return normalized.map(point => Cesium.Cartesian3.fromDegrees(point.lng, point.lat, point.height))
}
 
function resolveLngLatPoint(point) {
    if (!point) return null
    const lng = point?.lng ?? point?.longitude
    const lat = point?.lat ?? point?.latitude
    if (Number.isFinite(Number(lng)) && Number.isFinite(Number(lat))) {
        return {
            lng: Number(lng),
            lat: Number(lat),
            height: Number.isFinite(Number(point?.height)) ? Number(point.height) : 0,
        }
    }
    if (!viewer || !Number.isFinite(point?.x) || !Number.isFinite(point?.y) || !Number.isFinite(point?.z)) {
        return null
    }
    const val = cartesian3Convert(point, viewer)
    return {
        lng: val.longitude,
        lat: val.latitude,
        height: Number.isFinite(val.height) ? val.height : 0,
    }
}
 
function getShapeDisplayPoints(shape) {
    if (Array.isArray(shape?.displayPoints) && shape.displayPoints.length) {
        return shape.displayPoints
    }
    return shape?.points || []
}
 
function getAreaTypeStyle(areaType) {
    return AREA_TYPE_STYLE_MAP?.[String(areaType)] || DEFAULT_AREA_STYLE
}
 
function parseGeomJson(geomJson) {
    if (!geomJson) return null
    if (typeof geomJson === 'object') return geomJson
    if (typeof geomJson !== 'string') return null
    const trimmed = geomJson.trim()
    if (!trimmed) return null
    try {
        return JSON.parse(trimmed)
    } catch (error) {
        return null
    }
}
 
function resolveAreaShapes(area) {
    const extList = Array.isArray(area?.fwAreaDivideExtList) ? area.fwAreaDivideExtList : []
    if (!extList.length) return []
    return extList
        .map((item, index) => {
            const isShapePayload = item?.drawType || item?.points
            if (isShapePayload) {
                return {
                    id: item?.id || `shape_${Date.now()}_${index}_${Math.random().toString(16).slice(2, 6)}`,
                    drawType: item?.drawType ?? 'polygon',
                    areaType: item?.areaType ?? item?.areaTypeKey ?? '',
                    points: Array.isArray(item?.points) ? item.points : [],
                    displayPoints: Array.isArray(item?.displayPoints) ? item.displayPoints : null,
                    meta: item?.meta ?? null,
                }
            }
            const parsed = parseGeomJson(item?.geomJson)
            if (!parsed) return null
            return {
                id: parsed?.id || `shape_${Date.now()}_${index}_${Math.random().toString(16).slice(2, 6)}`,
                drawType: parsed?.drawType ?? 'polygon',
                areaType: item?.areaTypeKey ?? parsed?.areaType ?? '',
                points: Array.isArray(parsed?.points) ? parsed.points : [],
                displayPoints: Array.isArray(parsed?.displayPoints) ? parsed.displayPoints : null,
                meta: parsed?.meta ?? null,
            }
        })
        .filter(Boolean)
}
 
function pushRadiusBoundingPoints(positions, center, radius) {
    if (!center || !Number.isFinite(Number(radius)) || radius <= 0) return
    const resolved = resolveLngLatPoint(center) || {}
    const lng = Number(resolved.lng ?? resolved.longitude)
    const lat = Number(resolved.lat ?? resolved.latitude)
    if (!Number.isFinite(lng) || !Number.isFinite(lat)) return
    const baseLat = Cesium.Math.toRadians(lat)
    const earthRadius = Cesium.Ellipsoid.WGS84.maximumRadius
    const deltaLat = radius / earthRadius
    const deltaLng = radius / (earthRadius * Math.max(Math.cos(baseLat), 0.000001))
    const points = [
        { lng: Cesium.Math.toDegrees(Cesium.Math.toRadians(lng) + deltaLng), lat },
        { lng: Cesium.Math.toDegrees(Cesium.Math.toRadians(lng) - deltaLng), lat },
        { lng, lat: Cesium.Math.toDegrees(baseLat + deltaLat) },
        { lng, lat: Cesium.Math.toDegrees(baseLat - deltaLat) },
    ]
    points.forEach(point => {
        positions.push(Cesium.Cartesian3.fromDegrees(point.lng, point.lat, resolved.height || 0))
    })
}
 
function collectSceneAreaPositions() {
    const positions = []
    if (!viewer || !areaList.value.length) return positions
    areaList.value.forEach(area => {
        const shapes = resolveAreaShapes(area)
        shapes.forEach(shape => {
            const points = getShapeDisplayPoints(shape)
            if (Array.isArray(points) && points.length) {
                points.forEach(point => {
                    const resolved = resolveLngLatPoint(point)
                    const normalized = normalizeShapePoint(resolved)
                    if (!normalized) return
                    positions.push(Cesium.Cartesian3.fromDegrees(normalized.lng, normalized.lat, normalized.height))
                })
            }
            if (shape?.drawType === 'buffer' && shape?.meta?.center && Array.isArray(shape?.meta?.bufferRadii)) {
                const maxRadius = Math.max(...shape.meta.bufferRadii.filter(item => Number.isFinite(item)))
                pushRadiusBoundingPoints(positions, shape.meta.center, maxRadius)
            }
            if (shape?.drawType === 'ellipse' && shape?.meta?.center) {
                const major = Number(shape?.meta?.semiMajor)
                const minor = Number(shape?.meta?.semiMinor)
                const radius = Number.isFinite(major) && Number.isFinite(minor) ? Math.max(major, minor) : null
                pushRadiusBoundingPoints(positions, shape.meta.center, radius)
            }
        })
    })
    return positions
}
 
function fitViewToSceneAreas() {
    if (!viewer || !areaList.value.length) return
    const positions = collectSceneAreaPositions()
    if (positions.length < 2) return
    const boundingSphere = Cesium.BoundingSphere.fromPoints(positions)
    const range = Math.max(boundingSphere.radius * 2.4, 200)
    viewer.camera.flyToBoundingSphere(boundingSphere, {
        duration: 0,
        offset: new Cesium.HeadingPitchRange(viewer.camera.heading, Cesium.Math.toRadians(-90), range),
    })
}
 
function renderSceneAreas() {
    if (!visible.value) {
        clearAreaDisplay()
        return
    }
    if (!viewer) initMap()
    const dataSource = ensureAreaDisplaySource()
    if (!dataSource) return
    dataSource.entities.removeAll()
    areaList.value.forEach(area => {
        const shapes = resolveAreaShapes(area)
        shapes.forEach(shape => {
            if (shape.drawType === 'buffer' && shape.meta?.bufferRadii?.length && shape.meta?.center) {
                const center = shape.meta.center
                const centerCartesian = Cesium.Cartesian3.fromDegrees(center.lng, center.lat, center.height || 0)
                const radii = shape.meta.bufferRadii
                    .map(radius => Number(radius))
                    .filter(radius => Number.isFinite(radius) && radius > 0)
                radii.forEach((radius, index) => {
                    const style = BUFFER_LEVEL_STYLES[index] || BUFFER_LEVEL_STYLES[BUFFER_LEVEL_STYLES.length - 1]
                    dataSource.entities.add({
                        name: 'scene-manage-area-display',
                        customData: { drawType: shape.drawType, level: index + 1 },
                        position: centerCartesian,
                        ellipse: {
                            semiMajorAxis: radius,
                            semiMinorAxis: radius,
                            material: style.fill,
                            outline: false,
                            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                        },
                    })
                    const positions = buildEllipsePositions(centerCartesian, radius, radius)
                    dataSource.entities.add({
                        name: 'scene-manage-area-display',
                        customData: { drawType: shape.drawType, level: index + 1, outline: true },
                        polyline: {
                            positions: positions.length ? [...positions, positions[0]] : positions,
                            clampToGround: true,
                            width: 2,
                            material: style.outline,
                        },
                    })
                    addBufferRadiusLabelEntity(dataSource, centerCartesian, radius, {
                        name: 'scene-manage-area-display',
                        customData: { drawType: 'buffer', label: 'radius' },
                    })
                })
                return
            }
            const positions = buildShapePositions(getShapeDisplayPoints(shape))
            if (positions.length < 3) return
            const style = getAreaTypeStyle(shape.areaType)
            dataSource.entities.add({
                name: 'scene-manage-area-display',
                customData: { drawType: shape.drawType },
                polygon: {
                    hierarchy: new Cesium.PolygonHierarchy(positions),
                    material: style.fill,
                    outline: false,
                    heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                },
                polyline: {
                    positions: positions.length ? [...positions, positions[0]] : positions,
                    clampToGround: true,
                    width: 2,
                    material: style.outline,
                },
            })
        })
    })
}
 
async function ensureAreaExtList(rows) {
    const missingRows = rows.filter(row => row?.id && !Array.isArray(row?.fwAreaDivideExtList))
    if (!missingRows.length) return rows
    const detailList = await Promise.all(
        missingRows.map(row =>
            fwAreaDivideDetailApi({ id: row.id })
                .then(res => res?.data?.data)
                .catch(() => null)
        )
    )
    const detailMap = new Map(detailList.filter(Boolean).map(item => [String(item.id), item]))
    if (!detailMap.size) return rows
    return rows.map(item => {
        const detail = detailMap.get(String(item.id))
        return detail ? { ...item, ...detail } : item
    })
}
 
// ??????????
async function loadAreaList(sceneId) {
    if (!sceneId) {
        areaList.value = []
        clearAreaDisplay()
        return
    }
    const res = await fwAreaDivideListApi({ sceneId })
    const list = res?.data?.data ?? []
    areaList.value = await ensureAreaExtList(list)
    renderSceneAreas()
    await nextTick()
    fitViewToSceneAreas()
}
 
async function getSceneConfigList() {
    if (sceneConfigList.value.length) return
    const params = { unbound: 1 }
    if (dialogMode.value !== 'add' && formData.value?.id) {
        params.sceneManageId = formData.value.id
    }
    const res = await fwDefenseSceneListApi(params)
    sceneConfigList.value = res?.data?.data ?? []
}
 
// 获取场景配置名称
function getSceneConfigName(id) {
    if (!id) return ''
    const item = sceneConfigList.value.find(item => item.id === id)
    return item?.sceneName || id
}
 
// 格式化指挥点位置
function formatLocation(row) {
    if (row?.longitude == null || row?.latitude == null) return ''
    return `${_.round(row.longitude, 6)}, ${_.round(row.latitude, 6)}`
}
 
// 格式化有效时间
function formatEffectiveDate(row) {
    if (!row?.effectiveDateStart && !row?.effectiveDateEnd) return ''
    return `${row.effectiveDateStart || '-'} ~ ${row.effectiveDateEnd || '-'}`
}
 
// 初始化地图实例
function initMap() {
    const map = mapRef.value?.getMap()
    if (!map?.viewer) return
    viewer ||= map.viewer
    publicCesium ||= map.publicCesium
    if (!readonly.value && !leftClickBound) {
        map.publicCesium?.addLeftClickEvent?.(null, LeftClickEvent)
        leftClickBound = true
    }
    if (!readonly.value) ensurePointTooltip()
}
 
function ensurePointTooltip() {
    if (!viewer || !publicCesium || mouseMoveBound) return
    mapTooltip ||= new MapTooltip(viewer, { offset: { x: 28, y: 24 } })
    publicCesium.addMouseHandler?.(
        null,
        movement => {
            if (!visible.value || readonly.value) return
            mapTooltip?.show('点击地图选择指挥点位置', movement.endPosition)
        },
        tooltipEventKey
    )
    mouseMoveBound = true
}
 
function clearPointTooltip() {
    mapTooltip?.hide()
    if (publicCesium && mouseMoveBound) {
        publicCesium.removeMouseHandler?.(tooltipEventKey)
        mouseMoveBound = false
    }
}
 
// 地图左键点击事件
async function LeftClickEvent(click) {
    const pos = click.position
    // 优先使用 pickPosition 获取贴地坐标(包含地形高度)
    let cartesian3 = viewer.scene.pickPosition(pos)
    // 如果 pickPosition 失败,回退到 pickEllipsoid
    if (!cartesian3 || !Cesium.defined(cartesian3)) {
        cartesian3 = viewer.camera.pickEllipsoid(pos, viewer.scene.globe.ellipsoid)
    }
    if (!cartesian3) return
    const carto = Cesium.Cartographic.fromCartesian(cartesian3)
    const longitude = Cesium.Math.toDegrees(carto.longitude)
    const latitude = Cesium.Math.toDegrees(carto.latitude)
    formData.value.longitude = _.round(longitude, 6)
    formData.value.latitude = _.round(latitude, 6)
    setMapPoint(formData.value.longitude, formData.value.latitude)
}
 
// 设置地图点位
function setMapPoint(longitude, latitude) {
    if (!viewer || longitude == null || latitude == null) return
    if (!redPointEntity) {
        redPointEntity = viewer.entities.add({
            position: Cesium.Cartesian3.fromDegrees(longitude, latitude),
            billboard: {
                image: commandPost,
                width: 40,
                height: 56,
                verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
            },
            label: {
                text: `${longitude.toFixed(6)}, ${latitude.toFixed(6)}`,
                font: '14px',
                fillColor: Cesium.Color.WHITE,
                backgroundColor: Cesium.Color.BLACK.withAlpha(0.6),
                backgroundPadding: new Cesium.Cartesian2(5, 5),
                showBackground: true,
                style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                verticalOrigin: Cesium.VerticalOrigin.CENTER,
                outlineWidth: 1,
                outlineColor: Cesium.Color.WHITE,
                pixelOffset: new Cesium.Cartesian2(0, -72),
                heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
            },
        })
    } else {
        redPointEntity.position = Cesium.Cartesian3.fromDegrees(longitude, latitude)
        redPointEntity.label.text = `${longitude.toFixed(6)}, ${latitude.toFixed(6)}`
    }
}
 
// 打开弹框
async function open({ mode, row } = {}) {
    dialogMode.value = mode || 'add'
    formData.value = dialogMode.value === 'add' ? initForm() : { ...row }
    effectiveDateRange.value = []
    redPointEntity = null
    await nextTick()
    initMap()
    if (dialogMode.value === 'view') {
        clearPointTooltip()
    }
    await getSceneConfigList()
    if (dialogMode.value === 'add') {
        mapRef.value?.zoomToAdminBoundary?.()
    } else {
        await loadDetail()
    }
    await nextTick()
    setMapPoint(formData.value.longitude, formData.value.latitude)
    await loadAreaList(formData.value.defenseSceneId)
    fitViewToSceneAreas()
}
 
onMounted(() => {})
 
watch(
    () => formData.value.defenseSceneId,
    sceneId => {
        if (!visible.value) return
        loadAreaList(sceneId)
    }
)
 
watch(
    () => visible.value,
    val => {
        if (!val) {
            clearAreaDisplay()
            clearPointTooltip()
        }
    }
)
 
defineExpose({
    open,
})
</script>
 
<style scoped lang="scss"></style>