<script lang="ts" setup>
import { h, onMounted, ref, watch } from 'vue';
import { NButton, NSelect, NSpace } from 'naive-ui';
import { Pause } from '@vicons/ionicons5';
import { PlayCircle48Regular } from '@vicons/fluent';
import { create3D } from '@/api/utils/cesium';

let viewer: any = null;
const range = ref<any>();
const serarchData = ref({
  username: '',
  startTime: '',
  endTime: ''
});
const value = ref(null);
const options = [
  {
    label: '李四',
    value: '1'
  },
  {
    label: '王五',
    value: '2'
  },
  {
    label: '赵六',
    value: '3'
  }
];

// 进度条相关状态
const progress = ref(0);
const isPlaying = ref(false);
const currentTime = ref('00:00:00');
const totalTime = ref('00:00:00');
const speed = ref('1');
const speedOptions = [
  { label: '0.5x', value: '0.5' },
  { label: '1x', value: '1' },
  { label: '2x', value: '2' },
  { label: '4x', value: '4' }
];
let progressInterval: number | null = null;
const totalSeconds = ref(3600); // 默认总时长1小时
const elapsedSeconds = ref(0);

// 格式化秒数为时分秒
function formatTime(seconds: number): string {
  const h = Math.floor(seconds / 3600)
    .toString()
    .padStart(2, '0');
  const m = Math.floor((seconds % 3600) / 60)
    .toString()
    .padStart(2, '0');
  const s = (seconds % 60).toString().padStart(2, '0');
  return `${h}:${m}:${s}`;
}

// 更新进度
function updateProgress() {
  if (elapsedSeconds.value >= totalSeconds.value) {
    pauseProgress();
    elapsedSeconds.value = totalSeconds.value;
  }

  progress.value = (elapsedSeconds.value / totalSeconds.value) * 100;
  currentTime.value = formatTime(elapsedSeconds.value);
  totalTime.value = formatTime(totalSeconds.value);

  // 这里可以添加更新3D场景中人员位置的逻辑
}

// 开始进度
function startProgress() {
  if (isPlaying.value) return;

  isPlaying.value = true;
  const speedValue = Number.parseFloat(speed.value);

  progressInterval = window.setInterval(() => {
    elapsedSeconds.value += 1 * speedValue;
    updateProgress();
  }, 1000 / speedValue);
}

// 暂停进度
function pauseProgress() {
  if (!isPlaying.value) return;

  isPlaying.value = false;
  if (progressInterval) {
    clearInterval(progressInterval);
    progressInterval = null;
  }
}

// 监听倍速变化
watch(speed, () => {
  if (isPlaying.value) {
    pauseProgress();
    startProgress();
  }
});

// 在脚本部分添加计算时间差的函数
function getTimeDifference() {
  if (!serarchData.value.startTime || !serarchData.value.endTime) {
    return '';
  }
  const startTime = new Date(serarchData.value.startTime);
  const endTime = new Date(serarchData.value.endTime);
  const diffMs = endTime.getTime() - startTime.getTime();

  // 计算天、时、分
  const days = Math.floor(diffMs / (1000 * 60 * 60 * 24));
  const hours = Math.floor((diffMs % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  const minutes = Math.floor((diffMs % (1000 * 60 * 60)) / (1000 * 60));

  if (days > 0) {
    return `${days}天${hours}小时${minutes}分`;
  } else if (hours > 0) {
    return `${hours}小时${minutes}分`;
  }
  return `${minutes}分`;
}
function formatDateTime(date: any) {
  if (!date) return '';
  const d = new Date(date);
  return d.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
}

// 监听时间范围变化
function watchTimeData(newRange: any) {
  if (newRange && newRange.length === 2) {
    serarchData.value.startTime = newRange[0];
    serarchData.value.endTime = newRange[1];
    const startDate = new Date(newRange[0]);
    const endDate = new Date(newRange[1]);

    // 计算总时长（毫秒转秒）
    const durationMs = endDate.getTime() - startDate.getTime();
    totalSeconds.value = Math.floor(durationMs / 1000);
    elapsedSeconds.value = 0;
    updateProgress();
  }
}

function add3dtiles() {
  const CesiumConfig = {
    defaultAccessToken:
      'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI2NTE1OTUxOS1jNTc5LTQwNmMtOWU5My1jNTI3NTIyYzAxNTUiLCJpZCI6MjUwODM5LCJpYXQiOjE3Mjk5MjE1MzV9.xromwPD3oA1e0YsWV035DE5KmYvivkC6fxt344vwObA'
  };

  Cesium.Ion.defaultAccessToken = CesiumConfig.defaultAccessToken;

  viewer = new Cesium.Viewer('cesiumcontainer', {
    geocoder: false,
    homeButton: false,
    infoBox: false,
    animation: false,
    fullscreenButton: false,
    enableCompass: true, // 启用指南针
    enableCompassOuterRing: true, // 启用指南针外环
    sceneModePicker: false,
    timeline: false,
    navigationHelpButton: false,
    baseLayerPicker: false,
    enableZoomControls: false, // 禁用缩放控件
    enableDistanceLegend: false // 禁用比例尺
  });

  viewer.scene.globe.depthTestAgainstTerrain = true;
  viewer.scene.globe.depthTestAgainstTerrain = true;
  viewer.cesiumWidget.creditContainer.style.display = 'none';
  viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);

  const url = 'http://192.168.3.249:9995/model/2025-04-22_11-28-19/terra_b3dms/tileset.json';

  create3D(viewer, url, 80);
}

function handleclear() {
  serarchData.value.startTime = '';
  serarchData.value.endTime = '';
}

function handleSearch() {
  // 这里可以添加查询逻辑
  console.log('搜索参数:', serarchData.value);
}

function handleReset() {
  range.value = null;
  handleclear();
}

onMounted(() => {
  add3dtiles();
  updateProgress();
});
</script>

<template>
  <div class="track-page">
    <div style="margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center">
      <NSpace>
        <div style="display: flex; align-items: center">
          人员姓名
          <NSpace vertical style="width: 200px; margin-left: 10px">
            <NSelect v-model:value="value" :options="options" />
          </NSpace>
        </div>
        <div style="display: flex; align-items: center; margin-left: 30px">
          <NDatePicker
            v-model:value="range"
            type="datetimerange"
            clearable
            style="margin-left: 10px"
            @update:value="watchTimeData"
            @clear="handleclear"
          />
        </div>

        <NButton color="#2198f2" style="padding: 0px 17px; border-radius: 5px; margin-left: 40px" @click="handleSearch">
          查询
        </NButton>
        <NButton style="padding: 0px 17px; border-radius: 5px" @click="handleReset">重置</NButton>
      </NSpace>
    </div>

    <!-- cesium -->
    <div id="cesiumcontainer">
      <div class="progress-container">
        <!-- 添加开始和结束时间显示 -->
        <div class="time-range-display">
          <div class="start-time">{{ formatDateTime(serarchData.startTime) }}</div>
          <div class="end-time">{{ formatDateTime(serarchData.endTime) }}</div>
        </div>
        <div class="progress-controls">
          <!-- 左侧控制按钮 -->
          <div class="left-controls">
            <NIcon class="control-btn" size="35px" @click="isPlaying ? pauseProgress() : startProgress()">
              <component :is="isPlaying ? Pause : PlayCircle48Regular" />
            </NIcon>
          </div>
          <!-- 右侧倍速选择 -->
          <div class="right-controls">
            <span class="time-diff">{{ getTimeDifference() }}</span>
            <NSelect v-model:value="speed" :options="speedOptions" style="width: 80px; margin-left: 10px" />
          </div>
        </div>
        <!-- 进度条 -->
        <div class="progress-bar">
          <div class="progress-fill" :style="{ width: progress + '%' }"></div>
          <div class="progress-text">{{ Math.round(progress) }}%</div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
#home {
  width: 100%;
  height: 100%;
}

#cesiumcontainer {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
  box-sizing: border-box;
  contain: strict;
  isolation: isolate;
}

.progress-container {
  width: 100%;
  height: 90px;
  background: rgba(0, 0, 0, 0.514);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.274);
  position: fixed;
  z-index: 100;
  bottom: 0;
}

.time-range-display {
  height: 31px;
  display: flex;
  justify-content: space-between;
  padding: 10px 190px 0px 80px;
  color: #e8e8e7;
  font-size: 14px;
}

.start-time {
  text-align: left;
}

.end-time {
  text-align: right;
}

.progress-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  padding: 0 20px;
}

.left-controls {
}

.right-controls {
  display: flex;
  align-items: center;
}

.time-diff {
  color: #e8e8e7;
  font-size: 14px;
  margin-right: 3px;
}

.control-btn {
  border: none;
  color: white;
  font-size: 16px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.time-display {
  display: flex;
  align-items: center;
  gap: 5px;
}

.time-text {
  color: #a0c8ff;
  font-size: 14px;
  font-weight: 500;
  min-width: 70px;
  text-align: center;
}

.time-separator {
  color: #a0c8ff;
}

.progress-bar {
  width: 86%;
  height: 20px;
  background: #909090;
  border-radius: 15px;
  overflow: hidden;
  margin: 0 auto;
  position: relative;
  cursor: pointer;
  left: -55px;
  bottom: 40px;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #00c6ff, #0072ff);
  transition: width 0.3s ease;
  border-radius: 15px;
  box-shadow: 0 0 15px rgba(0, 114, 255, 0.5);
}

.progress-text {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: white;
  font-weight: bold;
  font-size: 14px;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
}
</style>
