吉安感知网项目-前端
chenyao
3 days ago 899f3474a9bc54d1a72710b4fd992176c1888e70
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
<template>
    <el-dialog
        v-model="visible"
        class="command-page-map-view-dialog"
        :show-close="false"
        :close-on-click-modal="false"
        destroy-on-close
        @closed="handleClosed"
    >
        <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>{{ formTitle }}</span>
 
                    <el-icon class="close-btn" @click.stop="visible = false"><Close /></el-icon>
                </div>
 
                <div class="content" v-if="dialogReadonly">
                    <el-row>
                        <el-col :span="24">
                            <div class="label">侦测设备</div>
                            <div class="val">{{ formData.deviceName || '-' }}</div>
                        </el-col>
                        <el-col :span="24">
                            <div class="label">设备类型</div>
                            <div class="val">{{ getDictLabel(formData.deviceType, dictObj.deviceType) }}</div>
                        </el-col>
                        <el-col :span="24">
                            <div class="label">设备位置</div>
                            <div class="val">{{ formData.deployLocation || '-' }}</div>
                        </el-col>
                        <el-col :span="24">
                            <div class="label">设备编号</div>
                            <div class="val">{{ formData.deviceSn || '-' }}</div>
                        </el-col>
                        <el-col :span="24">
                            <div class="label">设备型号</div>
                            <div class="val">{{ formData.deviceModel || '-' }}</div>
                        </el-col>
                        <el-col :span="24">
                            <div class="label">覆盖范围(m)</div>
                            <div class="val">{{ formatRange(formData.effectiveRangeKm) }}</div>
                        </el-col>
                    </el-row>
                </div>
 
                <el-form v-else ref="formRef" class="dialog-form" :model="formData" :rules="rules" label-width="110px">
                    <el-form-item label="侦测设备" prop="deviceId">
                        <el-select
                            class="command-select"
                            popper-class="command-select-popper"
                            v-model="formData.deviceId"
                            placeholder="请选择"
                            :disabled="dialogMode === 'edit'"
                            clearable
                            @change="handleDeviceChange"
                        >
                            <el-option v-for="item in deviceOptions" :key="item.value" :label="item.label" :value="item.value" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="设备类型" prop="deviceType">
                        <el-select
                            class="command-select"
                            popper-class="command-select-popper"
                            v-model="formData.deviceType"
                            disabled
                            placeholder="请选择"
                            clearable
                        >
                            <el-option
                                v-for="item in dictObj.deviceType"
                                :key="item.dictKey"
                                :label="item.dictValue"
                                :value="item.dictKey"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="设备位置" prop="deployLocation">
                        <el-input class="command-input" v-model="formData.deployLocation" disabled placeholder="请选择位置">
                            <template #suffix>
                                <span class="suffix-action">地图选点</span>
                            </template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="设备编号" prop="deviceSn">
                        <el-input class="command-input" v-model="formData.deviceSn" disabled placeholder="请输入" clearable />
                    </el-form-item>
                    <el-form-item label="设备型号" prop="deviceModel">
                        <el-input class="command-input" v-model="formData.deviceModel" disabled placeholder="请输入" clearable />
                    </el-form-item>
                    <el-form-item label="覆盖范围(m)" prop="effectiveRangeKm">
                        <el-input-number
                            class="command-input"
                            v-model="formData.effectiveRangeKm"
                            :min="0"
                            :precision="0"
                            :step="1"
                            :controls="false"
                            placeholder="请输入"
                        />
                    </el-form-item>
                </el-form>
                <div class="footer">
                    <el-button v-if="dialogMode != 'view'" color="#2B2B4C" @click="handleCancel">
                        {{ dialogReadonly ? '关闭' : '取消' }}
                    </el-button>
                    <el-button
                        color="#284FE3"
                        v-if="!dialogReadonly"
                        type="primary"
                        :loading="submitting"
                        :disabled="submitting"
                        @click="handleSubmit"
                    >
                        保存
                    </el-button>
                </div>
            </div>
        </div>
    </el-dialog>
</template>
 
<script setup>
import { getDictLabel } from '@ztzf/utils'
 
import { Close } from '@element-plus/icons-vue'
 
import { computed, inject, nextTick, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import {
    detectionRangeDetailApi,
    detectionRangePageApi,
    detectionRangeSubmitApi,
} from '@/api/detectionCountermeasure/detectionRange'
import CommonCesiumMap from '@/components/map-container/common-cesium-map.vue'
import * as Cesium from 'cesium'
import { saveOperationLog } from '@ztzf/apis'
import { useRoute } from 'vue-router'
import { MapTooltip } from '@ztzf/utils'
 
import equipment from '@/assets/images/dataCockpit/legend/equipment.png'
 
const initForm = () => ({
    deviceId: '', // 侦测设备ID
    deviceName: '', // 侦测设备
    deviceType: '', // 设备类型
    deployLocation: '', // 设备位置
    deviceSn: '', // 设备编号
    deviceModel: '', // 设备型号
    effectiveRangeKm: null, // 覆盖范围
})
 
const dictObj = inject('dictObj')
const emit = defineEmits(['success'])
const formRef = ref(null) // 表单实例
const formData = ref(initForm()) // 表单数据
const visible = defineModel() // 弹框显隐
const dialogMode = ref('') // 弹框模式
const submitting = ref(false) // 提交中
const deviceOptions = ref([])
const dialogReadonly = computed(() => dialogMode.value === 'view')
const mapRef = ref(null)
const route = useRoute()
let viewer
let redPointEntity
let rangeCircleEntity
let mouseMoveBound = false
let mapTooltip
let publicCesium
const tooltipEventKey = 'detection-range-point-tip'
const formTitle = computed(() => {
    if (dialogMode.value === 'edit') {
        return '编辑侦测范围'
    }
    if (dialogMode.value === 'view') {
        return '查看侦测范围'
    }
    return '新增侦测范围'
})
 
const rules = {
    deviceId: [{ required: true, message: '请选择侦测设备', trigger: ['blur', 'change'] }],
    deviceType: [{ required: true, message: '请选择设备类型', trigger: ['blur', 'change'] }],
    deployLocation: [{ required: true, message: '请选择设备位置', trigger: ['blur', 'change'] }],
    effectiveRangeKm: [{ required: true, message: '请输入覆盖范围', trigger: ['blur', 'change'] }],
}
 
function handleDeviceChange(value) {
    const target = deviceOptions.value.find(item => item.value === value)
    const raw = target?.raw
    if (!raw) return
    formData.value.deviceId = raw.id ?? formData.value.deviceId
    formData.value.deviceName = raw.deviceName ?? formData.value.deviceName
    formData.value.deviceType = raw.deviceType ?? formData.value.deviceType
    formData.value.deviceModel = raw.deviceModel ?? formData.value.deviceModel
    formData.value.deviceSn = raw.deviceSn ?? raw.deviceSn ?? raw.deviceNo ?? formData.value.deviceCode
    formData.value.deployLocation =
        raw.deployLocation ?? raw.address ?? raw.location ?? raw.deployAddress ?? formData.value.deployLocation
}
 
function getDeviceTypeLabel(value) {
    const list = dictObj?.deviceType ?? []
    const target = list.find(item => item.dictKey === value)
    return target?.dictValue ?? value ?? '-'
}
 
function formatRange(value) {
    if (value == null || value === '') return '-'
    const normalized = normalizeRange(value)
    return normalized == null ? '-' : `${normalized}`
}
 
function normalizeRange(value) {
    const numeric = Number(value)
    if (!Number.isFinite(numeric)) return null
    return Math.trunc(numeric)
}
 
// 关闭弹框
function handleCancel() {
    visible.value = false
}
 
// 提交新增/编辑
async function handleSubmit() {
    const isValid = await formRef.value?.validate().catch(() => false)
    if (!isValid) return
    submitting.value = true
    try {
        const { longitude, latitude } = parseDeployLocation(formData.value.deployLocation)
        const normalizedRange = normalizeRange(formData.value.effectiveRangeKm)
 
        const payload = {
            id: formData.value.id || formData.value.deviceId || undefined,
            effectiveRangeKmIsNotNull: normalizedRange != null ? 1 : 2,
            effectiveRangeKm: normalizedRange,
            longitude,
            latitude,
        }
        formData.value.effectiveRangeKm = normalizedRange
        delete payload.deviceId
        await detectionRangeSubmitApi(payload)
 
        const actionText = dialogMode.value === 'add' ? '新增' : '修改'
        saveOperationLog({
            requestUri: route.path,
            title: `${route.name || '侦测范围管理'}-${actionText}`,
            type: 1,
        })
 
        ElMessage.success(dialogMode.value === 'add' ? '新增成功' : '更新成功')
        visible.value = false
        emit('success')
    } finally {
        submitting.value = false
    }
}
 
// 加载详情
async function loadDetail(id) {
    if (!id) return null
    const res = await detectionRangeDetailApi({ id })
    return res?.data?.data ?? null
}
 
async function loadDeviceOptions() {
    const res = await detectionRangePageApi({
        current: 1,
        size: 200,
        effectiveRangeKmIsNotNull: 2,
        isTrack: 1,
    })
    const records = res?.data?.data?.records ?? []
    deviceOptions.value = records.map(item => ({
        label: item.deviceName ?? '-',
        value: item.id ?? '',
        raw: item,
    }))
}
 
// 关闭后重置
function handleClosed() {
    formData.value = initForm()
    clearRangeCircle()
    viewer = null
    redPointEntity = null
    rangeCircleEntity = null
    clearPointTooltip()
}
 
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: equipment, // 这里替换为你的图片路径或变量 deviceZcImg
                width: 40,
                height: 56,
                verticalOrigin: Cesium.VerticalOrigin.BOTTOM, // 设置图片底部对齐坐标点
                heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
            },
            label: {
                text: `${longitude.toFixed(6)}, ${latitude.toFixed(6)}`,
                font: '16px',
                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)}`
    }
    updateRangeCircle(longitude, latitude, formData.value.effectiveRangeKm)
}
 
function flyToRange(longitude, latitude, range) {
    if (!viewer || longitude == null || latitude == null) return
    const rangeMeters = Number(range)
    if (Number.isFinite(rangeMeters) && rangeMeters > 0) {
        const center = Cesium.Cartesian3.fromDegrees(longitude, latitude)
        const radius = Math.max(rangeMeters, 1000)
        const sphere = new Cesium.BoundingSphere(center, radius)
 
        viewer.camera.flyToBoundingSphere(sphere, {
            duration: 0,
            offset: new Cesium.HeadingPitchRange(viewer.camera.heading, Cesium.Math.toRadians(-90), radius * 1.8),
        })
        return
    }
    viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(longitude, latitude, 2000),
        orientation: {
            heading: viewer.camera.heading,
            pitch: Cesium.Math.toRadians(-65),
            roll: 0,
        },
        duration: 0,
    })
}
 
function parseDeployLocation(value) {
    if (!value) return null
    const [longitude, latitude] = value.split(',').map(item => Number(item.trim()))
    if (Number.isNaN(longitude) || Number.isNaN(latitude)) return null
    return { longitude, latitude }
}
 
function clearRangeCircle() {
    if (viewer && rangeCircleEntity) {
        viewer.entities.remove(rangeCircleEntity)
    }
}
 
function updateRangeCircle(longitude, latitude, range) {
    if (!viewer || longitude == null || latitude == null) return
    const rangeMeters = Number(range)
    if (!Number.isFinite(rangeMeters) || rangeMeters <= 0) {
        clearRangeCircle()
        rangeCircleEntity = null
        return
    }
    const position = Cesium.Cartesian3.fromDegrees(longitude, latitude)
    if (!rangeCircleEntity) {
        rangeCircleEntity = viewer.entities.add({
            position,
            ellipse: {
                semiMajorAxis: rangeMeters,
                semiMinorAxis: rangeMeters,
                material: Cesium.Color.fromCssColorString('#6b9ca8').withAlpha(0.6),
                outline: true,
                outlineColor: Cesium.Color.fromCssColorString('#6b9ca8').withAlpha(0.6),
                heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
            },
        })
        return
    }
    rangeCircleEntity.position = position
    rangeCircleEntity.ellipse.semiMajorAxis = rangeMeters
    rangeCircleEntity.ellipse.semiMinorAxis = rangeMeters
}
 
function initMap() {
    if (viewer) return
    const map = mapRef.value?.getMap()
    if (!map?.viewer) return
    viewer = map.viewer
    publicCesium = map.publicCesium
    if (!dialogReadonly.value) {
        map.publicCesium?.addLeftClickEvent?.(null, handleMapClick)
        ensurePointTooltip()
    }
}
 
function ensurePointTooltip() {
    if (!viewer || !publicCesium || mouseMoveBound) return
    mapTooltip ||= new MapTooltip(viewer, { offset: { x: 28, y: 24 } })
    publicCesium.addMouseHandler?.(
        null,
        movement => {
            if (!visible.value || dialogReadonly.value) return
            mapTooltip?.show('点击地图选择设备位置', movement.endPosition)
        },
        tooltipEventKey
    )
    mouseMoveBound = true
}
 
function clearPointTooltip() {
    mapTooltip?.hide()
    if (publicCesium && mouseMoveBound) {
        publicCesium.removeMouseHandler?.(tooltipEventKey)
        mouseMoveBound = false
    }
}
 
function handleMapClick(click) {
    const pos = click.position
    const ray = viewer.camera.getPickRay(pos)
    if (!ray) return
    const cartesian3 = viewer.scene.globe.pick(ray, viewer.scene)
    if (!cartesian3) return
    const carto = Cesium.Cartographic.fromCartesian(cartesian3)
    const longitude = Number(Cesium.Math.toDegrees(carto.longitude).toFixed(6))
    const latitude = Number(Cesium.Math.toDegrees(carto.latitude).toFixed(6))
    formData.value.deployLocation = `${longitude}, ${latitude}`
    setMapPoint(longitude, latitude)
}
 
// 打开弹框
async function open({ mode, row } = {}) {
    dialogMode.value = mode || 'add'
    clearPointTooltip()
    await nextTick()
    initMap()
    if (dialogMode.value === 'add') {
        mapRef.value?.zoomToAdminBoundary?.()
 
        await loadDeviceOptions()
        formData.value = initForm()
        return
    }
    formData.value = row
    if (dialogMode.value !== 'add') {
        const detail = await loadDetail(row?.id)
        formData.value = detail ?? row
    }
    formData.value.deployLocation = `${formData.value.longitude}, ${formData.value.latitude}`
    formData.value.deviceId = formData.value.id ?? formData.value.deviceId
    await loadDeviceOptions()
    const currentName = formData.value.deviceName
    const currentId = formData.value.deviceId
    if (currentId && !deviceOptions.value.some(item => item.value === currentId)) {
        deviceOptions.value.unshift({ label: currentName || '-', value: currentId })
    }
    const location = formData.value.deployLocation
    if (location) {
        const parsed = parseDeployLocation(location)
        if (parsed) {
            setMapPoint(parsed.longitude, parsed.latitude)
 
            flyToRange(parsed.longitude, parsed.latitude, formData.value.effectiveRangeKm)
        }
    }
}
 
defineExpose({ open })
 
watch(
    () => formData.value.effectiveRangeKm,
    value => {
        const normalized = normalizeRange(value)
        if (value != null && normalized == null) {
            formData.value.effectiveRangeKm = null
            return
        }
        if (value != null && normalized !== value) {
            formData.value.effectiveRangeKm = normalized
            return
        }
        const parsed = parseDeployLocation(formData.value.deployLocation)
        if (!parsed) return
        updateRangeCircle(parsed.longitude, parsed.latitude, normalized)
    }
)
</script>
 
<style scoped lang="scss"></style>