<script lang="ts" setup>
import dayjs from 'dayjs'

const emit = defineEmits<{ search: [] }>()

const startTime = defineModel<string>('startTime', { default: '' })
const endTime = defineModel<string>('endTime', { default: '' })

const activeShortcut = ref('')

const shortcuts = [
  {
    key: 'today',
    text: '今天',
    action: () => {
      const d = dayjs().format('YYYY-MM-DD')
      startTime.value = d
      endTime.value = d
    },
  },
  {
    key: '7d',
    text: '近7天',
    action: () => {
      startTime.value = dayjs().subtract(6, 'day').format('YYYY-MM-DD')
      endTime.value = dayjs().format('YYYY-MM-DD')
    },
  },
  {
    key: '30d',
    text: '近30天',
    action: () => {
      startTime.value = dayjs().subtract(29, 'day').format('YYYY-MM-DD')
      endTime.value = dayjs().format('YYYY-MM-DD')
    },
  },
  {
    key: 'semester',
    text: '本学期',
    action: () => {
      const m = dayjs().month()
      startTime.value = (m >= 1 && m <= 6 ? dayjs().month(1) : dayjs().month(7))
        .startOf('month')
        .format('YYYY-MM-DD')
      endTime.value = dayjs().format('YYYY-MM-DD')
    },
  },
]

function applyShortcut(s: (typeof shortcuts)[0]) {
  activeShortcut.value = s.key
  s.action()
  emit('search')
}

function onReset() {
  startTime.value = ''
  endTime.value = ''
  activeShortcut.value = ''
  emit('search')
}

const disabledStart = (d: Date) =>
  endTime.value ? dayjs(d).isAfter(dayjs(endTime.value), 'day') : false
const disabledEnd = (d: Date) =>
  startTime.value ? dayjs(d).isBefore(dayjs(startTime.value), 'day') : false
</script>

<template>
  <div class="flex flex-wrap items-center justify-between gap-4">
    <div class="flex gap-1.5">
      <button
        v-for="s in shortcuts"
        :key="s.key"
        type="button"
        class="rounded-full border px-4 py-1.5 text-sm font-medium transition-colors"
        :class="
          activeShortcut === s.key
            ? 'border-blue-500 bg-blue-500 text-white'
            : 'border-gray-200 text-gray-500 hover:border-blue-400 hover:text-blue-500'
        "
        @click="applyShortcut(s)"
      >
        {{ s.text }}
      </button>
    </div>
    <div class="flex items-center gap-2">
      <ElDatePicker
        v-model="startTime"
        type="date"
        placeholder="开始日期"
        format="YYYY-MM-DD"
        value-format="YYYY-MM-DD"
        :disabled-date="disabledStart"
        clearable
        style="width: 150px"
        @change="activeShortcut = ''"
      />
      <span class="text-gray-400">—</span>
      <ElDatePicker
        v-model="endTime"
        type="date"
        placeholder="结束日期"
        format="YYYY-MM-DD"
        value-format="YYYY-MM-DD"
        :disabled-date="disabledEnd"
        clearable
        style="width: 150px"
        @change="activeShortcut = ''"
      />
      <ElButton type="primary" @click="emit('search')">查询</ElButton>
      <ElButton @click="onReset">重置</ElButton>
    </div>
  </div>
</template>
