<!-- 新增/编辑分享降价活动弹窗 -->
<template>
    <ele-modal form :width="560" v-model="visible" :title="title">
        <SimpleForm
            :items="formItems"
            labelWidth="100px"
            ref="formRef"
            :initKeys="formData"
        />
        <template #footer>
            <el-button @click="handleCancel">关闭</el-button>
            <el-button type="primary" @click="handleSubmit">确定</el-button>
        </template>
    </ele-modal>
</template>

<script setup>
    import { reactive, ref, computed, nextTick } from 'vue';
    import SimpleForm from '@/components/CommonPage/SimpleForm.vue';
    import request from '@/utils/request';
    import { EleMessage } from 'ele-admin-plus/es';

    const emit = defineEmits(['success']);

    /** 弹窗是否打开 */
    const visible = ref(false);

    /** 表单标题 */
    const title = ref('新增活动');

    /** 表单引用 */
    const formRef = ref();

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

    /** 表单数据 */
    const formData = reactive({
        activityName: '',
        startTime: '',
        endTime: '',
        limitFirst: '0',
        timeRange: [],
        activityId: ''
    });

    /** 表单项配置 */
    const formItems = computed(() => {
        return [
            {
                type: 'input',
                label: '活动名称',
                prop: 'activityName',
                required: true
            },
            {
                type: 'datetimerange',
                label: '活动时间',
                required: true,
                prop: 'timeRange',
                props: {
                    format: 'YYYY-MM-DD HH:mm:ss',
                    valueFormat: 'YYYY-MM-DD HH:mm:ss',
                    rangeSeparator: '至'
                }
            },
            {
                type: 'radio',
                label: '限制首单',
                prop: 'limitFirst',
                options: [
                    { label: '是', value: '1' },
                    { label: '否', value: '0' }
                ],
                required: true
            }
        ];
    });

    /** 弹窗打开事件 */
    function handleOpen(data = {}) {
        visible.value = true;
        title.value = data && data.id ? '编辑活动' : '新增活动';

        // 重置表单数据
        for (const key in formData) {
            formData[key] = '';
        }

        // 设置默认值
        formData.limitFirst = '0';

        // 如果是编辑模式，合并数据
        if (data && data.id) {
            Object.assign(formData, data);
            formData.activityId = data.id;
            // 接口返回的 limitFirst 是 string '0' or '1'
            formData.limitFirst = String(data.limitFirst);
            formData.timeRange = [data.startTime, data.endTime];
        }

        nextTick(() => {
            formRef.value?.setData(formData);
        });
    }

    /** 提交表单 */
    function handleSubmit() {
        formRef.value?.submitForm().then((data) => {
            const url = formData.activityId
                ? '/activity/activityReduceInfo/update'
                : '/activity/activityReduceInfo/add';

            let params = {
                ...data,
                activityId: formData.activityId,
                startTime: data.timeRange[0],
                endTime: data.timeRange[1]
            };
            delete params.timeRange;

            request.post(url, params).then((res) => {
                if (res.data.code === 200) {
                    EleMessage.success('保存成功');
                    visible.value = false;
                    emit('success');
                } else {
                    EleMessage.error(res.data.msg || '保存失败');
                }
            });
        });
    }

    defineExpose({ handleOpen });
</script>
