const api = require('./api');
/**
 * 例子
 */
// app.http.get(url.format({
//   path方式 ...
//   }), {
//   header: {
//    ...
//   },
//   data: {
//     ...
//   }
// }).then(res => {

// })
//.catch(err => {

// })
var methods = {
    POST_METHOD: 'POST',
    DELETE_METHOD: 'DELETE',
    PUT_METHOD: 'PUT',
    GET_METHOD: 'GET'
};

/**
 * 新增
 * @param url
 * @param dataObj
 * @param args
 * @param successCallback
 * @param errorCallback
 * @param completeCallback
 */
function postJson(url, args) {
    return doAjax(url, methods.POST_METHOD, args);
}

/**
 * 删除
 * @param url
 * @param dataObj
 * @param args
 * @param successCallback
 * @param errorCallback
 * @param completeCallback
 */
function deleteForm(url, args) {
    return doAjax(url, methods.DELETE_METHOD, args);
}

/**
 * 修改
 * @param url
 * @param dataObj
 * @param args
 * @param successCallback
 * @param errorCallback
 * @param completeCallback
 */
function putJson(url, args) {
    return doAjax(url, methods.PUT_METHOD, args);
}

/**
 * 查询
 * @param url
 * @param dataObj
 * @param args
 * @param successCallback
 * @param errorCallback
 * @param completeCallback
 */
function getForm(url, args) {
    return doAjax(url, methods.GET_METHOD, args);
}

/**
 * 执行上传
 * @param url
 * @param method
 * @param dataObj
 * @param args
 * @param successCallback
 * @param errorCallback
 * @param completeCallback
 */
function doAjax(url, method, args) {
    // var headers = {};
    // if (args != null && typeof (args.headers) != 'undefined' && args.headers != null) {
    //     headers = args.headers;
    // }
    return new Promise((success, errorback) => {
        //构建请求Url
        var requestUrl = api.apis.url + url
        wx.request({
            url: requestUrl,
            method: method,
            data: args.data || {},
            header: args.header || {},
            timeout: 50000,
            dataType: 'json',
            success: res => {
                if (res.statusCode == 200) {
                    success(res)
                } else {
                    errorback(res)
                    var hintMsg = '网络错误'
                    if (err.data && res.data.msg) {
                        hintMsg = res.data.msg
                    }
                    wx.showToast({
                        title: hintMsg,
                        icon: 'error'
                    })
                }
            },
            fail: err => {
                wx.hideLoading({})
                errorback(err)
                var hintMsg = '网络错误'
                if (err.data && err.data.msg) {
                    hintMsg = err.data.msg
                }
                wx.showToast({
                    title: hintMsg + '(100)',
                    icon: 'error'
                })
            },
        })
    })
}

/**
 * 检测是路径参数有重复值
 * @param pathArgArray
 * @returns {boolean}
 */
function pathArgsHasSameValue(pathArgArray) {
    var tempArgIndex = 0;
    var tempArgs = pathArgArray[tempArgIndex];
    for (var i = (tempArgIndex + 1), item; item = pathArgArray[i]; i++) {
        if (tempArgs == item) {
            throw new Error('参数' + item + '有重复值!!!');
        }
        if (i == pathArgArray.length - 1) {
            tempArgs = pathArgArray[++tempArgIndex];
            i = tempArgIndex;
            continue;
        }
    }
}

/**
 * 获取页面间传递的参数
 * @param url
 */
function getParamsArg(url) {
    var params = url.split('?')[1];
    var paramsObj = {};
    if (typeof (params) == 'undefined' || params == null) {
        return paramsObj;
    }
    var paramsKVs = params.split('&');
    for (var i = 0, item = null; item = paramsKVs[i++];) {
        var kvs = item.split('=');
        if (kvs.length == 1) {
            paramsObj[kvs[0]] = null;
        }
        if (kvs.length == 2) {
            paramsObj[kvs[0]] = decodeURI(kvs[1]);
        }
    }
    return paramsObj;
}

/**
 * 构建路径
 * @param basePath 请求路径，{参数},
 * @param pathArgs 替换的路径参数，不能重复
 * @returns {*}
 */
function buildPath(basePath, pathArgs) {
    var path = basePath;
    if (!basePath || !(typeof (basePath) == 'string')) {
        throw new Error('basePath必须为字符串!!!');
    }
    if (!pathArgs || !Array.isArray(pathArgs)) {
        throw new Error('pathArgs必须为数组!!!');
    }
    var pathArgArray = basePath.match(/\{\w+\}/g);
    if (!pathArgArray) {
        return path;
    }
    pathArgsHasSameValue(pathArgArray);
    for (var i = 0, item; item = pathArgArray[i]; i++) {
        path = path.replace(item, pathArgs[i]);
    }
    return path;
}

/**
 * 通过form对象上传文件
 * @param url
 * @param formData
 * @param args
 * @param successCallback
 * @param errorCallback
 * @param beforeCallback
 * @param completeCallback
 */
function postFile(url, path, name, args, successCallback, errorCallback, completeCallback) {
    var headers = {};
    if (args != null && typeof (args.headers) != 'undefined' && args.headers != null) {
        headers = args.headers;
    }
    wx.uploadFile({
        filePath: path,
        name: name,
        url: url,
        header: headers,
        success: function (response) {
            if (response.statusCode == 200) {
                successCallback(response.statusCode, response.data, args);
            } else {
                if (errorCallback && typeof (errorCallback) == 'function') {
                    errorCallback(response.statusCode, response.data);
                }
            }
        },
        fail: function (response) {
            if (errorCallback && typeof errorCallback == 'function') {
                errorCallback(response.statusCode, response.data)
            }
        },
        complete: function () {
            if (completeCallback && typeof (completeCallback) == 'function') {
                completeCallback();
            }
        }
    })
};
/**
 * Promise 上传文件
 */
function upload(url, params) {
    return new Promise((success, errorback) => {
        var requestUrl = api.apis.url + url
        wx.uploadFile({
            filePath: params.path,
            name: params.name,
            url: requestUrl,
            header: params.header,
            success: function (response) {
                console.log('success')
                if (response.statusCode == 200) {
                    success(response.data);
                } else {
                    errorback(response)
                    if (typeof (response.data) != undefined) {
                        try {
                            var data = JSON.parse(response.data)
                            wx.showToast({
                                title: data.msg,
                                icon: 'none'
                            })
                        } catch (err) {
                            wx.showToast({
                                title: '网络错误',
                                icon: 'error'
                            })
                        }
                    } else {
                        wx.showToast({
                            title: '网络错误',
                            icon: 'error'
                        })
                    }
                }
            },
            fail: function (response) {
                wx.hideLoading({})
                try {
                    if (typeof (response.data.msg) != undefined) {
                        wx.showToast({
                            title: response.data.msg,
                            icon: 'none'
                        })
                    } else {
                        wx.showToast({
                            title: '网络错误(100)',
                            icon: 'error'
                        })
                    }
                } catch (err) {
                    wx.showToast({
                        title: '网络错误(100)',
                        icon: 'error'
                    })
                }
            }
        })
    })
}

/**
 * xss 转义
 * @param html
 * @returns {string}
 */
function escape(html) {
    return String(html || '').replace(/&(?!#?[a-zA-Z0-9]+;)/g, '&amp;')
        .replace(/</g, '&lt;').replace(/>/g, '&gt;')
        .replace(/'/g, '&#39;').replace(/"/g, '&quot;');
}

String.prototype.format = function (params) {
    let s = this
    for (let item in params) {
        let re = new RegExp('{' + item + '}', 'gm')
        s = s.replace(re, params[item])
    }
    return s
}


module.exports = {
    post: postJson,
    delete: deleteForm,
    put: putJson,
    get: getForm,
    params: getParamsArg,
    path: buildPath,
    escape: escape,
    file: postFile,
    upload: upload,
    apis: api.apis
}