<!-- 一键更新弹窗 -->
<template>
    <ele-modal
        form
        :width="440"
        v-model="visible"
        title="一键更新"
        @open="handleOpen"
    >
        <SimpleForm
            :items="items"
            labelWidth="80px"
            ref="formRef"
            :initKeys="form"
        />
        <template #footer>
            <el-button @click="handleCancel">取消</el-button>
            <el-button type="primary" @click="handleSubmit">确定</el-button>
        </template>
    </ele-modal>
</template>

<script setup>
    import { ref, reactive, nextTick } from 'vue';
    import SimpleForm from '@/components/CommonPage/SimpleForm.vue';
    import dayjs from 'dayjs';

    /** 弹窗是否打开 */
    const visible = defineModel({ type: Boolean });

    /** 关闭弹窗 */
    const handleCancel = () => {
        visible.value = false;
        nextTick(() => {
            formRef.value?.resetForm();
        });
    };

    const form = ref({
        alarmType: null,
        reloadTime: ''
    });

    // 获取当天凌晨3点的时间
    const getTodayThreeAM = () => {
        const now = dayjs();
        const today3AM = dayjs().hour(3).minute(0).second(0);
        // 如果当前时间已经过了今天3点，则返回明天3点
        return now.isAfter(today3AM) ? today3AM.add(1, 'day') : today3AM;
    };

    /** 弹窗打开事件 */
    const handleOpen = () => {
        visible.value = true;
        nextTick(() => {
            form.value.reloadTime = getTodayThreeAM().format(
                'YYYY-MM-DD HH:mm:ss'
            );
            formRef.value?.setData(form.value);
        });
    };

    const items = reactive([
        {
            label: '更新时间',
            prop: 'reloadTime',
            type: 'datetime',
            required: true,
            props: {
                placeholder: '请选择更新时间',
                format: 'YYYY-MM-DD HH:mm:ss',
                valueFormat: 'YYYY-MM-DD HH:mm:ss',
                disabledDate: (time) => {
                    return time.getTime() < Date.now() - 8.64e7; // 不能选择今天之前的日期
                }
            }
        }
    ]);

    const formRef = ref();

    const emit = defineEmits(['submit']);
    const handleSubmit = () => {
        formRef.value?.submitForm().then((data) => {
            emit('submit', data);
            visible.value = false;
        });
    };

    defineExpose({
        handleOpen
    });
</script>
