<template>
  <div class="flagTimeLineShow">
     <el-switch
    v-model="isFlagTimeLineShow"
    :active-action-icon="View"
    :inactive-action-icon="Hide"
  />
  </div>
  <div class="timeline-container" v-show="isFlagTimeLineShow">
    <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
            :disabled="useAppStoreInstance.globalDisableTimeLine"
            range-separator="→"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :disabled-date="disabledDate"
            @change="pick_select_date_handFn"
            :popper-options="{
              placement: 'bottom-start',
              modifiers: [
                {
                  name: 'offset',
                  options: {
                    offset: [-550, -125] // [水平偏移, 垂直偏移]
                  }
                }
              ]
            }"
          /> -->
          <div class="right_block">
            <!-- <el-button class="right_block_confirm_btn" size="mini" :disabled="useAppStoreInstance.globalDisableTimeLine" @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> -->
              <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>
              <!-- <el-button size="mini" @click="jumpToSpecificTime(new Date('2025-11-03 00:00:00'))">时间</el-button> -->
                <!-- <el-button circle class="right_block_conter_btn" @click="playForward">
                 <el-button circle class="right_block_conter_btn" @click="playForward">
                  <el-icon>
                    <img src="@/assets/images/footers/videoPlay_right.png" alt="" style="width: 8px; height: 10px;" />
                  </el-icon>
                </el-button> -->
                
            </div>
            <!-- <el-button size="mini" circle @click="changeSpeed" :disabled="is_flag_isRealtime" class="right_block_conter_btn_playbackSpeed" style="background: none;">x{{ playbackSpeed }}</el-button> -->
             <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>
          </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>
            
            <!-- 结束滑块     @mousedown="startDrag('end', $event)" -->
            <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 { Hide, View } from '@element-plus/icons-vue'
import { ElLoading, ElMessage } from 'element-plus'
import SubLoading from '@/pages/all/components/loadingComponent1/index.js'
import { ref, onMounted, onUnmounted, computed, watch, nextTick, onBeforeMount } from 'vue';
// import wss from '@/utils/subSystemRequestSocket.js'
import useAppStore from '@/store/module/app'
import SubWss from '@/utils/subSystemRequestSocket.js'

import { useRoute } from 'vue-router';


const allSubContent = ref([])
const LeftTopAllSubContentKey = ref([])
const LeftTopOriginAllSubContentKey = ref([])

const RightTopAllSubContentKey = ref([])
const RightTopOriginAllSubContentKey = ref([])

const RightBottomAllSubContentKey = ref([])
const RightBottomOriginAllSubContentKey = ref([])

const MiddleAllSubContentKey = ref([])
const MiddleOriginAllSubContentKey = ref([])

const OriginallMidderStationNameKeyInfo = ref([])
const allMidderStationNameKeyInfo = ref([])

const subWssInstance = ref(SubWss)
const playbackSpeedOptions = ref([
  {
    value: 1,
    label: '1x'
  },
  {
    value: 2,
    label: '2x'
  },
  {
    value: 4,
    label: '4x'
  },
  {
    value: 8,
    label: '8x'
  },
  {
    value: 10,
    label: '10x'
  },
])
// 获取要跳转的时间点
const subtractSeconds = (timeStr, sec) => {
  // 解析输入字符串为 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);

  // 减去 sec 秒（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 jumpToSpecificTime = (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 = false;
    is_flag_isRealtime.value = false;
    isConfirmedWithRange.value = false; // 设置为false以显示完整的选中区域

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

    //   // 调用UE5回调函数
    //   wssOpenHandle({
    //   // isRealtime: useAppStoreInstance.globalSubsystemIsFastForward? true: false,
    //   isFastForward: useAppStoreInstance.globalSubsystemIsFastForward? true: false, 
    //   speed: useAppStoreInstance.globalSubsystemSpeed,
    //   replayTime: formatDateTime(selectedEndTime.value), 
    //   taskCode: String(useAppStoreInstance.globalSubsystemTaskCode),
    //   satelliteId: useAppStoreInstance.globalSatelliteSearchID,
    // })
    // });
// playForward();
// toggleAutoPlay();
    return true;
  } catch (error) {
    console.error("跳转到指定时间点出错:", error);
    ElMessage.error('跳转时间点失败');
    return false;
  }
};








const route = useRoute();
const useAppStoreInstance = useAppStore();
const isFlagTimeLineShow = ref(true);
const wssOpenHandle = (data) => {
  //////console.log('subwssOpenHandle', subWssInstance.value,subWssInstance.value.readyState, WebSocket.OPEN);
  if ((subWssInstance.value).readyState === WebSocket.OPEN) {
    // 如果连接已打开，直接发送数据
    (subWssInstance.value).send(JSON.stringify(data));
  } else if ((subWssInstance.value).readyState === WebSocket.CLOSED) {
 
    (subWssInstance.value) = new WebSocket((subWssInstance.value).url);
    (subWssInstance.value).onopen = () => {
      (subWssInstance.value).send(JSON.stringify(data));
    };
    wssMessageHandle()
  }else 
  {
    // 否则等待连接打开后再发送
    (subWssInstance.value).onopen = () => {
      (subWssInstance.value).send(JSON.stringify(data));
    };
  }
};
const wssResponeFlag_isSuccess = ref(true);
const hasPlayed = ref(false);

const loading = ref('');
 const wssMessageHandle = () => { 
    (subWssInstance.value).onmessage = (event) => {
    const Jsondata = JSON.parse(event.data);
    ////console.log("我走了这里，收到数据1");

      // wssOpenHandle({ 
      //   type: "confirm",
      //   taskCode: toNumber(useAppStoreInstance.globalSubsystemTaskCode),
      //   clientType: "web"
      // })
    let flagToNext = 0
    SubLoading.hide()
    if (Jsondata.type === 'status') {
      //////console.log("我走了这里，收到数据2");
      if (Jsondata.status === 'STOP') {
        ////console.log("我走了这里4")
        stopAutoPlay() 
        hasPlayed.value = false;
      }
      isChange_flag_firstBackDate.value = false;
      hasPlayed.value = false;
      if (Jsondata.nextTimestamp || Jsondata.timeWindowEnd) {
        preTimeWindowEnd.value = Jsondata.nextTimestamp || Jsondata.timeWindowEnd ;
      }
    }
    else if (Jsondata.type === 'no_data') {
      //////console.log("我走了这里，收到数据3");
      isChange_flag_firstBackDate.value = false;
      // wssResponeFlag_isSuccess.value = false;
      // 关闭eleplate loading
      // (loading.value).close()
     SubLoading.hide()
      ElMessage({
        type: 'error',
        message: `已暂停，没有查询到该时间段的历史数据！！！`,
      })
      ////console.log("我走了这里5")
      stopAutoPlay();
      // hasPlayed.value = false;
      // //////console.log("获取的wssResponeFlag_isSuccess信息2:", wssResponeFlag_isSuccess.value);
      
    }
    else if (Jsondata.type === 'data_end') {
      //////console.log("我走了这里，收到数据4");
      isChange_flag_firstBackDate.value = false;
      SubLoading.hide()
      ElMessage({
        type: 'error',
        message: `已暂停，数据推送完成！！！`,
      })
      ////console.log("我走了这里6")
      stopAutoPlay();
    }else 
    // if (Jsondata.type === 'subsystem_data') { 
      // LeftTopAllSubContentKey.value = []
      // allSubContent.value = []
      // allSubContent.value = Jsondata
      // allSubContent.value.data[`${dataPickEndTime.value}`] = []
      // LeftTopAllSubContentKey.value = Object.keys(allSubContent.value.data)
      //////console.log("添加无关的key",allSubContent.value);
      // SubLoading.hide()
    // }
    // else 
    { 
      LeftTopAllSubContentKey.value = []
      allSubContent.value = []
      LeftTopOriginAllSubContentKey.value = []

      RightTopAllSubContentKey.value = []
      RightTopOriginAllSubContentKey.value = []

      RightBottomAllSubContentKey.value = []
      RightBottomOriginAllSubContentKey.value = []

      MiddleAllSubContentKey.value = []
      MiddleOriginAllSubContentKey.value = []

      allSubContent.value = Jsondata

      if (allSubContent.value?.data) {
        LeftTopAllSubContentKey.value = Object.keys(allSubContent.value?.data)
        LeftTopOriginAllSubContentKey.value = Object.keys(allSubContent.value?.data)
        LeftTopAllSubContentKey.value.unshift(dataPickStartTime.value)
        LeftTopAllSubContentKey.value.push(dataPickEndTime.value)
      }
      

      if (allSubContent.value?.arcSegmentInfoArray) {
        RightTopAllSubContentKey.value = Object.keys(allSubContent.value?.arcSegmentInfoArray?.data)
        RightTopOriginAllSubContentKey.value = Object.keys(allSubContent.value?.arcSegmentInfoArray?.data)
        RightTopAllSubContentKey.value.unshift(dataPickStartTime.value)
        RightTopAllSubContentKey.value.push(dataPickEndTime.value)
      }
      
      if (allSubContent.value?.satelliteAlertInfoArray) {
        RightBottomAllSubContentKey.value = Object.keys(allSubContent.value?.satelliteAlertInfoArray?.data)
        RightBottomOriginAllSubContentKey.value = Object.keys(allSubContent.value?.satelliteAlertInfoArray?.data)
        RightBottomAllSubContentKey.value.unshift(dataPickStartTime.value)
        RightBottomAllSubContentKey.value.push(dataPickEndTime.value)
      }
      
      if (allSubContent.value?.groundNetworkElementStatus?.controlTasks) {
        allMidderStationNameKeyInfo.value = Object.keys(allSubContent.value?.groundNetworkElementStatus?.controlTasks)
        OriginallMidderStationNameKeyInfo.value = Object.keys(allSubContent.value?.groundNetworkElementStatus?.controlTasks)
        allMidderStationNameKeyInfo.value.unshift(dataPickStartTime.value)
        allMidderStationNameKeyInfo.value.push(dataPickEndTime.value)
      }
      // console.log("1111111111111",OriginallMidderStationNameKeyInfo.value,allMidderStationNameKeyInfo.value);
      
      // MiddleAllSubContentKey.value = Object.keys(allSubContent.value?.data)
      // MiddleOriginAllSubContentKey.value = Object.keys(allSubContent.value?.data)
      // MiddleAllSubContentKey.value.unshift(dataPickStartTime.value)
      // MiddleAllSubContentKey.value.push(dataPickEndTime.value)

      //////console.log("添加无关的key",allSubContent.value );
      
      // 此时的后端还没写确认的逻辑
      // wssOpenHandle({
      //   type: "confirm",
      //   taskCode: String(useAppStoreInstance.globalSubsystemTaskCode),
      //   clientType: "web"
      // })
      //////console.log("我走了这里，收到数据4");
      
      if (Jsondata.nextTimestamp || Jsondata.timeWindowEnd) {
        preTimeWindowEnd.value = Jsondata.nextTimestamp || Jsondata.timeWindowEnd ;
      }
      
      isChange_flag_firstBackDate.value = true;
      // useAppStoreInstance.setSubsystemSocketContent(Jsondata)
      // if(loading.value){
      //   (loading.value).close()
      // }
      SubLoading.hide()
      // if (flagToNext !== 0) { 
      //    clearTimeout(flagToNext);
      // }
      // startAutoPlay(); 
      if (endDateTime.value === selectedEndTime.value.toISOString()) {
        stopAutoPlay();
        ////console.log("我走了这里7")
      }else{
        if (!hasPlayed.value) {
          playForward();
          hasPlayed.value = true;
        }
      }
    }
   
   
    // 使用 Promise 包装 setTimeout
    // await new Promise(resolve => {
    //   setTimeout(() => {
    //     loading.close()
    //     resolve()
    //   }, 2000)
    // })
    // //////console.log('我是timer获取的wssRespone:', data);
    // if (data.type === 'error') {
    //   wssResponeFlag_isSuccess.value = false;
    //   (loading.value).close()
    //   message.error("已暂停，没有查询到该时间段的历史数据！！！");
    //   // //////console.log("获取的wssResponeFlag_isSuccess信息1:", wssResponeFlag_isSuccess.value);
    //   useAppStoreInstance.setglobalStartWss(false)
    //   // 处理任务数据
    // } 
    // if (data.type === 'history') {
    //   // 处理日志数据
    //   // //////console.log("获取的wssResponeFlag_isSuccess信息2:", wssResponeFlag_isSuccess.value);
    //   useAppStoreInstance.setglobalStartWss(true)

    //   // playForward();
    //   startAutoPlay(); 
    //   // toggleAutoPlay();
    //   //////console.log("这里是startAutoPlay()");
      
    //   if(loading.value){
    //     (loading.value).close()
    //   }else{
  
        
    //   }
      wssResponeFlag_isSuccess.value = true;
      // message.success("同步时间轴数据状态成功！！！");
      // //////console.log('我是history的数据:', data);
    // }
    // if (data.type === 'EndProcess') {
    //   useAppStoreInstance.setglobalStartWss(false)
    //   // //////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());
    // }
   
    // 处理服务器返回的数据后续处理是否暂停处理
  //  flagToNext =  setTimeout(() => {
  //     stopAutoPlay();
  //   }, (1000*60)/playbackSpeed.value);
  };
}


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

// 日期时间状态 (精确到秒)
const endDateTime = ref(new Date(Date.now() ).toISOString());  // 当前时间作为结束时间
const startDateTime = ref(new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString());  // 三天前作为开始时间
const dateRange = ref([]);

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

// 拖动状态
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 is_flag_isRealtime = ref(true);

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

// 日期选择器快捷选项
// const shortcuts = [
//   {
//     text: '最近一周',
//     value: () => {
//       const end = new Date();
//       const start = new Date();
//       start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
//       return [start, end];
//     },
//   },
//   {
//     text: '最近一个月',
//     value: () => {
//       const end = new Date();
//       const start = new Date();
//       start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
//       return [start, end];
//     },
//   },
//   {
//     text: '最近三个月',
//     value: () => {
//       const end = new Date();
//       const start = new Date();
//       start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
//       return [start, end];
//     },
//   },
// ];

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),
//     // })));
//     // wssOpenHandle({
//     //   taskCode: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(Date.now());//每次进入分系统时，生成一个新的taskCode


const toNumber = (value) => {
  const num = Number(value);
  return isNaN(num) ? 0 : num; // 如果转换失败则返回0
}
// 点击确认后，处理日期范围变化
const handleDateRangeChange = async (val) => {
  // taskCode_everyChange.value = String(Date.now());
  // //////console.log("/****/*/*/*/*",val);
  jiangerTime.value = 0;
  isChange_flag_firstBackDate.value = false;
  hasPlayed.value = false;
  useAppStoreInstance.setglobalSubsystemTaskCode(taskCode_everyChange.value);
  if (val && val.length > 0) { 
    // if(isChange_flag_select_date.value) {
       wssResponeFlag_isSuccess.value = true;
       isPlaying.value = false;
      //element plus组件显示加载中
      // loading.value = ElLoading.service({
      // lock: true,
      // text: 'Loading',
      // background: 'rgba(0, 0, 0, 0.7)',
      // })
      SubLoading.show()
      if (val && val.length === 2) {
        //////console.log("cao cao11111111111111111",val[0]);
        
        startDateTime.value = new Date((new Date(val[0])).setSeconds(56)).toISOString();
        
        endDateTime.value = val[1].toISOString();
        isDraged.value = false;
        is_flag_isRealtime.value = false;
        useAppStoreInstance.setglobalSubsystemIsFastForward(false)
        isDateRangeNotEmpty.value = false;
        isConfirmedWithRange.value = true; // 标记为带范围确认
        clearInterval(autoUpdateDateRange.value);
        updateTimeline();
        
        // 重置滑块位置到开始位置
        startHandlePercent.value = 0;
        endHandlePercent.value = 0;
        

        // playForward(); 
        // 强制更新视图
        nextTick(() => {
          updateSelectedTimes();
        });
      }
        // wssOpenHandle({
        //   isFastForward:  is_flag_isRealtime.value? true: false,
        //   speed: playbackSpeed.value,
        //   startTime: formatDateTime(val[0]),
        //   endTime: formatDateTime(val[1]),
        //   taskCode: toNumber(useAppStoreInstance.globalSubsystemTaskCode),
        //   // type: socketTypeMap[useAppStoreInstance.globalSubsystemActiveIndex] || 'CONTROL',
        //   satelliteId:useAppStoreInstance.globalSatelliteSearchID,
        // })
      // 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),
      //   // })))
     
      // }

      
      wssMessageHandle()

      
      // if (wssResponeFlag_isSuccess.value) { 
      //   toggleAutoPlay();
      // }
      
      

    // } else { 
    //   message.warning("当前时间段未发生变化");
    // }
    isChange_flag_select_date.value = false;
  } else { 
    ElMessage({
      type: 'warning',
      message: "时间范围为空，自动执行最近24小时",
    })
    isDateRangeNotEmpty.value = true;
    isConfirmedWithRange.value = false; // 重置标记
    is_flag_isRealtime.value = true;//实时模式
    // useAppStoreInstance.set(true)
    playbackSpeed.value = 1;
      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),
        // })))
        // 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("我走了这里8")
    stopAutoPlay();
    // wss.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())]);
}, 1000);

watch(() => isDateRangeNotEmpty.value, (newVal) => {
  //////console.log("发生变化",newVal);
  
  if (newVal) {
    autoUpdateDateRange.value = setInterval(() => {
      //////console.log("开启循环",autoUpdateDateRange.value);
      // const realtimeStartTime = new Date(new Date(Date.now() - 3*24 * 60 * 60 * 1000).toISOString());
      // const realtimeEndTime = new Date(new Date(Date.now() ).toISOString());
    




      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) {
    startDateTime.value = val[0].toISOString();
    endDateTime.value = val[1].toISOString();
    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() + 1);
  }
  
  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: `${firstMarkerTime.getFullYear()}-${String(firstMarkerTime.getMonth() + 1).padStart(2, '0')}-${String(firstMarkerTime.getDate()).padStart(2, '0')} <br>${String(firstMarkerTime.getHours()).padStart(2, '0')}:${String(firstMarkerTime.getMinutes()).padStart(2, '0')}`,
    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 = new Date(nextHour);
  while (current <= end) {
    const position = ((current.getTime() - start.getTime()) / totalMs) * 100;
    markers.push({
      time: new Date(current),
      label: `${current.getFullYear()}-${String(current.getMonth() + 1).padStart(2, '0')}-${String(current.getDate()).padStart(2, '0')} <br>${String(current.getHours()).padStart(2, '0')}:${String(current.getMinutes()).padStart(2, '0')}`,
      position,
      isMajor: true, // 每小时都是主刻度
      showLabel: true
    });
    current.setHours(current.getHours() + 1); // 每次 +1 小时
  }

  return markers;
});

// 判断标记是否在选中范围内
const isMarkerInSelectedRange = (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');
  return `${year}-${month}-${day} ${formatTime(date)}`;
};

// 修改后的选中区域样式计算属性
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}%`);

// 修改后的 endHandlePosition 计算属性
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;
  




  // 调用UE5回调函数
  if (window.ue5) {
    if (isDraged.value) {
      if (!isPlaying.value) {
        // window.ue5("callBackTimeFn", String(JSON.stringify({
        //   isRealtime: false,
        //   replayTime: formatDateTime(selectedEndTime.value), 
        //   taskCode: String(taskCode_everyChange.value),
        // })));
        
      }
    } else {
      // window.ue5("callBackTimeFn", String(JSON.stringify({})));
    }
  }
};

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

// 切换自动播放状态
const toggleAutoPlay = () => {
  if (is_flag_isRealtime.value) {
    ElMessage({
      type: 'warning',
      message: '当前为实时播放模式,不可执行播放操作！',
    })
   
  }else{
    is_flag_playBackwarding.value = true;
  let status = 'continue';
  if (isPlaying.value) {
    status = 'stop';
    //////console.log("我是切换自动播放状态stopAutoPlay()",isPlaying.value);
    ////console.log("我走了这里9")
    stopAutoPlay();
    // if (window.ue5) {
    //   window.ue5("callBackSpeedFn", String(JSON.stringify({
    //     isRealtime: is_flag_isRealtime.value? true: false,
    //     status: "stop",
    //     step: playbackSpeed.value,
    //     taskCode: String(taskCode_everyChange.value),
    //   })));
      
    // }
    
  } else {
    status = 'continue';
    isConfirmedWithRange.value = false; // 开始播放时重置标记

    playForward();
  //    if(window.ue5) {
  //   window.ue5("callBackSpeedFn", String(JSON.stringify({
  //     isRealtime: is_flag_isRealtime.value? true: false,
  //     status: 'continue',
  //     step: playbackSpeed.value,
  //     taskCode: String(taskCode_everyChange.value),
  //   })));
  // } 
    //    wssOpenHandle({
    //   // isRealtime: useAppStoreInstance.globalSubsystemIsFastForward? true: false,
    //   status: 'continue', 
    //   speed: useAppStoreInstance.globalSubsystemSpeed,
    //   taskCode: String(useAppStoreInstance.globalSubsystemTaskCode),
    //   satelliteId: useAppStoreInstance.globalSatelliteSearchID,
    // })
    // 强制更新视图
    nextTick(() => {
      updateSelectedTimes();
    });
  }

  }
  
};

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


// 开始向前播放
const playForward = async () => {
  is_flag_playBackwarding.value = true;
  if (1) {
  
    //////console.log("我是开始向前播放stopAutoPlay()",isPlaying.value);
    // stopAutoPlay(); // 先停止当前播放
    isPlaying.value = true;
    isConfirmedWithRange.value = false; // 重置标记
    curplaybackDirection.value = false; 
    playbackDirection.value = 1;
    // wssOpenHandle({
    //   // isRealtime: useAppStoreInstance.globalSubsystemIsFastForward? true: false,
    //   status: 'continue', 
    //   speed: useAppStoreInstance.globalSubsystemSpeed,
    //   taskCode: useAppStoreInstance.globalSubsystemTaskCode,
    //   satelliteId: useAppStoreInstance.globalSubsystemSatelliteId,
    // })
    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);
    // wssOpenHandle({
    //   // isRealtime: useAppStoreInstance.globalSubsystemIsFastForward? true: false,
    //   status: 'stop', 
    //   taskCode: String(useAppStoreInstance.globalSubsystemTaskCode),
    //   satelliteId: useAppStoreInstance.globalSatelliteSearchID,
    // })
  if (playbackInterval.value) {
    clearInterval(playbackInterval.value);
    playbackInterval.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("我走了这里10")
    stopAutoPlay();
  }
  // wssOpenHandle({
  //         // isRealtime: useAppStoreInstance.globalSubsystemIsFastForward? true: false,
  //         isFastForward: useAppStoreInstance.globalSubsystemIsFastForward? true: false, 
  //         step: useAppStoreInstance.globalSubsystemSpeed,
  //         replayTime: formatDateTime(selectedEndTime.value), 
  //         taskCode: useAppStoreInstance.globalSubsystemTaskCode,
  //         satelliteId: useAppStoreInstance.globalSubsystemSatelliteId,
  //       })
  //  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 = () => {
  // const speeds = [1, 2, 4, 8, 10];
  // const currentIndex = speeds.indexOf(playbackSpeed.value);
  // const nextIndex = (currentIndex + 1) % speeds.length;
  // playbackSpeed.value = speeds[nextIndex];
  useAppStoreInstance.setglobalSubsystemSpeed(playbackSpeed.value)

  if (window.ue5) {
    // window.ue5("callBackSpeedFn", String(JSON.stringify({
    //   isFastForward: useAppStoreInstance.globalSubsystemIsFastForward === 1 || useAppStoreInstance.globalSubsystemIsFastForward === '1'? false: true, 
    //   step: playbackSpeed.value,
    //   taskCode: String(useAppStoreInstance.globalSubsystemTaskCode),
    //   satelliteId: useAppStoreInstance.globalSatelliteSearchID,
    // })))
    // wssOpenHandle({
    //   // isRealtime: useAppStoreInstance.globalSubsystemIsFastForward? true: false,
    //   isFastForward: playbackSpeed.value === 1 || playbackSpeed.value === '1'? false: true, 
    //   step: playbackSpeed.value,
    //   taskCode: String(useAppStoreInstance.globalSubsystemTaskCode),
    //   satelliteId: useAppStoreInstance.globalSatelliteSearchID,
    // })
  }
  
  // 如果正在播放，重新开始自动播放以应用新的速度
  if (isPlaying.value) {
    startAutoPlay();
  }
};

// 拖动开始
const startDrag = (handle, e) => {
  // if (is_flag_isRealtime.value) {
  //    return
  // }
  //////console.log("开始拖动");
  is_flag_isRealtime.value = false;
  useAppStoreInstance.setglobalSubsystemIsFastForward(false)
  isDateRangeNotEmpty.value = false;
  clearInterval(autoUpdateDateRange.value);
  isDraged.value = true;
  isDragging.value = true;
  currentDragHandle.value = handle;
  e.preventDefault();

  // 手动拖动时停止自动播放
  // if (isPlaying.value) {
  //   //////console.log("我是拖动开始stopAutoPlay()",isPlaying.value);
  //   //////console.log("我走了这里11")
  //   stopAutoPlay();
  // }
 
  // 添加全局事件监听器

      window.addEventListener('mousemove', handleDrag);
      window.addEventListener('mouseup', endDrag);
  

};

// 处理拖动
const handleDrag = (e) => {
  if (!isDragging.value || !currentDragHandle.value || !sliderTrack.value) return;
  
  // 手动拖动时停止自动播放
  // if (isPlaying.value) {
  //   //////console.log("我是处理拖动stopAutoPlay()",isPlaying.value);
  //   ////console.log("我走了这里12")
  //   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 endDrag = () => {
  hasPlayed.value = false;
  isDragging.value = false;
  currentDragHandle.value = null;
    //  window.ue5("callBackTimeFn", String(JSON.stringify({
    //       isRealtime: false,
    //       replayTime: formatDateTime(selectedEndTime.value), 
    //       taskCode: String(taskCode_everyChange.value),
    //     })));
    //   wssOpenHandle({
    //   // isRealtime: useAppStoreInstance.globalSubsystemIsFastForward? true: false,
    //   isFastForward: useAppStoreInstance.globalSubsystemIsFastForward? true: false, 
    //   speed: useAppStoreInstance.globalSubsystemSpeed,
    //   replayTime: formatDateTime(selectedEndTime.value), 
    //   taskCode: String(useAppStoreInstance.globalSubsystemTaskCode),
    //   satelliteId: useAppStoreInstance.globalSatelliteSearchID,
    // })
    // if (window.ue5) {
    //    // 发送时轴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(),
    //       })));
    // }
    
  // 移除全局事件监听器
  window.removeEventListener('mousemove', handleDrag);
  window.removeEventListener('mouseup', endDrag);
  updateSelectedTimes();
};

// 更新时间轴
const updateTimeline = () => {
  // 验证时间范围
  if (new Date(startDateTime.value) >= new Date(endDateTime.value)) {
    alert('结束时间必须大于开始时间');
    return;
  }
  
  generateTimelineDates();
  
  // 重置滑块位置
  startHandlePercent.value = 0;
  endHandlePercent.value = 0;
};


const dataPickFalg = ref(false);
const dataPickStartTime = ref('');
const dataPickEndTime = ref('');
const stratEndTimeTransformTime = (time) => { 

};

onBeforeMount(() => {
  // if (window.ue5) {
  //       window.ue5("callBackControlSwitchShowFn", String(JSON.stringify({
  //         type: "TimeLineShow",
  //         status:  "open" 
  //     })));}
    if (window.ue5) {
        window.ue5("callBackControlSwitchShowFn", String(JSON.stringify({
          type: "LegendShow",
          status: "open" 
      })));}
});


onMounted(() => {

preTimeWindowEnd.value = "2026-11-01 00:00:00"
// //////console.log("cao  ceshi ",compareTime("Sun Nov 02 2025 00:00:00 GMT+0800 (中国标准时间)","Sun Nov 02 2026 00:00:00 GMT+0800 (中国标准时间)"));

  // 添加实时模式的时间出路逻辑
if(!useAppStoreInstance.footerTimeHasedSelectTimeToSub) {
  updateTimeline();

  useAppStoreInstance.setglobalSubsystemTaskCode(Date.now())
  // 这里修改发送实时模式的数据内容
  // wssOpenHandle({
  //         // isRealtime: useAppStoreInstance.globalSubsystemIsFastForward? true: false,
  //         isFastForward: useAppStoreInstance.globalSubsystemIsFastForward? true: false, 
  //         speed: useAppStoreInstance.globalSubsystemSpeed,
  //         startTime: dataPickStartTime.value,
  //         endTime: dataPickEndTime.value,
   
  //         // startTime: formatDateTime(new Date(new Date(Date.now() - 3*24 * 60 * 60 * 1000).toISOString())),
  //         // endTime: formatDateTime(new Date(new Date(Date.now() ).toISOString())), 
  //         taskCode: String(useAppStoreInstance.globalSubsystemTaskCode),
  //         satelliteId: useAppStoreInstance.globalSatelliteSearchID,
  //       })
  //  Loading.show();
}else {
  // SubLoading.show();
  updateTimeline();
  //////console.log("我是初始",useAppStoreInstance.globalSubsystemSelectedTimeRange);
  useAppStoreInstance.setGlobalSubsystemSelectedTimeRange(useAppStoreInstance.globalSubsystemSelectedTimeRange);
  dataPickFalg.value = route.query.disabled || false;
  dateRange.value = useAppStoreInstance.globalSubsystemSelectedTimeRange
  dataPickStartTime.value = formatDateTime(useAppStoreInstance.globalSubsystemSelectedTimeRange[0]);
  dataPickEndTime.value = formatDateTime(useAppStoreInstance.globalSubsystemSelectedTimeRange[1]);
  handleDateRangeChange(useAppStoreInstance.globalSubsystemSelectedTimeRange);
  hasPlayed.value = false;
  wssOpenHandle({
          // isRealtime: useAppStoreInstance.globalSubsystemIsFastForward? true: false,
          isFastForward: useAppStoreInstance.globalSubsystemIsFastForward? true: false, 
          speed: useAppStoreInstance.globalSubsystemSpeed,
          startTime: dataPickStartTime.value,
          endTime: dataPickEndTime.value,
   
          // startTime: formatDateTime(new Date(new Date(Date.now() - 3*24 * 60 * 60 * 1000).toISOString())),
          // endTime: formatDateTime(new Date(new Date(Date.now() ).toISOString())), 
          taskCode: String(useAppStoreInstance.globalSubsystemTaskCode),
          satelliteId: useAppStoreInstance.globalSatelliteSearchID,
        })
    // SubLoading.show();
  // 初始化时，默认实时传输
  //  const realtimeTaskCode = Date.now();
//   watch(() => useAppStoreInstance.globalSatelliteSearchID, (newValue, oldValue) => { 
//     //////console.log("................",newValue,oldValue,newValue !== oldValue,newValue === oldValue);
    
//     if(newValue !== oldValue) { 
//        wssOpenHandle({
//           // isRealtime: useAppStoreInstance.globalSubsystemIsFastForward? true: false,
//           isFastForward: useAppStoreInstance.globalSubsystemIsFastForward? true: false, 
//           speed: useAppStoreInstance.globalSubsystemSpeed,
//           startTime: dataPickStartTime.value,
//           endTime: dataPickEndTime.value,
//           // startTime: formatDateTime(new Date(new Date(Date.now() - 3*24 * 60 * 60 * 1000).toISOString())),
//           // endTime: formatDateTime(new Date(new Date(Date.now() ).toISOString())), 
//           taskCode: String(useAppStoreInstance.globalSubsystemTaskCode),
//           satelliteId: useAppStoreInstance.globalSatelliteSearchID,
//         })
//     }
//     if(newValue===oldValue){
//              wssOpenHandle({
//       // isRealtime: useAppStoreInstance.globalSubsystemIsFastForward? true: false,
//       status: 'continue', 
//       speed: useAppStoreInstance.globalSubsystemSpeed,
//       taskCode: String(useAppStoreInstance.globalSubsystemTaskCode),
//       satelliteId: useAppStoreInstance.globalSatelliteSearchID,
//     })
//     }
//   });
}
});

const compareTime = (time1,allKeyArray=[]) => {
  // console.log('每隔开始compareTime----------', time1,typeof allKeyArray,allKeyArray);
  // 将时间字符串转换为 Date 对象
  const date1 = new Date(time1);
 

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

  for(let i = 0; i < allKeyArray.length-1; i++){
     const date2 = new Date(allKeyArray[i]);
      const date3 = new Date(allKeyArray[i+1]);
    if(date1 >= date2 && date1 <= date3){
      return {
        index: i,
        TimePeriod: date2.toString(),
        // type:true
      }
    }
  }
  // 比较时间戳
  // if (date1 >= date2) {
  //   return true;
  // }else {
  //   return false;
  // }
};
const isChange_flag_firstBackDate = ref(false)
const preTimeWindowEnd = ref(null);
const tempSubContent = ref({})
// 监听 selectedEndTime 的变化，二无停，时间是2025-11-02 16:01:00
// 检测时间间隔
const jiangerTime = ref(0)


const transformTorightTop = (objOrArr, index) => {
  if (index === 0) {
    return [];
  }
  if (Array.isArray(objOrArr)) {
    // 如果是数组，返回前 index项
    return objOrArr.slice(0, index );
  }

  if (objOrArr && typeof objOrArr === 'object') {
    // 如果是对象，获取其可枚举键（按插入顺序）
    const keys = Object.keys(objOrArr);
    
    
    const selectedKeys = keys.slice(0, index );
    // console.log("Object.keys(objOrArr);",keys,selectedKeys);
    // 构建新对象，只包含前 index个键
    const result = {};
    for (const key of selectedKeys) {
      result[key] = objOrArr[key];
    }
    return result;
  }

  // 其他类型（null、undefined、string 等）返回空数组或原值
  return [];
};

const tempMiderStationNameInfo = ref({})


watch(
  () => selectedEndTime.value,
  (val) => {
    // 检查是否满足条件
    if ( isChange_flag_firstBackDate.value) {
      // //////console.log("每隔开始进来");
      // //////console.log("我走了sub，LeftTopOrigin",LeftTopOriginAllSubContentKey.value[compareTime(formatDateTime(selectedEndTime.value),LeftTopAllSubContentKey.value).index]);
      // consol。e.log("我走了sub，RightTopOrigin",transformTorightTop(allSubContent.value?.satelliteAlertInfoArray?.data,compareTime(formatDateTime(selectedEndTime.value),RightBottomAllSubContentKey.value)?.index));
      // //////console.log("我走了sub，RightBottomOrigin",RightBottomOriginAllSubContentKey.value[compareTime(formatDateTime(selectedEndTime.value),RightBottomAllSubContentKey.value).index]);

      tempSubContent.value = {}



      

      tempSubContent.value = {
        leftTop:compareTime(formatDateTime(selectedEndTime.value),LeftTopAllSubContentKey.value)?.index === 0? {}:allSubContent.value?.data?.[LeftTopOriginAllSubContentKey.value[compareTime(formatDateTime(selectedEndTime.value),LeftTopAllSubContentKey.value)?.index]],
        rightTop:compareTime(formatDateTime(selectedEndTime.value),RightTopAllSubContentKey.value)?.index === 0? {}:transformTorightTop(allSubContent.value?.arcSegmentInfoArray?.data,compareTime(formatDateTime(selectedEndTime.value),RightTopAllSubContentKey.value)?.index),
        rightBottom:compareTime(formatDateTime(selectedEndTime.value),RightBottomAllSubContentKey.value)?.index === 0? {}:transformTorightTop(allSubContent.value?.satelliteAlertInfoArray?.data,compareTime(formatDateTime(selectedEndTime.value),RightBottomAllSubContentKey.value)?.index),
        // groundNetworkElementStatus:compareTime(formatDateTime(selectedEndTime.value),allMidderStationNameKeyInfo.value)?.index === 0? {}:transformTorightTop(allSubContent.value?.groundNetworkElementStatus?.controlTasks,compareTime(formatDateTime(selectedEndTime.value),allMidderStationNameKeyInfo.value)?.index),
        groundNetworkElementStatus:{
          ...(allSubContent.value?.groundNetworkElementStatus),
          siteName:compareTime(formatDateTime(selectedEndTime.value),allMidderStationNameKeyInfo.value)?.index === 0? {}:allSubContent.value?.groundNetworkElementStatus?.controlTasks[OriginallMidderStationNameKeyInfo.value[compareTime(formatDateTime(selectedEndTime.value),allMidderStationNameKeyInfo.value)?.index - 1]]
        },
        
      }
      useAppStoreInstance.setSubSystemTimeLineEndSelectTime(formatDateTime(selectedEndTime.value) )
      useAppStoreInstance.setSubsystemSocketContent(tempSubContent.value)
      // console.log("我走了sub，tempSubContent",tempSubContent.value);
      // 间隔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;
      // if (compareTime(formatDateTime(selectedEndTime.value), preTimeWindowEnd.value)) {
      //    //////console.log("我走了这里2，因为返回的数据不包含preTimeWindowEnd.value，所以会自动停止")
      //    if(isPlaying.value){
      //     //////console.log("我走了这里13")


      //       // 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;
        //   }
          
        // }, 1000*10);
  //  }
    } 
    // else {
    //   // 如果条件不满足，清除定时器
    //   if (intervalTimer.value) {
    //     //////console.log("清理定时器");
        
    //     clearInterval(intervalTimer.value);
    //     intervalTimer.value = null;
    //   }
    // }
  },
  { deep: true, immediate: true }
);
onUnmounted(() => {
  //////console.log("我走了这里14")
  // stopAutoPlay();
  // wssOpenHandle({
  //     // isRealtime: useAppStoreInstance.globalSubsystemIsFastForward? true: false,
  //     status: 'stop', 
  //     taskCode: String(useAppStoreInstance.globalSubsystemTaskCode),
  //     satelliteId: useAppStoreInstance.globalSatelliteSearchID,
  //   })
  useAppStoreInstance.setSubSystemTimeLineEndSelectTime("-")
  window.removeEventListener('mousemove', handleDrag);
  window.removeEventListener('mouseup', endDrag);
});
</script>

<style scoped>
  .flagTimeLineShow{
    position: absolute;
    bottom: 140px;

  }
.timeline-container {
  min-width: 800px;
  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);
}

.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: -37px;
  font-size: 10px;
  color: #b6b8b8;
  font-weight: 500;
  text-align: center;
  white-space: nowrap;
  padding: 2px 6px;
  border-radius: 4px;
}

/* 选中区域内的标签样式 */
.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>