<template>
    <ele-modal
        :model-value="visible"
        title="添加图书"
        @update:modelValue="updateVisible"
        @confirm="handleConfirm"
        @cancel="handleCancel"
    >
        <el-form :model="form" label-width="80px">
            <el-form-item label="ISBN">
                <el-input
                    v-model="form.isbn"
                    type="textarea"
                    :rows="4"
                    placeholder="请输入ISBN，多个ISBN请换行"
                />
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="handleCancel">取消</el-button>
            <el-button type="primary" :loading="loading" @click="handleConfirm"
                >保存</el-button
            >
        </template>
    </ele-modal>
</template>

<script setup>
    import { ref, defineEmits } from 'vue';
    import { ElMessage } from 'element-plus';
    import request from '@/utils/request';

    const emit = defineEmits(['success']);

    const visible = ref(false);
    const loading = ref(false);
    const form = ref({
        isbn: ''
    });

    const updateVisible = (val) => {
        visible.value = val;
    };

    const handleOpen = () => {
        visible.value = true;
        form.value.isbn = '';
    };

    const handleConfirm = async () => {
        if (!form.value.isbn) {
            ElMessage.warning('请输入ISBN');
            return;
        }
        loading.value = true;
        try {
            const res = await request.post('/activity/reduce/book/add', {
                isbn: form.value.isbn
            });
            if (res.data.code === 200) {
                ElMessage.success(res.data.msg || '添加成功');
                emit('success');
                updateVisible(false);
            } else {
                ElMessage.error(res.data.msg || '添加失败');
            }
        } catch (error) {
            console.error(error);
            ElMessage.error('添加失败');
        } finally {
            loading.value = false;
        }
    };

    const handleCancel = () => {
        updateVisible(false);
    };

    defineExpose({
        handleOpen
    });
</script>
