import { EVENT_TYPE } from "../../game/data/GameData";
import MKSwitch from "../../mk/MKSwitch";
import GameConst from "../data/GameConst";
import PlayerConst, { DATA_STORAGE_KEY } from "../data/PlayerConst";
import CashOutUI from "../view/CashOutUI";
import DataMgr from "./DataMgr";
import EffectMgr from "./EffectMgr";

import GameMgr, { UI_NAME } from "./GameMgr";
import StorageMgr from "./StorageMgr";

const { ccclass, property } = cc._decorator;

@ccclass
export default class HttpMgr {

    //单例模式---------------------------
    private static instance: HttpMgr = null;

    public static get Inst(): HttpMgr {
        if (!HttpMgr.instance) {
            HttpMgr.instance = new HttpMgr();
        }
        return HttpMgr.instance;
    }

    /**
   * 获取request
   * @param url        url
   * @param bodyData   数据
   * @param httpMethod method 默认GET,可以选择POST
   */
    httpRquest(url: string, bodyData: any = null, httpMethod: HTTP_METHOD): Promise<any> {

        if (!GameConst.ifConnectService) {
            mk.console.log("[HttpMgr] 不连接服务器开关打开");
            return new Promise((resolve, reject) => { reject() });
            return;
        }

        // LogUtil.log("[HttpMgr] 连接服务器" + url);

        // LogUtil.log("[getRequest] url", url);
        // LogUtil.log("[getRequest] bodyData", bodyData);

        return new Promise((resolve, reject) => {
            var request = cc.loader.getXMLHttpRequest();
            request.open(httpMethod, url, true)

            request.onerror = (err) => {
                mk.console.error(`${HTTP_METHOD[httpMethod]} 错误 onerror`);
                EffectMgr.Inst.addTip("您的网络发生异常,请检查下哈");
                reject(err);
            }

            request.ontimeout = (err) => {
                mk.console.error(`${HTTP_METHOD[httpMethod]} 超时 ontimeout`);
                reject(err);
            }

            request.onloadend = () => {
                let respone = request.response;
                if (!respone) {
                    mk.console.error("[getRequest] 获取用户信息错误 ", request);
                    reject();
                }

                let info;

                if (typeof (respone) === "string") {
                    info = JSON.parse(respone);
                }
                else {
                    info = respone;
                }

                // LogUtil.log("info", info);

                // LogUtil.log("url.split",url.split("/"))

                // LogUtil.log(`[HttpMgr] ${HTTP_METHOD[httpMethod]}：${url.split("/")[url.split("/").length - 1]}`, info.errmsg)

                if (info.errcode === 0) {
                    resolve(info)
                }
                else {
                    if (info.errcode === -20003) {
                        GameMgr.Inst.sendEvent("Error", `服务器发生-20003错误`);
                    }
                    reject(info);
                }
            }

            let headers = ["Content-Type", "application/json;charset=UTF-8"];

            for (var i = 0; i < headers.length; i += 2) {
                request.setRequestHeader(headers[i], headers[i + 1]);
            }

            //POST方式：跟后端了解,可以没有BodyData参数；GET一定没有BodyData参数
            if (bodyData) {
                request.send(bodyData)
            }
            else {
                request.send()
            }
        })
    }

    //----------------------------接口操作-------------------------------------

    /**上线
     * 如果有key 或者 uin 直接进入AccountInfo
     * 如果没有 连接
     */
    online() {
        //这个需要打印
        console.log("[HttpMgr] GameConst.url_service", GameConst.url_service);
        if (GameConst.session_key != '' && GameConst.uin != '') {
            mk.console.log("[HttpMgr] online 已经有缓存信息");
            HttpMgr.instance.getUserInfo();
        }
        else {
            mk.console.log("[HttpMgr] online 新用户");
            HttpMgr.instance.connect();
        }
    }

    /**连接
     * 获取零食的tmp_uin
     */
    connect() {

        // GameMgr.Inst.sendEvent(UI_NAME.Loading, "开始加载");

        let url = `${GameConst.url_service}/connect`;
        let bodyData = {
            "psk": GameConst.randomKey,
            "appid": GameConst.appid
        }
        mk.console.log("[connect]bodyData", bodyData)

        let encryptData = mk.encrypt.rsaEncrypt(JSON.stringify(bodyData));

        this.httpRquest(url, encryptData, HTTP_METHOD.POST).then((responseData) => {

            let decryptData = mk.encrypt.decrypt(responseData.encrypt, GameConst.randomKey, GameConst.appid);
            mk.console.log("[HttpMgr] connect", decryptData);
            if (decryptData) {
                GameConst.tmp_uin = JSON.parse(decryptData).tmp_uin;
                StorageMgr.Inst.setStorage(DATA_STORAGE_KEY.uin, GameConst.tmp_uin);

                HttpMgr.instance.wxlogin();
                //星云关键埋点
                GameMgr.Inst.sendEventCp(`${UI_NAME.Loading}1`, "开始加载");
            }

        }).catch((err) => {
            mk.console.log("[HttpMgr] connect err", err);
        });

    }

    /**微信登陆
     * @param ifWxAuthCallBack 是否授权回调
     */
    wxlogin(ifWxAuthCallBack: boolean = false) {

        mk.console.log("[Httpmgr] wxlogin 微信登陆");
        let url = `${GameConst.url_service}/wxlogin`;

        let data = {
            "code": GameConst.wxCode,
            "timestamp": Math.floor(new Date().getTime() * 0.001)
        }
        let bodydata = null;
        let encryptInfo = null

        let uin = GameConst.wxCode == '' ? GameConst.tmp_uin : GameConst.uin;
        let encryptKey = GameConst.wxCode == "" ? GameConst.randomKey : GameConst.session_key;

        encryptInfo = mk.encrypt.encrypt(JSON.stringify(data), encryptKey, GameConst.appid);

        bodydata = {
            "uin": uin,
            "encrypt": encryptInfo
        }

        // LogUtil.log("[Httpmgr] wxlogin uin",uin);
        // LogUtil.log("[Httpmgr] wxlogin encryptKey",encryptKey);
        // LogUtil.log("[Httpmgr] wxlogin encryptInfo",encryptInfo);

        // return;

        this.httpRquest(url, JSON.stringify(bodydata), HTTP_METHOD.POST).then((responseData) => {

            /**解密的数据 */
            let decryptData = null;
            if (GameConst.wxCode != '') {
                decryptData = mk.encrypt.decrypt(responseData.encrypt, GameConst.session_key, GameConst.appid)
            }
            else {
                decryptData = mk.encrypt.decrypt(responseData.encrypt, GameConst.randomKey, GameConst.appid)
            }

            if (decryptData) {

                let data_parse = JSON.parse(decryptData);

                //【测试状态】不发送事件,就不打印日志
                mk.console.log("[HttpMgr] wxlogin", data_parse);

                GameConst.login_ticket = data_parse.login_ticket

                /**加密的数据 */
                let encrypt_login_ticket =mk.encrypt.encrypt(GameConst.login_ticket, GameConst.localEncryptKey, GameConst.appid)
                StorageMgr.Inst.setStorage(DATA_STORAGE_KEY.login_ticket, encrypt_login_ticket);

                if (GameConst.uin != data_parse.uin) {
                    GameConst.uin = data_parse.uin
                    // GameConst.isNew = true; //根本无须判定,getDetailInfo那边会鉴定
                }
                else {
                    // GameConst.isNew = false;//根本无须判定,getDetailInfo那边会鉴定
                }
                mk.console.log("GameConst.isNew", GameConst.isNew);
                mk.console.log("GameConst.uin", GameConst.uin);
                let encrypt_uin = mk.encrypt.encrypt(GameConst.uin, GameConst.localEncryptKey, GameConst.appid)
                StorageMgr.Inst.setStorage(DATA_STORAGE_KEY.uin, encrypt_uin)

                HttpMgr.instance.checklogin(ifWxAuthCallBack);
            }
        }).catch((err) => {
            mk.console.log("[HttpMgr] wxlogin err", err);
        });
    }

    checklogin(ifWxAuthCallBack: boolean = false) {

        let url = `${GameConst.url_service}/checklogin`;

        let tmp_key
        if (GameConst.wxCode != '') {
            tmp_key = GameConst.session_key
        }
        else {
            tmp_key = mk.encrypt.randomString()
            GameConst.randomKey_new = tmp_key
        }

        let bodyData =
        {
            "tmp_key": tmp_key,
            "uin": GameConst.uin,
            "login_ticket": GameConst.login_ticket,
            "appid": GameConst.appid
        }

        let rasEncryptData = mk.encrypt.rsaEncrypt(JSON.stringify(bodyData));

        this.httpRquest(url, rasEncryptData, HTTP_METHOD.POST).then((responseData) => {

            let decryptData = null;
            if (GameConst.wxCode != '') {
                decryptData = mk.encrypt.decrypt(responseData.encrypt, GameConst.session_key, GameConst.appid)
            }
            else {
                decryptData = mk.encrypt.decrypt(responseData.encrypt, GameConst.randomKey_new, GameConst.appid)
            }

            mk.console.log("[HttpMgr] checklogin", decryptData);

            if (decryptData) {
                let data_parse = JSON.parse(decryptData)
                GameConst.session_key = data_parse.session_key

                let encrypt_session_key = mk.encrypt.encrypt(GameConst.session_key, GameConst.localEncryptKey, GameConst.appid)
                StorageMgr.Inst.setStorage(DATA_STORAGE_KEY.session_key, encrypt_session_key)

                HttpMgr.Inst.getUserInfo(ifWxAuthCallBack);
            }
        }).catch((err) => {
            mk.console.log("[HttpMgr] checklogin err", err);
        });;
    }

    /**获取账户信息 */
    getUserInfo(ifWxAuthCallBack: boolean = false) {

        let url = `${GameConst.url_service}/user`;

        let data =
        {
            "uin": GameConst.uin,
            "login_ticket": GameConst.login_ticket,
            "timestamp": Math.floor(new Date().getTime() * 0.001)
        }

        mk.console.log("getUserInfo", data);

        let encryptData = mk.encrypt.encrypt(JSON.stringify(data), GameConst.session_key, GameConst.appid)

        let bodyData = {
            "uin": GameConst.uin,
            "encrypt": encryptData
        }

        this.httpRquest(url, JSON.stringify(bodyData), HTTP_METHOD.POST).then((responseData) => {

            let data = this.parseResponseData(responseData)

            mk.console.log("[HttpMgr] user", data);

            // Object.keys(data).forEach((e) => {
            //     LogUtil.log("[HttpMgr]1 " + e);
            //     LogUtil.log("[HttpMgr]2 " + data[e]);
            // });

            if (data) {
                GameConst.isNew = data["is_new_user"];
                mk.console.log("[HttpMgr] user GameConst.isNew", GameConst.isNew);
                //新手 初始化引导
                if (GameConst.isNew) {
             
                }
                else {

                }
                // LogUtil.log("data.is_new_user", data.is_new_user);
                GameConst.isAuth = data["is_auth"]
                mk.console.log("GameConst.isAuth", GameConst.isAuth);
                //是否首次登陆
                PlayerConst.ifFirstLoginToday = data["is_first_login_today"];

                if (data.is_auth) {
                    let encrypt_auth = mk.encrypt.encrypt('true', GameConst.localEncryptKey, GameConst.appid)
                    StorageMgr.Inst.setStorage(DATA_STORAGE_KEY.isAuth, encrypt_auth)

                    PlayerConst.headImgUrl = data["HeadImgUrl"];
                    PlayerConst.nickName = data["NickName"];

                    let nickname = StorageMgr.Inst.getStorage(DATA_STORAGE_KEY.nickname);
                    if (!!nickname) {
                        //改名了
                        if (nickname != data["nickname"]) {
                            StorageMgr.Inst.setStorage(DATA_STORAGE_KEY.nickname, PlayerConst.nickName);
                        }
                    }

                    //原本放在初始化 首页、提现、用户信息的头像取消，采用分发事件代替

                    HttpMgr.Inst.getDetailInfo(ifWxAuthCallBack)
                }
                else {
                    HttpMgr.Inst.getDetailInfo(ifWxAuthCallBack)
                }
            }
        }).catch((err) => {
            mk.console.log("[HttpMgr] user err", err);
        });
    }

    //-----------------------------------游戏相关接口---------------------------------

    /**获取细节信息 */
    getDetailInfo(ifWxAuthCallBack: boolean = false) {
        // LogUtil.log("[HttpMgr] getDetailInfo");
        let url = `${GameConst.url_service}/game/details`;

        let data = {}
        let bodyData = this.encryptBodyData(data);
        // LogUtil.log("[HttpMgr] getDetailInfo", bodyData);
        this.httpRquest(url, JSON.stringify(bodyData), HTTP_METHOD.POST).then((responseData) => {
            let data = this.parseResponseData(responseData);

            mk.console.log("[HttpMgr] details", data);

            //解析获取的信息
            PlayerConst.getDetailInfo(data);

            //如果微信登陆回调返回
            if (ifWxAuthCallBack) {

                //检测是否刷新一下数据
                if (PlayerConst.ifFirstLoginToday) {
                    if (PlayerConst.cheeckIfNewAuthUser(data.register_date)) {
                        mk.console.log("[WxAuth] 首日新用户")
                    }
                    else {
                        mk.console.log("[WxAuth] 首日登陆老用户")
                        DataMgr.Inst.resteData();
                    }
                }
                else {
                    mk.console.log("[WxAuth] 非首日登陆")
                }

                //获取打卡信息
                HttpMgr.Inst.getClockInInfo();

                console.log("Detail  分发 微信授权事件");
                //分发微信授权返回事件
                mk.event.emit(EVENT_TYPE.BACK_WxAuth);

                //初始化游戏 Game
                //初始化结束按钮 gameOverUI
                //初始化每日提现 node_dailyCashOutUI
            }
            else {
                if (PlayerConst.ifFirstLoginToday) {
                    PlayerConst.ifFirstLoginToday = false;
                    DataMgr.Inst.resteData();
                }
            }

            /**是否登陆结束 */
            GameConst.ifLoginFinished = true;

        }).catch((err) => {
            mk.console.log("[HttpMgr] details", err);
        });
    }

    /**获取体力值 */
    getStrength(): Promise<any> {

        let url = `${GameConst.url_service}/game/strength`;

        let data = {}
        let bodyData = this.encryptBodyData(data);

        return new Promise((resolve, reject) => {
            this.httpRquest(url, JSON.stringify(bodyData), HTTP_METHOD.POST).then((responseData) => {
                let data = this.parseResponseData(responseData);
                mk.console.log("[HttpMgr] strength", data);
                resolve(data);
            }).catch((err) => {
                reject(err);
            });
        })

    }

    /**增减体力
     * @param:handle_type  1 是扣除 2 看视频获取 3 恢复体力
     * @param:num          数量
     * @param:curLevel     当前的关卡数目
     */
    strengthFigure(handle_type: number, num: number, curLevel: number): Promise<any> {
        let url = `${GameConst.url_service}/game/strength/figure`;

        let data = {
            "handel_type": handle_type,
            "num": num,
            "pass_no": curLevel
        }

        let bodyData = this.encryptBodyData(data);

        return new Promise((resolve, reject) => {
            this.httpRquest(url, JSON.stringify(bodyData), HTTP_METHOD.POST).then((responseData) => {
                let data = this.parseResponseData(responseData);
                mk.console.log("[HttpMgr] strength/figure", data, handle_type, PlayerConst.energyNum);
                resolve(data);
            }).catch((err) => {
                reject(err);
            });

        });
    }

    /**道具信息 */
    propsInfo() {
        let url = `${GameConst.url_service}/game/propsInfo`;

        let data = {}
        let bodyData = this.encryptBodyData(data);

        this.httpRquest(url, JSON.stringify(bodyData), HTTP_METHOD.POST).then((responseData) => {
            let data = this.parseResponseData(responseData);
            mk.console.log("[HttpMgr] propsInfo", data);
        });
    }

    /**道具
     * @param handel_type 处理类型 1 增 2 减 
     * @param prop_code   道具编号
     * @param prop_num    道具数量
     */
    prop(handel_type: number, prop_code: string, prop_num: number): Promise<any> {

        mk.console.log("prop_code", prop_code);
        let url = `${GameConst.url_service}/game/prop`;

        let data = {
            "handel_type": handel_type,
            "prop_code": prop_code,
            "count": prop_num
        }
        let bodyData = this.encryptBodyData(data);

        return new Promise((resolve, reject) => {
            this.httpRquest(url, JSON.stringify(bodyData), HTTP_METHOD.POST).then((responseData) => {
                let data = this.parseResponseData(responseData);
                mk.console.log("[HttpMgr] prop", data);
            }).catch((err) => {
                reject(err);
            });
        })
    }

    /**通关 
     * @param levelNum 关卡数目
     */
    pass(levelNum: number, score: number = 0): Promise<any> {

        let url = `${GameConst.url_service}/game/pass`;

        let data = {}
        if (score) {
            data = {
                "pass_no": levelNum,
                "score": score
            }
        }
        else {
            data = {
                "pass_no": levelNum,
            }
        }

        let bodyData = this.encryptBodyData(data);

        return new Promise((resolve, reject) => {
            this.httpRquest(url, JSON.stringify(bodyData), HTTP_METHOD.POST).then((responseData) => {
                let data = this.parseResponseData(responseData);
                mk.console.log("[HttpMgr] pass", data);
                this.getDetailInfo();
                resolve(data);
            }).catch((err) => {
                mk.console.log("[HttpMgr] pass err", err);
                reject(err);
            });
        })
    }

    /**获取打卡信息 */
    getClockInInfo(): Promise<any> {
        let url = `${GameConst.url_service}/cash/info`;

        let data = {

        }

        let bodyData = this.encryptBodyData(data);

        return new Promise((resolve, reject) => {
            this.httpRquest(url, JSON.stringify(bodyData), HTTP_METHOD.POST).then((responseData) => {
                let data = this.parseResponseData(responseData);
                mk.console.log("[HttpMgr]  getClickInInfo", data);
                PlayerConst.clockInCashInfo = data;

                let node_cashOutUI = mk.ui.getCurOnPanel("CashOutUI");
                if (node_cashOutUI) {
                    let cashOutUI = node_cashOutUI.getComponent(CashOutUI)
                    cashOutUI.initCashOutItem();
                    cashOutUI.setCurSelectItemBtn(cashOutUI.curSelectCashOutItem);
                }

                resolve(data);
            }).catch((err) => {
                mk.console.log("刷新提现！！！！！！！！！！！！！！！！！！！！！！！！err", err.errmsg);
                reject(err);
            });
        })
    }

    //-----------------------------------红包关接口-----------------------------------

    /**新手红包
     * @param:get_type   获取类型 0 普通 1 双倍
     * @param:pass_no    关卡数
     * @param:red_mondey 红包数目
     */
    newerRedPacket(get_type: number, pass_no: number, red_mondey: number): Promise<any> {

        let url = `${GameConst.url_service}/red-package/newer`;

        let data = {
            "get_type": get_type,
            "pass_no": pass_no,
            "red_money": red_mondey
        }
        // LogUtil.log("data",data);
        let bodyData = this.encryptBodyData(data);
        return new Promise((resolve, reject) => {
            this.httpRquest(url, JSON.stringify(bodyData), HTTP_METHOD.POST).then((responseData) => {
                let data = this.parseResponseData(responseData);
                mk.console.log("[HttpMgr] newerRedPacket", data);
            }).catch((err) => {
                reject(err);
            });
        })
    }

    /**登陆红包
     * @param:get_type   获取类型 0 普通 1 双倍
     * @param:pass_no    关卡数
     * @param:red_mondey 红包数目
     */
    loginRedPacket(get_type: number, pass_no: number, red_mondey: number): Promise<any> {

        let url = `${GameConst.url_service}/red-package/login`;

        let data = {
            "get_type": get_type,
            "pass_no": pass_no,
            "red_money": red_mondey
        }
        // LogUtil.log("data",data);
        let bodyData = this.encryptBodyData(data);

        return new Promise((resolve, reject) => {
            this.httpRquest(url, JSON.stringify(bodyData), HTTP_METHOD.POST).then((responseData) => {
                let data = this.parseResponseData(responseData);
                mk.console.log("[HttpMgr] loginRedPacket", data);
            }).catch((err) => {
                reject(err);
            });
        })
    }

    /**通关红包
    * @param:get_type   获取类型 0 普通 1 双倍
    * @param:pass_no    关卡数
    * @param:red_mondey 红包数目
    */
    passRedPacket(get_type: number, pass_no: number, red_mondey: number): Promise<any> {


        let url = `${GameConst.url_service}/red-package/pass`;

        let data = {
            "get_type": get_type,
            "pass_no": pass_no,
            "red_money": red_mondey
        }
        // LogUtil.log("data",data);
        let bodyData = this.encryptBodyData(data);

        return new Promise((resolve, reject) => {
            this.httpRquest(url, JSON.stringify(bodyData), HTTP_METHOD.POST).then((responseData) => {
                let data = this.parseResponseData(responseData);
                mk.console.log("[HttpMgr] passRedPacket", data);
                if (data.clock_date) {
                    PlayerConst.clockInDate = data.clock_date;
                }

                mk.console.log("data.clock_count", data.clock_count);
                if (data.clock_count) {
                    PlayerConst.clockInDay = data.clock_count;
                    mk.console.log("PlayerConst.clockInDay", PlayerConst.clockInDay);
                }
            }).catch((err) => {
                reject(err);
            });
        })
    }

    /**随机红包
    * @param:get_type   获取类型 0 普通 1 双倍
    * @param:pass_no    关卡数
    * @param:red_mondey 红包数目
    */
    randomRedPacket(get_type: number, pass_no: number, red_mondey: number): Promise<any> {

        let url = `${GameConst.url_service}/red-package/random`;

        let data = {
            "get_type": get_type,
            "pass_no": pass_no,
            "red_money": red_mondey
        }
        // LogUtil.log("data",data);
        let bodyData = this.encryptBodyData(data);

        return new Promise((resolve, reject) => {
            this.httpRquest(url, JSON.stringify(bodyData), HTTP_METHOD.POST).then((responseData) => {
                let data = this.parseResponseData(responseData);
                mk.console.log("[HttpMgr] randomRedPacket", data);
            }).catch((err) => {
                reject(err);
            });
        })
    }

    //-----------------------------------提现接口-----------------------------------
    /**提现
     * @param amount 提现数额
     * @param cash_type 提现类型
     */
    cash(amount: number, cash_type: number): Promise<any> {

        let url = `${GameConst.url_service}/cash/getCash`;
        let data = {
            "amount": amount,
            "cash_type": cash_type
        }
        let bodyData = this.encryptBodyData(data);

        mk.console.log("cash_type", cash_type);
        return new Promise((resolve, reject) => {
            this.httpRquest(url, JSON.stringify(bodyData), HTTP_METHOD.POST).then((responseData) => {
                let data = this.parseResponseData(responseData);
                mk.console.log("[HttpMgr] cash", data);
                resolve(data);
            }).catch((err) => {
                reject(err);
            });
        })
    }

    caseRecords(): Promise<any> {

        let url = `${GameConst.url_service}/cash/records`;
        let data = {

        }
        let bodyData = this.encryptBodyData(data);

        return new Promise((resolve, reject) => {
            this.httpRquest(url, JSON.stringify(bodyData), HTTP_METHOD.POST).then((responseData) => {
                let data = this.parseResponseData(responseData);
                mk.console.log("[HttpMgr] cash/records", data);
            }).catch((err) => {
                reject(err);
            });
        })
    }


    //--------------------------------积分 商城接口接口---------------------------------

    /**得分 暂且不用 合并到 pass接口*/
    public passScore(levelNum: number, score: number): Promise<any> {
        mk.console.log("[HttpMgr] game/passScore data", levelNum, score);
        let url = `${GameConst.url_service}/game/passScore`;
        let data = {
            "pass_no": levelNum,
            "score": score
        }
        let bodyData = this.encryptBodyData(data);

        return new Promise((resolve, reject) => {
            this.httpRquest(url, JSON.stringify(bodyData), HTTP_METHOD.POST).then((responseData) => {
                let data = this.parseResponseData(responseData);
                mk.console.log("[HttpMgr] game/passScore", data);
                resolve(data);
            }).catch((err) => {
                mk.console.log("[HttpMgr] game/passScore err", err);
                EffectMgr.Inst.addTip("你忘记啦,这关领取过哦");
                reject(err);
            });
        })
    }

    /**显示商城标题 */
    public shopGetSlogan() {
        let url = `${GameConst.url_service}/shopping-mall/getSlogan`;
        let data = {

        }
        let bodyData = this.encryptBodyData(data);

        return new Promise((resolve, reject) => {
            this.httpRquest(url, JSON.stringify(bodyData), HTTP_METHOD.POST).then((responseData) => {
                let data = this.parseResponseData(responseData);
                mk.console.log("[HttpMgr] shopping-mall/getSlogan", data);

            }).catch((err) => {
                mk.console.log("[HttpMgr] shopping-mall/getSlogan", err);
                reject(err);
            });
        })
    }


    /**商城商品列表 */
    public shopGoodsList() {
        let url = `${GameConst.url_service}/shopping-mall/goodsList`;
        let data = {

        }
        let bodyData = this.encryptBodyData(data);

        return new Promise((resolve, reject) => {
            this.httpRquest(url, JSON.stringify(bodyData), HTTP_METHOD.POST).then((responseData) => {
                let data = this.parseResponseData(responseData);
                mk.console.log("[HttpMgr] shopping-mall/goodsList", data);
                GameConst.getShopGoodsListConfig(data);
            }).catch((err) => {
                mk.console.log("[HttpMgr] shopping-mall/goodsList", err);
                reject(err);
            });
        })
    }

    /**商城转盘奖励列表 */
    public shopPrizeList() {
        let url = `${GameConst.url_service}/shopping-mall/prizeList`;
        let data = {

        }
        let bodyData = this.encryptBodyData(data);

        return new Promise((resolve, reject) => {
            this.httpRquest(url, JSON.stringify(bodyData), HTTP_METHOD.POST).then((responseData) => {
                let data = this.parseResponseData(responseData);
                mk.console.log("[HttpMgr] shopping-mall/prizeList", data);
                GameConst.getShopPrizeListConfig(data);
            }).catch((err) => {
                mk.console.log("[HttpMgr] shopping-mall/prizeList", err);
                reject(err);
            });
        })
    }

    /**抽奖 */
    public shopLuckDraw(): Promise<any> {
        let url = `${GameConst.url_service}/shopping-mall/luckdraw`;
        let data = {

        }
        let bodyData = this.encryptBodyData(data);

        return new Promise((resolve, reject) => {
            this.httpRquest(url, JSON.stringify(bodyData), HTTP_METHOD.POST).then((responseData) => {
                let data = this.parseResponseData(responseData);
                mk.console.log("[HttpMgr] shopping-mall/luckdraw", data);
                resolve(data);
            }).catch((err) => {
                mk.console.log("[HttpMgr] shopping-mall/luckdraw", err);
                reject(err);
            });
        })
    }

    /**显示记录
     * @param type 1兑换记录  2 抽奖记录
     * @param
     */
    public shopExchangeRecord(type: number): Promise<any> {
        let url = `${GameConst.url_service}/shopping-mall/exchangeRecord`;
        let data = {
            "type": type
        }
        let bodyData = this.encryptBodyData(data);

        return new Promise((resolve, reject) => {
            this.httpRquest(url, JSON.stringify(bodyData), HTTP_METHOD.POST).then((responseData) => {
                let data = this.parseResponseData(responseData);
                if (type === 1) {
                    GameConst.data_exchangeRecord = data;
                }
                else if (type === 2) {
                    GameConst.data_luckDrawRecord = data;
                }
                mk.console.log("[HttpMgr] shopping-mall/exchangeRecord", data);
                resolve(data);
            }).catch((err) => {
                mk.console.log("[HttpMgr] shopping-mall/exchangeRecord", err);
                reject(err);
            });
        })
    }

    /**商城兑换 
     * @param goods_code 商品code
     * @param count 个数 默认是1
    */
    public shopExchange(goods_code: string, count: number = 1): Promise<any> {
        let url = `${GameConst.url_service}/shopping-mall/doExChange`;
        let data = {
            "goods_code": goods_code,
            "count": count
        }
        let bodyData = this.encryptBodyData(data);

        return new Promise((resolve, reject) => {
            this.httpRquest(url, JSON.stringify(bodyData), HTTP_METHOD.POST).then((responseData) => {
                let data = this.parseResponseData(responseData);
                resolve(data);
                mk.console.log("[HttpMgr] shopping-mall/doExChange", data);
            }).catch((err) => {
                mk.console.log("[HttpMgr] shopping-mall/doExChange", err);
                reject(err);
            });
        })
    }

    //互推位相关接口--------------------------------------------------------------------

    /**抽奖 */
    public recommendList(): Promise<any> {
        let url = `${GameConst.url_service}/fission/recommendList`;
        let data = {

        }
        let bodyData = this.encryptBodyData(data);

        return new Promise((resolve, reject) => {
            this.httpRquest(url, JSON.stringify(bodyData), HTTP_METHOD.POST).then((responseData) => {
                let data = this.parseResponseData(responseData);
                mk.console.log("[HttpMgr] fission/recommendList", data);
                resolve(data);
            }).catch((err) => {
                mk.console.log("[HttpMgr] fission/recommendList", err);
                reject(err);
            });
        })
    }

    /**抽奖 */
    public appDownloadLog(downloadAppId: string): Promise<any> {
        let url = `${GameConst.url_service}/fission/appDownloadLog`;
        let data = {
            "downloadAppId": downloadAppId,
        }
        let bodyData = this.encryptBodyData(data);

        return new Promise((resolve, reject) => {
            this.httpRquest(url, JSON.stringify(bodyData), HTTP_METHOD.POST).then((responseData) => {
                let data = this.parseResponseData(responseData);
                mk.console.log("[HttpMgr] fission/appDownloadLog", data);
                resolve(data);
            }).catch((err) => {
                mk.console.log("[HttpMgr] fission/appDownloadLog", err);
                reject(err);
            });
        })
    }

    //API回传--------------------------------------------------------------------------
    /**更新设备信息 */
    public updateDeviceInfo(deviceInfo: any) {
        let url = `${GameConst.url_service}/user/machine`;
        let data = deviceInfo;
        let bodyData = this.encryptBodyData(data);
        return new Promise((resolve, reject) => {
            this.httpRquest(url, JSON.stringify(bodyData), HTTP_METHOD.POST).then((responseData) => {
                let data = this.parseResponseData(responseData);
                mk.console.log("[HttpMgr] user/machine", data);
            }).catch((err) => {
                reject(err);
                mk.console.log("[HttpMgr] user/machine err", err);
            });
        })
    }

    /**巨量API回传
     * @param type 0 激活 6 次留
     */
    public juliangAPIActive(type: number) {
        if (cc.sys.os != cc.sys.OS_ANDROID) {
            return;
        }

        mk.console.log("巨量回传 type", type);
        let url = `${GameConst.url_service}/ad/oe/callback/activate`;
        let data = {
            "event_type": type,
            "source": GameConst.appVersion + ';'
        }
        let bodyData = this.encryptBodyData(data);
        return new Promise((resolve, reject) => {
            this.httpRquest(url, JSON.stringify(bodyData), HTTP_METHOD.POST).then((responseData) => {
                let data = this.parseResponseData(responseData);
                mk.console.log("[HttpMgr] juliangcallback/activate", data);
            }).catch((err) => {
                mk.console.log("[HttpMgr] juliangcallback/activate err", err);
                reject(err);
            });
        })
    }

    //星云统计--------------------------------------------------------------------
    /** 向星云发送事件埋点 */
    public sendEventCp(eventKey: string, eventDes: string) {

        mk.console.log('seventKey  ', eventKey);
        mk.console.log('eventDes   ', eventDes)

        //使用
        let uin = !!GameConst.uin ? GameConst.uin : GameConst.tmp_uin;
        if (!uin) {
            mk.console.log("没有Uin，不执行");
            return;
        }
        let url = `${GameConst.url_service}/cp`;
        let isFirstDay = PlayerConst.loginDay == 1 ? 1 : 0;
        let data = {
            "appid": GameConst.appid,
            "uid": uin,
            "isFirstDay": isFirstDay, // 0 1 是第一天
            "umengChannel": GameConst.umengChannel,
            "deviceType": GameConst.deviceType,
            "androidVerison": GameConst.androidVersion,
            "version": GameConst.appVersion,
            "point": eventKey,
            "description": eventDes
        }

        // LogUtil.log("[HttpMgr] sendEventCp data", data);
        let bodyData = this.encryptBodyData(data);

        this.httpRquest(url, JSON.stringify(bodyData), HTTP_METHOD.POST).then((responseData) => {
            let data = this.parseResponseData(responseData);
            mk.console.log("[HttpMgr] sendEventCp", data);
        }).catch((err) => {
            mk.console.log("[HttpMgr] sendEventCp err", err);
        });
    }

    updateGameVersion(version: string) {
        let url = `${GameConst.url_service}/game/updateVersion`;
        let data = {
            "version": version,
        }
        let bodyData = this.encryptBodyData(data);
        return new Promise((resolve, reject) => {
            this.httpRquest(url, JSON.stringify(bodyData), HTTP_METHOD.POST).then((responseData) => {
                let data = this.parseResponseData(responseData);
                mk.console.log("[HttpMgr] game/updateVersion", data);
            }).catch((err) => {
                mk.console.log("[HttpMgr] game/updateVersion err", err);
                reject(err);
            });
        })
    }

    /** 更新观看广告次数
   */
    updateVideoTimes(placementId, adunit_format, network_type, network_placement_id,
        network_firm_id, adsource_id, adsource_index, adsource_price,
        adsource_isheaderbidding, publisher_revenue, precision, ecpm_level) {

        if (!GameConst.ifShowAd) {
            return;
        }

        let url = `${GameConst.url_service}/video/updateVideo`;
        let data = {
            "imei": GameConst.imei,
            "idfa": GameConst.idfa,
            "oaid": GameConst.oaid,
            "uin": GameConst.uin,
            "version": GameConst.appVersion,
            "tf_channel": GameConst.tf_channel,
            "destoon_ad_place": placementId,
            "ad_type": 1,
            "adunit_format": adunit_format,
            "network_type": network_type,
            "network_placement_id": network_placement_id,
            "network_firm_id": network_firm_id,
            "adsource_id": adsource_id,
            "adsource_index": adsource_index,
            "adsource_price": adsource_price,
            "adsource_isheaderbidding": adsource_isheaderbidding,
            "publisher_revenue": publisher_revenue,
            "precision": precision,
            "ecpm_level": ecpm_level
        }

        mk.console.log("[HttpMgr] updateVideoTimes data", data);

        Object.keys(data).forEach((key) => {
            mk.console.log(`updateVideo ${key}`, data[key]);
        })

        let bodyData = this.encryptBodyData(data);

        this.httpRquest(url, JSON.stringify(bodyData), HTTP_METHOD.POST).then((responseData) => {
            let data = this.parseResponseData(responseData);
            mk.console.log("[HttpMgr] updateVideoTimes ok", data);
        }).catch((err) => {
            mk.console.log("[HttpMgr] updateVideoTimes err", err);
        });
    }

    /** 更新其他广告次数
         * @param type 1:激励视频成功、 2:插屏、3:信息流 4 观看视频
         */
    public updateADLog(type, placementId, adunit_format, network_type, network_placement_id,
        network_firm_id, adsource_id, adsource_index, adsource_price,
        adsource_isheaderbidding, publisher_revenue, precision, ecpm_level) {

        if (!GameConst.ifShowAd) {
            return;
        }

        let url = `${GameConst.url_service}/video/updateADLog`;
        let data = {
            "imei": GameConst.imei,
            "idfa": GameConst.idfa,
            "oaid": GameConst.oaid,
            "uin": GameConst.uin,
            "version": GameConst.appVersion,
            "tf_channel": GameConst.tf_channel,
            "destoon_ad_place": placementId,
            "ad_type": type,
            "adunit_format": adunit_format,
            "network_type": network_type,
            "network_placement_id": network_placement_id,
            "network_firm_id": network_firm_id,
            "adsource_id": adsource_id,
            "adsource_index": adsource_index,
            "adsource_price": adsource_price,
            "adsource_isheaderbidding": adsource_isheaderbidding,
            "publisher_revenue": publisher_revenue,
            "precision": precision,
            "ecpm_level": ecpm_level
        }

        mk.console.log("[HttpMgr] updateADLog data", data);

        let bodyData = this.encryptBodyData(data);

        this.httpRquest(url, JSON.stringify(bodyData), HTTP_METHOD.POST).then((responseData) => {
            let data = this.parseResponseData(responseData);
            mk.console.log("[HttpMgr] updateADLog ok", data);
        }).catch((err) => {
            mk.console.log("[HttpMgr] updateADLog err", err);
        });
    }

    //-----------------------------------加解密-----------------------------------
    /**加密参数 */
    private encryptBodyData(data: any): any {

        let encryptBodyData: any = null;
        let encryptData: any = null;

        //LogUtil.log("GameConst.tmp_uin",GameConst.tmp_uin);

        data.timestamp = Math.floor(new Date().getTime() * 0.001);
        if (GameConst.isAuth) {
            encryptData = mk.encrypt.encrypt(JSON.stringify(data), GameConst.session_key, GameConst.appid);
            encryptBodyData = {
                "uin": GameConst.uin,
                "encrypt": encryptData
            }
        }
        else {
            encryptData = mk.encrypt.encrypt(JSON.stringify(data), GameConst.session_key, GameConst.appid);
            encryptBodyData = {
                "uin": GameConst.tmp_uin,
                "encrypt": encryptData
            }
        }
        return encryptBodyData;
    }

    /**
     * 解析返回的数据
     * @param response    返回数据
     * @param ifDataClear 是否数据是明文发送 默认暗文
     */
    private parseResponseData(response: any, ifDataClear: boolean = false): any {
        let data = null
        if (ifDataClear) {
            data = response.data
        }
        else {
            if (response.encrypt) {
                data = mk.encrypt.decrypt(response.encrypt, GameConst.session_key, GameConst.appid)
                data = JSON.parse(data)
            }
            else if (response.data) {
                data = response.data
            }
        }
        return data
    }

}

export enum HTTP_METHOD {
    GET = "GET",
    POST = "POST"
}

export enum HTTP_TYPE {
    connect = "connect",
    recommendList = "recommendList"

}

//通关接口ERR CODE
export enum PASS_ERR_CODE {
    /** 关卡号不正*/
    PASSNO_INCORRECT = 9001,
    /**关卡号不能为空或者小于1 */
    PASSNO_NULL = 9002,//
    /***获取积分异常(积分传参非法)*/
    SCORE_PARAM_ILLEGAL = 9003,
    /**已达单关积分获取次数*/
    SCORE_OVER_TIMES = 9004,
    /**已达今日积分上限*/
    SCORE_REACH_LIMIT = 9005
}
