<template>
    <ele-modal
        :width="600"
        title="新建图书商品"
        v-model="visible"
        @closed="handleClosed"
    >
        <el-form
            ref="formRef"
            :model="form"
            :rules="rules"
            label-width="120px"
            class="mt-4"
        >
            <el-form-item label="ISBN：" prop="isbn">
                <el-input v-model="form.isbn" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="一般品价格：" prop="price">
                <el-input v-model="form.price" placeholder="请输入" />
            </el-form-item>
        </el-form>

        <template #footer>
            <el-button type="primary" @click="handleSubmit" :loading="loading"
                >提交</el-button
            >
            <el-button @click="visible = false">取消</el-button>
        </template>
    </ele-modal>
</template>

<script setup>
    import { ref, reactive } from 'vue';
    import { EleMessage } from 'ele-admin-plus/es';
    import request from '@/utils/request';

    const emit = defineEmits(['done']);
    // const visible = defineModel({ type: Boolean });
    const visible = ref(false);
    const loading = ref(false);
    const formRef = ref(null);

    const open = () => {
        visible.value = true;
    };

    defineExpose({ open });

    const form = reactive({
        isbn: '',
        price: ''
    });

    const rules = reactive({
        isbn: [{ required: true, message: '请输入ISBN', trigger: 'blur' }],
        price: [
            { required: true, message: '请输入一般品价格', trigger: 'blur' }
        ]
    });

    const handleSubmit = async () => {
        if (!formRef.value) return;
        await formRef.value.validate(async (valid) => {
            if (valid) {
                loading.value = true;
                try {
                    // TODO: 替换为实际 API 接口
                    // const res = await request.post('/goods/book/add', form);
                    // if (res.data.code === 200) {
                    //     EleMessage.success('新建成功');
                    //     visible.value = false;
                    //     emit('done');
                    // }

                    // 暂时模拟成功
                    setTimeout(() => {
                        EleMessage.success('新建成功 (Mock)');
                        visible.value = false;
                        emit('done');
                        loading.value = false;
                    }, 1000);
                } catch (e) {
                    loading.value = false;
                }
            }
        });
    };

    const handleClosed = () => {
        formRef.value?.resetFields();
        form.isbn = '';
        form.price = '';
    };
</script>
