<template>
    <div>
        <el-upload
            ref="upload"
            action=""
            :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
        >
            <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>
        <!--        <el-button @click="download">下载</el-button>-->
    </div>
</template>

<script>
export default {
    name: "upload",
    props: {
        // 限制上传的个数
        limit: {
            type: Number,
            default: 100,
        },
        // 一组文件传相同的值，保证其为一组
        objectPath: {
            type: String,
            default: "1",
        },
        type: {
            type: String,
            default: "1",
        },
        // 是否需要处理大文件上传
        needInstance: {
            type: Boolean,
            default: false,
        },
        // 上传url
        uploadUrl: {
            type: String,
            default: "",
        },
    },
    data() {
        return {
            fileList: [],
            attachmentList: [],
            defaultParam: {},
        };
    },
    methods: {
        handleChange(file, fileList) {
            this.fileList = fileList;
        },
        handleExceed(files, fileList) {
            this.$message.warning(
                `当前限制选择 ${this.limit} 个文件，本次选择了 ${
                    files.length
                } 个文件，共选择了 ${files.length + fileList.length} 个文件`
            );
        },
        handleRemove(file, fileList) {
            let md5 = "";
            if (file.raw) {
                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;
                }
            });
            this.attachmentList.splice(removeIndex, 1);
            this.$emit("attachmentChange", this.attachmentList);
        },
        async toUpload(file) {
            let _this = this;
            // 获取MD5值
            /* await this.$md5(file.file).then((res) => {
                _this.defaultParam = {
                    file: file.file,
                    md5: res,
                };
            }); */
            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("file", file.file);

                let axios = this.$axios;
                // 处理大文件上传
                if (this.needInstance) {
                    axios = this.$instance;
                }

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

                let url = this.uploadUrl;
                if (!url) {
                    url = this.$api.common.uploadWj;
                }

                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({
                                // attachmentName: file.file.name,
                                // attachmentAddress: res.params,
                                // md5: _this.defaultParam.md5,
                                // uid: file.file.uid,
                                fileType: file.file.type,
                                fileName: res.info.fileName,
                                videoPreview: res.info.videoPreview,
                            });
                            resolve("成功");
                            this.$emit("attachmentChange", this.attachmentList);
                            // 上传完成后进行通知
                            this.$emit("didUpload", "success");
                        } else {
                            this.$message.error(res.message || "上传失败");
                            this.$emit("didUpload", "fail");
                        }
                    })
                    .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>
