<template>
  <div class="time-slider-container">
    <h4 class="time-title">{{ title }}</h4>
    <div class="time-info">当前时间：{{ formatTime(currentTimeStamp) }}</div>
    <input
      type="range"
      :min="startTimeStamp"
      :max="endTimeStamp"
      :value="currentTimeStamp"
      :step="step"
      @input="handleSliderChange"
      class="slider"
    />
    <div class="time-range">
      <span>{{ formatTime(startTimeStamp) }}</span>
      <span>{{ formatTime(endTimeStamp) }}</span>
    </div>
    <div class="time-controls" v-if="showPlayBtn">
      <button @click="togglePlay" class="play-btn">
        {{ isPlaying ? '暂停' : '播放' }}
      </button>
    </div>
  </div>
</template>

<script setup>
// 👉 关键修复：添加 onUnmounted 导入
import { ref, watch, defineProps, defineEmits, computed, onUnmounted } from 'vue'

// 定义属性（明确类型，增加默认值容错）
const props = defineProps({
  title: { type: String, default: '时间轴控制' },
  startTime: { type: Number, required: true, default: 0 },
  endTime: { type: Number, required: true, default: 0 },
  currentTime: { type: Number, required: true, default: 0 },
  step: { type: Number, default: 3600000 },
  showPlayBtn: { type: Boolean, default: true },
  playSpeed: { type: Number, default: 1000 }
});

// 定义事件
const emit = defineEmits(['timeChange']);

// 计算属性（确保是数字类型，容错NaN）
const startTimeStamp = computed(() => {
  return isNaN(props.startTime) ? Date.now() : props.startTime;
});
const endTimeStamp = computed(() => {
  return isNaN(props.endTime) ? Date.now() : props.endTime;
});
const currentTimeStamp = computed(() => {
  return isNaN(props.currentTime) ? Date.now() : props.currentTime;
});

// 播放状态
const isPlaying = ref(false);
let playTimer = null;

// 修复核心：先把时间戳转成Date对象，再格式化（增加容错）
const formatTime = (timeStamp) => {
  // 容错：如果不是数字/无效时间戳，返回默认值
  if (isNaN(timeStamp) || timeStamp <= 0) {
    return '2025-10-27 00:00:00';
  }
  // 时间戳转Date对象
  const date = new Date(timeStamp);
  // 格式化：YYYY-MM-DD HH:mm:ss
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
};

// 滑动条变化
const handleSliderChange = (e) => {
  const newTime = Number(e.target.value);
  emit('timeChange', newTime);
};

// 播放/暂停（适配10小时步长，到达结束时间停止）
const togglePlay = () => {
  if (isPlaying.value) {
    clearInterval(playTimer);
    isPlaying.value = false;
  } else {
    isPlaying.value = true;
    playTimer = setInterval(() => {
      let nextTime = currentTimeStamp.value + props.step;
      // 到达结束时间后停止播放
      if (nextTime > endTimeStamp.value) {
        clearInterval(playTimer);
        isPlaying.value = false;
        return;
      }
      emit('timeChange', nextTime);
    }, props.playSpeed);
  }
};

// 清理定时器（组件卸载时）
watch(() => isPlaying.value, (newVal) => {
  if (!newVal && playTimer) clearInterval(playTimer);
});

// 组件卸载时清理定时器（已导入 onUnmounted）
onUnmounted(() => {
  clearInterval(playTimer);
  isPlaying.value = false;
});

defineExpose({
  stopPlay: () => {
    clearInterval(playTimer);
    isPlaying.value = false;
  }
});
</script>

<style scoped>
.time-slider-container {
  background: rgba(0, 0, 0, 0.85);
  color: #fff;
  padding: 15px;
  border-radius: 8px;
  min-width: 300px;
  box-sizing: border-box;
}

.time-title {
  margin: 0 0 10px 0;
  font-size: 16px;
  font-weight: 500;
}

.time-info {
  margin: 10px 0;
  font-size: 14px;
  color: #f0f0f0;
}

.slider {
  width: 100%;
  margin: 15px 0;
  cursor: pointer;
  accent-color: #409eff;
}

.time-range {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #ccc;
  margin-bottom: 10px;
}

.time-controls {
  text-align: center;
}

.play-btn {
  background: #409eff;
  color: #fff;
  border: none;
  border-radius: 4px;
  padding: 4px 12px;
  cursor: pointer;
  font-size: 14px;
  transition: background 0.2s;
}

.play-btn:hover {
  background: #66b1ff;
}
</style>