<script lang="ts" setup>
import Times from '@/common/utils/times.ts'

const props = withDefaults(
  defineProps<{
    changeHandler?: () => void
    modelValue: [ string | undefined, string | undefined ] | undefined | null
    type?: 'year' | 'years' | 'month' | 'months' | 'date' | 'dates' | 'week' | 'datetime' | 'datetimerange' | 'daterange' | 'monthrange' | 'yearrange'
  }>(),
  {
    type: 'datetimerange',
    changeHandler: () => {
    },
  },
)

const emits = defineEmits([ 'update:modelValue' ])
const times = computed({
  get: () => (props.modelValue == null || props.modelValue.length !== 2 || props.modelValue[0] == null || props.modelValue[1] == null) ? null : [ Times.parse(props.modelValue[0]).toJSDate(), Times.parse(props.modelValue[1]).toJSDate() ],
  set: (val) => {
    emits('update:modelValue', val == null ? [ undefined, undefined ] : val.map((item) => item == null ? null : Times.format(item)))
  },
})


const createTimeDefaultTime: [ Date, Date ] = [
  Times.toDate(Times.beginOfDay()),
  Times.toDate(Times.endOfDay()),
]
const shortcuts = [
  {
    text: '今天',
    value: () => [ Times.toDate(Times.beginOfDay()), Times.toDate(Times.endOfDay()) ],
  },
  {
    text: '昨天',
    value: () => {
      const time = Times.now().minus({day: 1})
      return [ Times.toDate(Times.beginOfDay(time)), Times.toDate(Times.endOfDay(time)) ]
    },
  },
  {
    text: '本周',
    value: () => {
      return [ Times.toDate(Times.beginOfWeek()), Times.toDate(Times.endOfWeek()) ]
    },
  },
  {
    text: '本月',
    value: () => {
      return [ Times.toDate(Times.beginOfMonth()), Times.toDate(Times.endOfMonth()) ]
    },
  },
  {
    text: '今年',
    value: () => {
      return [ Times.toDate(Times.beginOfYear()), Times.toDate(Times.endOfYear()) ]
    },
  },
]
</script>

<template>
  <ElDatePicker
    v-model="times"
    :default-time="createTimeDefaultTime"
    :shortcuts="shortcuts"
    clearable
    end-placeholder="结束时间"
    start-placeholder="开始时间"
    :type="type"
    @change="changeHandler"
  />
</template>

<style lang="stylus" scoped>

</style>
