export function qiniuyun() {
    var d: any = {
        qiniuUploadURL: "",
        qiniuImageURLPrefix: "",
        qiniuUploadToken: "",
        qiniuUploadTokenURL: "",
        qiniuUploadTokenFunction: null
    };

    function f(g: any) {
        d = {
            qiniuUploadURL: "",
            qiniuImageURLPrefix: "",
            qiniuUploadToken: "",
            qiniuUploadTokenURL: "",
            qiniuUploadTokenFunction: null
        };
        e(g)
    }

    function e(g: any) {
        if (g.uploadURL) {
            d.qiniuUploadURL = g.uploadURL
        } else {
            console.error("qiniu uploader need uploadURL")
        } if (g.uptoken) {
            d.qiniuUploadToken = g.uptoken
        } else {
            if (g.uptokenURL) {
                d.qiniuUploadTokenURL = g.uptokenURL
            } else {
                if (g.uptokenFunc) {
                    d.qiniuUploadTokenFunction = g.uptokenFunc
                }
            }
        } if (g.domain) {
            d.qiniuImageURLPrefix = g.domain
        }
    }

    function c(i: any, j: any, g: any, h: any) {
        if (null == i) {
            console.error("qiniu uploader need filePath to upload");
            return
        }
        if (h) {
            f(h)
        }
        if (d.qiniuUploadToken) {
            b(i, j, g, h)
        } else {
            if (d.qiniuUploadTokenURL) {
                a(function () {
                    b(i, j, g, h)
                })
            } else {
                if (d.qiniuUploadTokenFunction) {
                    d.qiniuUploadToken = d.qiniuUploadTokenFunction()
                } else {
                    console.error("qiniu uploader need one of [uptoken, uptokenURL, uptokenFunc]");
                    return
                }
            }
        }
    }

    function b(j: any, l: any, g: any, i: any) {
        var h = d.qiniuUploadURL;
        var m = j.split("//")[1];
        if (i && i.key) {
            m = i.key
        }
        var k = {
            "token": d.qiniuUploadToken,
            "key": m
        };
        uni.uploadFile({
            url: h,
            filePath: j,
            name: "file",
            formData: k,
            success: function (o) {
                var q = o.data;
                var p = JSON.parse(q);
                var n = d.qiniuImageURLPrefix + p.key;
                p.imageURL = n;
                l(p)
            },
            fail: function (n) {
                g(n)
            }
        })
    }

    function a(g: any) {
        uni.request({
            url: d.qiniuUploadTokenURL,
            success: function (i: any) {
                var h = i.data.uptoken;
                d.qiniuUploadToken = h;
                if (g) {
                    g()
                }
            },
            fail: function (h) {
                console.log(h)
            }
        })
    }


    return {
        init: f,
        upload: c,
    }
}