<template>
  <div>
    <el-date-picker
      v-model="dateRange"
      type="daterange"
      unlink-panels
      range-separator="To"
      start-placeholder="开始日期"
      end-placeholder="结束日期"
      :shortcuts="shortcuts"
      size="default"
      value-format="YYYY-MM-DD"
      :disabled-date="disabledDate"
      :clearable="false"
      :popper-options="{placement: props.popperPlacement}"
      @change="changedValue"
      style="border-radius: 0;"
    />
  </div>
</template>

<script lang="ts">
import { useShopInfo } from '/@/stores/shopInfo'
const timezoneDefault = useShopInfo().profile.time_zone
export default {}
</script>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import dayjs, { Dayjs } from 'dayjs'

defineOptions({
  name: 'DateRangePicker'
})

const props = defineProps({
  modelValue: {type: Array, required: true },
  timezone: { type: String, default: timezoneDefault },
  popperPlacement: { type: String, default: 'bottom-start' }
})

const dateRange = ref(props.modelValue)
const emits = defineEmits(['update:modelValue', 'change'])
const changedValue = (newVal: string[]) => {
  emits('update:modelValue', newVal)
  emits('change', newVal)
}

function disabledDate(datetime: Date) {
  const now = dayjs(new Date()).tz(props.timezone)
  const now_tz = now.startOf("day")
  return now_tz.isBefore(dayjs(datetime).tz(props.timezone))
}

function tzFormat(dt_tz: Dayjs) {
  return dt_tz.format("YYYY-MM-DD HH:mm:ss")
}

function recentDays(days: number):string[] {
  const now_tz = dayjs(new Date()).tz(props.timezone)
  const start = now_tz.subtract(days, 'day')
  const end = now_tz.subtract(1, 'day')
  return [tzFormat(start), tzFormat(end)]
}

function currentWeekMonthYear(dim: 'month'|'week'|'year'): string[] {
  const end = dayjs(new Date()).tz(props.timezone)
  const start = end.startOf(dim)
  return [tzFormat(start), tzFormat(end)]
}

function lastWeekMonthYear(dim: 'month'|'week'|'year'): string[] {
  const last = dayjs(new Date()).tz(props.timezone).subtract(1, dim)
  return [tzFormat(last.startOf(dim)), tzFormat(last.endOf(dim))]
}

const shortcuts = [
  {
    text: '今天',
    value: () => {
      const now_tz = dayjs(new Date()).tz(props.timezone)
      return [tzFormat(now_tz), tzFormat(now_tz)]
    },
  },
  {
    text: '昨天',
    value: () => recentDays(1)
  },
  {
    text: '最近7天',
    value: () => recentDays(7)
  },
  {
    text: '最近15天',
    value: () => recentDays(15)
  },
  {
    text: '最近30天',
    value: () => recentDays(30)
  },
  {
    text: '本周',
    value: () => currentWeekMonthYear('week')
  },
  {
    text: '上周',
    value: () => lastWeekMonthYear('week')
  },
  {
    text: '本月',
    value: () => currentWeekMonthYear('month')
  },
  {
    text: '上月',
    value: () => lastWeekMonthYear('month')
  },
  {
    text: '本年',
    value: () => currentWeekMonthYear('year')
  }
]
</script>

<style scoped>

</style>
