<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) {
            this.loading && this.loading.close();
            let os = this.onSuccess(res, file);
            if (os != undefined && os == false) return false;

            const hasSuc = res.findIndex(r => r.isSuccess) != -1;
            const errorList = res.filter(r => !r.isSuccess);
            if (!errorList.length) ElMessage.success("导入成功");
            else {
                const element = errorList.map(err => `<li>序号${err.index}：${err.errorMsg}</li>`).reduce((p, v) => p + v);
                ElNotification.error({
                    title: "导入文件未成功",
                    duration: 0,
                    dangerouslyUseHTMLString: true,
                    message: `<ul style="max-height: calc(100vh - 90px);overflow: auto;">${element}</ul>`
                })
            }

            hasSuc && 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 => {
                        if (res.code == 200) param.onSuccess(res.data);
                        else param.onError(res.msg || "未知错误");
                    }).catch(() => param.onError());
                } else param.onError(upRes.msg || "未知错误");
            }).catch(() => param.onError());
        }
    }
}
</script>