guonan
2025-07-03 f37845dd0a787dd42bf6c72e923433f30fcd8cc3
src/views/left/KGSimOption/RealTimeSimulation.vue
@@ -2,247 +2,408 @@
  <div class="real-time-simulation">
    <div class="left-top">
      <span>实时模拟</span>
      <span class="clickable-text" @click="toggleDetails">{{ isCollapsed ? '展开' : '收起' }}</span>
      <span class="clickable-text" @click="toggleDetails">{{
        isCollapsed ? "展开" : "收起"
      }}</span>
    </div>
    <div class="details" :class="{ hidden: isCollapsed }">
      <div class="input-group">
        <div class="input-item">
          <label>雨量数据:</label>
          <el-select v-model="selectedRainfall" placeholder="请选择" popper-class="mySelectStyle">
            <el-option
              v-for="item in rainfallData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
    <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>
      </div>
      <div class="table-container">
        <div class="table-row" v-for="(item, index) in filteredTableData" :key="index">
          <input type="checkbox" v-model="item.selected" />
          <span>{{ item.name }}</span>
        </div>
      </div>
      <!-- <div style="margin-top: 10px;">
      </el-collapse-transition>
    </el-form>
    <!-- <div style="margin-top: 10px;">
        <label>仿真参数:</label>
        <div style="width: 100%; height: 60px; background-color: #fff;"></div>
      </div> -->
    </div>
    <div class="buttons">
      <el-button type="primary" @click="openSaveDialog">保存方案</el-button>
      <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>
    <!-- 保存方案对话框 -->
    <el-dialog
      v-model="saveDialogVisible"
      title="保存方案"
      width="50%"
      :before-close="handleClose"
       custom-class="custom-dialog"
    >
      <div class="dialog-content">
        <p><strong>所选重点沟:</strong>{{ props.selectedArea }}</p>
        <p><strong>模拟类型:</strong>实时模拟</p>
        <p><strong>雨量数据类型:</strong>{{ selectedRainfallName }}</p>
        <p><strong>设备信息:</strong></p>
        <ul>
          <li v-for="item in selectedDevices" :key="item.id">{{ item.name }}</li>
        </ul>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="saveDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmSave">确定保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, watch, defineProps, computed, inject } from 'vue';
import { ElMessage } from 'element-plus';
import {
  ref,
  watch,
  defineProps,
  computed,
  inject,
  reactive,
  onMounted,
  onUnmounted,
} from "vue";
import { ElMessage } from "element-plus";
import { initeWaterPrimitiveView } from "@/utils/water";
import { useSimStore } from "@/store/simulation.js"; // 引入 Store
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 { startSimulate, endSimulate } = inject("simulateActions");
function startPlay() {
  const selectedItems = filteredTableData.value.filter(item => item.selected);
  if (selectedItems.length > 0) {
    console.log('选中的项:', selectedItems.map(item => item.name));
  } else {
    console.log('未选中任何项');
  }
  console.log('当前选中的区域:', props.selectedArea);
  console.log('当前选中的雨量数据:', selectedRainfall.value);
  initeWaterPrimitiveView();
  startSimulate();
}
// 工具函数:深拷贝并设置默认选中状态
function deepCloneAndSetSelected(data) {
  const newData = {};
  for (const key in data) {
    newData[key] = data[key].map(item => ({ ...item, selected: true }));
  }
  return newData;
}
// 表单数据
const formData = reactive({
  name: "方案名称",
  selectedRainfall: "",
  type: 2,
  gauges: [],
});
// 接收父组件传递的 props
const props = defineProps({
  selectedArea: {
    type: String,
    required: true
  }
    type: Object,
    required: true,
  },
});
// 子组件内部状态
const rainfallData = ref([]); // 雨量数据
const tableData = ref({}); // 表格数据(按雨量数据分组)
const selectedRainfall = ref(''); // 当前选中的雨量数据
const isCollapsed = ref(false); // 控制展开/收起状态
const saveDialogVisible = ref(false); // 控制保存方案对话框显示状态
// 模拟不同区域的数据
const areaDataMap = {
  孙胡沟: {
    rainfallData: [
      { id: '1', name: '气象实时数据 - 孙胡沟' },
      { id: '2', name: '雨量计实时数据 - 孙胡沟' }
    ],
    tableData: {
      '1': [
        { id: '001', name: '孙胡沟气象站001' },
        { id: '002', name: '孙胡沟气象站002' }
      ],
      '2': [
        { id: '003', name: '孙胡沟雨量计003' },
        { id: '004', name: '孙胡沟雨量计004' }
      ]
// 雨量计下拉框
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;
    }
  },
  鱼水洞后沟: {
    rainfallData: [
      { id: '1', name: '气象实时数据 - 鱼水洞后沟' },
      { id: '2', name: '雨量计实时数据 - 鱼水洞后沟' }
    ],
    tableData: {
      '1': [
        { id: '005', name: '鱼水洞后沟气象站005' },
        { id: '006', name: '鱼水洞后沟气象站006' }
      ],
      '2': [
        { id: '007', name: '鱼水洞后沟雨量计007' },
        { id: '008', name: '鱼水洞后沟雨量计008' }
      ]
    // 如果还没有加载过数据,则先请求接口加载
    if (rainListNoFilter.value.length === 0) {
      getRainListAll(); // 加载全部数据后会自动过滤
    } else {
      updateShgListByArea(); // 已有数据就直接过滤
    }
  },
  于家西沟: {
    rainfallData: [
      { id: '1', name: '气象实时数据 - 于家西沟' },
      { id: '2', name: '雨量计实时数据 - 于家西沟' }
    ],
    tableData: {
      '1': [
        { id: '009', name: '于家西沟气象站009' },
        { id: '010', name: '于家西沟气象站010' }
      ],
      '2': [
        { id: '011', name: '于家西沟雨量计011' },
        { id: '012', name: '于家西沟雨量计012' }
      ]
    }
  } else {
    shgList.value = [];
  }
};
// 根据 selectedArea 更新数据
// 监听区域变化,重新过滤数据
watch(
  () => props.selectedArea,
  (newArea) => {
    if (areaDataMap[newArea]) {
      rainfallData.value = areaDataMap[newArea].rainfallData;
      // 使用深拷贝设置默认选中状态
      tableData.value = deepCloneAndSetSelected(areaDataMap[newArea].tableData);
      selectedRainfall.value = ''; // 清空选中的雨量数据
    } else {
      rainfallData.value = [];
      tableData.value = {};
      selectedRainfall.value = '';
    if (!newArea) {
      ElMessage.warning("请选择一个区域");
      shgList.value = [];
    } else if (formData.selectedRainfall === "雨量计实时数据") {
      handleChange(formData.selectedRainfall);
    }
  },
  { immediate: true } // 立即执行一次,确保初始数据正确
  { immediate: true }
);
// 动态计算表格数据
const filteredTableData = computed(() => {
  return selectedRainfall.value && tableData.value[selectedRainfall.value]
    ? tableData.value[selectedRainfall.value]
    : [];
});
// 重置表单
const resetForm = () => {
  formData.name = "";
  formData.selectedRainfall = "";
  shgList.value = [];
};
// 获取当前选中的雨量数据名称
const selectedRainfallName = computed(() => {
  const selected = rainfallData.value.find(item => item.id === selectedRainfall.value);
  return selected ? selected.name : '';
});
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 selectedDevices = computed(() => {
  return filteredTableData.value.filter(item => item.selected);
});
// 保存方案
const saveSim = async () => {
  try {
    // getYLJData("1101160300070101")
    updateSelectedGauges();
    formData.geom = props.selectedArea;
    await simAPIStore.addSimCheme(formData);
    resetForm();
    EventBus.emit("close-selectArea");
  } catch (err) {}
};
// 打开保存方案对话框
const openSaveDialog = () => {
  if (!props.selectedArea || !selectedRainfall.value || selectedDevices.value.length === 0) {
    ElMessage.warning('请先选择区域、雨量数据并勾选设备');
// 注入模拟操作方法
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;
  }
  saveDialogVisible.value = true;
};
// 关闭保存方案对话框
const handleClose = () => {
  saveDialogVisible.value = false;
};
  EventBus.emit("close-selectArea");
// 确认保存
const confirmSave = () => {
  // 构造新的方案对象
  const newScheme = {
    id: Date.now().toString(), // 唯一 ID
    area: props.selectedArea, // 区域
    name: selectedRainfallName.value, // 方案名称(雨量数据类型)
    createTime: new Date().toISOString(), // 创建时间
    taskStatus:1, // 初始状态为未开始
    rainfallType: selectedRainfallName.value, // 雨量数据类型
    devices: selectedDevices.value.map((item) => item.name), // 设备信息
  };
  const loadingMessage = ElMessage({
    type: "info",
    message: "正在启动模拟...",
    duration: 0,
    offset: 80,
  });
  // 调用 Store 的方法添加方案
  simStore.addSchemCard(newScheme);
  try {
    await getSimStart(schemeId);
  console.log("保存方案成功", newScheme);
  ElMessage.success("方案已保存");
    // 定义一个函数用于轮询获取数据
    const pollForResult = async () => {
      try {
        const res = await getSimresult(schemeId);
        console.log(res.data, "实时模拟 - 轮询结果");
  // 关闭对话框
  saveDialogVisible.value = false;
};
        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('未来预测按钮被点击');
  console.log("未来预测按钮被点击");
};
onUnmounted(() => {
  EventBus.off("close-time");
  stopPolling();
});
</script>
<style scoped>
@@ -275,6 +436,8 @@
  display: flex;
  flex-direction: column;
  gap: 10px;
  padding-right: 10px;
  box-sizing: border-box;
}
.input-item {
@@ -297,6 +460,7 @@
.table-container {
  font-size: 12px;
  height: 120px;
  width: 96%;
  overflow-y: auto;
  border: 1px solid #ddd;
  border-radius: 4px;
@@ -326,10 +490,13 @@
.buttons {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding-right: 10px;
  box-sizing: border-box;
}
.el-button {
  flex: 1;
}
</style>
</style>