<template>
    <ele-modal
        :width="460"
        title="导入图书"
        :body-style="{ paddingTop: '8px' }"
        :model-value="visible"
        @update:modelValue="updateVisible"
        @confirm="handleConfirm"
        @cancel="handleCancel"
    >
        <div class="flex mb-2">
            <div class="text-sm">请先下载'降价营销书单导入模板':</div>
            <el-button
                @click="
                    downloadOssLink(
                        'https://shuhi.oss-cn-qingdao.aliyuncs.com/default/reduce_book_isbn_template.xlsx',
                        '降价营销书单导入模板'
                    )
                "
                link
                type="primary"
                >下载降价营销书单导入模板</el-button
            >
        </div>

        <div class="flex flex-col mb-2">
            <div class="text-sm text-yellow-500">使用说明：</div>
            <div class="text-sm">1.支持通过导入批量添加图书</div>
            <div class="text-sm">2.文件ISBN不存在或者错误，会自动过滤掉</div>
            <div class="text-sm mb-2">3.导入文件第一行需与模版完全一致</div>
        </div>
        <div v-loading="loading" class="user-import-upload">
            <el-upload
                v-model:file-list="fileList"
                ref="uploadRef"
                action=""
                accept=".xls,.xlsx"
                :before-upload="doUpload"
                :auto-upload="false"
                :limit="1"
                :on-exceed="handleExceed"
            >
                <el-button type="primary" class="mr-2">选择文件</el-button>
                <ele-text type="placeholder">只能上传 xls、xlsx 文件</ele-text>
            </el-upload>
        </div>

        <template #footer>
            <el-button @click="handleCancel">关闭</el-button>
            <el-button type="primary" @click="handleConfirm" :loading="loading"
                >导入</el-button
            >
        </template>
    </ele-modal>
</template>

<script setup>
    import { ref, defineEmits } from 'vue';
    import { genFileId } from 'element-plus';
    import { ElMessage } from 'element-plus';
    import { EleMessage } from 'ele-admin-plus/es';
    import { UploadFilled } from '@element-plus/icons-vue';
    import { downloadOssLink } from '@/utils/common';
    import request from '@/utils/request';

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

    const visible = ref(false);
    const loading = ref(false);
    const fileList = ref([]);
    const uploadRef = ref(null);

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

    const handleOpen = () => {
        visible.value = true;
        fileList.value = [];
    };

    function handleExceed(files) {
        uploadRef.value?.clearFiles();
        const file = files[0];
        file.uid = genFileId();
        uploadRef.value?.handleStart(file);
    }

    const doUpload = (file) => {
        if (
            ![
                'application/vnd.ms-excel',
                'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            ].includes(file.type)
        ) {
            EleMessage.error('只能选择 excel 文件');
            return false;
        }
        if (file.size / 1024 / 1024 > 10) {
            EleMessage.error('大小不能超过 10MB');
            return false;
        }
        return false;
    };

    //导入图书
    async function importBooks(file) {
        const formData = new FormData();
        formData.append('file', file);

        const res = await request.post(
            '/activity/reduce/book/import',
            formData
        );
        if (res.data.code === 200) {
            return res.data;
        }
        return Promise.reject(new Error(res.data.msg));
    }

    /** 提交 */
    const handleConfirm = () => {
        loading.value = true;
        let file = fileList.value[0];
        importBooks(file.raw)
            .then((res) => {
                loading.value = false;
                ElMessage.success(res.data || res.msg);
                visible.value = false;
                emit('success');
            })
            .catch((e) => {
                loading.value = false;
            });
    };

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

    defineExpose({
        handleOpen
    });
</script>
