2
wangjuncheng
2025-07-01 9aed93946a567c874c847b4d3e356058b0455ae7
src/components/menu/TimeLine.vue
@@ -2,30 +2,20 @@
  <div class="timeline-container">
    <div class="controls">
      <div class="control-btn" @click="skipBackward">
        <img
          src="@/assets/img/timeline/left.png"
          class="fas fa-step-backward"
        />
        <img src="@/assets/img/timeline/left.png" class="fas fa-step-backward" />
      </div>
      <div class="control-btn play-btn" @click="togglePlay">
        <img v-show="isPlaying" src="@/assets/img/timeline/stop.png" />
        <img v-show="!isPlaying" src="@/assets/img/timeline/start.png" />
      </div>
      <div class="control-btn" @click="skipForward">
        <img
          src="@/assets/img/timeline/right.png"
          class="fas fa-step-forward"
        />
        <img src="@/assets/img/timeline/right.png" class="fas fa-step-forward" />
      </div>
      <div class="speed-control" v-show="speedShow">
        <div @click="toggleSpeedMenu">{{ playbackRate }}X</div>
        <div class="speed-menu" v-show="showSpeedMenu">
          <div
            v-for="rate in playbackRates"
            :key="rate"
            @click.capture="setPlaybackRate(rate)"
            :class="{ active: playbackRate === rate }"
          >
          <div v-for="rate in playbackRates" :key="rate" @click.capture="setPlaybackRate(rate)"
            :class="{ active: playbackRate === rate }">
            {{ rate }}X
          </div>
        </div>
@@ -35,33 +25,19 @@
    <div class="timeline">
      <div class="dates">
        <div class="current-date">当前播放时间:{{ currentPlayingTime }}</div>
        <div
          v-for="(date, index) in visibleDates"
          :key="index"
          class="date-label"
        >
        <div v-for="(date, index) in visibleDates" :key="index" class="date-label">
          <!-- {{ formatDate(date) }} -->
        </div>
        <div>
          专题渲染:
          <el-switch
            v-model="isColorRenderEnabled"
            @change="handleColorRenderChange"
            style="margin-top: -3px"
            :disabled="!isPlaying || !isWaterPrimitiveCreated"
          />
          <el-switch v-model="isColorRenderEnabled" @change="handleColorRenderChange" style="margin-top: -3px"
            :disabled="!isPlaying || !isWaterPrimitiveCreated" />
          <!-- active-text="开" inactive-text="关" -->
        </div>
      </div>
      <div class="timeline-track" ref="timelineTrack" @click="seekToPosition">
        <div
          class="timeline-progress"
          :style="{ width: progressPercentage + '%' }"
        ></div>
        <div
          class="timeline-cursor"
          :style="{ left: progressPercentage + '%' }"
        ></div>
        <div class="timeline-progress" :style="{ width: progressPercentage + '%' }"></div>
        <div class="timeline-cursor" :style="{ left: progressPercentage + '%' }"></div>
        <div class="scale-markers">
          <div class="scale-marker" style="left: 0%"></div>
          <div class="scale-marker" style="left: 25%"></div>
@@ -70,12 +46,8 @@
          <div class="scale-marker" style="left: 100%"></div>
        </div>
        <div class="time-markers">
          <div
            v-for="(time, index) in timeMarkers"
            :key="index"
            class="time-marker"
            :style="{ left: `${index * 25}%`, transform: 'translateX(-50%)' }"
          >
          <div v-for="(time, index) in timeMarkers" :key="index" class="time-marker"
            :style="{ left: `${index * 25}%`, transform: 'translateX(-50%)' }">
            <div class="date-part">{{ time.split(" ")[0] }}</div>
            <div class="time-part">{{ time.split(" ")[1] }}</div>
          </div>
@@ -84,38 +56,27 @@
    </div>
    <div>
      <div style="display: flex">
        <ratelevel
          ref="ratelevelRef"
          :playing-time="sendCurrentPlayingTime"
          @finish-calculation="handleFinishCalculation"
          style="
        <ratelevel ref="ratelevelRef" :playing-time="sendCurrentPlayingTime"
          @finish-calculation="handleFinishCalculation" style="
            margin-top: 12px;
            margin-left: 28px;
            margin-right: 10px;
            justify-content: flex-end;
          "
        />
        <crossanalysis
          ref="crossRef"
          style="
          " />
        <crossanalysis ref="crossRef" style="
            margin-top: 12px;
            margin-left: 16px;
            margin-right: 20px;
            justify-content: flex-end;
          "
        />
          " />
      </div>
      <el-button
        @click="handleBack"
        style="
      <el-button @click="handleBack" style="
          margin-top: 3px;
          margin-left: 28px;
          margin-right: 10px;
          width: 75%;
          height: 30%;
        "
        >结束模拟</el-button
      >
        ">结束模拟</el-button>
    </div>
  </div>
</template>
@@ -202,9 +163,6 @@
});
let minFlowRate = ref();
let maxFlowRate = ref();
// 全局变量记录最大阶段和透明度
let maxStage = 0;
let maxAlpha = -0.3; // 初始透明度对应stage 0
// 计算属性
const progressPercentage = computed(
  () => (currentTime.value / duration.value) * 100
@@ -344,7 +302,17 @@
      // 如果需要触发某些更新函数,也可以保留
      updateWaterColorByTime();
      updateWeatherByProgress();
      // updateWeatherByProgress();
      // 修改为固定阶段,缓慢下雨的状态
      const rainParams = {
        rainSize: 0.5,
        rainSpeed: 20,
        rainDensity: 15,
        rainColor: "#ADD8E6",
      };
      console.log("实时模拟开始下雨");
      // 调用工具方法更新雨效
      mapUtils.toggleRain(rainParams, true);
    }, 5000); // 每 5 秒执行一次
  } else {
    // 这里面还是你的播放代码,上面的if中是五秒钟跳动一次的实时模拟
@@ -386,9 +354,10 @@
    console.warn("selectedScheme 或 data 不存在");
    return;
  }
  // 注意:有时 data 可能是一个字符串(例如 JSON 字符串)
  let data = selectedScheme.value.data;
  // 如果是字符串,则尝试解析成对象
  // 如果是字符串,则尝试解析为对象
  if (typeof data === "string") {
    try {
      data = JSON.parse(data);
@@ -398,28 +367,69 @@
      return;
    }
  }
  // 打印降雨强度的单位
  console.log("降雨强度的单位是:", data.intensityUnit);
  // 根据 intensityUnit 调整 rainfalls 中的 intensity 值
  if (data.intensityUnit === "mm/min") {
    data.rainfalls.forEach((r) => (r.intensity *= 60));
    console.log("将 mm/min 转换为 mm/h 后的 rainfalls:", data.rainfalls);
  } else if (data.intensityUnit === "mm/5min") {
    data.rainfalls.forEach((r) => (r.intensity *= 12));
    console.log("将 mm/5min 转换为 mm/h 后的 rainfalls:", data.rainfalls);
  } else if (data.intensityUnit !== "mm/h") {
    console.warn("未知的 intensity 单位,无法进行转换");
  // 判断 rainfalls 是否为对象,如果是则转成数组
  let rainfalls = data.rainfalls;
  if (typeof rainfalls === "object" && !Array.isArray(rainfalls)) {
    rainfalls = Object.values(rainfalls);
    console.warn("⚠️ rainfalls 是对象,已转换为数组");
  }
  const rainfallList = data.rainfalls;
  console.log("最终的 rainfallList:", rainfallList);
  rainTotalInfo.value = rainfallList;
  calculateTimeStep(rainTotalInfo.value);
  // 使用示例
  // 按小时聚合降雨数据
  const hourlyRainfallMap = {};
  rainfalls.forEach((record) => {
    const originalTime = new Date(record.time);
    if (isNaN(originalTime.getTime())) {
      console.warn("无效的时间格式:", record.time);
      return;
    }
    // 构造“小时”级别的时间键,比如:2024-08-25 20:00:00
    const hourKey = new Date(
      originalTime.getFullYear(),
      originalTime.getMonth(),
      originalTime.getDate(),
      originalTime.getHours()
    );
    const hourStr = hourKey.toISOString().slice(0, 16).replace("T", " ");
    if (!hourlyRainfallMap[hourStr]) {
      hourlyRainfallMap[hourStr] = {
        intensity: 0,
        time: hourStr,
        total: record.total, // 默认用第一个记录的 total
      };
    }
    hourlyRainfallMap[hourStr].intensity += record.intensity;
    // 取最大的 total(因为是累积值)
    if (record.total > hourlyRainfallMap[hourStr].total) {
      hourlyRainfallMap[hourStr].total = record.total;
    }
  });
  // 转换 map 成数组并排序
  const hourlyRainfallList = Object.values(hourlyRainfallMap).sort((a, b) =>
    a.time.localeCompare(b.time)
  );
  console.log("✅ 按小时聚合后的降雨数据:", hourlyRainfallList);
  // 设置全局变量
  rainTotalInfo.value = hourlyRainfallList;
  // 计算时间步长
  timeStepInfo = calculateTimeStep(rainTotalInfo.value);
  // 提取 intensity 值
  rainFallValues.value = rainfallList.map((r) => r.intensity);
  rainFallValues.value = hourlyRainfallList.map((r) => r.intensity);
  minRainValue.value = Math.min(...rainFallValues.value);
  maxRainValue.value = Math.max(...rainFallValues.value);
  console.log(
    "当前方案下最小雨量和最大雨量:",
    minRainValue.value,
@@ -549,52 +559,46 @@
    { hex: "#8B5A3A", luminance: 101.0 }, // stage 4
    { hex: "#744C33", luminance: 84.5 },  // stage 5
    { hex: "#5D3D2C", luminance: 68.1 }   // stage 6
];
  ];
  const alphaStops = [
    -0.3,   // stage 0
    -0.4,   // stage 1
    -0.5,   // stage 2
    -0.6,   // stage 3
    -0.7,   // stage 4
    -0.75,  // stage 5
    -0.2,   // stage 0
    -0.3,   // stage 1
    -0.4,   // stage 2
    -0.5,   // stage 3
    -0.6,   // stage 4
    -0.7,   // stage 5
    -0.8    // stage 6
  ];
  // 计算每个阶段首次达到的时间点
  const stages = [];
  const thresholds = [0, 0.2, 0.4, 0.6, 0.8, 1.0];
  // 计算每个时间点的强度
  const timeIntensities = [];
  // 累计降雨量阈值(mm)
  const R_THRESHOLDS = [0, 200, 240, 280, 310, 350]; // 共6个阶段对应6个阈值
  // 时间和降雨量信息
  const timeTotals = [];
  const initialTimestamp = new Date(rainTotalInfo.value[0].time).getTime();
  for (let i = 0; i < rainTotalInfo.value.length; i++) {
    const timestamp = new Date(rainTotalInfo.value[i].time).getTime();
    const D = (timestamp - initialTimestamp) / (1000 * 60 * 60) + 0.0001;
    const IR = 56.9 * Math.pow(D, -0.746);
    const intensity = rainTotalInfo.value[i].intensity;
    timeIntensities.push({
      time: (timestamp - initialTimestamp) / 1000,
      intensity,
      IR
    const time = (timestamp - initialTimestamp) / 1000;
    const total = rainTotalInfo.value[i].total; // 使用 total 替代 intensity
    timeTotals.push({
      time,
      total
    });
  }
  // 找出每个阶段首次达到的时间点
  for (let stage = 1; stage < COLOR_STOPS.length; stage++) {
    const threshold = thresholds[stage - 1];
    for (let i = 0; i < timeIntensities.length; i++) {
      const { time, intensity, IR } = timeIntensities[i];
      if (intensity >= threshold * IR) {
        // 找到该阶段开始时间点
  const stages = [];
  for (let stage = 1; stage < R_THRESHOLDS.length + 1; stage++) {
    const threshold = R_THRESHOLDS[stage - 1];
    for (let i = 0; i < timeTotals.length; i++) {
      const { time, total } = timeTotals[i];
      if (total >= threshold) {
        stages[stage] = {
          startTime: time,
          color: COLOR_STOPS[stage].hex,
          alpha: alphaStops[stage],
          threshold: threshold
          threshold
        };
        break;
      }
@@ -614,7 +618,7 @@
function updateWaterColorByTime(isForceUpdate = false) {
  if (!rainTotalInfo.value || rainTotalInfo.value.length === 0) return;
  // 首次调用时预计算颜色阶段
  if (colorState.colorStages === null) {
    precomputeColorStages();
@@ -650,7 +654,7 @@
    // 正常时间前进时,保持渐进变化
    const newColor = colorState.colorStages[currentStage].color;
    const newAlpha = colorState.colorStages[currentStage].alpha;
    // 只应用更暗的颜色和更低的透明度
    if (calculateLuminance(newColor) < calculateLuminance(colorState.currentColor)) {
      colorState.currentColor = newColor;
@@ -662,7 +666,29 @@
  // 更新时间记录
  colorState.lastTime = currentTime.value;
  // ====== 新增:在 updateWaterColor 前打印当前信息 ======
  // // 获取当前累计降雨量
  let currentTotal = null;
  const baseTimestamp = new Date(rainTotalInfo.value[0].time).getTime();
  const currentTimeMs = baseTimestamp + currentTime.value * 1000;
  // 找到最接近的降雨数据点
  for (let i = rainTotalInfo.value.length - 1; i >= 0; i--) {
    const dataTimeMs = new Date(rainTotalInfo.value[i].time).getTime();
    if (dataTimeMs <= currentTimeMs) {
      currentTotal = rainTotalInfo.value[i].total;
      break;
    }
  }
  // 打印信息
  // console.log("========================================");
  // console.log(`【时间戳】: ${new Date(currentTimeMs).toLocaleString()}`);
  // console.log(`【累计降雨量 R】: ${currentTotal !== null ? currentTotal.toFixed(2) : '未知'} mm`);
  // console.log(`【当前阶段】: 第 ${currentStage} 阶段`);
  // console.log(`【颜色 HEX】: ${colorState.colorStages[currentStage]?.color || '未定义'}`);
  // console.log(`【透明度 Alpha】: ${colorState.colorStages[currentStage]?.alpha || '未定义'}`);
  // console.log("========================================");
  // 应用颜色
  updateWaterColor(colorState.currentColor, colorState.currentAlpha);
}
@@ -692,18 +718,18 @@
  const closestIndex = findClosestTimestampIndex(targetTime);
  const baseTimestamp = waterTimestamps.value[0];
  const newTime = (waterTimestamps.value[closestIndex] - baseTimestamp) / 1000;
  // 判断是否需要强制更新颜色
  const isGoingBackward = newTime < currentTime.value;
  const isBeforeMaxColor = colorState.maxColorTime !== null && newTime <= colorState.maxColorTime;
  const shouldForceUpdate = isGoingBackward || isBeforeMaxColor;
  currentTime.value = newTime;
  setTimeForWaterSimulation(closestIndex);
  // 根据条件更新颜色
  updateWaterColorByTime(shouldForceUpdate);
  if (!isPlaying.value) pauseWaterSimulation();
};
// ============================================================================
@@ -722,11 +748,11 @@
  // const rainValue = currentRain + (nextRain - currentRain) * alpha;
  const rainValue = currentRain + (nextRain - currentRain);
  // 打印当前处理的雨量数据
  console.log(
    `正在处理的雨量数据点: 当前=${currentRain}, 下一个=${nextRain}, 插值后=${rainValue.toFixed(
      2
    )}, 索引=${index}`
  );
  // console.log(
  //   `正在处理的雨量数据点: 当前=${currentRain}, 下一个=${nextRain}, 插值后=${rainValue.toFixed(
  //     2
  //   )}, 索引=${index}`
  // );
  // 如果当前索引未变化且插值差异不大,跳过重复更新
  if (index === lastUsedIndex && Math.abs(rainValue - lastRainValue) < 0.1) {
    // console.log('由于数据无显著变化,跳过本次更新');
@@ -753,7 +779,7 @@
    rainDensity: rainLevel.density,
    rainColor: rainLevel.color,
  };
  console.log("当前雨量数据:", rainValue, "当前雨形:", rainLevel);
  // console.log("当前雨量数据:", rainValue, "当前雨形:", rainLevel);
  // 调用工具方法更新雨效
  mapUtils.toggleRain(rainParams, true);
}
@@ -905,7 +931,6 @@
    }
    // console.log('获取到的 serviceName:', serviceInfo);
    // 根据 layer.json 获取时间轴信息
    const {
      waterTimestamps: timestamps,
@@ -930,7 +955,6 @@
        "YYYY-MM-DD HH:mm:ss"
      );
    }
    minFlowRate = watersMinHeight;
    maxFlowRate = watersMaxHeight;
  } catch (error) {
@@ -947,9 +971,7 @@
  // 因为这个函数实时模拟监听也需要使用,所以封装了一个函数
  await initializeSimulationData();
});
const shouldAutoPlay = ref(false);
// 监听 layerDate 变化后标记准备播放
watch(
  () => layerDate.value,
@@ -960,7 +982,6 @@
  },
  { deep: true }
);
// 等待 finishPlay 成功后再播放
watchEffect(() => {
  if (shouldAutoPlay.value && finishPlay.value && !isPlaying.value) {
@@ -969,7 +990,6 @@
    shouldAutoPlay.value = false;
  }
});
// 根据返回数据的个数去渲染时间轴
function updateTimelineRange() {
  if (waterTimestamps.value.length > 0) {
@@ -980,7 +1000,6 @@
    duration.value = (last - first) / 1000; // 毫秒转秒
  }
}
onBeforeUnmount(() => {
  stopPlayback();
  destoryWaterPrimitive();