;(function () {
    const { netdiskApi, authorization } = require('sys-config'),
        request = require('request'),
        transfer = require('transfer');

    const baseRequest = (url) => {
        let base = request.defaults({
            headers: {
                'authorization': `Basic ${authorization}`,
                'content-type': 'application/json'
            }
        });
        return Q((resolve, reject) => {

            base.get(url, success).on('error', function (err) {
                 
                resolve({
                    ret: 0,
                    msg: '网络错误'
                });
            });
            function success(err, d) {
              
                if (err || d.statusCode != 200) {
                    resolve({
                        ret: 0,
                        msg: '网络错误'
                    });
                } else {
                    let data = typeof d.body == 'string' ? (JSON.parse(d.body)) : ((d.body));
                    data.ret = data.success;
                    //  获取到的是 一个指向文件的url链接
                    resolve(data);
                }
            }
        });
    }
    const Q = (caller) => {
        let promise = new Promise(function (resolve, reject) {
            caller(resolve, reject);
        });
        promise.catch(() => {

        });
        return promise;
    }

    const geteWay = {
        download: (md5) => {
            let url = `${netdiskApi}/api/download/${md5}`;
            return baseRequest(url);
        },
        upload: (md5) => {
            let url = `${netdiskApi}/api/upload/tcp/${md5}`;
            return baseRequest(url);
        }
    };
    transfer.wfsGateway = geteWay;
}());