<script setup lang="ts">
import {
  Play as PlayIcon,
  Pause as PauseIcon,
  Refresh as ResetIcon,
} from '@vicons/ionicons5'
import { Ship as ShipIcon } from '@vicons/tabler'
import { h } from 'vue'
import type { VNode } from 'vue'
import Panel from '@/components/Panel/index.vue'
import { useMBTrajectory } from './hooks/mbTraj'

const {
  mbData,
  showOrHideHisTraj,
  times,
  loadHisTraj,
  customElapsedTime,
  isAnimationRunning,
  isPaused,
  play,
  pause,
  reset,
  animationSpeed,
  isFollow,
  changeTime,
} = useMBTrajectory()

const timeRange = ref<string[]>()

const rangeShortcuts = {
  近一天: () => {
    const cur = new Date().getTime()
    return [cur - 24 * 60 * 60 * 1000, cur]
  },
  近一周: () => {
    const cur = new Date().getTime()
    return [cur - 7 * 24 * 60 * 60 * 1000, cur]
  },
  近一月: () => {
    const cur = new Date().getTime()
    return [cur - 30 * 24 * 60 * 60 * 1000, cur]
  },
  近一年: () => {
    const cur = new Date().getTime()
    return [cur - 365 * 24 * 60 * 60 * 1000, cur]
  },
}

// const timeArray = [time, time + 3 * 60 * 60 * 1000]
const timelineValue = ref<number>(0)

watch(customElapsedTime, () => {
  timelineValue.value =
    times.value[0] + Math.floor(customElapsedTime.value * 1000)
})

const updateTimeline = (val: number) => {
  console.log((new Date(val).getTime() - times.value[0]) / 1000)
  changeTime((new Date(val).getTime() - times.value[0]) / 1000)
}

const marks = ref({})

const speedOptions = [
  {
    label: 1,
    value: 1,
  },
  {
    label: 5,
    value: 5,
  },
  {
    label: 10,
    value: 10,
  },
  {
    label: 20,
    value: 20,
  },
]
watch(times, timeArray => {
  const segments = divideTimeRangeIntoFiveParts(
    timeArray[0],
    timeArray[timeArray.length - 1]
  )
  marks.value = segments.reduce<{ [key: string]: VNode }>((acc, cur, index) => {
    // console.log(new Date(cur).toLocaleString())
    acc[cur] = h('div', { class: 'text-center' }, [
      h('div', { class: 'text-xs' }, new Date(cur).toLocaleDateString()),
      h('div', { class: 'text-xs' }, new Date(cur).toLocaleTimeString()),
      h(
        'div',
        { class: 'text-xs' },
        index === 0 ? '开始' : index === segments.length - 1 ? '结束' : ''
      ),
    ])
    return acc
  }, {})
})
function divideTimeRangeIntoFiveParts(
  startTime: number,
  endTime: number
): number[] {
  const totalDuration = endTime - startTime
  const segmentDuration = totalDuration / 5
  const segments = [startTime]
  for (let i = 0; i < 5; i++) {
    const end = startTime + (i + 1) * segmentDuration
    segments.push(end)
  }
  return segments
}
</script>

<template>
  <div>
    <panel
      :title="`${mbData.targetName}轨迹回放`"
      showClose
      :closeClick="showOrHideHisTraj"
    >
      <div class="flex h-full flex-col justify-center">
        <div>
          <div class="flex items-center gap-2">
            <n-date-picker
              v-model:formatted-value="timeRange"
              clearable
              type="datetimerange"
              :shortcuts="rangeShortcuts"
              :update-value-on-close="true"
              format="yyyy-MM-dd HH:mm:ss"
            />
            <n-button type="primary" @click="loadHisTraj(mbData.id, timeRange)">
              加载轨迹
            </n-button>
            <n-divider vertical />
            <div class="flex items-center">
              <label class="w-[48px]">速度：</label
              ><n-select
                class="w-[100px]"
                v-model:value="animationSpeed"
                :options="speedOptions"
              >
              </n-select>
            </div>
            <div class="flex items-center">
              <label class="w-[48px]">跟随：</label>
              <n-switch v-model:value="isFollow" />
            </div>
          </div>
        </div>
        <n-empty class="m-auto flex" v-if="times.length < 2"></n-empty>
        <div v-else class="flex flex-1 gap-2 pt-14">
          <n-button
            tertiary
            circle
            @click="pause"
            v-show="isAnimationRunning && !isPaused"
          >
            <template #icon>
              <n-icon><pause-icon /></n-icon>
            </template>
          </n-button>
          <n-button
            tertiary
            circle
            @click="play"
            v-show="!isAnimationRunning || isPaused"
          >
            <template #icon>
              <n-icon><play-icon /></n-icon>
            </template>
          </n-button>
          <n-button tertiary circle @click="reset">
            <template #icon>
              <n-icon><reset-icon /></n-icon>
            </template>
          </n-button>
          <n-slider
            class="px-10"
            v-model:value="timelineValue"
            show-tooltip
            :format-tooltip="value => new Date(value).toLocaleString()"
            :step="1000"
            :min="times[0]"
            :max="times[times.length - 1]"
            :marks="marks"
            @update:value="updateTimeline"
          >
            <template #thumb>
              <n-icon-wrapper :size="24" :border-radius="12">
                <n-icon :size="18" :component="ShipIcon" />
              </n-icon-wrapper>
            </template>
          </n-slider>
        </div>
      </div>
    </panel>
  </div>
</template>
