<template>
    <ele-page flex-table :bodyStyle="{ padding: 0 }">
        <div class="common-section">
            <div class="common-title mb-4">加价营销规则</div>
            <el-form :model="form" class="common-form" label-width="auto">
                <el-form-item label="加价比例：">
                    <ele-input
                        v-model="form.upsellRate"
                        placeholder="请输入"
                        suffixStr="(%)"
                    />
                </el-form-item>
                <el-form-item label="加价限制时间：">
                    <ele-input
                        v-model="form.inviteExpireHour"
                        placeholder="请输入"
                        suffixStr="(小时)"
                    />
                    <span class="ml-2 text-gray-500">以点击分享链接计算</span>
                </el-form-item>
                <el-form-item label="每人每种书可加价次数：">
                    <ele-input
                        v-model="form.upsellTimesPerIsbn"
                        placeholder="请输入"
                        suffixStr="(次)"
                    />
                </el-form-item>
                <el-form-item label="每个ID每天助力限制：">
                    <ele-input
                        v-model="form.assistTimesEveryDay"
                        placeholder="请输入"
                        suffixStr="(次)"
                    />
                </el-form-item>
                <el-form-item label="预留手机号：">
                    <ele-input v-model="form.mobile" placeholder="请输入" />
                    <el-button
                        v-if="requireMobileVerification"
                        type="primary"
                        size="default"
                        class="ml-2"
                        @click="getVerificationCode"
                        :disabled="cooldown > 0"
                    >
                        {{
                            cooldown > 0 ? `${cooldown}秒后重试` : '获取验证码'
                        }}
                    </el-button>
                </el-form-item>
                <el-form-item label="验证码：" v-if="needVerification">
                    <ele-input v-model="form.code" placeholder="请输入验证码" />
                </el-form-item>
                <el-form-item label="单本最高加价：">
                    <ele-input
                        v-model="form.maxPerIsbn"
                        placeholder="请输入"
                        suffixStr="(元)"
                    />
                </el-form-item>
                <el-form-item label="单本最低加价：">
                    <ele-input
                        v-model="form.minPerIsbn"
                        placeholder="请输入"
                        suffixStr="(元)"
                    />
                </el-form-item>
                <el-form-item label="加价结算场景：">
                    <el-select
                        v-model="form.upsellValidScenario"
                        multiple
                        style="width: 500px"
                        placeholder="请选择加价结算场景"
                    >
                        <el-option label="验货不合格（其他原因）" :value="2" />
                        <el-option label="验货合格" :value="1" />
                        <el-option label="验货不合格（无此书）" :value="3" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button
                        type="success"
                        style="
                            width: 100px;
                            margin-top: 100px;
                            margin-left: 50px;
                        "
                        plain
                        @click="onSubmit"
                        v-permission="'ipMarkup:rules:update'"
                        >保存</el-button
                    >
                </el-form-item>
            </el-form>
        </div>
    </ele-page>
</template>

<script setup>
    import { reactive, ref, onMounted, onUnmounted } from 'vue';
    import EleInput from '@/components/CommonPage/EleInput.vue';
    import { ElMessage } from 'element-plus';
    import request from '@/utils/request';

    const form = reactive({
        upsellRate: '',
        inviteExpireHour: '',
        upsellTimesPerIsbn: '',
        assistTimesEveryDay: '',
        mobile: '',
        maxPerIsbn: '',
        minPerIsbn: '',
        upsellValidScenario: [],
        code: ''
    });

    const cooldown = ref(0);
    const needVerification = ref(false);
    const requireMobileVerification = ref(true);
    let timer = null;

    // 获取当前设置
    function getRules() {
        request.get('/activity/upsell/manage/rule/get').then((res) => {
            if (res.data.code === 200) {
                const data = res.data.data;
                form.upsellRate = data.upsellRate;
                form.inviteExpireHour = data.inviteExpireHour;
                form.upsellTimesPerIsbn = data.upsellTimesPerIsbn;
                form.assistTimesEveryDay = data.assistTimesEveryDay;
                form.maxPerIsbn = data.maxPerIsbn;
                form.minPerIsbn = data.minPerIsbn;
                form.upsellValidScenario = data.upsellValidScenario;

                // 检查是否有mobile字段
                if (data.mobile) {
                    form.mobile = data.mobile;
                    requireMobileVerification.value = true;
                } else {
                    form.mobile = '';
                    requireMobileVerification.value = false;
                    // 如果不需要验证，则重置验证状态
                    needVerification.value = false;
                }
            } else {
                ElMessage.error(res.data.msg);
            }
        });
    }

    // 获取验证码
    const getVerificationCode = () => {
        if (!form.mobile) {
            ElMessage.warning('请输入手机号');
            return;
        }

        request
            .post('/activity/upsell/manage/rule/getCode', {
                mobile: form.mobile
            })
            .then((res) => {
                if (res.data.code === 200) {
                    ElMessage.success('验证码已发送');
                    needVerification.value = true;
                    startCooldown();
                } else {
                    ElMessage.error(res.data.msg);
                }
            });
    };

    // 开始倒计时
    const startCooldown = () => {
        cooldown.value = 60;
        if (timer) clearInterval(timer);
        timer = setInterval(() => {
            if (cooldown.value > 0) {
                cooldown.value--;
            } else {
                clearInterval(timer);
                timer = null;
            }
        }, 1000);
    };

    // 保存设置
    const onSubmit = () => {
        // 验证表单
        if (requireMobileVerification.value) {
            if (!form.mobile) {
                ElMessage.warning('请输入预留手机号');
                return;
            }

            if (needVerification.value && !form.code) {
                ElMessage.warning('请输入验证码');
                return;
            }
        }

        const requestData = {
            upsellRate: form.upsellRate,
            inviteExpireHour: form.inviteExpireHour,
            upsellTimesPerIsbn: form.upsellTimesPerIsbn,
            assistTimesEveryDay: form.assistTimesEveryDay,
            maxPerIsbn: form.maxPerIsbn,
            minPerIsbn: form.minPerIsbn,
            mobile: form.mobile,
            code: form.code,
            upsellValidScenario: form.upsellValidScenario
        };

        // 只有在需要验证的情况下才添加mobile和code字段
        if (requireMobileVerification.value) {
            requestData.mobile = form.mobile;
            requestData.code = form.code;
        }

        request
            .post('/activity/upsell/manage/rule/update', requestData)
            .then((res) => {
                if (res.data.code === 200) {
                    ElMessage.success('保存成功');
                    needVerification.value = false;
                    form.code = '';
                } else {
                    ElMessage.error(res.data.msg);
                }
            });
    };

    onMounted(() => {
        getRules();
    });

    // 组件销毁时清理定时器
    onUnmounted(() => {
        if (timer) {
            clearInterval(timer);
            timer = null;
        }
    });
</script>
