<template>
  <a-form-item label="" class="table-search-item">
    <a-select :value="props.cycleType" @change="changeType">
      <a-select-option value="date">日报</a-select-option>
      <a-select-option value="month">月报</a-select-option>
      <a-select-option value="year">年报</a-select-option>
    </a-select>
  </a-form-item>
  <a-space direction="vertical" :size="12">
    <a-range-picker v-if="props.cycleType === 'date'" v-model:value="vdata.date" :disabled-date="disabledDate" @change="changeDate" />
    <a-range-picker v-else-if="props.cycleType === 'month'" v-model:value="vdata.date" picker="month" @change="changeDate" />
    <a-range-picker v-else-if="props.cycleType === 'year'" v-model:value="vdata.date" picker="year" @change="changeDate" />
  </a-space>
</template>
<script setup lang="ts">
import { reactive, onMounted, watch } from 'vue'
import dayjs, { Dayjs } from 'dayjs'
const emit = defineEmits(['changeDate', 'changeDateType'])

const disabledDate = (current: Dayjs) => {
  return current && current > dayjs().subtract(1).startOf('day')
}

const props = defineProps({
  cycleType: { type: String, default:'date' },
  date: { type: String, default: '' }
})

const vdata = reactive({
  type: '日报',
  cycleType: 'date',//周期类型
  date: [] as any,
  startDate: dayjs().subtract(30, 'day'),
  endDate: dayjs().subtract(1, 'day')
})
onMounted(() => {
  if (!props.date) {
    vdata.date = [dayjs(vdata.startDate, 'YYYY-MM-DD'), dayjs(vdata.endDate, 'YYYY-MM-DD')]
  }
})

// 重置按钮，不能直接重置时间选择，需要通过watch监听，进行重置
watch( () => props.date ,(newVal,oldVal)=>{
  if (!props.date) {
    vdata.date = []
  }
})

function changeType(e) {
  vdata.cycleType = e
  vdata.date = []
  emit('changeDateType', vdata.cycleType)
  // 清空时间具体值，保留时间类型
  emit('changeDate', { timeParams: '' })
}

function changeDate(e) {
  let unit = vdata.cycleType
  if (vdata.cycleType == 'date') {
    unit = 'day'
  }

  let start = e[0].startOf(unit).format('YYYY-MM-DD HH:mm:ss')
  let end = e[1].endOf(unit).format('YYYY-MM-DD HH:mm:ss')

  let timeParameter = 'customDateTime_' + start + '_' + end
  let dateObject = reactive({
    startDate: start,
    endDate: end,
    timeParams: timeParameter
  })
  emit('changeDate', dateObject)
}
</script>