吉安感知网项目-前端
罗广辉
2026-01-13 1d46e10e2a56b2cf56d5453d908e06d2ba24ef3e
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
<template>
    <el-dialog v-model="visible" :title="titleEnum[dialogMode]" :close-on-click-modal="false" width="80%">
        <div class="bodyBox">
            <div class="leftMap ztzf-cesium" id="mapContainer"></div>
            <div class="rightInfo">
                <div v-if="readonly">
                    <el-row>
                        <el-col :span="24">
                            <div>区域名称: {{ formData.areaName }}</div>
                        </el-col>
                        <el-col :span="24">
                            <div>区域位置: {{ formatLocation(formData) }}</div>
                        </el-col>
                        <el-col :span="24">
                            <div>区域面积: {{ formData.areaSize || '-' }}k㎡</div>
                        </el-col>
                        <el-col :span="24">
                            <div>区域类型: {{ getDictLabel(formData.areaType, dictObj.areaType) }}</div>
                        </el-col>
                        <el-col :span="24">
                            <div>触发条件: {{ formData.triggerCondition }}</div>
                        </el-col>
                        <el-col :span="24">
                            <div>响应机制: {{ formData.responseMechanism }}</div>
                        </el-col>
                        <el-col :span="24">
                            <div>管控级别: {{ getDictLabel(formData.controlLevel, dictObj.controlLevel) }}</div>
                        </el-col>
                        <el-col :span="24">
                            <div>关联派出所: {{ formData.policeStationName }}</div>
                        </el-col>
                        <el-col :span="24">
                            <div>可飞行时间段: {{ formatFlyDate(formData) }}</div>
                        </el-col>
                    </el-row>
                </div>
                <el-form v-else ref="formRef" :model="formData" :rules="rules" :disabled="readonly" label-width="100px">
                    <el-row>
                        <el-col :span="24">
                            <el-form-item label="区域名称" prop="areaName">
                                <el-input v-model="formData.areaName" maxlength="50" placeholder="请输入" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="区域位置" prop="longitude">
                                <div>{{ formatLocation(formData) }}</div>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="区域面积" prop="areaSize">{{ formData.areaSize || '-' }}k㎡</el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="区域类型" prop="areaType">
                                <el-select v-model="formData.areaType" placeholder="请选择" clearable>
                                    <el-option
                                        v-for="item in dictObj.areaType"
                                        :key="item.dictKey"
                                        :label="item.dictValue"
                                        :value="item.dictKey"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="响应机制" prop="responseMechanism">
                                <el-input v-model="formData.responseMechanism" maxlength="200" placeholder="请输入" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="触发条件" prop="triggerCondition">
                                <el-input v-model="formData.triggerCondition" maxlength="200" placeholder="请输入" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="管控级别" prop="controlLevel">
                                <el-select v-model="formData.controlLevel" placeholder="请选择" clearable>
                                    <el-option
                                        v-for="item in dictObj.controlLevel"
                                        :key="item.dictKey"
                                        :label="item.dictValue"
                                        :value="item.dictKey"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="可飞行时段" prop="flyDateStart">
                                <el-date-picker
                                    v-model="flyDateRange"
                                    type="datetimerange"
                                    range-separator="至"
                                    start-placeholder="开始时间"
                                    end-placeholder="结束时间"
                                    value-format="YYYY-MM-DD HH:mm:ss"
                                    clearable
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="关联派出所" prop="policeStationId">
                                <el-select v-model="formData.policeStationId" placeholder="请选择" clearable>
                                    <el-option
                                        v-for="item in policeStationOptions"
                                        :key="item.id"
                                        :label="item.stationName"
                                        :value="item.id"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="关联设备" prop="deviceIds">
                                <el-table
                                    ref="deviceTableRef"
                                    :data="deviceOptions"
                                    row-key="id"
                                    @selection-change="handleDeviceSelectionChange"
                                >
                                    <el-table-column type="selection" width="55" />
                                    <el-table-column prop="deviceName" label="设备名称" />
                                </el-table>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
        </div>
        <template #footer>
            <el-button @click="handleCancel">{{ readonly ? '关闭' : '取消' }}</el-button>
            <el-button v-if="!readonly" type="primary" :loading="submitting" :disabled="submitting" @click="handleSubmit">
                确定
            </el-button>
        </template>
    </el-dialog>
</template>
 
<script setup>
import { computed, inject, nextTick, onMounted, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { fwAreaDivideDetailApi, fwAreaDivideSubmitApi } from './partitionApi'
import { fieldRules, getDictLabel } from '@ztzf/utils'
import { PublicCesium } from '@/utils/cesium/publicCesium'
import { DrawPolygon } from '@/utils/cesium/DrawPolygon'
import { cartesian3Convert } from '@/utils/cesium/mapUtil'
import * as turf from '@turf/turf'
import * as Cesium from 'cesium'
import { fwPoliceStationListApi } from '@/views/areaManage/precinctInfo/precinctInfoApi'
import { fwDeviceListApi } from '@/views/basicManage/deviceStock/fwDevice'
 
const initForm = () => ({
    areaName: '', // 区域名称
    areaSize: null, // 区域面积
    areaType: '', // 区域类型
    controlLevel: '', // 管控级别
    deviceIds: '', // 关联设备ID
    flyDateEnd: '', // 可飞行结束
    flyDateStart: '', // 可飞行开始
    latitude: null, // 区域中心纬度
    longitude: null, // 区域中心经度
    policeStationId: '', // 关联派出所id
    responseMechanism: '', // 响应机制
    triggerCondition: '', // 触发条件
})
 
const emit = defineEmits(['success'])
const formRef = ref(null) // 表单实例
const formData = ref(initForm()) // 表单数据
const visible = defineModel() // 弹框显隐
const dialogMode = ref('add') // 弹框模式
const submitting = ref(false) // 提交中
const readonly = computed(() => dialogMode.value === 'view')
const titleEnum = ref({ edit: '编辑', view: '查看', add: '新增' })
const flyDateRange = ref([]) // 飞行时间
const deviceTableRef = ref(null)
const selectedDeviceRows = ref([])
const policeStationOptions = ref([]) // 关联派出所
const deviceOptions = ref([]) // 关联设备
const dictObj = inject('dictObj')
let viewer
let drawPolygonExample
let pointList = []
 
const rules = {
    areaName: fieldRules(true, 50),
    longitude: fieldRules(true),
    areaType: fieldRules(true),
    responseMechanism: fieldRules(true, 200),
    triggerCondition: fieldRules(true, 200),
    controlLevel: fieldRules(true),
    flyDateStart: fieldRules(true),
    policeStationId: fieldRules(true),
    deviceIds: 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 {
        let str = [...pointList, pointList[0]].map(item => `${item.longitude} ${item.latitude}`).join(',')
        formData.value.geom = `POLYGON((${str}))`
        await fwAreaDivideSubmitApi(formData.value)
        ElMessage.success(dialogMode.value === 'add' ? '新增成功' : '更新成功')
        visible.value = false
        emit('success')
    } finally {
        submitting.value = false
    }
}
 
watch(
    () => flyDateRange.value,
    () => {
        formData.value.flyDateStart = flyDateRange.value[0] || ''
        formData.value.flyDateEnd = flyDateRange.value[1] || ''
    }
)
 
// 加载详情
async function loadDetail() {
    if (!formData.value.id) return
    const res = await fwAreaDivideDetailApi({ id: formData.value.id })
    formData.value = res?.data?.data ?? initForm()
    flyDateRange.value = [formData.value.flyDateStart, formData.value.flyDateEnd].filter(Boolean)
}
 
// 格式化区域位置
function formatLocation(row) {
    if (row?.longitude == null || row?.latitude == null) return ''
    return `${_.round(row.longitude, 6)}, ${_.round(row.latitude, 6)}`
}
 
// 格式化可飞行时间段
function formatFlyDate(row) {
    if (!row?.flyDateStart && !row?.flyDateEnd) return ''
    return `${row.flyDateStart || '-'} ~ ${row.flyDateEnd || '-'}`
}
 
// 初始化地图实例
function initMap() {
    const publicCesiumInstance = new PublicCesium({
        dom: 'mapContainer',
        flatMode: false,
        terrain: true,
        layerMode: 4,
        boundary: false,
    })
    viewer = publicCesiumInstance.getViewer()
}
 
// 绘制完成回调
const drawFinished = async data => {
    pointList = _.cloneDeep(data).map(item => {
        const val = cartesian3Convert(item, viewer)
        return { ...val, lng: val.longitude, lat: val.latitude }
    })
    const polygon = turf.polygon([
        [...pointList.map(item => [item.longitude, item.latitude]), [pointList[0].longitude, pointList[0].latitude]],
    ])
    const center = turf.centerOfMass(polygon)
    const areaSqm = turf.area(polygon) // 平方米
    formData.value.areaSize = _.round(areaSqm / 1_000_000, 2) // 平方千米
    formData.value.longitude = center.geometry.coordinates[0]
    formData.value.latitude = center.geometry.coordinates[1]
}
 
// 新增模式绘制
function addPolygon() {
    drawPolygonExample = new DrawPolygon(viewer)
    drawPolygonExample.initHandler(viewer)
    drawPolygonExample.subscribe('getPolygonPositions', drawFinished)
}
 
// 解析经纬度
function getLonLat(str) {
    if (!str) return []
    return str
        .replace('POLYGON((', '')
        .replace('))', '')
        .split(',')
        .map(pair => {
            const [lon, lat] = pair.trim().split(' ').map(Number)
            return [lon, lat]
        })
}
 
// 编辑面
function editPolygon() {
    if (!formData.value?.geom) return
    const grouped = getLonLat(formData.value.geom)
    grouped.pop()
    pointList = grouped.map(item => ({ longitude: item[0], latitude: item[1] }))
    drawPolygonExample?.destroy()
    drawPolygonExample = new DrawPolygon(viewer)
    drawPolygonExample.initPolygon(
        viewer,
        grouped.map(item => ({ lng: item[0], lat: item[1] }))
    )
    drawPolygonExample.subscribe('getPolygonPositions', drawFinished)
}
 
// 查看面
function viewPolygon() {
    if (!formData.value?.geom) return
    const grouped = getLonLat(formData.value.geom)
    grouped.pop()
    pointList = grouped.map(item => ({ longitude: item[0], latitude: item[1] }))
    const result = grouped.flat().flat()
    const mian = viewer.entities?.add({
        customType: 'control_group',
        position: Cesium.Cartesian3.fromDegrees(result[0], result[1]),
        polyline: {
            positions: Cesium.Cartesian3.fromDegreesArray(result),
            clampToGround: true,
            width: 3,
            material: Cesium.Color.RED,
        },
    })
    viewer.flyTo(mian)
}
 
// 获取派出所列表
async function getPoliceStationList() {
    const res = await fwPoliceStationListApi()
    policeStationOptions.value = res?.data?.data ?? []
}
 
// 获取设备列表
async function getDeviceList() {
    if (deviceOptions.value.length) return
    const res = await fwDeviceListApi({ isAreaSelect: 1 })
    deviceOptions.value = res?.data?.data ?? []
}
 
// 关联设备变更
function handleDeviceSelectionChange(rows) {
    selectedDeviceRows.value = rows
    const ids = rows.map(item => item.id)
    formData.value.deviceIds = ids.join(',')
}
 
function getDeviceIdList() {
    if (!formData.value.deviceIds) return []
    return formData.value.deviceIds.split(',').filter(Boolean)
}
 
function syncDeviceSelection() {
    if (!deviceTableRef.value) return
    deviceTableRef.value.clearSelection()
    console.log(getDeviceIdList())
    const ids = new Set(getDeviceIdList().map(String))
    const rows = []
    deviceOptions.value.forEach(row => {
        if (ids.has(String(row.id))) {
            deviceTableRef.value.toggleRowSelection(row, true)
            rows.push(row)
        }
    })
    selectedDeviceRows.value = rows
}
 
// 打开弹框
async function open({ mode, row } = {}) {
    dialogMode.value = mode || 'add'
    formData.value = dialogMode.value === 'add' ? initForm() : row
    selectedDeviceRows.value = []
    await nextTick()
    initMap()
    await getDeviceList()
    if (dialogMode.value === 'add') {
        addPolygon()
    } else if (dialogMode.value === 'edit') {
        await loadDetail()
        editPolygon()
    } else {
        await loadDetail()
        viewPolygon()
    }
    await nextTick()
    syncDeviceSelection()
}
 
onMounted(() => {
    getPoliceStationList()
    getDeviceList()
})
 
defineExpose({
    open,
})
</script>
 
<style scoped lang="scss">
.bodyBox {
    display: flex;
    height: 600px;
    .leftMap {
        width: 70%;
        height: 100%;
    }
    .rightInfo {
        width: 30%;
        height: 100%;
        overflow: auto;
    }
}
</style>