<!-- 修改回收折扣弹窗 -->
<template>
    <ele-modal
        form
        :width="460"
        v-model="visible"
        title="修改回收折扣"
        @open="handleOpen"
    >
        <SimpleForm
            :items="items"
            labelWidth="100px"
            ref="formRef"
            :initKeys="form"
        />
        <template #footer>
            <el-button @click="handleCancel">关闭</el-button>
            <el-button type="primary" @click="handleSumbit">确定</el-button>
        </template>
    </ele-modal>
</template>

<script setup>
    import { ref, reactive, nextTick } from 'vue';
    import SimpleForm from '@/components/CommonPage/SimpleForm.vue';
    import validators from '@/utils/validators';
    import request from '@/utils/request';

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

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

    const form = ref({
        isbn: '',
        recycleDiscount: ''
    });

    /** 弹窗打开事件 */
    const handleOpen = (data) => {
        visible.value = true;
        nextTick(() => {
            if (data?.isbn) {
                form.value.isbn = data.isbn;
                getParams(data.isbn);
            }
        });
    };

    //根据isbn获取参数
    const getParams = (isbn) => {
        request.get(`/book/bookRecycleInfo/getSepSet/${isbn}`).then((res) => {
            let data = res.data.data;
            form.value.recycleDiscount = data.recycleDiscount;
            formRef.value?.setData(form.value);
        });
    };

    const items = reactive([
        {
            label: '回收折扣',
            prop: 'recycleDiscount',
            type: 'input',
            required: true,
            itemProps: {
                rules: [validators.decimalRange10]
            }
        }
    ]);

    const formRef = ref();

    const emit = defineEmits(['refresh']);
    const handleSumbit = () => {
        formRef.value?.submitForm().then((data) => {
            data.isbn = form.value.isbn;
            request
                .post('/book/bookRecycleInfo/updateDiscount', data)
                .then(() => {
                    visible.value = false;
                    ElMessage.success('修改成功');
                    emit('refresh');
                });
        });
    };

    defineExpose({
        handleOpen
    });
</script>
