import AppConfig from "../../FrameWork/Config/AppConfig";
import User from "../../FrameWork/User/User";
import AppPlatform from "../../FrameWork/Util/AppPlatform";
import LevelUpManager from "../../Scripts/Manager/LevelUpManager";
import UserManager from "../../Scripts/Manager/UserManager";
import Common5 from "./Common5";

export default class CommonDefine {
    public static loginCode: string = '';
    //获取登录信息
    public static tryIndex = 0;


    public static replayGetLoginInfo(onSuccesscall?: Function) {

        console.log('replayGetLoginInfo++=')
        this.tryIndex++
        if (this.tryIndex >= 5) {
            return
        }

        let successcall = (code) => {
            CommonDefine.loginCode = code;

            let onFail = () => {

            }

            let onSuccess = (response) => {
                console.log(response, '数据+++=====')
                if (response.msg == 'OK') {
                    User.setUserId(response.openid)
                    if (onSuccesscall) {
                        onSuccesscall()
                    }
                }
            }

            CommonDefine.getLoginInfo(CommonDefine.loginCode, onFail, onSuccess)


        }

        let failcall = () => {

        }
        AppPlatform.loginPlatform_custom(successcall, failcall)


    }

    public static getLoginInfo(code, onFail, onSuccess) {
        let url = "https://xmb.ioe-times.com/api/getopenid"
        let headersTab = {}; //头数据
        let xhr: XMLHttpRequest = new XMLHttpRequest();
        xhr.timeout = 15000;

        //请求过程发生意外的回调
        xhr.onerror = function (error) {
            onSuccess(null);
            console.log("网络请求异常getLoginInfo");
        }
        //超时
        xhr.ontimeout = function (error) {
            onSuccess(null);
            console.log("网络超时getLoginInfo");
        }

        xhr.onreadystatechange = function () {

            let readyState = xhr.readyState;
            let status = xhr.status;

            if (readyState === 4) {
                let tab = { code: 1 }
                if (status >= 200 && status < 300) {
                    let responseText = xhr.responseText;
                    const response = JSON.parse(responseText);
                    console.log(response, 'CommonDefine ++= getLoginInfo data+++++')
                    onSuccess(response);

                } else {
                    let statusText = xhr.statusText;
                    console.log("接收内容:" + statusText)
                    onSuccess(null);
                }
            }
        }

        xhr.open("POST", url, true);

        if (!headersTab["Content-Type"]) {
            headersTab["Content-Type"] = "application/json";
        }
        if (headersTab) {
            for (let key in headersTab) {
                xhr.setRequestHeader(key, headersTab[key]);
            }
        }

        console.log(code, '用户code')
        let params = { GameName: "TiaoZhanRenShengDianFeng", Anonymous_code: "", "Code": code };
        let sendMsg = JSON.stringify(params);
        xhr.send(sendMsg);
    }




    // public static getServerData(onSuccess: Function, onFail: Function) {
    //     let userid = User.getUserId()
    //     if (userid == '') {
    //         cc.log('userid为空号getServerData')
    //         CommonDefine.replayGetLoginInfo()
    //         return
    //     }
    //     let url = "https://xmb.ioe-times.com/api/getdata"
    //     let headersTab = {}; //头数据
    //     let xhr: XMLHttpRequest = new XMLHttpRequest();
    //     xhr.timeout = 15000;

    //     //请求过程发生意外的回调
    //     xhr.onerror = function (error) {
    //         console.log('网络请求异常getServerData')
    //         onFail("网络请求异常");
    //     }
    //     //超时
    //     xhr.ontimeout = function (error) {
    //         console.log('网络超时getServerData')
    //         onFail("网络超时");
    //     }

    //     xhr.onreadystatechange = function () {

    //         let readyState = xhr.readyState;
    //         let status = xhr.status;

    //         if (readyState === 4) {
    //             let tab = { code: 1 }
    //             if (status >= 200 && status < 300) {
    //                 // console.log(xhr, 'xhr+++++')


    //                 let responseText = xhr.responseText;

    //                 // console.log(responseText, 'responseText+++++')


    //                 const response = JSON.parse(responseText);
    //                 if (response.flag == 0 && response.data != "") {
    //                     let data = JSON.parse(response.data)
    //                     console.log(data.GameData, 'getServerData+++++')
    //                     onSuccess(data.GameData);
    //                 }
    //                 else {
    //                     onFail(null);
    //                 }

    //             } else {
    //                 let statusText = xhr.statusText;
    //                 console.log("接收内容:" + statusText)
    //                 onFail(null);
    //             }
    //         } else {
    //             onFail();
    //         }
    //     }

    //     xhr.open("POST", url, true);

    //     if (!headersTab["Content-Type"]) {
    //         headersTab["Content-Type"] = "application/json";
    //     }
    //     if (headersTab) {
    //         for (let key in headersTab) {
    //             xhr.setRequestHeader(key, headersTab[key]);
    //         }
    //     }


    //     let params = { GameID: "TiaoZhanRenShengDianFeng", GameUserID: userid };
    //     let sendMsg = JSON.stringify(params);
    //     xhr.send(sendMsg);
    // }



    // public static setServerData(sendData, onSuccess: Function, onFail: Function) {
    //     let userid = User.getUserId()
    //     if (userid == '') {
    //         CommonDefine.replayGetLoginInfo()
    //         cc.log('userid为空号setServerData')
    //         return
    //     }
    //     let url = "https://xmb.ioe-times.com/api/setdata"
    //     let headersTab = {}; //头数据
    //     let xhr: XMLHttpRequest = new XMLHttpRequest();
    //     xhr.timeout = 15000;

    //     //请求过程发生意外的回调
    //     xhr.onerror = function (error) {

    //         onFail("网络请求异常");
    //     }
    //     //超时
    //     xhr.ontimeout = function (error) {

    //         onFail("网络超时");
    //     }

    //     xhr.onreadystatechange = function () {

    //         let readyState = xhr.readyState;
    //         let status = xhr.status;

    //         if (readyState === 4) {
    //             let tab = { code: 1 }
    //             if (status >= 200 && status < 300) {
    //                 let responseText = xhr.responseText;
    //                 const response = JSON.parse(responseText);
    //                 console.log('setServerData+++++')
    //                 onSuccess(response);
    //             } else {
    //                 let statusText = xhr.statusText;
    //                 console.log("接收内容:" + statusText)
    //                 onSuccess(null);
    //             }
    //         }
    //     }

    //     xhr.open("POST", url, true);

    //     if (!headersTab["Content-Type"]) {
    //         headersTab["Content-Type"] = "application/json";
    //     }
    //     if (headersTab) {
    //         for (let key in headersTab) {
    //             xhr.setRequestHeader(key, headersTab[key]);
    //         }
    //     }

    //     let params = { GameID: "TiaoZhanRenShengDianFeng", GameUserID: userid, "GameData": sendData };
    //     let sendMsg = JSON.stringify(params);
    //     xhr.send(sendMsg);
    // }


    public static sendRankData(onSuccess: Function, onFail: Function, isZhouBang: boolean) {
        let level = User.getMyLevel()
        let chenghao = LevelUpManager.getChengHao()
        let userId = User.getUserId()
        let headLink = User.getUserLinkHead()
        let userName = User.getUserName()
        let userNameRandom = User.getUserNameRandom()
        let time = new Date().getTime()

        let name = ''
        if (userName == '') {
            if (userNameRandom == '') {
                name = ""//假名字
            } else {
                name = userNameRandom
            }
        } else {
            name = userName
        }



        if (User.getUserId() == '') {
            if (ZYSDK.ZYSDK.getUserId()) {
                ZYSDK.ZYSDK.getUserId().then((uid) => {
                    console.log('uid+++++++++===', uid)
                    User.setUserId(uid)
                    console.log('再来一次++++')

                })
            }

            console.log('没有获取到userid,重新获取一次??')
            return
        }

        let url = "https://xx.ioe-times.com/rank/api/v1/rank/setrank"
        let headersTab = {}; //头数据
        let xhr: XMLHttpRequest = new XMLHttpRequest();
        xhr.timeout = 5000;

        //请求过程发生意外的回调
        xhr.onerror = function (error) {

            onFail("网络请求异常");
        }
        //超时
        xhr.ontimeout = function (error) {

            onFail("网络超时");
        }

        xhr.onreadystatechange = function () {

            let readyState = xhr.readyState;
            let status = xhr.status;

            if (readyState === 4) {
                let tab = { code: 1 }
                if (status >= 200 && status < 300) {
                    let responseText = xhr.responseText;
                    const response = JSON.parse(responseText);
                    console.log(response, 'setServerData11+++++')
                    onSuccess(response);
                } else {
                    let statusText = xhr.statusText;
                    console.log("接收内容:" + statusText)
                    onSuccess(null);
                }
            }
        }

        xhr.open("POST", url, true);

        if (!headersTab["Content-Type"]) {
            headersTab["Content-Type"] = "application/json";
        }
        if (headersTab) {
            for (let key in headersTab) {
                xhr.setRequestHeader(key, headersTab[key]);
            }
        }


        if (isZhouBang) {
            let myWeekDayTime = User.getStatistics("myWeekDayTime")
            //不是一周内的新玩家,就去拿前20名,不需要自己的排名
            if (Date.now() > myWeekDayTime) {
                let params = {
                    "gid": AppConfig.TT_APP_ID_custom + '_zb',          //游戏gid
                    "userid": userId,             //用户id
                    "nickname": name,  //昵称
                    "pic": headLink,                     //头像
                    "score": -1,              //等级
                    "remark": JSON.stringify({ chenghao: chenghao }),
                    "ts": time,      //时间戳13位
                    "firstsize": 20,
                };
                let sendMsg = JSON.stringify(params);
                //console.log(params, 'params+++++++++++++===')
                xhr.send(sendMsg);
            } else {
                let params = {
                    "gid": AppConfig.TT_APP_ID_custom + '_zb',          //游戏gid
                    "userid": userId,             //用户id
                    "nickname": name,  //昵称
                    "pic": headLink,                     //头像
                    "score": level,              //等级
                    "remark": JSON.stringify({ chenghao: chenghao }),
                    "ts": time      //时间戳13位
                };
                let sendMsg = JSON.stringify(params);
                //console.log(params, 'params+++++++++++++===')
                xhr.send(sendMsg);
            }
        } else {
            let params = {
                "gid": AppConfig.TT_APP_ID_custom,          //游戏gid
                "userid": userId,             //用户id
                "nickname": name,  //昵称
                "pic": headLink,                     //头像
                "score": level,              //等级
                "remark": JSON.stringify({ chenghao: chenghao }),
                "ts": time      //时间戳13位
            };
            let sendMsg = JSON.stringify(params);
            //console.log(params, 'params+++++++++++++===')
            xhr.send(sendMsg);
        }

    }

    /**
     * 新的读取数据库备份数据接口
     * @param finishCall 读取成功后的回调(重新加载场景)
     */
    public static getServerData(finishCall?) {
        let userID = User.getUserId()

        if (userID == '') {
            //读取数据
            console.log('存档数据拉取中')
            let comSuccesscall = (GameData) => {
                console.error('存档数据拉取成功')

                ZYSDK.ZYSDK.getUserId().then((uid) => {
                    console.log('uid+++++++++===', uid)
                    User.setUserId(uid)
                })
                // User.setUserId('userIdcomSuccesscall')
                User.setFirstIn(false);

                UserManager.readDataByUrl(GameData)
                if (finishCall) {
                    finishCall()
                }
            }

            let comFailcall = () => {
                console.error('存档数据拉取失败')
            }
            ZYSDK.ZYSDK.getGameData(comSuccesscall, comFailcall)
        } else {
            console.log('不需要拉取存档数据')
        }
    }

    public static saveData(isShow = false) {
        if (Common5.saveTime == 0) {
            let sendData = UserManager.sendDataToUrl()
            Common5.saveTime = 30
            ZYSDK.ZYSDK.setGameData(sendData, () => {

                console.error('保存数据成功')

            }, (error) => {
                console.error(error, '保存数据失败')
            })
        } else {
            console.log('保存数据过于频繁')
        }
    }

}