<template>
    <ele-page flex-table>
        <ele-card flex-table header="异常签收设置">
            <el-form
                ref="formRef"
                style="max-width: 520px"
                :model="form"
                :rules="rules"
                label-width="160px"
            >
                <el-form-item label="每人每日异常签收限量" prop="maxSignPerNum">
                    <el-input v-model="form.maxSignPerNum">
                        <template #append>次</template>
                    </el-input>
                </el-form-item>
                <el-form-item label="每日异常签收限量" prop="maxSignDayNum">
                    <el-input v-model="form.maxSignDayNum">
                        <template #append>次</template>
                    </el-input>
                </el-form-item>
                <el-form-item label="预留手机号" prop="mobile">
                    <el-input v-model="form.mobile" :maxlength="11" />
                </el-form-item>
                <el-form-item label="手机验证码" prop="code">
                    <div style="display: flex">
                        <el-input
                            v-model="form.code"
                            placeholder="请输入验证码"
                            style="flex: 1"
                        />
                        <el-button
                            type="primary"
                            :disabled="countdown > 0"
                            style="margin-left: 10px; width: 120px"
                            @click="sendVerificationCode"
                        >
                            {{
                                countdown > 0
                                    ? `${countdown}秒后重发`
                                    : '发送验证码'
                            }}
                        </el-button>
                    </div>
                </el-form-item>
                <el-form-item>
                    <el-button
                        style="min-width: 100px"
                        type="primary"
                        @click="submitForm(formRef)"
                        v-permission="'recycleLogistics:abnormalSetting:update'"
                    >
                        确认修改
                    </el-button>
                </el-form-item>
            </el-form>
        </ele-card>
    </ele-page>
</template>

<script setup>
    import { ElMessage } from 'element-plus';
    import { getCurrentInstance, ref, reactive, onMounted } from 'vue';
    const { proxy } = getCurrentInstance();

    const formRef = ref(null);
    const countdown = ref(0);
    const form = reactive({
        maxSignPerNum: '',
        maxSignDayNum: '',
        mobile: '',
        code: ''
    });

    // 表单验证规则
    const rules = {
        mobile: [
            {
                pattern: /^1[3-9]\d{9}$/,
                message: '请输入正确的手机号格式',
                trigger: 'blur'
            }
        ],
        code: [
            { required: true, message: '请输入验证码', trigger: 'blur' },
            { pattern: /^\d{6}$/, message: '验证码格式不正确', trigger: 'blur' }
        ]
    };

    // 获取设置数据
    const getSettings = async () => {
        const res = await proxy.$http.get(
            '/order/ordersign/routeExceptionSignQuery'
        );
        if (res.data?.code === 200) {
            const { maxSignPerNum, maxSignDayNum, mobile } = res.data.data;
            Object.assign(form, {
                maxSignPerNum,
                maxSignDayNum,
                mobile
            });
        }
    };

    // 发送验证码
    const sendVerificationCode = async () => {
        if (!form.mobile) {
            ElMessage.warning('请先输入手机号');
            return;
        }

        if (!/^1[3-9]\d{9}$/.test(form.mobile)) {
            ElMessage.warning('请输入正确的手机号格式');
            return;
        }

        try {
            const res = await proxy.$http.post(
                '/order/ordersign/routeExceptionSign/getCode',
                {
                    mobile: form.mobile
                }
            );

            if (res.data?.code === 200) {
                ElMessage.success('验证码发送成功');
                // 开始倒计时
                countdown.value = 60;
                const timer = setInterval(() => {
                    countdown.value--;
                    if (countdown.value <= 0) {
                        clearInterval(timer);
                    }
                }, 1000);
            } else {
                ElMessage.error(res.data?.msg || '验证码发送失败');
            }
        } catch (error) {
            console.error('发送验证码失败:', error);
            ElMessage.error('验证码发送失败，请稍后重试');
        }
    };

    // 提交表单
    const submitForm = async (formEl) => {
        if (!formEl) return;
        await formEl.validate(async (valid, fields) => {
            if (valid) {
                const res = await proxy.$http.post(
                    '/order/ordersign/routeExceptionSign',
                    {
                        maxSignPerNum: form.maxSignPerNum,
                        maxSignDayNum: form.maxSignDayNum,
                        mobile: form.mobile,
                        code: form.code
                    }
                );
                if (res.data?.code === 200) {
                    ElMessage.success('设置保存成功');
                } else {
                    ElMessage.error(res.data?.msg || '保存失败');
                }
            } else {
                console.log('error submit!', fields);
            }
        });
    };

    // 页面加载时获取设置
    onMounted(() => {
        getSettings();
    });
</script>
