<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>
          </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 }"></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 } from 'vue';
// import wss from '@/utils/subSystemRequestSocket.js'
import useAppStore from '@/store/module/app'
import { Hide, View } from '@element-plus/icons-vue'

import { useRoute } from 'vue-router';



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

    // 停止当前自动播放
    if (isPlaying.value) {
      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: toNumber(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('wssOpenHandle', wss,wss.readyState, WebSocket.OPEN);
  if (useAppStoreInstance.subsystemSocket.readyState === WebSocket.OPEN) {
    // 如果连接已打开，直接发送数据
    useAppStoreInstance.subsystemSocket.send(JSON.stringify(data));
  } else 
  {
    // 否则等待连接打开后再发送
    useAppStoreInstance.subsystemSocket.onopen = () => {
      useAppStoreInstance.subsystemSocket.send(JSON.stringify(data));
    };
  }
};
const wssResponeFlag_isSuccess = ref(true);
const loading = ref('');
 const wssMessageHandle = () => { 
    useAppStoreInstance.subsystemSocket.onmessage = (event) => {
    const Jsondata = JSON.parse(event.data);
      // wssOpenHandle({ 
      //   type: "confirm",
      //   taskCode: toNumber(useAppStoreInstance.globalSubsystemTaskCode),
      //   clientType: "web"
      // })
    let flagToNext = 0
    
    // console.log("222222222FOOT2---------",Jsondata);
    if (Jsondata.type === 'no_data') {
      // wssResponeFlag_isSuccess.value = false;
      // 关闭eleplate loading
      // (loading.value).close()
     Loading.hide()
      ElMessage({
        type: 'error',
        message: `已暂停，没有查询到该时间段的历史数据！！！`,
      })
      stopAutoPlay();
      // console.log("获取的wssResponeFlag_isSuccess信息2:", wssResponeFlag_isSuccess.value);
      
    }else if (Jsondata.type === 'data_end') {
      Loading.hide()
      ElMessage({
        type: 'error',
        message: `已暂停，数据推送完成！！！`,
      })
      stopAutoPlay();
    }else  { 

       useAppStoreInstance.setSubsystemSocketContent(Jsondata)
      // if(loading.value){
      //   (loading.value).close()
      // }
      Loading.hide()
      if (flagToNext !== 0) { 
         clearTimeout(flagToNext);
      }
      // startAutoPlay(); 
      if (endDateTime.value === selectedEndTime.value.toISOString()) {
        stopAutoPlay();
      }else{
        playForward();
      }
    }
   
    // 使用 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{
    //     console.log("99999999999999",loading.value);
        
    //   }
      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() - 24 * 60 * 60 * 1000).toISOString());  // 当前时间作为结束时间
const startDateTime = ref(new Date(Date.now() - 4 * 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(endDateTime.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);
  
  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)',
      // })
      Loading.show()
      if (val && val.length === 2) {
        console.log("11111111111111111",val[0]);
        
        startDateTime.value = val[0].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()
      // console.log("9999999999",wssResponeFlag_isSuccess.value);
      
      // 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()");
    
    stopAutoPlay();
    // wss.close()
  }
})

const isDateRangeNotEmpty = ref(false);
const autoUpdateDateRange = ref(null);
autoUpdateDateRange.value = setInterval(() => {
  autoHandleDateRangeChange([new Date(new Date(Date.now() - 3*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() - 3*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;
  
  // 生成每半小时的刻度
  const currentTime = new Date(start);
  currentTime.setMinutes(0, 0, 0); // 重置到整点
  
  while (currentTime <= end) {
    // 确保时间在范围内
    if (currentTime >= start) {
      const position = ((currentTime.getTime() - start.getTime()) / totalMs) * 100;
      // 将0分和30分设为主要刻度
      const minutes = currentTime.getMinutes();
      const isMajor = minutes === 0 ;
      
      // 格式化标签显示
      const year = currentTime.getFullYear();
      const month = String(currentTime.getMonth() + 1).padStart(2, '0');
      const day = String(currentTime.getDate()).padStart(2, '0');
      const hours = String(currentTime.getHours()).padStart(2, '0');
      const mins = String(currentTime.getMinutes()).padStart(2, '0');
      
      // 对于主要刻度显示完整时间，次要刻度只显示时间
      let label = `${year}-${month}-${day} <br>${hours}:${mins}`;
      
      markers.push({
        time: new Date(currentTime),
        label: label,
        position: position,
        isMajor: isMajor,
        showLabel: true
      });
    }
    
    // 增加30分钟
    currentTime.setMinutes(currentTime.getMinutes() + 30);
  }
  
  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);
    stopAutoPlay();
       
  } else {
    status = 'continue';
    isConfirmedWithRange.value = false; // 开始播放时重置标记

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

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 stopAutoPlay = () => {
  isPlaying.value = false;
   console.log("停止自动播放", playbackInterval.value);
wssOpenHandle({
      // isRealtime: useAppStoreInstance.globalSubsystemIsFastForward? true: false,
      status: 'stop', 
      
      taskCode: toNumber(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 * playbackSpeed.value * 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);
    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("callBackTimeFn", String(JSON.stringify({
    //   isRealtime: is_flag_isRealtime.value? true: false,
    //   isFastForward: true, 
    //   step: playbackSpeed.value,
    //   taskCode: String(taskCode_everyChange.value),
    // })))
    wssOpenHandle({
      // isRealtime: useAppStoreInstance.globalSubsystemIsFastForward? true: false,
      isFastForward: useAppStoreInstance.globalSubsystemIsFastForward? true: false, 
      speed: useAppStoreInstance.globalSubsystemSpeed,
      taskCode: toNumber(useAppStoreInstance.globalSubsystemTaskCode),
      satelliteId: useAppStoreInstance.globalSatelliteSearchID,
    })
  }
  
  // 如果正在播放，重新开始自动播放以应用新的速度
  if (isPlaying.value) {
    startAutoPlay();
  }
};

// 拖动开始
const startDrag = (handle, e) => {
  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);
    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);
    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 = () => {
  isDragging.value = false;
  currentDragHandle.value = null;
      wssOpenHandle({
      // isRealtime: useAppStoreInstance.globalSubsystemIsFastForward? true: false,
      isFastForward: useAppStoreInstance.globalSubsystemIsFastForward? true: false, 
      speed: useAppStoreInstance.globalSubsystemSpeed,
      replayTime: formatDateTime(selectedEndTime.value), 
      taskCode: toNumber(useAppStoreInstance.globalSubsystemTaskCode),
      satelliteId: useAppStoreInstance.globalSatelliteSearchID,
    })
  // 移除全局事件监听器
  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 = isConfirmedWithRange.value ? 0 : 100;
};


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

};
onMounted(() => {
  updateTimeline();
  console.log("我是初始",useAppStoreInstance.globalSubsystemSelectedStartTime);
  dataPickFalg.value = route.query.disabled || false;
  dateRange.value = useAppStoreInstance.globalSubsystemSelectedStartTime
  dataPickStartTime.value = formatDateTime(useAppStoreInstance.globalSubsystemSelectedStartTime[0]);
  dataPickEndTime.value = formatDateTime(useAppStoreInstance.globalSubsystemSelectedStartTime[1]);
  handleDateRangeChange(useAppStoreInstance.globalSubsystemSelectedStartTime);



     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: toNumber(useAppStoreInstance.globalSubsystemTaskCode),
          satelliteId: useAppStoreInstance.globalSatelliteSearchID,
        })
  // 初始化时，默认实时传输
  //  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: toNumber(useAppStoreInstance.globalSubsystemTaskCode),
          satelliteId: useAppStoreInstance.globalSatelliteSearchID,
        })
    }
    if(newValue===oldValue){
             wssOpenHandle({
      // isRealtime: useAppStoreInstance.globalSubsystemIsFastForward? true: false,
      status: 'continue', 
      speed: useAppStoreInstance.globalSubsystemSpeed,
      taskCode: toNumber(useAppStoreInstance.globalSubsystemTaskCode),
      satelliteId: useAppStoreInstance.globalSatelliteSearchID,
    })
    }
  });
     
});

onUnmounted(() => {
  stopAutoPlay();
  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;
}

</style>