<template>
    <div>
        <el-upload
            ref="upload"
            action=""
            :before-upload="beforeUpload"
            :on-change="handleChange"
            :on-remove="handleRemove"
            :on-preview="preview"
            :on-success="success"
            :on-error="error"
            :http-request="toUpload"
            :auto-upload="true"
            :file-list="fileList"
            :limit="limit"
            :on-exceed="handleExceed"
            :multiple="multiple"
        >
            <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>
        <!--        <el-button @click="download">下载</el-button>-->
    </div>
</template>

<script>
export default {
    name: "uploadPar", // 处理par文件
    props: {
        // 限制上传的个数
        limit: {
            type: Number,
            default: 1,
        },
        // 一组文件传相同的值，保证其为一组
        objectPath: {
            type: String,
            default: "1",
        },
        type: {
            type: String,
            default: "1",
        },
        // 是否需要处理大文件上传
        needInstance: {
            type: Boolean,
            default: false,
        },
        multiple: {
            type: Boolean,
            default: true,
        },
        // 上传url
        uploadUrl: {
            type: String,
            default: "",
        },
    },
    data() {
        return {
            fileList: [],
            attachmentList: [],
            defaultParam: {},
        };
    },
    methods: {
        beforeUpload(file) {
            let arr = ["par"];
            let i = file.name.lastIndexOf(".");

            if (!arr.includes(file.name.slice(i + 1).toLowerCase())) {
                this.$message.warning("请上传以par为后缀名的文件");
                return false;
            }
        },
        handleChange(file, fileList) {
            this.fileList = fileList;
        },
        handleExceed(files, fileList) {
            this.$message.warning(
                `当前限制选择 ${this.limit} 个文件，本次选择了 ${
                    files.length
                } 个文件，共选择了 ${files.length + fileList.length} 个文件`
            );
        },
        async handleRemove(file, fileList) {
            let md5 = "";
            if (file.raw) {
                await this.$md5(file.raw).then((res) => {
                    md5 = res;
                });
            } else {
                md5 = file.md5;
            }

            let removeIndex = "";
            this.attachmentList.forEach((item, index) => {
                if (md5 === item.md5) {
                    removeIndex = index;
                }
            });

            // if (removeIndex < 0) {
            //     this.$message.error("删除失败");
            // }

            this.attachmentList.splice(removeIndex, 1);
            this.$emit("attachmentChange", false);
        },
        async toUpload(file) {
            let _this = this;

            return new Promise(async (resolve, reject) => {
                let formData = new FormData();
                // await formData.append("name", file.file.name);
                // await formData.append('type', _this.defaultParam.md5)
                // await formData.append("type", this.type);
                // await formData.append("objectPath", this.objectPath);
                // await formData.append("md5", _this.defaultParam.md5);
                await formData.append("par", file.file);
                let fileName = file.file.name;

                let axios = this.$axios;
                // 处理大文件上传 instance已被设置不携带token
                // if (this.needInstance) {
                //     axios = this.$instance;
                // }

                // 上传前进行通知
                this.$emit("willUpload");

                /* let url = this.uploadUrl;
                let defaultParam = {};
                if (!url) {
                    url = this.$api.common.uploadWj;
                    // 获取MD5值
                    await this.$md5(file.file).then((res) => {
                        defaultParam = {
                            // file: file.file,
                            md5: res,
                        };
                    });
                } */

                let url = this.$api.modelLibrary.parsePar;
                // let defaultParam = {};
                // 获取MD5值
                // await this.$md5(file.file).then((res) => {
                //     defaultParam = {
                //         // file: file.file,
                //         md5: res,
                //     };
                // });

                await axios({
                    method: "post",
                    url,
                    data: formData,
                    withCredentials: true,
                    headers: {
                        "Content-type": "multipart/form-data",
                    },
                })
                    .then((res) => {
                        if (res.code == 200 && res.info) {
                            this.attachmentList.push({
                                info: res.info,
                            });
                            resolve("成功");
                            this.$emit("attachmentChange", res.info, fileName);
                            // 上传完成后进行通知
                            this.$emit("didUpload", "success");
                        } else {
                            this.$message.error(res.message || "上传失败");
                            this.$emit("didUpload", "fail");
                            reject("失败");
                        }
                    })
                    .catch((err) => {
                        this.$emit("didUpload", "error");
                        reject(err);
                    });
            });
        },
        success(response, file, fileList) {
            this.$message.success("上传成功 ");
        },
        error(response, file, fileList) {
            this.$message.warning("上传失败");
        },
        preview(file) {
            return false;
            console.log(file);
            console.log(this.attachmentList);
            let item = this.attachmentList.find((item) =>
                item.fileName.endsWith(file.name)
            );
            this.download(item.fileName, item.attachmentName);
        },
        download(downPath, downName) {
            this.$axios({
                method: "post",
                url: this.$api.common.download,
                responseType: "blob",
                data: {
                    objectName: downPath,
                },
            }).then((res) => {
                const blob = new Blob([res]); //构造一个blob对象来处理数据
                const fileName = downName;
                //对于<a>标签，只有 Firefox 和 Chrome（内核） 支持 download 属性
                //IE10以上支持blob但是依然不支持download
                if ("download" in document.createElement("a")) {
                    //支持a标签download的浏览器
                    const link = document.createElement("a"); //创建a标签
                    link.download = fileName; //a标签添加属性
                    link.style.display = "none";
                    link.href = URL.createObjectURL(blob);
                    document.body.appendChild(link);
                    link.click(); //执行下载
                    URL.revokeObjectURL(link.href); //释放url
                    document.body.removeChild(link); //释放标签
                } else {
                    //其他浏览器
                    navigator.msSaveBlob(blob, fileName);
                }
            });
        },
    },
};
</script>

<style scoped>
</style>
