
const ResponseStateCode = require('../utils/GameEnum').ResponseStateCode;

class Api {

    static createImageFromUrl(avatarUrl, success, fail) {

        var index = avatarUrl.indexOf('https:');
        var httpIndex = avatarUrl.indexOf('http:');
        if (index === 0 || httpIndex === 0) {
            //以'https:'开头

        } else {
            avatarUrl = 'https:' + avatarUrl;
        }
        if (window.wx != undefined) {
            try {
                let image = wx.createImage();
                image.onload = () => {
                    try {
                        let texture = new cc.Texture2D();
                        texture.initWithElement(image);
                        texture.handleLoadedTexture();
                        success(new cc.SpriteFrame(texture))
                    } catch (e) {
                        cc.log(e);
                        fail();
                    }
                };
                image.src = avatarUrl;
            } catch (e) {
                cc.log(e);
                fail();
            }
        } else {
            cc.loader.load({
                url: avatarUrl, type: 'jpg'
            }, (err, texture) => {
                if (err === undefined || err === null) {
                    success(new cc.SpriteFrame(texture));
                } else {
                    fail();
                }
            });
        }
    }

    /**
     * 测试网络用的方法，可以注释掉
     */
    testGetBuildingInfo() {
        Api.httpGet({
            url: '/building/getUserBuildings.do',
            data: {
                targetUid: 1,
                // cityId: 1
            },
            success: (response) => {
                // console.log('success: ' + JSON.stringify(response));
            },
            fail: (response) => {
                console.log('success: ' + JSON.stringify(response));
            },
            complete: () => {

            }
        });
    }



    /**
     * 测试网络用的方法，可以注释掉
     */
    testUpgradeBuildingInfo() {
        Api.httpPost({
            url: '/building/upGrade.do',
            data: {
                formInfo: '1'
            },
            success: (response) => {
                console.log('success: ' + JSON.stringify(response));
            },
            fail: (response) => {
                console.log('success: ' + JSON.stringify(response));
            },
            complete: () => {

            }
        });
    }

    /**
     * get请求对外暴露的方法
     * @param {object} requestBody 请求body
     * @param {string} requestBody.url 请求地址
     * @param {object} requestBody.data 请求发送的data
     * @param {function} requestBody.success 请求成功的回调
     * @param {function} requestBody.fail 请求失败的回调
     */
    static httpGet(requestBody) {
        requestBody.data = Api.baseParam(requestBody.data);
        requestBody.url = Api.requestUrl(requestBody.url);
        if (window.wx != undefined) {
            Api.wxGet(requestBody);
        } else {
            Api.jsGet(requestBody);
        }
    }

    /**
     * post请求对外暴露的方法
     * @param {*} requestBody 
     */
    static httpPost(requestBody) {
        requestBody.data = Api.baseParam(requestBody.data);
        requestBody.url = Api.requestUrl(requestBody.url);
        if (window.wx != undefined) {
            Api.wxPost(requestBody);
        } else {
            Api.jsPost(requestBody);
        }
    }

    static wxGet(requestBody) {
        let onSuccess = requestBody.success;
        let onFail = requestBody.fail;
        let onComplete = requestBody.complete;

        wx.request({
            url: requestBody.url,
            data: requestBody.data,
            method: requestBody.method === undefined ? 'GET' : 'POST',
            header: requestBody.header === undefined ? {} : requestBody.header,
            success: (res) => {
                //直接处理登录失效的逻辑
                if (res.data.code === ResponseStateCode.LOGIN_INVALIDATE) {
                    Global.needLogin = true;
                    cc.director.loadScene('login');
                    return;
                }

                if (res.data.code === ResponseStateCode.OK) {
                    if (onSuccess != undefined) {
                        onSuccess(res.data.data, res.data.msg);
                    }
                } else {
                    if (onFail != undefined) {
                        onFail(res.data.code, res.data.msg);
                    }
                }
            },
            fail: (res) => {
                if (onFail != undefined) {
                    onFail(-1, res.errMsg);
                }
            },
            complete: onComplete,
        });
    }


    static wxPost(requestBody) {
        requestBody.header = {
            "Content-Type": "application/x-www-form-urlencoded"
        };
        requestBody.method = 'POST';
        Api.wxGet(requestBody);
    }

    static jsGet(requestBody) {
        let url = requestBody.url;
        let data = requestBody.data;

        url = url + "?";
        for (var key in data) {
            url = url + key + '=' + data[key] + '&';
        }
        url = url.substr(0, url.length - 1)

        var xhr = Api.jsBaseRequest(requestBody.success, requestBody.fail, requestBody.complete);
        xhr.open("GET", url, true);
        xhr.send();
    }

    static jsPost(requestBody) {
        let data = requestBody.data;
        var xhr = Api.jsBaseRequest(requestBody.success, requestBody.fail, requestBody.complete);
        xhr.open("POST", requestBody.url, true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        let formData = new String();
        for (var key in data) {
            formData = formData + key + '=' + data[key] + "&";
        }
        xhr.send(formData.substr(0, formData.length - 1));
    }

    static jsBaseRequest(onSuccess, onFail, onComplete) {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = () => {
            if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) {
                // console.log('response:' + xhr.responseText);
                var response = JSON.parse(xhr.responseText);
                if (response.code == ResponseStateCode.OK) {
                    if (onSuccess != undefined) {
                        onSuccess(response.data, response.msg);
                    }
                } else {
                    if (onFail != undefined) {
                        onFail(response.code, response.msg)
                    }
                }
                if (onComplete != undefined) {
                    onComplete();
                }
            }
        };
        return xhr;
    }

    /**
     * get请求对外暴露的方法
     * @param {*} requestBody 
     */
    static httpGetPromise(url, data) {
        url = Api.requestUrl(url);
        data = Api.baseParam(data);
        if (window.wx != undefined) {
            return Api.wxGetP(url, data);
        } else {
            return Api.jsGetP(url, data);
        }
    }

    /**
     * post请求对外暴露的方法
     * @param {*} requestBody 
     */
    static httpPostPromise(url, data) {
        url = Api.requestUrl(url);
        data = Api.baseParam(data);
        if (window.wx != undefined) {
            return Api.wxPostP(url, data);
        } else {
            return Api.jsPostP(url, data);
        }
    }

    static wxGetP(url, data) {
        return Api.wxRequestPromise(url, data, 'GET');
    }

    static wxPostP(url, data) {
        let header = {
            "Content-Type": "application/x-www-form-urlencoded"
        };
        return Api.wxRequestPromise(url, data, 'POST', header);
    }

    static wxRequestPromise(url, data, method, header) {
        return new Promise((resolve, reject) => {
            wx.request({
                url: url,
                data: data,
                method: method,
                header: header === undefined ? {} : header,
                success: (res) => {
                    //直接处理登录失效的逻辑
                    if (res.data.code === ResponseStateCode.LOGIN_INVALIDATE) {
                        Global.needLogin = true;
                        cc.director.loadScene('login');
                        reject(res.data);
                    }

                    if (res.data.code === ResponseStateCode.OK) {
                        resolve(res.data);
                    } else {
                        reject(res.data);
                    }
                },
                fail: (res) => {
                    reject({
                        code: -1,
                        msg: '微信接口调用失败'
                    });
                },
                complete: {},
            });
        });
    }

    static jsGetP(url, data) {
        return new Promise((resolve, reject) => {
            url = url + "?";
            for (var key in data) {
                url = url + key + '=' + data[key] + '&';
            }
            url = url.substr(0, url.length - 1);

            var xhr = Api.jsBaseRequestP(resolve, reject);
            xhr.open("GET", url, true);
            xhr.send();
        });
    }

    static jsPostP(url, data) {
        return new Promise((resolve, reject) => {
            var xhr = Api.jsBaseRequestP(resolve, reject);
            xhr.open("POST", url, true);
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            let formData = new String();
            for (var key in data) {
                formData = formData + key + '=' + data[key] + "&";
            }
            xhr.send(formData.substr(0, formData.length - 1));
        });
    }



    static jsBaseRequestP(resolve, reject) {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = () => {
            if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) {
                // console.log('response:' + xhr.responseText);
                var response = JSON.parse(xhr.responseText);
                if (response.code == ResponseStateCode.OK) {
                    resolve(response);
                } else {
                    reject(response);
                }
            }
        };
        return xhr;
    }

    /**
     * 将每个接口都需要的公用参数都放到这里
     * @param target [Object] 请求参数
     */
    static baseParam(target) {
        if (target === undefined) {
            target = {};
        }
        target.thirdType = 1;
        target.channel = Global.channel;
        target.ver = Global.ver;
        target.os = Global.os;
        target.uid = Global.user ? Global.user.uid : '';
        target.token = Global.user ? Global.user.token : '';
        return target;
    }

    /**
     * 自动拼接请求接口
     * @param targetUrl [string] 请求接口
     */
    static requestUrl(targetUrl) {
        let host = Global.debug ? 'https://test-api-allstar.duowan.com' : 'https://api-allstar.duowan.com';
        // let host = Global.debug ? 'http://172.16.15.170:8080' : 'https://api-allstar.duowan.com';
        return host + targetUrl;
    }

}

module.exports = Api;