/*
 * @Descripttion: 上传文件到cdn服务器
 * @Author: Zhong
 * @Date: 2019-12-31 15:38:44
 */

const UPLOAD_CDN = (() => {
    
    const config = {
        useCdnDomain: true,
        disableStatisticsReport: false,
        retryCount: 6,
        region: qiniu.region.z2
    };

    // 上传
    function upload(file, key, token, callback, errCallback) {
        const putExtra = {
            fname: "",
            params: {"x:name":key.split(".")[0]},
            mimeType: null
        };
        const observable = qiniu.upload(file, key, token, putExtra, config);
        observable.subscribe({
            error:function (err) {
                console.log(err);
                if (errCallback) {
                    errCallback(err);
                }
            },
            complete:function(res){
                if (callback) {
                    callback(res);
                }
            }
        })
    }

    // 同步上传
    function uploadSync(file, key, token) {
        return new Promise((resolve, reject) => {
            const putExtra = {
                fname: "",
                params: {"x:name":key.split(".")[0]},
                mimeType: null
            };
            const observable = qiniu.upload(file, key, token, putExtra, config);
            observable.subscribe({
                error:function (err) {
                    reject(err);
                },
                complete:function(res){
                    resolve(res);
                }
            })
        });
    }

    return {
        upload,
        uploadSync,
    };
})();
