
import notifyCenter from "./Comming/NotificationCenter";


// import CryptoJS  from "./encrypt/cryptojs";
// import JSEncrypt from "./encrypt/jsencrypt";

//通用工具函数类
var utils = {
    version: "0.15",

    // baseUrl: "https://www.yuyekeji.cn/game/",
    // baseUrl: "http://127.0.0.1:26001/api_dapp/game/",
    // baseUrl: "https://www.yuyekeji.cn/api_dapp/game/",
    baseUrl: window['dappHost'] + '/api_dapp/game/',

    api: {
        //获取public 和 系统设置
        publicKeyAndSys: 'comUsers/publicKeyAndSys',

        /**
         * @deprecated 用loginTokenAndVerification 替代
         */
        loginToken: 'comUsers/loginToken',
        loginTokenAndVerification: 'comUsers/loginTokenAndVerification',
        //平台账户相关信息
        userInfo: 'comUsers/getUserInfo',
        userSnbInfo: 'comUsers/getUserSnb',
        //角色的信息和属性
        playerInfo: 'comPlayers/getPlayerAndBattleAttribute',
        playerPushInfo: 'comPlayers/playerPushInfo',
        playerPullInfo: 'comPlayers/playerPullInfo',
        //获取玩家属性
        playerAttribute: 'comPlayersAttri/getPlayerAttribute',
        /**
         * 获取是否租赁过的状态
         */
        playerExchangeState: 'comPlayers/getPlayerExchangeState',
        //获取游戏config土地列表
        landConfig: 'configLand/getList',
        //获取用户已经租赁的土地
        userLandList: 'comPlayerLand/getList',
        //获取用户可以偷取的列表信息
        canStealUserList: 'comPlayerLand/getCanStealUserList',

        //获取土地信息
        landState: 'comPlayerLand/getState',
        //种植
        plant: 'comPlayerLand/plant',
        //种子
        mallSeed: 'comMallSeed/getMallSeed',
        /**
       * 用钻石兑换一包种子
       */
        exchangeSeeds: 'comMallSeed/exchangeSeeds',


        //仓库种子和果实
        getSeedAndFruit: 'comPlayerGoods/getSeedAndFruit',
        //背包的种子数量
        getSeedState: 'comPlayerGoods/getSeedState',
        //收取果实
        addFruit: 'comPlayerGoods/addFruit',
        //一键偷取全部果实
        stealAllFruit: 'comPlayerGoods/stealAllFruit',

        /**
         * 偷菜时候，收取对方用户果实
         */
        stealFruit: 'comPlayerGoods/stealFruit',

        //出售果实
        saleFruit: 'comPlayerGoods/saleFruit',
        //赠送果实
        grantFruit: 'comPlayerGoods/grantFruit',
        //神农呗购买种子
        snbBuySeeds: 'comMallSeed/snbBuySeeds',
        //获取操作的snb日志
        snbList: 'comSnbTran/getList'

    },
    /** 登录获取的token */
    token: null,
    /** 后端RSA公钥 */
    javaPublicKey: null,
    /** api加密开关 */
    sysApiEncrypt: null,
    /** 设置token格式 */
    setToken(value) {
        // "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxMDAyIiwiZXhwIjoxNjQyNDUyNjU2LCJpYXQiOjE2NDI0NDU0NTZ9.Wr-u0KIa94_-yJjf28sj2znLmU_NwHpFaAaE_5rQLdUkYQGAHn-kMq2fdQHk_XwMrG71A2vzgz6BCmJtI8cL9Q"
        this.token = "Bearer " + value;
    },
    /**设置一个错误token测试 */
    onTestToken() {
        this.token = "Bearer " + "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxMDAyIiwiZXhwIjoxNjQyNDUyNjU2LCJpYXQiOjE2NDI0NDU0NTZ9.Wr-u0KIa94_-yJjf28sj2znLmU_NwHpFaAaE_5rQLdUkYQGAHn-kMq2fdQHk_XwMrG71A2vzgz6BCmJtI8cL9Q";
    },
    setJavaPublicKeyAndSysApiEncrypt(javaPublicKey, sysApiEncrypt) {
        this.javaPublicKey = javaPublicKey;
        this.sysApiEncrypt = sysApiEncrypt;
    },
    get(url, params, callback) {
        let dataStr = '';
        Object.keys(params).forEach(key => {
            dataStr += key + '=' + encodeURIComponent(params[key]) + '&';
        })
        if (dataStr !== '') {
            dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
            url = url + '?' + dataStr;
        }
        url = this.baseUrl + url;
        let xhr = cc.loader.getXMLHttpRequest();
        xhr.open("GET", url, true);
        xhr.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
        if (this.token) {
            xhr.setRequestHeader("Authorization", this.token);
        }
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                let response = xhr.responseText;
                if (xhr.status >= 200 && xhr.status < 300) {
                    // let aesKeyS = aesUtil.genKey();
                    // let encryptS = aesUtil.encrypt(response, aesKeyS);
                    // let aesKeyE = rsaUtil.encrypt(aesKeyS, sessionStorage.getItem('javaPublicKey')),//后端RSA公钥加密后的AES的key
                    // console.log('aesKeyS:',aesKeyS);
                    // console.log('encryptS:',encryptS);
                    // data = aesUtil.decrypt(data.data.data, rsaUtil.decrypt(data.data.aesKey, window.jsPrivateKey));
                    // todo 处理token过期操作？
                    // 301,302,303,304
                    let _response = JSON.parse(response);
                    if (301 === _response.code || 302 === _response.code || 303 === _response.code || 304 === _response.code) {
                        console.log("token异常" + _response.msg);
                        //这里要处理重新登录请求了，让用户刷新浏览器重新登录
                        cc.loader.loadRes("prefab/gameToast", (err, texture) => {
                            let _pause = cc.instantiate(texture);
                            let _uiCamera = cc.find("Canvas/UICamera");
                            _pause.parent = _uiCamera ? _uiCamera : cc.find("Canvas");
                            _pause.zIndex = 999;
                            let DetailLabel = _pause.getChildByName('DetailLabel');
                            DetailLabel.getComponent(cc.Label).string = "游戏登录失效，请重新刷新页面登录！";
                            setTimeout(() => {
                                cc.game.pause();
                            }, 60)
                        });

                        return;
                    }
                    if (404 === _response.code) {
                        cc.loader.loadRes("prefab/gameToast", (err, texture) => {
                            let _pause = cc.instantiate(texture);
                            let _uiCamera = cc.find("Canvas/UICamera");
                            _pause.parent = _uiCamera ? _uiCamera : cc.find("Canvas");
                            _pause.zIndex = 999;
                            let DetailLabel = _pause.getChildByName('DetailLabel');
                            DetailLabel.getComponent(cc.Label).string = _response.data.msg;
                            setTimeout(() => {
                                cc.game.pause();
                            }, 60)
                        });

                        return;
                    }
                    // let httpStatus = xhr.statusText;
                    if (callback)
                        callback(true, _response);
                    notifyCenter.emit("netSuccess", _response);
                } else {
                    console.error("访问：" + url + "失败!");
                    let _response = null;
                    if (typeof response.value == 'string' && !response.value) {
                        _response = JSON.parse(response);
                    }
                    if (callback)
                        callback(false, _response);
                    notifyCenter.emit("netError", _response);

                    if (window['GlobalD'].GameData && window['GlobalD'].GameData.getToast()) {
                        GlobalD.GameData.showToast(cc.find("Canvas/UICamera"), "网络请求失败！", 1);
                    } else {
                        cc.loader.loadRes("prefab/gameToast", (err, texture) => {
                            let _pause = cc.instantiate(texture);
                            let _uiCamera = cc.find("Canvas/UICamera");
                            _pause.parent = _uiCamera ? _uiCamera : cc.find("Canvas");
                            _pause.zIndex = 999;
                            let DetailLabel = _pause.getChildByName('DetailLabel');
                            DetailLabel.getComponent(cc.Label).string = "网络请求失败！";
                            setTimeout(() => {
                                _pause.destroy();
                            }, 1000)
                        });
                    }
                }
            }
        };
        xhr.send();
    },

    //Post请求
    post(url, param, callback) {
        url = this.baseUrl + url;
        var xhr = cc.loader.getXMLHttpRequest();
        let dataStr = '';
        Object.keys(param).forEach(key => {
            dataStr += key + '=' + encodeURIComponent(param[key]) + '&';
        })
        if (dataStr !== '') {
            dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
        }
        xhr.open("POST", url, true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        if (this.token) {
            xhr.setRequestHeader("Authorization", this.token);
        }
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                let response = xhr.responseText;
                if (xhr.status >= 200 && xhr.status < 300) {

                    let _response = JSON.parse(response);
                    if (301 === _response.code || 302 === _response.code || 303 === _response.code || 304 === _response.code) {
                        console.log("token异常" + _response.msg);
                        //这里要处理重新登录请求了，让用户刷新浏览器重新登录
                        cc.loader.loadRes("prefab/gameToast", (err, texture) => {
                            let _pause = cc.instantiate(texture);
                            let _uiCamera = cc.find("Canvas/UICamera");
                            _pause.parent = _uiCamera ? _uiCamera : cc.find("Canvas");
                            _pause.zIndex = 999;
                            let DetailLabel = _pause.getChildByName('DetailLabel');
                            DetailLabel.getComponent(cc.Label).string = "游戏登录失效，请重新刷新页面登录！";
                            setTimeout(() => {
                                cc.game.pause();
                            }, 60)
                        });

                        return;
                    }
                    if (404 === _response.code) {
                        cc.loader.loadRes("prefab/gameToast", (err, texture) => {
                            let _pause = cc.instantiate(texture);
                            let _uiCamera = cc.find("Canvas/UICamera");
                            _pause.parent = _uiCamera ? _uiCamera : cc.find("Canvas");
                            _pause.zIndex = 999;
                            let DetailLabel = _pause.getChildByName('DetailLabel');
                            DetailLabel.getComponent(cc.Label).string = _response.data.msg;
                            setTimeout(() => {
                                cc.game.pause();
                            }, 60)
                        });

                        return;
                    }
                    // let httpStatus = xhr.statusText;
                    if (callback)
                        callback(true, _response);
                    notifyCenter.emit("netSuccess", _response);

                } else {
                    console.error("访问：" + url + "失败!");
                    let _response = null;
                    if (typeof response.value == 'string' && !response.value) {
                        _response = JSON.parse(response);
                    }
                    if (callback)
                        callback(false, _response);
                    notifyCenter.emit("netError", _response);

                    if (window['GlobalD'].GameData && window['GlobalD'].GameData.getToast()) {
                        GlobalD.GameData.showToast(cc.find("Canvas/UICamera"), "网络请求失败！", 1);
                    } else {
                        cc.loader.loadRes("prefab/gameToast", (err, texture) => {
                            let _pause = cc.instantiate(texture);
                            let _uiCamera = cc.find("Canvas/UICamera");
                            _pause.parent = _uiCamera ? _uiCamera : cc.find("Canvas");
                            _pause.zIndex = 999;
                            let DetailLabel = _pause.getChildByName('DetailLabel');
                            DetailLabel.getComponent(cc.Label).string = "网络请求失败！";
                            setTimeout(() => {
                                _pause.destroy();
                            }, 1000)
                        });
                    }


                }
            }
        };
        xhr.send(dataStr);
    },

    // getKey(){
    //     let aesKey = aesUtil.genKey();
    //     console.log('aesKey:',aesKey);
    // }

    init(id, callback: Function, target: any) {
        if (this.ws != null) return;
        // https://www.yuyekeji.cn/api_dapp/index 192.168.0.106:26001 
        // wss://www.yuyekeji.cn/api_dapp/websocket/dappBack/
        console.log("utils.token:", utils.token);
        this.ws = new WebSocket(window['dappWss'] + id, ["11"]);
        this.ws.onopen = (event: Event) => {
            callback.call(target, "登录成功");
        }

        this.ws.onmessage = (event: MessageEvent) => {
            callback.call(target, event.data);
        }

        this.ws.onerror = function (e) {
            console.error("WebSocket连接发生错误");
        };
    },
    sendMsg(data: string) {
        if (this.ws != null && this.ws.readyState != WebSocket.OPEN) return;
        this.ws.send(data);
    }
};


/**
 * 加解密操作简单封装一下
 */
// let aesUtil = {

//     //获取key，
//     genKey : function (length = 16) {
//         let random = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
//         let str = "";
//         for (let i = 0; i < length; i++) {
//             str  = str + random.charAt(Math.random() * random.length)
//         }
//         return str;
//     },

//     //加密
//     encrypt : function (plaintext,key) {
//         if (plaintext instanceof Object) {
//             //JSON.stringify
//             plaintext = JSON.stringify(plaintext)
//         }
//         let encrypted = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(plaintext), CryptoJS.enc.Utf8.parse(key), {mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7});
//         return encrypted.toString();
//     },

//     //解密
//     decrypt : function (ciphertext,key) {
//         let decrypt = CryptoJS.AES.decrypt(ciphertext, CryptoJS.enc.Utf8.parse(key), {mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7});
//         let decString = CryptoJS.enc.Utf8.stringify(decrypt).toString();
//         if(decString.charAt(0) === "{" || decString.charAt(0) === "[" ){
//             //JSON.parse
//             decString = JSON.parse(decString);
//         }
//         return decString;
//     }
// };
// let rsaUtil = {
//     //RSA 位数，这里要跟后端对应
//     bits: 1024,

//     //当前JSEncrypted对象
//     thisKeyPair: {},

//     //生成密钥对(公钥和私钥)
//     genKeyPair: function (bits = rsaUtil.bits) {
//         let genKeyPair = {};
//         rsaUtil.thisKeyPair = new JSEncrypt({default_key_size: bits});

//         //获取私钥
//         genKeyPair.privateKey = rsaUtil.thisKeyPair.getPrivateKey();

//         //获取公钥
//         genKeyPair.publicKey = rsaUtil.thisKeyPair.getPublicKey();

//         return genKeyPair;
//     },

//     //公钥加密
//     encrypt: function (plaintext, publicKey) {
//         if (plaintext instanceof Object) {
//             //1、JSON.stringify
//             plaintext = JSON.stringify(plaintext)
//         }
//         publicKey && rsaUtil.thisKeyPair.setPublicKey(publicKey);
//         return rsaUtil.thisKeyPair.encrypt(plaintext);
//     },

//     //私钥解密
//     decrypt: function (ciphertext, privateKey) {
//         privateKey && rsaUtil.thisKeyPair.setPrivateKey(privateKey);
//         let decString = rsaUtil.thisKeyPair.decrypt(ciphertext);
//         if(decString.charAt(0) === "{" || decString.charAt(0) === "[" ){
//             //JSON.parse
//             decString = JSON.parse(decString);
//         }
//         return decString;
//     }
// };

export { utils as default };



