<!-- 申请恢复订单弹窗 -->
<template>
    <ele-modal
        form
        :width="500"
        v-model="visible"
        title="申请恢复订单"
        @open="handleOpen"
    >
        <el-form
            ref="formRef"
            :model="form"
            :rules="rules"
            label-width="80px"
            @submit.prevent=""
        >
            <el-form-item label="订单编号">
                <el-text>{{ form.orderId }}</el-text>
            </el-form-item>
            <el-form-item label="申请原因" prop="reason">
                <el-input
                    v-model="form.reason"
                    type="textarea"
                    :rows="4"
                    placeholder="请输入申请原因"
                />
            </el-form-item>
        </el-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, getCurrentInstance } from 'vue';
    import { EleMessage } from 'ele-admin-plus/es';

    const { proxy } = getCurrentInstance();
    const emit = defineEmits(['success']);

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

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

    /** 表单数据 */
    const form = reactive({
        orderId: '',
        reason: ''
    });

    /** 表单验证规则 */
    const rules = reactive({
        reason: [
            {
                required: true,
                message: '请输入申请原因',
                trigger: 'blur'
            }
        ]
    });

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

    /** 重置表单 */
    const resetForm = () => {
        form.orderId = '';
        form.reason = '';
        formRef.value?.resetFields();
    };

    /** 弹窗打开事件 */
    const handleOpen = (row) => {
        if (row && row.orderId) {
            visible.value = true;
            form.orderId = row.orderId;
        }
    };

    /** 提交表单 */
    const handleSubmit = () => {
        formRef.value?.validate(async (valid) => {
            if (!valid) return;
            proxy.$http
                .post('/order/orderInfo/adminCancelRecover', {
                    orderId: form.orderId,
                    reason: form.reason
                })
                .then((res) => {
                    if (res.data.code === 200) {
                        EleMessage.success('申请恢复订单成功');
                        emit('success');
                        handleCancel();
                    } else {
                        EleMessage.error(res.data.msg || '申请恢复订单失败');
                    }
                });
        });
    };

    defineExpose({
        handleOpen
    });
</script>
