<!-- 指定折扣弹窗 -->
<template>
    <ele-modal
        form
        :width="440"
        v-model="visible"
        title="指定折扣加回收书单"
        @open="handleOpen"
    >
        <SimpleForm
            :items="items"
            labelWidth="0"
            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({
        isbnList: [],
        recycleDiscount: ''
    });

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

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

    const formRef = ref();

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

    defineExpose({
        handleOpen
    });
</script>
