<template>
    <el-dialog
        v-model="visible"
        :title="form.id ? '编辑弹窗' : '弹窗广告设置'"
        width="800px"
        destroy-on-close
        @closed="handleClose"
        top="5vh"
    >
        <el-form :model="form" ref="formRef" label-width="120px" :rules="rules">
            <el-form-item label="名称:" prop="name">
                <el-input v-model="form.name" placeholder="请输入" />
            </el-form-item>

            <el-form-item label="弹窗图片:" prop="img">
                <ImageUpload
                    v-model="form.img"
                    :limit="1"
                    :drag="true"
                    accept="image/*"
                    tips="建议尺寸200*350"
                />
            </el-form-item>

            <el-form-item label="跳转页面:" prop="jumpPage">
                <el-input v-model="form.jumpPage" placeholder="请输入" />
            </el-form-item>

            <el-form-item label="投放端:" prop="plat">
                <el-select
                    v-model="form.plat"
                    placeholder="请选择投放端"
                    style="width: 100%"
                >
                    <el-option label="微信" value="1" />
                    <el-option label="支付宝" value="2" />
                </el-select>
            </el-form-item>

            <el-form-item label="投放页面:" prop="deliveryPage">
                <el-select
                    v-model="form.deliveryPage"
                    placeholder="请选择投放页面"
                    style="width: 100%"
                >
                    <el-option label="首页" value="1" />
                    <el-option label="订单完成页" value="2" />
                    <el-option label="个人中心浮窗" value="3" />
                </el-select>
            </el-form-item>

            <el-form-item label="关闭设置:" prop="userClose">
                <div class="close-settings">
                    <el-checkbox
                        v-model="form.userClose"
                        true-value="1"
                        false-value="2"
                        >用户手动关闭</el-checkbox
                    >
                    <div class="auto-close-section">
                        <el-checkbox
                            v-model="form.autoClose"
                            true-value="1"
                            false-value="2"
                            >显示</el-checkbox
                        >
                        <el-select
                            v-model="form.autoCloseTime"
                            placeholder="5秒"
                            :disabled="form.autoClose == 2"
                            style="width: 100px"
                        >
                            <el-option label="5秒" :value="5" />
                            <el-option label="10秒" :value="10" />
                            <el-option label="15秒" :value="15" />
                            <el-option label="30秒" :value="30" />
                        </el-select>
                        <span class="auto-close-text">后自动关闭</span>
                    </div>
                </div>
            </el-form-item>

            <el-form-item label="出现频次:" prop="frequency">
                <el-radio-group v-model="form.frequency">
                    <div class="frequency-settings">
                        <el-radio value="1"
                            >首次访问时出现，之后不出现</el-radio
                        >
                        <div class="interval-section">
                            <el-radio value="2">间隔</el-radio>

                            <div style="display: flex; align-items: center">
                                <el-select
                                    v-model="form.frequencyTime"
                                    placeholder="24小时"
                                    :disabled="form.frequency == 1"
                                    style="width: 120px"
                                >
                                    <el-option label="24小时" :value="24" />
                                    <el-option label="48小时" :value="48" />
                                    <el-option label="72小时" :value="72" />
                                </el-select>
                                <div
                                    style="margin-left: 5px; width: fit-content"
                                    >后再次出现</div
                                >
                            </div>
                        </div>
                        <el-radio value="3">常驻</el-radio>
                    </div>
                </el-radio-group>
            </el-form-item>

            <el-form-item label="起止时间:" prop="timeRange">
                <el-date-picker
                    v-model="form.timeRange"
                    type="datetimerange"
                    range-separator="至"
                    start-placeholder="开始日期时间"
                    end-placeholder="结束日期时间"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    format="YYYY-MM-DD HH:mm:ss"
                    style="width: 100%"
                />
            </el-form-item>
        </el-form>

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="visible = false">取消</el-button>
                <el-button
                    type="primary"
                    @click="handleSubmit"
                    :loading="loading"
                >
                    {{ form.id ? '保存' : '创建' }}
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

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

    defineOptions({ name: 'DialogEdit' });

    const emit = defineEmits(['success']);
    const visible = ref(false);
    const loading = ref(false);
    const formRef = ref(null);

    let defaultForm = {
        id: '',
        name: '',
        jumpPage: '',
        plat: '',
        deliveryPage: '',
        userClose: '1',
        autoClose: '2',
        autoCloseTime: 5,
        frequency: '1',
        frequencyTime: 24,
        status: 1,
        timeRange: [],
        img: ''
    };

    // 表单数据
    const form = reactive(defaultForm);

    // 表单验证规则
    const rules = {
        name: [{ required: true, message: '请输入弹窗名称', trigger: 'blur' }],
        jumpPage: [
            { required: true, message: '请输入跳转页面', trigger: 'blur' }
        ],
        plat: [{ required: true, message: '请选择投放端', trigger: 'change' }],
        deliveryPage: [
            { required: true, message: '请选择投放页面', trigger: 'change' }
        ],
        timeRange: [
            { required: true, message: '请选择起止时间', trigger: 'change' }
        ],
        img: [{ required: true, message: '请上传弹窗图片', trigger: 'change' }],
        frequency: [
            { required: true, message: '请选择出现频次', trigger: 'change' }
        ]
    };

    // 打开弹窗
    function handleOpen(data) {
        // 重置表单为默认值
        Object.assign(form, defaultForm);

        // 如果有数据，则填充表单
        console.log(data, 'data');
        if (data) {
            // 设置基本字段
            form.id = data.id;
            form.img = data.img;
            form.name = data.name;
            form.jumpPage = data.jumpPage;
            form.plat = data.plat;
            form.deliveryPage = data.deliveryPage;
            form.userClose = data.userClose;
            form.autoClose = data.autoClose;
            form.autoCloseTime = data.autoCloseTime;
            form.frequency = data.frequency;
            form.frequencyTime = data.frequencyTime;
            console.log(form, 'xxx');

            // 设置时间范围
            if (data.startTime && data.endTime) {
                form.timeRange = [data.startTime, data.endTime];
            }
        }

        visible.value = true;
    }

    // 关闭弹窗
    function handleClose() {
        formRef.value?.resetFields();
    }

    // 提交表单
    function handleSubmit() {
        formRef.value?.validate((valid) => {
            if (!valid) return;

            loading.value = true;

            // 根据是否有ID决定是新增还是修改
            const url = form.id
                ? '/sys/dialogInfo/update'
                : '/sys/dialogInfo/add';

            // 构建符合API要求的参数对象
            const params = JSON.parse(JSON.stringify(form));
            params.startTime =
                form.timeRange && form.timeRange.length > 0
                    ? form.timeRange[0]
                    : '';
            params.endTime =
                form.timeRange && form.timeRange.length > 0
                    ? form.timeRange[1]
                    : '';
            params.status = 1;

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

    // 暴露方法给父组件调用
    defineExpose({
        handleOpen
    });
</script>

<style scoped>
    .close-settings {
        display: flex;
        align-items: center;
        gap: 20px;
    }

    .auto-close-section {
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .auto-close-text {
        margin-left: 5px;
    }

    .frequency-settings {
        display: flex;
        flex-direction: column;
        gap: 15px;
    }

    .interval-section {
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .dialog-footer {
        display: flex;
        justify-content: center;
        gap: 20px;
        margin-top: 20px;
    }
</style>
