import uploadAPI from '@/api/upload';
import uploadAnyFileAPI from '@/api/uploadAnyFile';
import global from '@/config/global';

export default {
    data() {
        return {};
    },
    methods: {
        filterFile(fileList, type) {
            //文件过滤函数;格式，大小
            fileList.forEach((file) => {
                if (type.includes(`image/${file.type}`)) {
                    throw this.$message.error(`上传头像图片只能是 ${type.join(',')} 格式!`);
                }
                if (file.size / 1024 / 1024 > global.IMAGE_SIZE_MAX) {
                    throw this.$message.error(`上传图片大小不能超过 ${global.IMAGE_SIZE_MAX}MB!`);
                }
            });
        },
        filterAnyFile(fileList) {
            //多文件过滤函数大小
            let fileSizeList = fileList.map((file) => file.size);
            let sumSize = fileSizeList.reduce(function (total, value) {
                return total + value;
            }, 0);
            if (sumSize / 1024 / 1024 > global.FILE_SIZE_MAX) {
                throw new Error(`上传文件大小不能超过 ${global.FILE_SIZE_MAX}MB!`);
            }
        },
        filesRename(files, names) {
            //name作为重命名依据，无则忽略
            names.forEach((name, index) => {
                let formatType = files[index].name.substring(files[index].name.lastIndexOf('.', files[index].name.length - 1));
                files[index] = new File([files[index]], `${name}${formatType}`, {type: files[index].type});
            });
            return files;
        },
        uploadFile(files, paths, names) {
            //文件上传函数,path为${业务名}/${id}组成的string数组,name无需包含文件格式
            files = this.filesRename(files, names);
            return uploadAPI.upload(files, paths).then((res) => {
                // console.log("res",res)
                return res;
            });
        },
        uploadFileRemoteRename(files, paths, names) {
            //文件上传函数,path为${业务名}/${id}组成的string数组,name必须包含文件格式
            return uploadAPI.upload(files, paths, names).then((res) => {
                // console.log("res",res)
                return res;
            });
        },
        uploadAnyFileRemoteRename(files, paths, names) {
            //文件上传函数,path为${业务名}/${id}组成的string数组,name必须包含文件格式
            return uploadAnyFileAPI.uploadAnyFile(files, paths, names).then((res) => {
                // console.log("res",res)
                return res;
            });
        },
        closeTag() {
            this.$store.dispatch('tagsView/delView', this.$route);
        },
    },
};
