<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/book_info_export_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.导入文件属性值不存在或者超长，会自动过滤掉</div
            >
            <div class="text-sm mb-2">3.导入文件第一行需与模版完全一致</div>

            <el-radio-group v-model="coverImport">
                <el-radio :value="1">相同ISBN覆盖导入</el-radio>
                <el-radio :value="0">相同ISBN忽略导入</el-radio>
            </el-radio-group>
        </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, h } from 'vue';
    import { genFileId } from 'element-plus';
    import { ElMessageBox } from 'element-plus/es';
    import { EleMessage } from 'ele-admin-plus/es';
    import { CloudUploadOutlined } from '@/components/icons';
    import { downloadOssLink } from '@/utils/common';
    import request from '@/utils/request';

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

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

    /** 导入请求状态 */
    const loading = ref(false);
    /** 是否覆盖 */
    const coverImport = ref(1);

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

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

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

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

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

    /** 上传 */
    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;
    };
</script>
