<template>
  <div class="timeline-container">
    <div class="timeline-header">
      <div class="timeline-controls">
        <div>时间轴</div>
        <div class="block">
          <span class="demonstration">时间段</span>

          <el-date-picker v-model="dateRange" type="daterange" popper-class="custom-date-picker" unlink-panels
            range-separator="→" start-placeholder="开始日期" end-placeholder="结束日期" :disabled-date="disabledDate"
            @change="pick_select_date_handFn" :popper-options="{
              placement: 'bottom-start',
              modifiers: [
                {
                  name: 'offset',
                  options: {
                    offset: [-650, -125] // [水平偏移, 垂直偏移]
                  }
                }
              ]
            }" />
          <div class="right_block">
            <!--限制 :disabled="!is_flag_confirmAndPauseAndSpeed" -->
            <el-button class="right_block_confirm_btn" size="small"
              @click="handleDateRangeChange(pick_select_date)">确认</el-button>
            <div class="right_block_center">
              <!-- <el-button circle class="right_block_conter_btn" @click="playBackward">
                <el-icon>
                  <img src="@/assets/images/footers/videoPlay_left.png" alt="" style="width: 8px; height: 10px;" />
                </el-icon>
              </el-button> -->
              <!--限制 :disabled="!is_flag_confirmAndPauseAndSpeed" -->
              <el-button circle class="right_block_conter_btn_center" @click="toggleAutoPlay">
                <el-icon>
                  <img v-if="!isPlaying" src="@/assets/images/footers/videoPause.png" alt=""
                    style="width: 8px; height: 10px;" />
                  <img v-if="isPlaying" src="@/assets/images/footers/videoPlay.png" alt=""
                    style="width: 8px; height: 10px;" />
                </el-icon>
              </el-button>

            </div>
            <el-select v-model="playbackSpeed" style="width: 70px" class="satellite-select"
              :disabled="is_flag_isRealtime">
              <el-option v-for="item in playbackSpeedOptions" :key="item.value" :label="item.label" :value="item.value"
                @click="() => {
                  //console.log('我是喧杂',playbackSpeed);
                  changeSpeed()
                }" />
            </el-select>
            <!-- <el-button size="mini" circle @click="changeSpeed" :disabled="is_flag_isRealtime || !is_flag_confirmAndPauseAndSpeed" class="right_block_conter_btn_playbackSpeed" style="background: none;">x{{ playbackSpeed }}</el-button> -->
          </div>
        </div>
      </div>
    </div>

    <!-- 时间轴主体 -->
    <div class="timeline">
      <!-- 时间轴内容区域 -->
      <div class="timeline-content">
        <!-- 时间刻度 -->
        <div class="time-markers">
          <div v-for="(marker, index) in timeMarkers" :key="index" class="time-marker"
            :style="{ left: marker.position + '%' }">
            <div class="marker-line"
              :class="{ 'major-line': marker.isMajor, 'minor-line_color': (index) % showLengthmarkerLine === 0 || index === timeMarkers.length - 1 }">
            </div>
            <span class="marker-label" :class="{ 'selected-label': isMarkerInSelectedRange(marker) }"
              v-if="((index) % showLength === 0 || index === timeMarkers.length - 1)" v-html="marker.label"></span>

          </div>
        </div>

        <!-- 滑块和选中区域 -->
        <div class="slider-container">
          <div class="slider-track" ref="sliderTrack">
            <div class="selected-range" :style="selectedRangeStyle"></div>

            <!-- 开始滑块 -->
            <div class="slider-handle start-handle" :style="{ left: startHandlePosition }">
              <div class="handle-rail"></div>
              <div class="handle-tooltip">{{ formatDateTime(selectedStartTime) }}</div>
            </div>

            <!-- 结束滑块 -->
            <div class="slider-handle end-handle" :style="{ left: endHandlePosition }"
              @mousedown="startDrag('end', $event)">
              <div class="handle-rail">
                <div class="handle-tooltip" :class="{ 'handle-tooltip_auto': !is_flag_isRealtime }">{{
                  formatDateTime(selectedEndTime) }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { VideoPlay, VideoPause, CaretLeft, CaretRight } from '@element-plus/icons-vue';

import { ElLoading, ElMessage } from 'element-plus'
import Loading from '@/pages/all/components/loadingComponent/index.js'
import { ref, onMounted, onUnmounted, computed, watch, nextTick, watchEffect } from 'vue';
import wss from '@/utils/requestSocekt.js'
import wsTime from '@/utils/requestSocektTime.js'
import useAppStore from '@/store/module/app'
import dayjs from 'dayjs';
import { timeInfoApi } from '../../../api/Zodiac.js';

const wssInstance = ref(wss)
const wsTimeInstance = ref(wsTime)
// import { loading } from 'vxe-pc-ui';
// 用于表示速度改变时，正常数据返回后才能够再次改变速度
const speedChangedNormalDataBack = ref(false)
const playbackSpeedOptions = ref([
  {
    value: 1,
    label: '1x'
  },
  {
    value: 2,
    label: '2x'
  },
  {
    value: 4,
    label: '4x'
  },
  {
    value: 8,
    label: '8x'
  },
  {
    value: 10,
    label: '10x'
  },
])
const useAppStoreInstance = useAppStore();

const is_flag_confirmAndPauseAndSpeed = ref(true)
// 跳转到指定时间点
const jumpToSpecificTime = (targetTime, PerformDrag = false) => {
  console.log('跳转到指定时间点:', targetTime);
  // isChange_flag_firstBackDate.value = false;
  hasPlayed.value = false;
  try {
    if (!startDateTime.value || !endDateTime.value) {
      console.error("时间轴起始时间或结束时间未定义");
      ElMessage.error('时间轴未初始化');
      return false;
    }

    // 停止当前自动播放
    // if (isPlaying.value) {
    //    //console.log("我走了这里3")
    //   stopAutoPlay();
    // }

    const start = new Date(startDateTime.value).getTime();
    const end = new Date(endDateTime.value).getTime();
    const totalMs = totalMilliseconds.value;

    // 校验目标时间是否有效
    if (!(targetTime instanceof Date) || isNaN(targetTime.getTime())) {
      console.error("目标时间无效:", targetTime);
      ElMessage.error('目标时间格式无效');
      return false;
    }

    const targetMs = targetTime.getTime();

    // 校验目标时间是否在范围内
    if (targetMs < start || targetMs > end) {
      console.error("目标时间不在时间轴范围内:", targetTime);
      ElMessage.warning('目标时间不在当前时间轴范围内');
      return false;
    }

    // 计算目标时间点的百分比位置
    const percentPosition = ((targetMs - start) / totalMs) * 100;

    // 只更新结束滑块位置
    endHandlePercent.value = Math.max(0, Math.min(100, percentPosition));

    // 更新选中时间
    updateSelectedTimes();

    // 标记为手动选择时间点
    isDraged.value = true;
    is_flag_isRealtime.value = false;
    isConfirmedWithRange.value = false; // 设置为false以显示完整的选中区域

    // 强制更新视图
    // nextTick(() => {
    //   updateSelectedTimes();
    //   //console.log("跳转到指定时间:", targetTime, "滑块位置:", percentPosition);

    //   // 调用UE5回调函数
    //   // if (window.ue5) {
    //   //   window.ue5("callBackTimeFn", String(JSON.stringify({
    //   //     isRealtime: false,
    //   //     replayTime: formatDateTime(targetTime),
    //   //     taskCode: String(taskCode_everyChange.value) === "" ? useAppStoreInstance.globalRecordMainSysTaskCode || (useAppStoreInstance.globalSubsystemTaskCode) : String(taskCode_everyChange.value),
    //   //   })));
    //   //   wssOpenHandle({
    //   //     isRealtime: false,
    //   //     replayTime: formatDateTime(targetTime),
    //   //     taskCode: String(taskCode_everyChange.value) === "" ? useAppStoreInstance.globalRecordMainSysTaskCode || (useAppStoreInstance.globalSubsystemTaskCode) : String(taskCode_everyChange.value),
    //   //   });
    //   // }
    // });
    // playForward();
    if (PerformDrag) {
      endDrag();
      // moveEndHandle();
    }

    return true;
  } catch (error) {
    console.error("跳转到指定时间点出错:", error);
    ElMessage.error('跳转时间点失败');
    return false;
  }
};


const wssOpenHandle = (data) => {
  console.log("发送数据", (wssInstance.value).readyState);
  if ((wssInstance.value).readyState === WebSocket.OPEN) {
    // 如果连接已打开，直接发送数据
    (wssInstance.value).send(JSON.stringify(data));
    wssMessageHandle();
    // console.warn('WebSocket 已连接，无法发送数据:', data);
  } else if ((wssInstance.value).readyState === WebSocket.CLOSED) {
    console.warn('WebSocket 已关闭，无法发送数据:', data);
    (wssInstance.value) = new WebSocket((wssInstance.value).url);
    (wssInstance.value).onopen = () => {
      (wssInstance.value).send(JSON.stringify(data));
    };
    console.log("发送数据1111");
    wssMessageHandle();
  } else {
    // 否则等待连接打开后再发送
    (wssInstance.value).onopen = () => {
      (wssInstance.value).send(JSON.stringify(data));
    };
    wssMessageHandle();
  }
  startAutoPlay();
};
const wssResponeFlag_isSuccess = ref(true);
const loading = ref('');





const compareTime = (time1, time2) => {
  // console.log('cao每隔开始compareTime----------1', time1, time2);
  // 将时间字符串转换为 Date 对象
  const date1 = new Date(time1);
  if (time2 === null || time2 === "" || time2 === undefined) {
    time2 = new Date(
      new Date(selectedStartTime.value).getTime() + 60 * 1000
    ).toISOString();
    // //console.log('每隔开始compareTime----------', time1, time2);
  }
  const date2 = new Date(time2);

  // 检查时间是否有效
  if (isNaN(date1.getTime()) || isNaN(date2.getTime())) {
    throw new Error("无效的时间格式");
  }

  // 比较时间戳
  if (date1 >= date2) {
    return true;
  } else {
    return false;
  }
};



// 将科学计数法，转换为普通数字字符串
const toPlainNumber = (num) => {
  if (typeof num !== 'number' && typeof num !== 'string') return num;

  const str = String(num);
  // 如果不是科学计数法格式，直接返回
  if (!/e/i.test(str)) return str;

  const [mantissa, exponent] = str.toLowerCase().split('e');
  const precision = Math.max(0, -parseInt(exponent) + (mantissa.includes('.') ? mantissa.split('.')[1].length : 0));
  return Number(num).toFixed(precision);
};

const wsTimeInstanceFn = () => {
  if (wsTimeInstance.value) {
    (wsTimeInstance.value).onmessage = (event) => {
      const data = JSON.parse(event.data);
      // console.log('data', data)
      startDateTime.value = data.startTime;
      endDateTime.value = data.endTime;
      const currentEndTimeMs = selectedEndTime.value
        ? selectedEndTime.value.getTime()
        : null;
      nextTick(() => {
        // 只刷新刻度，不调 updateTimeline（它会重置滑块）
        generateTimelineDates();

        // 把滑块按比例映射到新时间范围
        if (currentEndTimeMs) {
          const newStartMs = new Date(data.startTime).getTime();
          const newEndMs = new Date(data.endTime).getTime();
          const newTotalMs = newEndMs - newStartMs;

          if (newTotalMs > 0) {
            // 当前时间在新范围中的百分比位置
            const newPercent = ((currentEndTimeMs - newStartMs) / newTotalMs) * 100;
            // 限制在 0~100
            endHandlePercent.value = Math.max(0, Math.min(100, newPercent));
          }
        }

        // 同步选中时间
        updateSelectedTimes();
      });
    }
  }
}


const preTimeWindowEnd = ref(null);
const preTimeAllDate = ref(null);
// watch(() => selectedEndTime.value, val => {
//   if (compareTime(formatDateTime(val),preTimeWindowEnd.value)) { 
//         stopAutoPlay();
//       }
// }, { deep: true, immediate: true });
const onMessageIndex = ref(0);
const hasPlayed = ref(false);//只是个标志
const unlesscount = ref(0);
const subSysToMainSysFirstDataBack = ref(true);
const wssMessageHandle = () => {
  // let WwflagToNext = 0
  (wssInstance.value).onmessage = (event) => {
    const data = JSON.parse(event.data);
    console.log('data', data)
    if (data.type === "realtime") {
      playForward();
      useAppStoreInstance.setGlobalLeftWssCONTINE(data);
    }
    // 只有history和实时模式数据，回复已收到数据的确认。要修改以下代码
    if ((data.type === 'history' && !(data?.isLagrangeInterpolation === true))) {
      wssOpenHandle({
        type: "confirm",
        taskCode: String(taskCode_everyChange.value) === "" ? useAppStoreInstance.globalRecordMainSysTaskCode || (useAppStoreInstance.globalSubsystemTaskCode) : String(taskCode_everyChange.value),
        clientType: "web"
      })
    }
    if (data.type === 'control' && (data.controlType === 'continue' && data?.messageTypeFalg === 'true')) {

      jumpToSpecificTime(new Date(subtractSecondsAndFormat(alignTo56Seconds(tempDateTime.value).toISOString(), data.remainingTimeMs + 1)), false)
      if (!hasPlayed.value) {
        //console.log("我是playForward--3");
        playForward();
        hasPlayed.value = true;
      }
    }
    // //console.log('setTimeout:', (1000*60)/playbackSpeed.value,playbackSpeed.value);
    if ((data.type === 'history' && (data?.isLagrangeInterpolation === true)) && (data.controlType === 'SMOOTH')) {
      //console.log("我是playForward--1");
      if (data.nextTimestamp) {
        preTimeWindowEnd.value = data.nextTimestamp;
      }
      jumpToNextTime.value = data.remainingTimeMs || 0;
      hasDraged_first_falseToTrue.value = true;

      isChange_flag_firstBackDate.value = true;
      playForward();
      hasPlayed.value = true;

      useAppStoreInstance.setGlobalLeftWssCONTINE(data);
      // console.log("useAppStoreInstance.globalLeftWssCONTINE;执行了");

    }
    // 使用 Promise 包装 setTimeout
    // await new Promise(resolve => {
    //   setTimeout(() => {
    //     loading.close()
    //     resolve()
    //   }, 2000)
    // })
    //console.log('我是timer获取的wssRespone:', data);
    //console.log("我走了seekConfirm",!(data?.isLagrangeInterpolation  === true));
    let flagToNext = 0
    Loading.hide()
    if (data.type === 'control' && !(data.controlType === 'stop') && !(data.controlType === 'continue')) {
      if (data.nextTimestamp) {
        preTimeWindowEnd.value = data.nextTimestamp || data.dataTime;
      }
      // if (!hasPlayed.value) {
      //   //console.log("我是playForward--2");
      //     playForward();
      //     hasPlayed.value = true;
      //   }
      // jumpToNextTime.value = data.remainingTimeMs || 0;
      hasDraged_first_falseToTrue.value = true;

      jumpToSpecificTime(new Date(subtractSecondsAndFormat(alignTo56Seconds(selectedEndTime.value).toISOString(), data.remainingTimeMs + 1)));
      //console.log("我走了ElMessage",hasDraged_first_falseToTrue.value  , !(data?.isLagrangeInterpolation  === true) , (data.controlType === 'seekConfirm'));
      // ElMessage.warning("dsadasd",jumpToNextTime.value)
      if (hasDraged_first_falseToTrue.value && !(data?.isLagrangeInterpolation === true) && (data.controlType === 'seekConfirm')) {
        // ElMessage({
        //   type: 'success',
        //   message: `${jumpToNextTime.value/1000}秒后可进行下次时间轴拖动！！！`,
        // })
      }
      isChange_flag_firstBackDate.value = true;
    }
    if (data.type === 'error') {
      wssResponeFlag_isSuccess.value = false;
      // eleplate plus 关闭loading
      // (loading.value).close()

      ElMessage({
        type: 'error',
        message: data.message ? `主系统:${data.message} ` : `已暂停，没有查询到该时间段的历史数据！！！`,
      })
      // //console.log("获取的wssResponeFlag_isSuccess信息1:", wssResponeFlag_isSuccess.value);
      useAppStoreInstance.setglobalStartWss(false)
      //console.log("我走了这里4")
      stopAutoPlay();
      // isChange_flag_firstBackDate.value = false;
      hasPlayed.value = false;
      // 处理任务数据
    }
    if (data.type === 'history' && !(data?.isLagrangeInterpolation === true)) {
      // if (useAppStoreInstance.footerTimeHasedSelectTimeToSub && !subSysToMainSysFirstDataBack.value) {
      //   jumpToSpecificTime(new Date(tempDateTime.value),false)
      //   // jumpToSpecificTime(new Date(subtractSecondsAndFormat(alignTo56Seconds(tempDateTime.value).toISOString(),0)),true)
      //   subSysToMainSysFirstDataBack.value = true;
      // }
      useAppStoreInstance.setGlobalLeftWssCONTINE(data);
      // 处理日志数据
      // //console.log("endDateTime.value === selectedEndTime.value:", endDateTime.value , selectedEndTime.value.toISOString(),endDateTime.value === selectedEndTime.value);
      useAppStoreInstance.setglobalStartWss(true)
      speedChangedNormalDataBack.value = false;
      if (data.nextTimestamp || data.timeWindowEnd) {
        preTimeWindowEnd.value = data.nextTimestamp || data.timeWindowEnd;
      }
      hasDraged_first_falseToTrue.value = false;

      if (!(is_flag_confirmAndPauseAndSpeed.value) && !(is_flag_isRealtime.value)) {
        //console.log("我走了is_flag_confirmAndPauseAndSpeed",!(is_flag_confirmAndPauseAndSpeed.value) && !(is_flag_isRealtime.value));

        is_flag_confirmAndPauseAndSpeed.value = true;
      }


      // 跳转到上次时间点
      //        if (useAppStoreInstance.footerTimeHasedSelectTimeToSub) {
      //          jumpToSpecificTime(new Date(useAppStoreInstance.globalTimeLineEndSelectTime),true) 
      //        }
      preTimeAllDate.value = data;
      // clearTimeout(WwflagToNext);
      if (flagToNext !== 0) {
        clearTimeout(flagToNext);
      }
      isChange_flag_firstBackDate.value = true;

      onMessageIndex.value += 1

      if (endDateTime.value === selectedEndTime.value.toISOString()) {
        //console.log("我走了这里1",endDateTime.value === selectedEndTime.value.toISOString(),endDateTime.value,selectedEndTime.value.toISOString());

        stopAutoPlay();
      } else {
        if (!hasPlayed.value) {
          //console.log("我是playForward--3");
          playForward();
          hasPlayed.value = true;
        }
        // startAutoPlay()
      }

      // startAutoPlay(); 
      // toggleAutoPlay();
      //console.log("这里是startAutoPlay()");

      // if(loading.value){
      // (loading.value).close()

      // }else{


      // }
      wssResponeFlag_isSuccess.value = true;
      // message.success("同步时间轴数据状态成功！！！");
      // //console.log('我是history的数据:', data);
      // //console.log("compareTime*******",compareTime( formatDateTime(selectedEndTime.value),data.timeWindowEnd));
      // preTimeWindowEnd.value = new Date(formatDateTime(selectedStartTime.value))
      // if (data.timeWindowEnd ) {

      // }
      // if (compareTime( formatDateTime(selectedEndTime.value),preTimeWindowEnd.value)) { 
      //   stopAutoPlay();
      // }
    }
    if (data.type === 'EndProcess') {
      useAppStoreInstance.setglobalStartWss(false)
      // useAppStoreInstance.setglobalStartWss(false)
      // isChange_flag_firstBackDate.value = false;
      ElMessage({
        type: 'error',
        message: data.message || `已暂停，没有查询到该时间段的历史数据！！！`,
      })
      stopAutoPlay();
      // //console.log('我是left,type == time获取的wssRespone:', JSONdata, typeof JSONdata.time);
      // //console.log('我是left,type == time获取的wssRespone:', JSONdata.time, typeof JSONdata.time);
      // //console.log('我是left,type == time获取的wssRespone:', JSONdata.time.toLocaleString(), typeof JSONdata.time.toLocaleString());
    }

    unlesscount.value += 1
    // 处理服务器返回的数据,减去1000毫秒延迟，防止setTimeout和返回数据重叠在一个时间点上
    // flagToNext =  setTimeout(() => {
    //   stopAutoPlay();
    //   hasPlayed.value = false;
    // }, ((1000*60)/playbackSpeed.value)-1000);
  };

}






// 日期时间状态 (精确到秒)
const now = dayjs().format('YYYY-MM-DD HH:mm:ss')
const tomorrow = dayjs().add(1, 'day').format('YYYY-MM-DD HH:mm:ss')
// console.log('now', now, tomorrow)
// const startDateTime = ref(now);
// const endDateTime = ref(tomorrow);
const startDateTime = ref("2025-11-08 23:59:56");
const endDateTime = ref("2025-11-09 23:59:56");
// console.log('startDateTime', startDateTime.value)
const dateRange = ref([]);

// 滑块位置（百分比）
const startHandlePercent = ref(0);
const endHandlePercent = ref(0);

// 拖动状态
const isDragging = ref(false);
const currentDragHandle = ref(null);

// 滑块DOM引用
const sliderTrack = ref(null);

// 选中的时间
const selectedStartTime = ref(new Date(startDateTime.value));
const selectedEndTime = ref(new Date(startDateTime.value));

// 自动播放相关状态
const isPlaying = ref(false);
const playbackSpeed = ref(1); // 播放速度倍数
const playbackDirection = ref(1); // 1表示向前播放，-1表示向后播放
const playbackInterval = ref(null);

// 新增：标识是否是带时间范围的确认操作
const isConfirmedWithRange = ref(false);

// 时间轴总毫秒数
const totalMilliseconds = computed(() => {
  return new Date(endDateTime.value).getTime() - new Date(startDateTime.value).getTime();
});


const showLengthmarkerLine = computed(() => {
  return Math.round(timeMarkers.value.length / 8);
})
const showLength = computed(() => {
  return Math.round(timeMarkers.value.length / 8);
})


// 定义实时
const is_flag_isRealtime = ref(true);

// 禁用今天之后的日期
const disabledDate = (time) => {
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  return time.getTime() > today.getTime();
};


const pick_select_date = ref();
const pick_select_date_handFn = (val) => {
  if (!isDraged.value) {
    // window.ue5("callBackTimeFn", String(JSON.stringify({
    //   taskCode:String(taskCode_everyChange.value) === "" ? useAppStoreInstance.globalRecordMainSysTaskCode || (useAppStoreInstance.globalSubsystemTaskCode) : String(taskCode_everyChange.value),
    // })));
  }
  pick_select_date.value = val;
  //console.log("dddddd",val);
  isChange_flag_select_date.value = true;
}

const isChange_flag_select_date = ref(false);
const taskCode_everyChange = ref('');

// 点击确认后，处理日期范围变化
const handleDateRangeChange = async (val, flag = false) => {
  //console.log("0000000.02222",val,typeof val,flag);
  // if(typeof val !== 'object') { 
  //     ElMessage({
  //       message: '请选择正确的日期范围',
  //       type: 'warning',
  //     })
  //     dateRange.value = [];
  //   return;
  // }
  jiangerTime.value = 0;
  isChange_flag_firstBackDate.value = false;
  hasPlayed.value = false;
  if (!flag) {
    taskCode_everyChange.value = String(Date.now());
    useAppStoreInstance.setglobalSubsystemTaskCode(taskCode_everyChange.value);
    useAppStoreInstance.setGlobalRecordMainSysTaskCode(taskCode_everyChange.value)
    useAppStoreInstance.setFooterTimeHasedSelectTimeToSub(true);
  }
  if (val && val.length > 0) {
    if (isChange_flag_select_date.value || useAppStoreInstance.globalisFromTosub) {
      wssResponeFlag_isSuccess.value = true;
      isPlaying.value = false;
      //  element plus组件显示加载中
      // loading.value = ElLoading.service({
      // lock: true,
      // text: 'Loading',
      // background: 'rgba(0, 0, 0, 0.7)',
      // })
      if (!flag) {
        Loading.show()
        //console.log("cao cao1,Loading.show()");

      }
      // debugger
      // Loading.show()
      if (val && val.length === 2) {
        //console.log("cao cao11",val);

        startDateTime.value = new Date((new Date(val[0])).setSeconds(56)).toISOString();
        // preTimeWindowEnd.value  = new Date((new Date(val[0])).setSeconds(56+60)).toISOString();
        endDateTime.value = new Date((new Date(val[1]))).toISOString();
        // //console.log("//////////////////",val[0],"4444444444--",pick_select_date.value[0]);
        // preTimeWindowEnd.value = new Date((new Date(new Date(selectedStartTime.value))).setSeconds(56+60)).toISOString();

        useAppStoreInstance.setglobalSubsystemSelectedStartTime(val);
        // useAppStoreInstance.setglobalSubsystemSelectedEndTime(formatDateTime(val[1]));


        isDraged.value = false;
        is_flag_isRealtime.value = false;
        isDateRangeNotEmpty.value = false;
        isConfirmedWithRange.value = true; // 标记为带范围确认
        clearInterval(autoUpdateDateRange.value);
        updateTimeline();

        // 重置滑块位置到开始位置
        startHandlePercent.value = 0;
        endHandlePercent.value = 0;

        // 强制更新视图
        nextTick(() => {
          updateSelectedTimes();
        });
      }

      playbackSpeed.value = 1;
      if (!flag) {
        wssOpenHandle({
          isRealtime: is_flag_isRealtime.value ? true : false,
          startTime: formatDateTime(val[0]),
          endTime: formatDateTime(val[1]),
          taskCode: String(taskCode_everyChange.value) === "" ? useAppStoreInstance.globalRecordMainSysTaskCode || (useAppStoreInstance.globalSubsystemTaskCode) : String(taskCode_everyChange.value),
        })
      }
      if (window.ue5) {

        window.ue5("callBackTimeFn", String(JSON.stringify({
          isRealtime: is_flag_isRealtime.value ? true : false,
          startTime: (formatDateTime(val[0])),
          speed: playbackSpeed.value,
          endTime: (formatDateTime(val[1])),
          taskCode: String(taskCode_everyChange.value) === "" ? useAppStoreInstance.globalRecordMainSysTaskCode || (useAppStoreInstance.globalSubsystemTaskCode) : String(taskCode_everyChange.value),

          currentTime: (formatDateTime(selectedEndTime.value)),
          status: isPlaying.value ? "stop" : "continue",
          //时间参数


        })))

      }
      wssMessageHandle()
    } else {

      ElMessage({
        type: 'warning',
        message: `当前时间段未发生变化，请重新选时间段`,
      })
      // dateRange.value = [];
    }
    isChange_flag_select_date.value = false;
    // dateRange.value = [];
  } else {

    ElMessage({
      type: 'warning',
      message: `时间范围为空，自动执行最近24小时`,
    })
    useAppStoreInstance.setGlobalisFromTosub(false);
    useAppStoreInstance.setFooterTimeHasedSelectTimeToSub(false);
    isDateRangeNotEmpty.value = true;
    isConfirmedWithRange.value = false; // 重置标记
    is_flag_isRealtime.value = true;
    isChange_flag_select_date.value = false;//表示已经选过时间段了
    playbackSpeed.value = 1;
    stopAutoPlay();
    // 切换实时模式的时候，之前的播放任务停止
    // wssOpenHandle({
    //   isRealtime: is_flag_isRealtime.value? true: false,
    //   // status: "stop",
    //   // taskCode: String(taskCode_everyChange.value) === "" ? useAppStoreInstance.globalRecordMainSysTaskCode || (useAppStoreInstance.globalSubsystemTaskCode) : String(taskCode_everyChange.value),
    // })
    // 标志实时模式
    // if(window.ue5) {
    //   window.ue5("callBackTimeFn", String(JSON.stringify({
    //     isRealtime:  is_flag_isRealtime.value? true: false,
    //     // startTime: formatDateTime(pick_select_date.value[0]),
    //     // endTime: formatDateTime(pick_select_date.value[1]),
    //     // taskCode: String(taskCode_everyChange.value) === "" ? useAppStoreInstance.globalRecordMainSysTaskCode || (useAppStoreInstance.globalSubsystemTaskCode) : String(taskCode_everyChange.value),
    //   })))
    //   wssOpenHandle({
    //     isRealtime:  is_flag_isRealtime.value? true: false,
    //   })
    // }

    // 强制更新视图
    nextTick(() => {
      updateTimeline();
    });
  }
};

watch(() => wssResponeFlag_isSuccess.value, (newVal) => {
  //console.log("我是这里再监测数值变化，",newVal);

  if (newVal) {

    startAutoPlay();
    // toggleAutoPlay();

  }
  else {
    //console.log("我是watch(())stopAutoPlay()");
    //console.log("我走了这里6")
    stopAutoPlay();
    // (wssInstance.value).close()
  }
})

const isDateRangeNotEmpty = ref(false);
const autoUpdateDateRange = ref(null);
autoUpdateDateRange.value = setInterval(() => {
  // autoHandleDateRangeChange([new Date(new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString()), new Date(new Date(Date.now()).toISOString())]);
  autoHandleDateRangeChange([startDateTime.value, endDateTime.value]);
}, 1000);

watch(() => isDateRangeNotEmpty.value, (newVal) => {
  console.log("发生变化", newVal);
  if (newVal) {
    autoUpdateDateRange.value = setInterval(() => {
      //  //console.log("开启循环",autoUpdateDateRange.value);
      autoHandleDateRangeChange([new Date(new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString()), new Date(new Date(Date.now()).toISOString())]);
    }, 1000);
  } else {
    // //console.log("关闭循环",autoUpdateDateRange.value);
    clearInterval(autoUpdateDateRange.value);
  }
});

const autoHandleDateRangeChange = (val) => {
  if (val && val.length === 2) {
    // console.log("自动更新日期范围", val);
    if (val[0] instanceof Date && val[1] instanceof Date) {
      startDateTime.value = val[0]?.toISOString();
      endDateTime.value = val[1]?.toISOString();
      // console.log("自动更新日期范围格式正确", val);
    } else {
      // console.log("自动更新日期范围格式错误", val);
      return;
    }
    isDraged.value = false;
    updateTimeline();
  }
}

// 生成时间轴日期 - 只显示图片中的格式: MM-DD
const timelineDates = ref([]);
const generateTimelineDates = () => {
  const start = new Date(startDateTime.value);
  const end = new Date(endDateTime.value);
  const dates = [];

  // 重置到当天0点
  const current = new Date(start);
  current.setHours(0, 0, 0, 0);

  while (current <= end) {
    dates.push(new Date(current));
    current.setDate(current.getDate() + 60);
  }

  timelineDates.value = dates;
  updateSelectedTimes();
};

const timeMarkers = computed(() => {
  const markers = [];
  const start = new Date(startDateTime.value);
  const end = new Date(endDateTime.value);
  const totalMs = totalMilliseconds.value;

  if (totalMs <= 0) return []; // 防止除零错误

  // 第一个刻度：直接使用 start 时间（保留原始分钟/秒）
  const firstMarkerTime = new Date(start);
  const firstPosition = 0; // 因为就是起点
  markers.push({
    time: firstMarkerTime,
    label: dayjs(firstMarkerTime).format('YYYY-MM-DD HH:mm'),
    position: firstPosition,
    isMajor: true, // 起始点视为主刻度
    showLabel: true
  });

  // 后续刻度：从 start 的下一个**整点**开始，每 60 分钟加一个
  // const nextHour = new Date(start);
  // nextHour.setMinutes(0, 0, 0); // 先对齐到当前小时整点
  // nextHour.setHours(nextHour.getHours() + 1); // 跳到下一个整点（避免重复）

  let current = dayjs(start).toDate();
  // console.log(dayjs(current).format('YYYY-MM-DD HH:mm'))
  console.log('end', dayjs(end).format('YYYY-MM-DD HH:mm'))
  while (current < end) {
    const position = ((current.getTime() - start.getTime()) / totalMs) * 100;
    markers.push({
      time: new Date(current),
      label: dayjs(current).format('YYYY-MM-DD HH:mm'),
      position,
      isMajor: true, // 每小时都是主刻度
      showLabel: true
    });
    current.setHours(current.getHours() + 1); // 每次 +1 小时
  }

  // console.log('markers',markers)

  return markers;
});

const isMarkerInSelectedRange = (marker) => {
  // //console.log("-----------------------,",marker);

  const markerTime = marker.time.getTime();
  const startTime = selectedStartTime.value.getTime();
  const endTime = selectedEndTime.value.getTime();

  return markerTime >= startTime && markerTime <= endTime;
};

// 日期格式化函数 - 修改为只显示 MM-DD
const formatDate = (date) => {
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${month}-${day}`;
};

// 时间格式化函数
const formatTime = (date) => {
  if (!date) return '';
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${hours}:${minutes}:${seconds}`;
};

// 日期时间格式化函数
const formatDateTime = (date) => {
  if (!date) return '未选择';
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 修改后的选中区域样式计算属性
const selectedRangeStyle = computed(() => {
  // 如果是带范围确认且未在播放状态，则选中区域宽度为0
  if (isConfirmedWithRange.value && !isPlaying.value) {
    return {
      left: startHandlePosition.value,
      width: '0%'
    };
  }
  // 自动播放状态或手动拖动状态
  else {
    const left = Math.min(startHandlePercent.value, endHandlePercent.value);
    const right = Math.max(startHandlePercent.value, endHandlePercent.value);
    return {
      left: `${left}%`,
      width: `${right - left}%`
    };
  }
});

// 滑块位置计算
const startHandlePosition = computed(() => `${startHandlePercent.value}%`);


const endHandlePosition = computed(() => {

  if (isConfirmedWithRange.value && !isPlaying.value) {
    return `${startHandlePercent.value}%`;
  }

  return `${endHandlePercent.value}%`;
});


const updateSelectedTimes = () => {
  if (!startDateTime.value || !endDateTime.value) return;

  const start = new Date(startDateTime.value).getTime();
  const totalMs = totalMilliseconds.value;


  const startTime = new Date(start + (totalMs * startHandlePercent.value / 100));
  const endTime = new Date(start + (totalMs * endHandlePercent.value / 100));


  selectedStartTime.value = startTime;
  selectedEndTime.value = endTime;
  if (!is_flag_isRealtime.value) {
    useAppStoreInstance.setGlobalTimeLineEndSelectTime(formatDateTime(selectedEndTime.value));
  }

  // //console.log("************",useAppStoreInstance.globalTimeLineEndSelectTime);

};

const isDraged = ref(false);
// false: 播放方向为向前播放，true: 播放方向为向后播放
const curplaybackDirection = ref(false);

// 切换自动播放状态
const toggleAutoPlay = () => {
  if (is_flag_isRealtime.value) {
    // ElMessage({
    //   type: 'warning',
    //   message: '当前为实时播放模式,不可执行播放操作！',
    // })
    isPlaying.value = !isPlaying.value
    console.log('isPlaying', isPlaying.value)
    if (isPlaying.value) {
      // stopAutoPlay();
      if (window.ue5) {
        startAutoPlay()

        taskCode_everyChange.value = String(Date.now());
        useAppStoreInstance.setglobalSubsystemTaskCode(taskCode_everyChange.value);
        useAppStoreInstance.setGlobalRecordMainSysTaskCode(taskCode_everyChange.value)
        useAppStoreInstance.setFooterTimeHasedSelectTimeToSub(true);

        console.log('is_flag_isRealtime', is_flag_isRealtime.value)
        console.log('taskCode', taskCode_everyChange.value)
        // console.log('startTime',selectedStartTime.value)
        // console.log('endTime',selectedEndTime.value)
        console.log('startTime', formatDateTime(new Date(startDateTime.value)))
        console.log('endTime', formatDateTime(new Date(endDateTime.value)))
        console.log('currentTime', (formatDateTime(selectedEndTime.value)))


        // return

        wssOpenHandle({
          isRealtime: is_flag_isRealtime.value ? true : false,
          startTime: formatDateTime(new Date(startDateTime.value)),
          endTime: formatDateTime(new Date(endDateTime.value)),
          taskCode: String(taskCode_everyChange.value) === "" ? useAppStoreInstance.globalRecordMainSysTaskCode || (useAppStoreInstance.globalSubsystemTaskCode) : String(taskCode_everyChange.value),
        })

        window.ue5("callBackTimeFn", String(JSON.stringify({
          isRealtime: is_flag_isRealtime.value ? true : false,
          startTime: formatDateTime(new Date(startDateTime.value)),
          endTime: formatDateTime(new Date(endDateTime.value)),
          speed: playbackSpeed.value,
          taskCode: String(taskCode_everyChange.value) === "" ? useAppStoreInstance.globalRecordMainSysTaskCode || (useAppStoreInstance.globalSubsystemTaskCode) : String(taskCode_everyChange.value),

          currentTime: (formatDateTime(selectedEndTime.value)),
          status: isPlaying.value ? "stop" : "continue",
          //时间参数


        })))


      }


    }

  } else {
    is_flag_playBackwarding.value = true;

    if (isPlaying.value) {

      //console.log("我是切换自动播放状态stopAutoPlay()",isPlaying.value);
      //console.log("我走了这里7")
      stopAutoPlay();
      if (window.ue5) {

        window.ue5("callBackSpeedFn", String(JSON.stringify({
          isRealtime: is_flag_isRealtime.value ? true : false,
          status: "stop",
          speed: playbackSpeed.value,
          taskCode: String(taskCode_everyChange.value) === "" ? useAppStoreInstance.globalRecordMainSysTaskCode || (useAppStoreInstance.globalSubsystemTaskCode) : String(taskCode_everyChange.value),
        })));

        wssOpenHandle({
          isRealtime: is_flag_isRealtime.value ? true : false,
          status: "stop",
          taskCode: String(taskCode_everyChange.value) === "" ? useAppStoreInstance.globalRecordMainSysTaskCode || (useAppStoreInstance.globalSubsystemTaskCode) : String(taskCode_everyChange.value),
        })
      }
    } else {

      isConfirmedWithRange.value = false; // 开始播放时重置标记
      jiangerTime.value = 0;
      playForward();

      jumpToSpecificTime(new Date(addOneSecond(formatDateTime(selectedEndTime.value), 1)));
      if (window.ue5) {
        window.ue5("callBackSpeedFn", String(JSON.stringify({
          isRealtime: is_flag_isRealtime.value ? true : false,
          status: 'continue',
          speed: playbackSpeed.value,
          taskCode: String(taskCode_everyChange.value) === "" ? useAppStoreInstance.globalRecordMainSysTaskCode || (useAppStoreInstance.globalSubsystemTaskCode) : String(taskCode_everyChange.value),
        })));
        wssOpenHandle({
          isRealtime: is_flag_isRealtime.value ? true : false,
          status: 'continue',
          taskCode: String(taskCode_everyChange.value) === "" ? useAppStoreInstance.globalRecordMainSysTaskCode || (useAppStoreInstance.globalSubsystemTaskCode) : String(taskCode_everyChange.value),
        })
      }
      // 强制更新视图
      nextTick(() => {
        updateSelectedTimes();
      });
    }

  }

};

const is_flag_playForwarding = ref(true);
const is_flag_playBackwarding = ref(true);


// 开始向前播放
const playForward = async () => {
  is_flag_playBackwarding.value = true;
  // if (flag_SetTimeOutCycle.value === null) {
  //   handleSetTimeOutCycle();
  // }
  if (1) {

    //console.log("再次我是开始向前播放stopAutoPlay()",isPlaying.value);
    // stopAutoPlay(); // 先停止当前播放
    isPlaying.value = true;
    isConfirmedWithRange.value = false; // 重置标记
    curplaybackDirection.value = false;
    playbackDirection.value = 1;
    startAutoPlay();

    // 强制更新视图
    nextTick(() => {
      updateSelectedTimes();
    });
  } else {
    ElMessage({
      type: 'warning',
      message: '正在前向播放！',
    })
  }

  is_flag_playForwarding.value = false;
};

// 开始向后播放
// const playBackward = async () => {
//   is_flag_playForwarding.value = true;
//   if (is_flag_playBackwarding.value) {
//     const loading = ElLoading.service({
//       lock: true,
//       text: 'Loading',
//       background: 'rgba(0, 0, 0, 0.7)',
//     })

//     // 使用 Promise 包装 setTimeout
//     await new Promise(resolve => {
//       setTimeout(() => {
//         loading.close()
//         resolve()
//       }, 2000)
//     })

//     stopAutoPlay(); // 先停止当前播放
//     isPlaying.value = true;
//     isConfirmedWithRange.value = false; // 重置标记
//     curplaybackDirection.value = true; 
//     playbackDirection.value = -1;
//     startAutoPlay();

//     // 强制更新视图
//     nextTick(() => {
//       updateSelectedTimes();
//     });
//   } else {
//     message.warning('正在后向播放！');
//   }
//   is_flag_playBackwarding.value = false;
// };

// 开始自动播放  第一版
// const startAutoPlay = () => {
//   // 清除之前的定时器
//   if (playbackInterval.value) {
//     clearInterval(playbackInterval.value);
//   }

//   // 设置新的定时器，每秒更新一次
//   playbackInterval.value = setInterval(() => {
//     moveEndHandle();
//   }, 1000 ); // 根据播放速度调整间隔
// };
// 第二版
const startAutoPlay = () => {
  if (playbackInterval.value) {
    clearInterval(playbackInterval.value);
  }

  let expectedTime = Date.now() + (1000 / playbackSpeed.value);

  const update = () => {
    const drift = Date.now() - expectedTime;
    moveEndHandle();
    expectedTime += (1000 / playbackSpeed.value);
    playbackInterval.value = setTimeout(update, Math.max(0, (1000 / playbackSpeed.value) - drift));
  };

  playbackInterval.value = setTimeout(update, 1000 / playbackSpeed.value);
};

// 停止自动播放
const stopAutoPlay = () => {
  isPlaying.value = false;
  //console.log("停止自动播放", playbackInterval.value);
  if (playbackInterval.value) {
    clearInterval(playbackInterval.value);
    playbackInterval.value = null;
  }

  if (flag_SetTimeOutCycle.value !== null) {
    clearInterval(flag_SetTimeOutCycle.value);
    flag_SetTimeOutCycle.value = null;
  }

  // 强制更新视图
  nextTick(() => {
    updateSelectedTimes();
  });
};

// 移动结束滑块 - 以秒为单位移动
const moveEndHandle = () => {
  if (!isPlaying.value) return;
  // //console.log("开始进行移动滑块");

  // 计算每秒对应的百分比增量
  const totalMs = totalMilliseconds.value;
  const msPerSecond = 1000; // 1秒 = 1000毫秒
  const percentPerSecond = (msPerSecond / totalMs) * 100;

  // 根据播放方向和速度调整结束滑块位置
  const increment = percentPerSecond * playbackDirection.value;
  // 这里可以尝试
  endHandlePercent.value += increment;
  // //console.log("endHandlePercent.value",endHandlePercent.value);

  // 边界检查
  if (endHandlePercent.value >= 100) {
    // 向前播放到达终点，停止播放
    endHandlePercent.value = 100;
    useAppStoreInstance.setglobalStartWss(false)
    //console.log("我是移动结束滑块stopAutoPlay()",isPlaying.value);
    //console.log("我走了这里8")
    stopAutoPlay();
  }
  //  else if (endHandlePercent.value <= 0 && playbackDirection.value < 0) {
  //   // 向后播放到达起点，停止播放
  //   endHandlePercent.value = 0;
  //   stopAutoPlay();
  // }

  // 确保值在有效范围内
  endHandlePercent.value = Math.max(0, Math.min(100, endHandlePercent.value));

  // 更新选中时间
  updateSelectedTimes();
};

// 切换播放速度
const changeSpeed = () => {
  //console.log("我是changeSpeed",playbackSpeed.value);
  speedChangedNormalDataBack.value = true;
  // const speeds = [1, 2, 4, 8, 10];
  // const currentIndex = speeds.indexOf(playbackSpeed.value);
  // const nextIndex = (currentIndex + 1) % speeds.length;
  hasPlayed.value = false;
  // playbackSpeed.value = speeds[nextIndex];
  jiangerTime.value = 0;
  if (window.ue5) {
    window.ue5("callBackSpeedFn", String(JSON.stringify({
      // isRealtime: is_flag_isRealtime.value? true: false,
      // isFastForward: playbackSpeed.value === 1 || playbackSpeed.value === '1'?false:true, 
      speed: playbackSpeed.value,
      // taskCode: String(taskCode_everyChange.value) === "" ? useAppStoreInstance.globalRecordMainSysTaskCode || (useAppStoreInstance.globalSubsystemTaskCode) : String(taskCode_everyChange.value),
    })))
    wssOpenHandle({
      isRealtime: is_flag_isRealtime.value ? true : false,
      isFastForward: playbackSpeed.value === 1 || playbackSpeed.value === '1' ? false : true,
      step: playbackSpeed.value,
      taskCode: String(taskCode_everyChange.value) === "" ? useAppStoreInstance.globalRecordMainSysTaskCode || (useAppStoreInstance.globalSubsystemTaskCode) : String(taskCode_everyChange.value),
    })
  }

  // 如果正在播放，重新开始自动播放以应用新的速度
  if (isPlaying.value) {
    startAutoPlay();
  }
};


const startDrag = (handle, e) => {
  //console.log("开始拖动");
  // if (is_flag_isRealtime.value) {
  //   ElMessage({
  //     type: 'warning',
  //     message: '实时模式下无法进行拖拽',
  //   })
  //   return
  // }
  // is_flag_isRealtime.value = false;
  isDateRangeNotEmpty.value = false;
  clearInterval(autoUpdateDateRange.value);
  isDraged.value = true;
  isDragging.value = true;
  currentDragHandle.value = handle;
  e.preventDefault();
  endDrag_opeartioning.value = false
  console.log("拖动开始", selectedEndTime.value);

  // 手动拖动时停止自动播放
  // if (isPlaying.value) {
  //   //console.log("我是拖动开始stopAutoPlay()",isPlaying.value);
  //   //console.log("我走了这里9")
  //   stopAutoPlay();
  // }


  window.addEventListener('mousemove', handleDrag);
  window.addEventListener('mouseup', endDrag);
  // if(!hasDraged_first_falseToTrue.value) {
  //   // 添加全局事件监听器
  // window.addEventListener('mousemove', handleDrag);
  // window.addEventListener('mouseup', endDrag);
  // }else{
  //   ElMessage.warning("已拖动过，请等待执行下次拖动！");
  // }

};


const handleDrag = (e) => {
  if (!isDragging.value || !currentDragHandle.value || !sliderTrack.value) return;

  // 手动拖动时停止自动播放
  // if (isPlaying.value) {
  //   //console.log("我是处理拖动stopAutoPlay()",isPlaying.value);
  //   //console.log("我走了这里10")
  //   stopAutoPlay();
  // }

  const rect = sliderTrack.value.getBoundingClientRect();
  let percentage = ((e.clientX - rect.left) / rect.width) * 100;

  // 限制在0-100%之间
  percentage = Math.max(0, Math.min(100, percentage));

  if (currentDragHandle.value === 'start') {
    startHandlePercent.value = percentage;
  } else {
    endHandlePercent.value = percentage;
  }

  // 更新选中时间
  updateSelectedTimes();
};


const alignTo56Seconds = (date) => {
  const d = new Date(date);
  const seconds = d.getSeconds();

  if (seconds <= 56) {
    d.setSeconds(56, 0); // 设置秒为56，毫秒为0
  } else {
    // 超过56秒，跳到下一分钟的56秒
    d.setMinutes(d.getMinutes() + 1);
    d.setSeconds(56, 0);
  }

  return d;
};


const addOneSecond = (timeStr, sec = 1) => {
  // 解析输入字符串为 Date 对象（注意：需指定时区为本地时间）
  const [datePart, timePart] = timeStr.split(' ');
  const [year, month, day] = datePart.split('-').map(Number);
  const [hour, minute, second] = timePart.split(':').map(Number);

  // 创建本地时间的 Date 对象（避免 UTC 解析偏差）
  const date = new Date(year, month - 1, day, hour, minute, second);

  // 加 1 秒（1000 毫秒）
  date.setTime(date.getTime() + sec * 1000);

  // 格式化回 YYYY-MM-DD HH:mm:ss
  const pad = (n) => String(n).padStart(2, '0');
  const newYear = date.getFullYear();
  const newMonth = pad(date.getMonth() + 1);
  const newDay = pad(date.getDate());
  const newHour = pad(date.getHours());
  const newMinute = pad(date.getMinutes());
  const newSecond = pad(date.getSeconds());

  return `${newYear}-${newMonth}-${newDay} ${newHour}:${newMinute}:${newSecond}`;
};


const subtractSecondsAndFormat = (isoString, secondsToSubtract) => {


  // 1. 解析 ISO 字符串（它代表 UTC 时间）
  const date = new Date(isoString); // 这个 Date 对象内部是 UTC，但 JS 会按本地时区显示

  // 2. 减去指定秒数
  const newTime = date.getTime() - (secondsToSubtract * 1000);
  // （毫秒）的话
  // const newTime = date.getTime() - (secondsToSubtract /1000);
  const newDate = new Date(newTime);

  // 3. 使用本地时间（中国标准时间）格式化，秒不补零
  const year = newDate.getFullYear(); // 本地年
  const month = String(newDate.getMonth() + 1).padStart(2, '0');
  const day = String(newDate.getDate()).padStart(2, '0');
  const hours = String(newDate.getHours()).padStart(2, '0'); // 本地小时
  const minutes = String(newDate.getMinutes()).padStart(2, '0');
  const seconds = newDate.getSeconds(); // 不补零！

  //console.log("我走了isoString",isoString,secondsToSubtract,`${year}-${month}-${day} ${hours}:${minutes}:${seconds}`);
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

const jumpToNextTime = ref(0);

const hasDraged_first_falseToTrue = ref(false);

const endDrag_opeartioning = ref(false)
const endDrag = () => {

  endDrag_opeartioning.value = true
  isDragging.value = false;
  currentDragHandle.value = null;
  hasPlayed.value = false;

  if (window.ue5) {
    console.log(window.ue5, "拖动结束", isDraged.value,is_flag_isRealtime.value,useAppStoreInstance.globalLeftWssCONTINE);
    if (isDraged.value) {
      if (is_flag_isRealtime.value || useAppStoreInstance.globalLeftWssCONTINE.type === "realtime") {
        //实时
        wssOpenHandle({
          isRealtime: true,
          replayTime: formatDateTime(selectedEndTime.value),
          // taskCode: String(taskCode_everyChange.value) === "" ? useAppStoreInstance.globalRecordMainSysTaskCode || (useAppStoreInstance.globalSubsystemTaskCode) : String(taskCode_everyChange.value),
          isFastForward: false,
        })
        window.ue5("callBackTimeFn", String(JSON.stringify({
          isRealtime: true,
          replayTime: (formatDateTime(selectedEndTime.value)),
          taskCode: String(taskCode_everyChange.value) === "" ? useAppStoreInstance.globalRecordMainSysTaskCode || (useAppStoreInstance.globalSubsystemTaskCode) : String(taskCode_everyChange.value),
          speed: playbackSpeed.value,
          status: isPlaying.value ? "continue" : "stop",
        })));
      } else {
        window.ue5("callBackTimeFn", String(JSON.stringify({
          isRealtime: false,
          replayTime: (formatDateTime(selectedEndTime.value)),
          taskCode: String(taskCode_everyChange.value) === "" ? useAppStoreInstance.globalRecordMainSysTaskCode || (useAppStoreInstance.globalSubsystemTaskCode) : String(taskCode_everyChange.value),
          speed: playbackSpeed.value,
          status: isPlaying.value ? "continue" : "stop",
        })));

        wssOpenHandle({
          isRealtime: false,
          replayTime: formatDateTime(selectedEndTime.value),
          taskCode: String(taskCode_everyChange.value) === "" ? useAppStoreInstance.globalRecordMainSysTaskCode || (useAppStoreInstance.globalSubsystemTaskCode) : String(taskCode_everyChange.value),
        })
      }



      // 发送时轴de 当前时间给ue
      window.ue5("callTimeLineCurrentTimeFn", String(JSON.stringify({
        year: selectedEndTime.value.getFullYear(),
        month: selectedEndTime.value.getMonth() + 1,
        day: selectedEndTime.value.getDate(),
        hour: selectedEndTime.value.getHours(),
        minute: selectedEndTime.value.getMinutes(),
        second: selectedEndTime.value.getSeconds(),
      })));

      // }
    } else {
      // window.ue5("callBackTimeFn", String(JSON.stringify({})));
    }
  }

  window.removeEventListener('mousemove', handleDrag);
  window.removeEventListener('mouseup', endDrag);
  updateSelectedTimes();
  is_flag_confirmAndPauseAndSpeed.value = false;
  stopAutoPlay();
};


const updateTimeline = () => {
  // 验证时间范围
  if (new Date(startDateTime.value) >= new Date(endDateTime.value)) {
    alert('结束时间必须大于开始时间');
    return;
  }

  generateTimelineDates();

  // 重置滑块位置
  startHandlePercent.value = 0;
  endHandlePercent.value = 0;
};

const convertTimeFormat = (input) => {
  // 使用正则匹配格式：YYYY.MM.DD-HH.mm.ss
  const match = input.match(/^(\d{4})\.(\d{2})\.(\d{2})-(\d{2})\.(\d{2})\.(\d{2})$/);
  if (!match) {
    console.warn('Invalid time format:', input);
    return null; // 抛出错误
  }
  const [, year, month, day, hour, minute, second] = match;
  return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
};

const trackCycleTimePoint = (timeStr) => {
  // 支持传入 Date 对象或字符串
  const date = timeStr instanceof Date ? timeStr : new Date(timeStr);

  if (isNaN(date.getTime())) {
    console.error('Invalid time string:', timeStr);
    return '';
  }
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  return `${year}.${month}.${day}-${hours}.${minutes}.${seconds}`;
};
const flag_SetTimeOutCycle = ref(null)

const formatDateTimeOne = (timeStr) => {
  // 支持传入 Date 对象或字符串
  const date = timeStr instanceof Date ? timeStr : new Date(timeStr);

  if (isNaN(date.getTime())) {
    console.error('Invalid time string:', timeStr);
    return '';
  }
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
const handleSetTimeOutCycle = () => {
  if (flag_SetTimeOutCycle.value === null) {
    flag_SetTimeOutCycle.value = setInterval(() => {
      // //console.log("我走了setInterval",(formatDateTimeOne(selectedEndTime.value)));

      if (window.ue5) {
        window.ue5("callBackCycleTimePointFn", String(JSON.stringify({
          // currentTime: trackCycleTimePoint(formatDateTime(selectedEndTime.value)), 
          currentTime: (formatDateTimeOne(selectedEndTime.value)),
        })));
      }
    }, 1000 * 2);
  }

}

// watch(() => is_flag_isRealtime.value, (newVal, oldVal) => {
//   if (newVal === false && isPlaying.value) {
//     handleSetTimeOutCycle();
//   }else {
//     // 👇 切换到实时模式，关闭循环
//     if (flag_SetTimeOutCycle.value !== null) {
//       clearInterval(flag_SetTimeOutCycle.value);
//       flag_SetTimeOutCycle.value = null;
//     }
//   }
// });
const tempDateTime = ref(new Date(useAppStoreInstance.globalTimeLineEndSelectTime))
onMounted(() => {
  timeInfoApi().then((res) => {
    if (res && res.data) {
      const { startTime, endTime } = res.data;
      startDateTime.value = startTime;
      endDateTime.value = endTime;
    }
  })
  wsTimeInstanceFn();
  tempDateTime.value = ""
  if (useAppStoreInstance.footerTimeHasedSelectTimeToSub) {
    console.log("初始化走上面");

    tempDateTime.value = useAppStoreInstance.globalTimeLineEndSelectTime

    subSysToMainSysFirstDataBack.value = false;

    dateRange.value = [new Date((new Date(useAppStoreInstance.globalSubsystemSelectedStartTime[0]))).toISOString(), new Date((new Date(useAppStoreInstance.globalSubsystemSelectedStartTime[1]))).toISOString()]
    pick_select_date.value = [new Date(dateRange.value[0]).toString(), new Date(dateRange.value[1]).toString()]

    {
      handleDateRangeChange(useAppStoreInstance.globalSubsystemSelectedStartTime, true);
      // Loading.show();
      wssOpenHandle({
        isRealtime: is_flag_isRealtime.value ? true : false,
        status: 'continue',
        messageTypeFalg: true,
        taskCode: useAppStoreInstance.globalRecordMainSysTaskCode || (useAppStoreInstance.globalSubsystemTaskCode),
      })
    }

  } else {
    updateTimeline();
    console.log("初始化走下面");
    if (window.ue5) {

      window.ue5("callBackTimeFn", String(JSON.stringify({
        // isRealtime:"false",
        // startTime:"2025-11-03 00:00:00",
        // endTime:"2025-11-04 00:00:00",
        // taskCode:"1111111111"
        isRealtime: is_flag_isRealtime.value,
        taskCode: String(taskCode_everyChange.value) === "" ? useAppStoreInstance.globalRecordMainSysTaskCode || (useAppStoreInstance.globalSubsystemTaskCode) : String(taskCode_everyChange.value),
        speed: playbackSpeed.value,
        status: isPlaying.value ? "continue" : "stop",
      })))
      // wssOpenHandle({
      //   isRealtime:  is_flag_isRealtime.value? true: false,
      // })
    }
  }
  useAppStoreInstance.setGlobalisFromTosub(false)

  console.log('isPlaying', isPlaying.value)
  if (!isPlaying.value) {
    if (window.ue5) {
      // startAutoPlay()
      // taskCode_everyChange.value = String(Date.now());
      // useAppStoreInstance.setglobalSubsystemTaskCode(taskCode_everyChange.value);
      // useAppStoreInstance.setGlobalRecordMainSysTaskCode(taskCode_everyChange.value)
      // useAppStoreInstance.setFooterTimeHasedSelectTimeToSub(true);
      isChange_flag_select_date.value = true
      // const startTime = formatDateTime(new Date(startDateTime.value))
      // const endTime = formatDateTime(new Date(endDateTime.value))
      // console.log('startTime',startTime)
      // console.log('endTime',endTime)
      realTimeData()

    }
  }

});
// 定义定时器引用

const realTimeData = () => {
  // startAutoPlay()
  taskCode_everyChange.value = String(Date.now());
  useAppStoreInstance.setglobalSubsystemTaskCode(taskCode_everyChange.value);
  useAppStoreInstance.setGlobalRecordMainSysTaskCode(taskCode_everyChange.value)
  useAppStoreInstance.setFooterTimeHasedSelectTimeToSub(true);
  wssOpenHandle({
    isRealtime: true,
    taskCode: String(taskCode_everyChange.value) === "" ? useAppStoreInstance.globalRecordMainSysTaskCode || (useAppStoreInstance.globalSubsystemTaskCode) : String(taskCode_everyChange.value),
    speed: 1
  })

  if (window.ue5) {
    // console.log('1', dayjs(startDateTime.value).format('YYYY-MM-DD HH:mm'))
    // console.log('2', dayjs(endDateTime.value).format('YYYY-MM-DD HH:mm'))
    // console.log('3', dayjs(selectedEndTime.value).format('YYYY-MM-DD HH:mm'))
    window.ue5("callBackTimeFn", String(JSON.stringify({
      isRealtime: is_flag_isRealtime.value ? true : false,
      startTime: dayjs(startDateTime.value).format('YYYY-MM-DD HH:mm'),
      speed: playbackSpeed.value,
      endTime: dayjs(endDateTime.value).format('YYYY-MM-DD HH:mm'),
      taskCode: String(taskCode_everyChange.value) === "" ? useAppStoreInstance.globalRecordMainSysTaskCode || (useAppStoreInstance.globalSubsystemTaskCode) : String(taskCode_everyChange.value),

      currentTime: dayjs(selectedEndTime.value).format('YYYY-MM-DD HH:mm'),
      status: isPlaying.value ? "stop" : "continue",
      //时间参数

    })))

  }




}

const isChange_flag_firstBackDate = ref(false)
const intervalTimer = ref(null);
// 监听 selectedEndTime 的变化，二无停，时间是2025-11-02 16:01:00
// 检测时间间隔
const jiangerTime = ref(0)
const isFirst = ref(true)
watch(
  () => selectedEndTime.value,
  (val) => {
    // //console.log("每隔111111111122222-----bianhua");
    if (window.ue5) {
      // console.log("每隔1秒，callBackCycleTimePointFn",(formatDateTimeOne(selectedEndTime.value)));
      window.ue5("callBackCycleTimePointFn", String(JSON.stringify({
        // currentTime: trackCycleTimePoint(formatDateTime(selectedEndTime.value)), 
        currentTime: (formatDateTimeOne(selectedEndTime.value)),
      })));
      endDrag_opeartioning.value = false;
    }
    // 检查是否满足条件
    if (isChange_flag_firstBackDate.value) {

      // preTimeWindowEnd.value = new Date((new Date(new Date(selectedStartTime.value))).setSeconds(56+60)).toISOString();
      // //console.log("我走了",compareTime(formatDateTime(selectedEndTime.value), preTimeWindowEnd.value),formatDateTime(selectedEndTime.value),preTimeWindowEnd.value,300%7.8947 ===0.0014);

      // 间隔5分钟即300秒，发送时轴de 当前时间给ue
      const adjustedStep = Math.ceil(300 / playbackSpeed.value);
      if (jiangerTime.value % adjustedStep === 0) {
        if (window.ue5) {
          window.ue5("callTimeLineCurrentTimeFn", String(JSON.stringify({
            year: selectedEndTime.value.getFullYear(),
            month: selectedEndTime.value.getMonth() + 1,
            day: selectedEndTime.value.getDate(),
            hour: selectedEndTime.value.getHours(),
            minute: selectedEndTime.value.getMinutes(),
            second: selectedEndTime.value.getSeconds(),
          })));
        }
      }
      jiangerTime.value += 1;
      // console.log("111111111111111",formatDateTime(selectedEndTime.value), preTimeWindowEnd.value);

      if (compareTime(formatDateTime(selectedEndTime.value), preTimeWindowEnd.value)) {
        //console.log("我走了这里2")
        if (isPlaying.value) {
          stopAutoPlay();
          hasPlayed.value = false;
          isChange_flag_firstBackDate.value = false;
        }

        // clearInterval(intervalTimer.value);
        // intervalTimer.value = null;
      }
      //  if (!intervalTimer.value) {
      //       intervalTimer.value = setInterval(() => {
      //         //console.log("每隔一秒执行一次逻辑",compareTime(formatDateTime(selectedEndTime.value), preTimeWindowEnd.value));
      //         // 在这里执行你需要的逻辑
      //         if (compareTime(formatDateTime(selectedEndTime.value), preTimeWindowEnd.value)) {
      //           stopAutoPlay(); 
      //           clearInterval(intervalTimer.value);
      //           intervalTimer.value = null;
      //           hasPlayed.value = false;
      //           isChange_flag_firstBackDate.value = false;
      //         }

      //       }, 1000*10);
      //  }
    }
    // else {
    //   // 如果条件不满足，清除定时器
    //   if (intervalTimer.value) {
    //     //console.log("清理定时器");

    //     clearInterval(intervalTimer.value);
    //     intervalTimer.value = null;
    //   }
    // }
  },
  { deep: true, immediate: true }
);

const getDayRangeFromTime = (timeStr) => {
  const [datePart] = timeStr.split(' ');
  const [year, month, day] = datePart.split('-').map(Number);
  const startOfDay = new Date(year, month - 1, day, 0, 0, 0);
  const endOfDay = new Date(year, month - 1, day + 1, 0, 0, 0);
  return [startOfDay, endOfDay];
};
onUnmounted(() => {
  stopAutoPlay();
  window.removeEventListener('mousemove', handleDrag);
  window.removeEventListener('mouseup', endDrag);
  useAppStoreInstance.setGlobalSubsystemSelectedTimeRange(getDayRangeFromTime(useAppStoreInstance.globalTimeLineEndSelectTime));
  //console.log("jieshuli 1，组件卸载时要发暂停",getDayRangeFromTime(useAppStoreInstance.globalTimeLineEndSelectTime)[0],getDayRangeFromTime(useAppStoreInstance.globalTimeLineEndSelectTime)[1]);
  if (is_flag_isRealtime.value) {
    // 实时传输时，组件卸载时要发暂停
    // todo list
  } else {
    // 非实时传输时，组件卸载时要发暂停
    if (window.ue5) {

      window.ue5("callBackSpeedFn", String(JSON.stringify({
        isRealtime: is_flag_isRealtime.value ? true : false,
        status: "stop",
        speed: playbackSpeed.value,
        taskCode: String(taskCode_everyChange.value) === "" ? useAppStoreInstance.globalRecordMainSysTaskCode || (useAppStoreInstance.globalSubsystemTaskCode) : String(taskCode_everyChange.value),



      })));

      // window.ue5("callBackTimeFn", String(JSON.stringify({
      //     isRealtime: is_flag_isRealtime.value? true: false,
      //     status: "stop",
      //     taskCode: String(taskCode_everyChange.value) === "" ? useAppStoreInstance.globalRecordMainSysTaskCode || (useAppStoreInstance.globalSubsystemTaskCode) : String(taskCode_everyChange.value),
      //   })));
      wssOpenHandle({
        isRealtime: is_flag_isRealtime.value ? true : false,
        status: "stop",
        taskCode: String(taskCode_everyChange.value) === "" ? useAppStoreInstance.globalRecordMainSysTaskCode || (useAppStoreInstance.globalSubsystemTaskCode) : String(taskCode_everyChange.value),
      })
    }
  }



});

</script>



<style scoped>
.timeline-container {
  /* min-width: 800px; */
  max-width: 1600px;
  height: 140px;
  margin: 0 auto;
  padding: 10px 45px;
  /* font-family: 'Consolas', monospace;  */
  background-color: #000000;
  border-radius: 8px;
  /* box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2); */
  opacity: 1 !important;
}

.timeline-controls {
  display: flex;
  justify-content: space-between;
  font-weight: 600;
  font-size: 13px;
  align-items: center;
}

.block {
  display: flex;
  align-items: center;
}

.demonstration {
  margin-right: 10px;
  color: #ababab;
}

.right_block {
  display: flex;
  justify-content: space-between;
  padding: 0 10px;
}

.right_block_center {
  margin: 0 30px;
}

.right_block_conter_btn {
  border: none;
}

.right_block_conter_btn_playbackSpeed {
  background: none;
  border: none;
  color: rgba(255, 255, 255, 1);
  font-size: 20px;
}

.right_block_conter_btn {
  background-color: #404040;
}

.right_block_conter_btn:hover {
  background-color: #8b8b8b;
}

.right_block_conter_btn_center {
  background-color: #2e7dff;
}

.right_block_conter_btn_center:hover {
  background-color: #8CB8FF;
}

:deep(.right_block_confirm_btn) {
  background: linear-gradient(to bottom, #2E7DFF 0%, #000000 100%) !important;
  border: none;
  border-radius: 0;
  border-bottom: 1px solid #062ee1 !important;
  color: rgba(255, 255, 255, 1);
}

/* 时间轴主体 */
.timeline {
  position: relative;
  /* padding-top: -16px; */
  top: 60px;
  background-color: #f80808;
}

/* 时间刻度 - 调整为图片中的样式 */
.time-markers {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 24px;
  z-index: 1;
}

.time-marker {
  position: absolute;
  transform: translateX(-50%);
}

.marker-line {
  position: absolute;
  top: 0;
  left: 0;
  width: 1px;
  height: 8px;
}

/* 修改为主刻度样式 - 红色 */
.marker-line.major-line {
  height: 6px;
  background-color: #929292;
}

.marker-line.minor-line_color {
  height: 10px;
  background-color: rgba(255, 255, 255, 1);
}

/* 时间标签 - 调整为图片中的样式 */
.marker-label {
  position: absolute;
  top: -40px;
  left: -33px;
  font-size: 10px;
  color: #b6b8b8;
  font-weight: 500;
  text-align: center;
  /* white-space: nowrap; */
  padding: 2px 6px;
  border-radius: 4px;
  width: 80px;
  overflow-wrap: break-word;
}

/* 选中区域内的标签样式 */
.marker-label.selected-label {
  color: #ffffff;
  font-weight: bold;
}

/* 滑块容器 */
.slider-container {
  position: absolute;
  top: -6px;
  left: -7px;
  right: -9px;
  margin-top: 8px;
  padding: 0 8px;
}

.slider-track {
  position: relative;
  height: 8px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s;
}

/* 选中区域 */
.selected-range {
  position: absolute;
  top: -2px;
  height: 100%;
  border-radius: 4px;
  background: #3498db;
  transition: left 0.1s ease, width 0.1s ease;
}

/* 滑块样式 */
.slider-handle {
  position: absolute;
  top: 50%;
  width: 24px;
  height: 24px;
  transform: translate(-50%, -50%);
  cursor: grab;
  z-index: 1;
  transition: transform 0.1s;
}

.slider-handle:active {
  cursor: grabbing;
  transform: translate(-50%, -50%) scale(1.1);
}

.handle-rail {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 5px;
  height: 16px;
  background-color: white;
  box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.8);
  transform: translate(-50%, -50%);
}

.handle-rail:after {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  width: 4px;
  height: 15px;
  background-color: #3498db;
  transform: translate(-50%, -50%);
}

/* 滑块提示框 */
.handle-tooltip {
  position: absolute;
  bottom: 100%;
  left: 50%;
  transform: translateX(-50%);
  background-color: #2c3e50;
  color: white;
  padding: 6px 10px;
  border-radius: 6px;
  font-size: 12px;
  white-space: nowrap;
  margin-bottom: 12px;
  opacity: 0;
  transition: opacity 0.2s;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.1);
  pointer-events: none;
  z-index: 10;
}

/* 当鼠标悬停在.handle-rail上时显示.tooltip */
.handle-rail:hover .handle-tooltip,
.handle-rail:hover+.handle-tooltip,
.handle-rail:hover~.handle-tooltip {
  opacity: 1;
}

/* 自动播放时始终显示 */
.handle-tooltip_auto {
  opacity: 1 !important;
}

/* 强制穿透 Scoped CSS，覆盖 Element Plus 默认样式 */
:deep(.el-date-editor.el-input__wrapper) {
  background-color: #1a1a1a !important;
  border-color: #424242 !important;
  box-shadow: none !important;
}

:deep(.el-date-editor .el-input__inner) {
  background-color: #1a1a1a !important;
  color: #ffffff !important;
}

:deep(.el-range-input) {
  color: #ffffff !important;
}

:deep(.el-range-separator) {
  color: #ffffff !important;
}

:deep(.right_block_conter_btn_center) {
  border: none;
}

:deep(.right_block_conter_btn_center:focus) {
  outline: none;
}

:deep(.right_block_conter_btn_playbackSpeed) {
  border: none;
}

:deep(.right_block_conter_btn_playbackSpeed:focus) {
  outline: none;
}

:deep(.satellite-select .el-select__wrapper) {
  height: 12.5px;
}

:deep(.satellite-select .el-select__selected-item) {
  color: #ffffff;
  /* font-size: 10px; */
}

:deep(.satellite-select .el-tooltip__trigger) {
  background-color: #000000 !important;
  color: #f9fafd !important;
  border: none !important;
  box-shadow: none;
}

:deep(.el-select__suffix) {
  opacity: 0;
}
</style>