wangjuncheng
2025-07-08 f373e0c0797e1800bf066fdfbb748bb9242230f6
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
<template>
  <div class="real-time-simulation">
    <div class="left-top">
      <span>实时模拟</span>
      <span class="clickable-text" @click="toggleDetails">{{
        isCollapsed ? "展开" : "收起"
      }}</span>
    </div>
 
    <el-form
      :model="formData"
      label-width="auto"
      style="max-width: 600px; padding-right: 10px; box-sizing: border-box"
    >
      <el-collapse-transition style="margin-top: 10px">
        <div v-show="!isCollapsed">
          <el-form-item label="方案名称:">
            <el-input
              v-model="formData.name"
              type="text"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
          <el-form-item label="雨量数据:">
            <el-select
              @change="handleChange"
              v-model="formData.selectedRainfall"
              placeholder="请选择"
              popper-class="mySelectStyle"
            >
              <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.name"
                :value="item.name"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <div class="table-container">
              <div
                class="table-row"
                v-for="(item, index) in shgList"
                :key="index"
              >
                <input type="checkbox" v-model="item.selected" />
                <span>{{ item.deviceName }}</span>
              </div>
            </div>
          </el-form-item>
        </div>
      </el-collapse-transition>
    </el-form>
 
    <!-- <div style="margin-top: 10px;">
        <label>仿真参数:</label>
        <div style="width: 100%; height: 60px; background-color: #fff;"></div>
      </div> -->
    <div class="buttons">
      <el-button type="primary" @click="saveSim">保存方案</el-button>
      <el-button type="success" @click="startPlay">开始模拟</el-button>
      <el-button type="success" @click="futurePredictions">未来预测</el-button>
    </div>
  </div>
</template>
 
<script setup>
import {
  ref,
  watch,
  defineProps,
  computed,
  inject,
  reactive,
  onMounted,
  onUnmounted,
} from "vue";
import { ElMessage } from "element-plus";
import { initeWaterPrimitiveView } from "@/utils/water";
import { SimAPIStore } from "@/store/simAPI";
import { useSimStore } from "@/store/simulation.js";
import { EventBus } from "@/eventBus"; // 引入事件总线
import { getDeviceInfoSHG, getYLJData } from "@/api/hpApi";
import { getSimStart, getSimDataById, getSimresult } from "@/api/trApi";
import { ControlSchemeType } from "@/assets/js/lib-pixelstreamingfrontend.esm";
 
// 获取 Store 实例
const simAPIStore = SimAPIStore();
 
const simStore = useSimStore();
 
// 表单数据
const formData = reactive({
  name: "方案名称",
  selectedRainfall: "",
  type: 2,
  gauges: [],
});
 
// 接收父组件传递的 props
const props = defineProps({
  selectedArea: {
    type: Object,
    required: true,
  },
});
 
const tableData = ref({}); // 表格数据(按雨量数据分组)
const isCollapsed = ref(false); // 控制展开/收起状态
 
// 雨量计下拉框
const options = ref([
  { id: "1", name: "气象实时数据" },
  { id: "2", name: "雨量计实时数据" },
]);
 
// 雨量计列表
const shgList = ref([]);
// 所有的雨量计列表
const rainListNoFilter = ref([]);
 
// 获取所有雨量计数据(来自接口)
const getRainListAll = () => {
  // 雨量计类型id
  const ids = "1917487171642212354";
  getDeviceInfoSHG(ids).then((res) => {
    rainListNoFilter.value = res.data.pageData;
    // 根据当前选择的区域自动过滤
    updateShgListByArea();
  });
};
 
// 根据 props.selectedArea.label 过滤雨量计列表,并设置 selected: true
const updateShgListByArea = () => {
  const currentArea = props.selectedArea?.label;
 
  if (!currentArea) {
    shgList.value = [];
    return;
  }
 
  shgList.value = rainListNoFilter.value
    .filter((item) => item.deviceName?.includes(currentArea))
    .map((device) => ({
      ...device,
      selected: true, // 默认选中
    }));
 
  console.log(shgList.value, "shgList.valueshgList.value");
};
 
// 下拉框选中值的表格数据变化
const handleChange = async (item) => {
  formData.selectedRainfall = item;
 
  if (item === "雨量计实时数据") {
    if (!props.selectedArea) {
      ElMessage.warning("请先选择区域");
      shgList.value = [];
      return;
    }
    // 如果还没有加载过数据,则先请求接口加载
    if (rainListNoFilter.value.length === 0) {
      getRainListAll(); // 加载全部数据后会自动过滤
    } else {
      updateShgListByArea(); // 已有数据就直接过滤
    }
  } else {
    shgList.value = [];
  }
};
 
// 监听区域变化,重新过滤数据
watch(
  () => props.selectedArea,
  (newArea) => {
    if (!newArea) {
      ElMessage.warning("请选择一个区域");
      shgList.value = [];
    } else if (formData.selectedRainfall === "雨量计实时数据") {
      handleChange(formData.selectedRainfall);
    }
  },
  { immediate: true }
);
 
// 重置表单
const resetForm = () => {
  formData.name = "";
  formData.selectedRainfall = "";
  shgList.value = [];
};
 
const updateSelectedGauges = () => {
  formData.gauges = shgList.value
    .filter((item) => item.selected)
    .map((item) => ({
      id: item.deviceCode,
      name: item.deviceName,
      x: item.longitude,
      y: item.latitude,
      r: 10000,
    }));
};
 
// 保存方案
const saveSim = async () => {
  try {
    // getYLJData("1101160300070101")
    updateSelectedGauges();
    formData.geom = props.selectedArea;
    await simAPIStore.addSimCheme(formData);
    // 打印拦挡坝所需要的数据
    // printDamEntities();
    resetForm();
    EventBus.emit("close-selectArea");
  } catch (err) {}
};
 
// 注入模拟操作方法
const { startSimulate, endSimulate } = inject("simulateActions");
 
// 实时模拟定时器
let pollingInterval = null;
// 用于记录上次数据条数
let lastDataLength = 0;
 
let pollingTimer = null; // 用于保存定时器引用
 
async function startPlay() {
  updateSelectedGauges();
  formData.geom = props.selectedArea;
 
  const resApi = await simAPIStore.addSimCheme(formData);
  const schemeId = resApi.data?.data?.id;
 
  if (!schemeId) {
    ElMessage.error("方案保存失败,未获取到有效 ID");
    return;
  }
 
  EventBus.emit("close-selectArea");
 
  const loadingMessage = ElMessage({
    type: "info",
    message: "正在启动模拟...",
    duration: 0,
    offset: 80,
  });
 
  try {
    await getSimStart(schemeId);
 
    // 定义一个函数用于轮询获取数据
    const pollForResult = async () => {
      try {
        const res = await getSimresult(schemeId);
        console.log(res.data, "实时模拟 - 轮询结果");
 
        if (res.code === 200 && res.data.length > 0) {
          // 成功拿到数据
          loadingMessage.close();
          handleNewData(res.data, schemeId);
          startPolling(schemeId);
 
          // ✅ 清除定时器
          if (pollingTimer) {
            clearTimeout(pollingTimer);
            pollingTimer = null;
          }
        } else {
          // 数据无效,继续轮询
          pollingTimer = setTimeout(pollForResult, 10 * 1000);
        }
      } catch (error) {
        console.error("请求模拟结果失败", error);
        pollingTimer = setTimeout(pollForResult, 10 * 1000); // 请求出错也继续轮询
      }
    };
 
    // 首次延迟 2 分钟开始轮询
    pollingTimer = setTimeout(async () => {
      await pollForResult(); // 开始第一次轮询
    }, 3 * 60 * 1000); // 3分钟后第一次请求
  } catch (error) {
    loadingMessage.close();
    ElMessage.error("请求失败:" + (error.message || "未知错误"));
    console.error("调用 getSimStart 出错:", error);
 
    if (pollingTimer) {
      clearTimeout(pollingTimer);
      pollingTimer = null;
    }
  }
}
 
// 定时五分钟请求
function startPolling(schemeId) {
  stopPolling(); // 确保不会重复启动
 
  pollingInterval = setInterval(async () => {
    try {
      const res = await getSimresult(schemeId);
 
      if (res.data && res.data.length > 0) {
        if (res.data.length === lastDataLength) {
          console.log("主轮询:无新数据,切换为 10 秒高频轮询");
 
          clearInterval(pollingInterval);
          pollingInterval = null;
 
          startFastPolling(schemeId); // 启动高频轮询
        } else {
          handleNewData(res.data, schemeId);
        }
      }
    } catch (error) {
      console.error("轮询获取模拟结果失败", error);
    }
  }, 5.6 * 60 * 1000); // 每 5.5 分钟执行一次
}
 
let fastPollingInterval = null;
// 如果五分钟没拿到最新的数据,则开启十秒钟调用一次,拿到最新的数据就停止
function startFastPolling(schemeId) {
  fastPollingInterval = setInterval(async () => {
    try {
      const res = await getSimresult(schemeId);
 
      if (res.data && res.data.length > 0) {
        if (res.data.length !== lastDataLength) {
          console.log("高频轮询:检测到新数据,恢复主轮询");
 
          clearInterval(fastPollingInterval);
          fastPollingInterval = null;
 
          handleNewData(res.data, schemeId);
 
          startPolling(schemeId); // 重新启动主轮询
        }
      }
    } catch (error) {
      console.error("高频轮询获取模拟结果失败", error);
    }
  }, 10 * 1000); // 每 10 秒执行一次
}
 
// 拿取最新的layer.json存储到pinia中
async function handleNewData(dataArray, schemeId) {
  // 拿服务名称
  const res = await getSimDataById(schemeId);
  simStore.setSelectedScheme(res.data[0]); // 更新方案数据
 
  const latestItem = dataArray[dataArray.length - 1];
  const currentLength = dataArray.length;
 
  if (currentLength <= lastDataLength) {
    console.log("本轮无新数据(长度未变化)");
    return;
  }
 
  // 更新标识
  lastDataLength = currentLength;
 
  // 执行更新逻辑
  console.log("检测到新数据,更新中...");
  console.log(latestItem, "last");
  simStore.layerDate = latestItem;
  initeWaterPrimitiveView();
 
  try {
    startSimulate();
  } catch (error) {
    console.error("调用 startSimulate 出错:", error);
  }
}
 
// 停止轮询函数
function stopPolling() {
  if (pollingInterval) {
    clearInterval(pollingInterval);
    pollingInterval = null;
  }
 
  if (fastPollingInterval) {
    clearInterval(fastPollingInterval);
    fastPollingInterval = null;
  }
 
  console.log("轮询已停止");
}
 
EventBus.on("close-time", () => {
  stopPolling();
});
 
const toggleDetails = () => {
  isCollapsed.value = !isCollapsed.value;
};
 
const futurePredictions = () => {
  console.log("未来预测按钮被点击");
};
 
onUnmounted(() => {
  EventBus.off("close-time");
  stopPolling();
});
// ========================================拦挡坝===============================================================
// 获取拦挡坝数据
function printDamEntities() {
  const entities = viewer.entities.values;
  const damDataList = [];
 
  for (let i = 0; i < entities.length; i++) {
    const entity = entities[i];
 
    if (entity.name && (entity.name === '栏档坝1' || entity.name === '栏档坝2')) {
      damDataList.push({
        name: entity.name,
        position: entity.position?._value,
        heading: entity.heading?._value ?? entity.heading,
        pitch: entity.pitch?._value ?? entity.pitch,
        roll: entity.roll?._value ?? entity.roll,
        modelScale: entity.model?.scale?._value ?? entity.model?.scale
      });
    }
  }
  if (damDataList.length > 0) {
    console.log("【栏档坝实体数据列表】:", damDataList);
    deleteDamEntitiesAfterDelay();
  } else {
    console.log("未找到任何名为 '栏档坝1' 或 '栏档坝2' 的实体");
  }
}
// 保存方案后定时清除新建的拦挡坝数据
function deleteDamEntitiesAfterDelay() {
  setTimeout(() => {
    const entities = Array.from(viewer.entities.values);
    const damsToDelete = entities.filter(
      entity => entity.name === '栏档坝1' || entity.name === '栏档坝2'
    );
 
    damsToDelete.forEach(entity => {
      viewer.entities.remove(entity);
    });
 
    if (damsToDelete.length > 0) {
      console.log(`【已删除】共 ${damsToDelete.length} 个栏档坝实体`);
    } else {
      console.log("未找到任何可删除的栏档坝实体");
    }
  }, 5000);
}
</script>
 
<style scoped>
.custom-dialog {
  z-index: 3000 !important;
}
.real-time-simulation {
  margin-bottom: 20px;
}
 
.clickable-text {
  margin-left: 160px;
  cursor: pointer;
  font-size: 14px;
  color: #61f7d4;
}
 
.details {
  margin-top: 10px;
  transition: height 0.3s ease, opacity 0.3s ease;
  overflow: hidden;
}
 
.hidden {
  height: 0;
  opacity: 0;
}
 
.input-group {
  display: flex;
  flex-direction: column;
  gap: 10px;
  padding-right: 10px;
  box-sizing: border-box;
}
 
.input-item {
  display: flex;
  align-items: center;
}
 
label {
  text-align: left;
  white-space: nowrap;
  margin-right: 10px;
}
 
.el-select {
  flex: 4;
  text-align: left;
  margin-bottom: 10px;
}
 
.table-container {
  font-size: 12px;
  height: 120px;
  width: 96%;
  overflow-y: auto;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 5px;
}
 
.table-row {
  display: flex;
  justify-content: space-between;
  padding: 5px 0;
  border-bottom: 1px solid #ddd;
}
 
.table-row:last-child {
  border-bottom: none;
}
 
.table-row span {
  flex: 1;
  text-align: left;
}
 
.table-row input[type="checkbox"] {
  margin-right: 10px;
}
 
.buttons {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding-right: 10px;
  box-sizing: border-box;
}
 
.el-button {
  flex: 1;
}
</style>