<template>
    <div class="app-daterange">
        <label style="color:var(--el-text-color-regular)">报表类型</label>
        <el-select placeholder="请选择" v-model="selectedType" @change="onSelectChange">
            <el-option v-for="option in cycleTypes" :key="option.value" :value="option.value" :label="option.label" />
        </el-select>
        <el-date-picker :type="datePickerType" placeholder="请选择" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" v-model="selectedValue" />
    </div>
</template>

<script lang="ts" setup>
import { PropType, computed } from 'vue'
import { formatDate } from '@/filters'

const props = defineProps({
    cycleType: {
        type: Number,
        default: 0
    },
    dateValue: {
        type: Array as PropType<string[]>,
        default: () => ([])
    }
})

const emit = defineEmits(['update:cycleType', 'update:dateValue'])

const cycleTypes = [
    { label: '日报表', type: 'daterange', value: 5 },
    { label: '月报表', type: 'monthrange', value: 1 },
    { label: '年报表', type: 'monthrange', value: 3 }
]

// 日期选择器类型
const datePickerType = computed(() => {
    const item = cycleTypes.find((e) => e.value === props.cycleType)
    return item?.type ?? ''
})

// 当前选中的周期类型
const selectedType = computed({
    get: () => props.cycleType,
    set: (val) => emit('update:cycleType', val)
})

// 当前选中的日期值
const selectedValue = computed<string[]>({
    get: () => props.dateValue,
    set: (date) => {
        const [begindate, enddate] = date ?? []
        const value = []
        if (begindate && enddate) {
            switch (props.cycleType) {
                case 1: {
                    value[0] = formatDate(begindate, 'YYYYMM')
                    value[1] = formatDate(enddate, 'YYYYMM')
                    break
                }
                case 3: {
                    value[0] = formatDate(begindate, 'YYYY')
                    value[1] = formatDate(enddate, 'YYYY')
                    break
                }
                default: {
                    value[0] = formatDate(begindate, 'YYYYMMDD')
                    value[1] = formatDate(enddate, 'YYYYMMDD')
                }
            }
        }
        emit('update:dateValue', value)
    }
})

// 切换周期类型
const onSelectChange = () => {
    selectedValue.value = []
}
</script>

<style lang="less" scoped>
@import './index.less';
</style>