<!-- 修改销售价格弹窗 -->
<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="handleSubmit">确定</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';
    import { ElMessage } from 'element-plus';

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

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

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

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

    const items = reactive([
        {
            label: '销售价格',
            prop: 'productPrice',
            type: 'input',
            required: true,
            itemProps: {
                rules: [validators.money]
            }
        }
    ]);

    const formRef = ref();

    const emit = defineEmits(['refresh']);
    const handleSubmit = () => {
        formRef.value?.submitForm().then((data) => {
            data.isbn = form.value.isbn;
            request
                .post('/book/bookInfo/changeProductPrice', data)
                .then((res) => {
                    if (res.data.code === 200) {
                        visible.value = false;
                        ElMessage.success('修改成功');
                        emit('refresh', data.productPrice);
                    } else {
                        ElMessage.error(res.data.msg || '修改失败');
                    }
                });
        });
    };

    defineExpose({
        handleOpen
    });
</script>
