<template>
    <el-upload ref="uploader"
        action=""
        accept=".xlsx, .xls"
        :limit="1"
        :show-file-list="false"
        :http-request="request"
        :before-upload="before"
        :on-success="success"
        :on-error="error">
        <slot>
            <el-button icon="upload-filled">导入</el-button>
        </slot>
    </el-upload>
</template>

<script>
import Folder from "@/api/folder";

export default {
    props: {
        url: { type: String, default: "" },
        maxSize: { type: Number, default: 50 },
        onSuccess: { type: Function, default: () => true }
    },

    data() {
        return {
            loading: null
        }
    },

    methods: {
        before(file) {
            if (!this.url) return false;
            const maxSize = file.size / 1024 / 1024 < this.maxSize;
            if (!maxSize) {
                ElMessage.warning(`上传文件大小不能超过 ${this.maxSize}MB!`);
                return false;
            }
        },

        success(res, file) {
            let os = this.onSuccess(res, file);
            if (os != undefined && os == false) return false;

            ElMessage.success("导入成功");
            this.$emit("importSuc");
            this.$refs.uploader.clearFiles();
        },

        error(message) {
            this.loading && this.loading.close();
            message && ElNotification.error({ title: "导入文件未成功", message });
        },

        request(param) {
            this.loading = ElLoading.service({
                lock: true,
                text: "上传中请等待…",
                spinner: "el-icon-loading",
                background: "rgba(0, 0, 0, 0.7)"
            });

            const data = new FormData();
            data.append(param.filename, param.file);
            
            Folder.up(data).then(upRes => {
                if (upRes.code == 200) {
                    this.loading.setText("导入中请等待…");
                    Folder.import(this.url, upRes.data.link).then(res => {
                        this.loading.close();
                        if (res.code == 200) {
                            if (res.data.length) param.onError(`有${res.data.length}条数据导入失败，序号为: ${res.data.map(d => d.index).join()}`);
                            else param.onSuccess(res.data);
                        } else param.onError(res.msg || "未知错误");
                    }).catch(() => param.onError());
                } else param.onError(upRes.msg || "未知错误");
            }).catch(() => param.onError());
        }
    }
}
</script>