<template>
    <ele-modal
        :width="460"
        title="批量导入"
        :body-style="{ paddingTop: '8px' }"
        v-model="visible"
    >
        <div class="flex mb-2">
            <div class="text-sm">请先下载'导入模板':</div>
            <el-button
                @click="
                    downloadOssLink(
                        'https://shuhi.oss-cn-qingdao.aliyuncs.com/default/search_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="visible = false">关闭</el-button>
            <el-button type="primary" @click="handleSumbit" :loading="loading"
                >导入</el-button
            >
        </template>
    </ele-modal>
</template>

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

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

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

    /** 导入请求状态 */
    const loading = ref(false);

    const uploadRef = ref(null);
    const fileList = ref([]);

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

    //导入图书 (Mock)
    async function importBooks(file) {
        // const formData = new FormData();
        // formData.append('file', file);
        // const res = await request.post('/book/bookInfo/exportByFile', formData);
        return new Promise((resolve) => {
            setTimeout(() => {
                resolve({ code: 200, msg: '导入成功' });
            }, 1000);
        });
    }

    /** 提交 */
    const handleSumbit = () => {
        if (fileList.value.length === 0) {
            ElMessage.error('请选择文件');
            return;
        }
        loading.value = true;
        let file = fileList.value[0];
        importBooks(file.raw)
            .then((res) => {
                loading.value = false;
                ElMessage.success(res.msg);
                visible.value = false;
                emit('done');
            })
            .catch((e) => {
                loading.value = false;
                ElMessage.error('导入失败');
            });
    };

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