<template>
    <up-datetime-picker :show="show" v-model="innerValue" :mode="mode" :minDate="minDate" :maxDate="maxDate"
        closeOnClickOverlay :formatter="formatter" :confirmText="confirmText" :cancelText="cancelText"
        confirmColor="#ea002a" @confirm="handleConfirm" @cancel="handleClose" @close="handleClose" />
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import dayjs from "dayjs";
const { t } = useI18n()
const props = defineProps({
    modelValue: { type: [String, Number] },
    disabled: Boolean,
    show: Boolean,
    minDate: { type: Date, default: () => new Date(1920, 0, 1).getTime() },
    maxDate: { type: Date, default: () => new Date().getTime() },
});
function formatter(type, value) {
    if (type === 'year') {
        return `${value}${t('common.year')}`
    }
    if (type === 'month') {
        return `${value}${t('common.month')}`
    }
    if (type === 'day') {
        return `${value}${t('common.day')}`
    }
    return value
}

/** emits */
const emit = defineEmits<{
    (e: 'update:modelValue', value?: number): void
    (e: 'update:show', value: boolean): void
    (e: 'confirm', value: {
        timestamp: number
        formatted: string
        raw: any
    }): void
    (e: 'cancel'): void
}>()

/** v-model 代理 */
const innerValue = computed({
    get: () => dayjs(props.modelValue).valueOf() || new Date().getTime(),
    set: (value) => { emit('update:modelValue', value) }
})

/** 多语言 */
const confirmText = computed(() => t('common.confirm'))
const cancelText = computed(() => t('common.cancel'))

const minDate = computed(() =>
    props.minDate ?? new Date(1920, 0, 1).getTime()
)

const maxDate = computed(() =>
    props.maxDate ?? Date.now()
)


/** 关闭 */
function handleClose() {
    emit('update:show', false)
    emit('cancel')
}

/** 确认 */
function handleConfirm(e: any) {
    const { value } = e;
    const dateValue =
        typeof value === "number" ? value : new Date(value).getTime();
    const formatted = dayjs(dateValue).format("YYYY-MM-DD");
    emit('confirm', { formatted, ...e })
    emit('update:show', false)
}
</script>
