/*
17玩H5
*/

import Config from "../Config";
import GameController from "../GameController";
import { PlayerLogin, PlayerLoginPram } from "../common/Xyc";
import { LoadEvent } from "../data/const/EventConst";
import { ConstItem, GameErrCode, PayProductParam, ReportRoleType } from "../data/const/TypeConst";
import UIHelp from "../logic/ui/UIHelp";
import EventMng from "../manager/EventMng";
import PlatformBase from "./PlatformBase";
import { SevBack } from "../common/Xys";
import { gameMethod } from "../common/gameMethod";
import GameDataCenter from "../data/GameDataCenter";
import Gamecfg from "../common/gameCfg";

export default class PlatformWan17H5 extends PlatformBase {

    constructor() {
        super()

        //监听屏幕切回来的状态 (防止切回来游戏却收不到支付成功的回调)
        cc.game.on(cc.game.EVENT_SHOW, function () {
            if (Config.paySuccAdokId != null) {
                clearInterval(Config.paySuccAdokId)
                Config.paySuccAdokId = null
            }
            Config.paySuccAdokIndex = 0
            Config.paySuccAdokId = setInterval(() => {
                Config.paySuccAdokIndex++
                if (Config.paySuccAdokIndex >= 5) {
                    clearInterval(Config.paySuccAdokId)
                    Config.paySuccAdokId = null
                }
                GameDataCenter.time.sendAdok()
            }, 1000)
            GameDataCenter.audio.resumeMusic();
        });

        cc.game.on(cc.game.EVENT_HIDE, () => {
            GameDataCenter.audio.pauseMusic();
        })
    }

    private getQueryString(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) {
            return unescape(r[2]);
        } else {
            return null;
        }
    }

    showLoginView(): void {
        console.log("初始化&登录SDK")
        EventMng.emit(LoadEvent.LOAD_PROGRESS, 0.25, "login")
        try {
            let packageInfo = Gamecfg.packageInfo.getItem(Config.pid)
            let gameid = packageInfo.params[0];
            let gamekey = packageInfo.params[1];
            Sdk.init(gameid, gamekey);

            setTimeout(() => {
                EventMng.emit(LoadEvent.LOAD_PROGRESS, 0.75, "login")

                let a_pub = this.getQueryString("a_pub")
                let a_accountid = this.getQueryString("a_accountid")
                let a_sessionid = this.getQueryString("a_sessionid")

                if (!a_accountid || !a_sessionid) {
                    return;
                }

                let params: PlayerLoginPram = {
                    pid: Config.pid,
                    param: [a_accountid, a_sessionid]
                }
                GameController.network.send(PlayerLogin.url, params, (result: SevBack) => {
                    console.log("后段验证返回")
                    if (result.type != 1) {
                        if (gameMethod.isEmpty(result.win) || gameMethod.isEmpty(result.win.msgOut)) {
                            GameDataCenter.plat.showErrDialog(GameErrCode.errGamePlatLogin)
                        }
                        return
                    }
                    EventMng.emit(LoadEvent.LOAD_PROGRESS, 1, "login")
                    if (result.type == 1 && result.platBack) {
                        GameDataCenter.plat.instance.openId = result.platBack.openid
                        GameDataCenter.plat.instance.loginParams = [result.platBack.token]
                        console.log("后端验证成功", this.openId)
                        GameDataCenter.plat.instance.login()
                    } else {
                        console.log("PlayerLogin.url 返回数据异常")
                        if (gameMethod.isEmpty(result.win) || gameMethod.isEmpty(result.win.msgOut)) {
                            GameDataCenter.plat.showErrDialog(GameErrCode.errGamePlatLogin)
                        }
                    }
                })
            }, 3000);
        } catch (error) {
            UIHelp.ShowSystemDialog({ content: error })
        }
    }

    pay(orderId: string, order10cs: string, param: PayProductParam): void {


        let packageInfo = Gamecfg.packageInfo.getItem(Config.pid)
        let payUrl: string = packageInfo.wayhttp + "player/pay/" + Config.pid
        let orderData = {
            callbackurl: payUrl,//游戏方充值回调地址
            paymoney: param.price,//游戏充值金额
            custominfo: "",//游戏透传参数，回调时原样返回
            customorderid: orderId,//订单号
            productdesc: param.productDesc,//充值描述
            productfeecode: order10cs, // 计费点ID（苹果的商品id）
        };

        var orderDataJson = JSON.stringify(orderData);

        Sdk.pay(orderDataJson, function (result) {
            if (result.code != 0) {
                console.log("支付失败，失败原因：" + result.msg);
            } else {
                if (Config.paySuccAdokId != null) {
                    clearInterval(Config.paySuccAdokId)
                    Config.paySuccAdokId = null
                }
                Config.paySuccAdokIndex = 0
                Config.paySuccAdokId = setInterval(() => {
                    Config.paySuccAdokIndex++
                    if (Config.paySuccAdokIndex >= 5) {
                        clearInterval(Config.paySuccAdokId)
                        Config.paySuccAdokId = null
                    }
                    GameDataCenter.time.sendAdok()
                }, 1000)
            }
        });

        //17玩 如果有的渠道没有充值回调的，只能强行调用充值的时候就开始刷心跳包了
        // if (Config.paySuccAdokId != null) {
        //     clearInterval(Config.paySuccAdokId)
        //     Config.paySuccAdokId = null
        // }
        // Config.paySuccAdokIndex = 0
        // Config.paySuccAdokId = setInterval(() => {
        //     Config.paySuccAdokIndex++
        //     if (Config.paySuccAdokIndex >= 30) {
        //         clearInterval(Config.paySuccAdokId)
        //         Config.paySuccAdokId = null
        //     }
        //     GameDataCenter.time.sendAdok()
        // }, 1000)

    }
    // 上报角色数据
    reportRole(event: ReportRoleType): void {

        if (GameDataCenter.sevBack == null) { return }
        if (GameDataCenter.sevBack.userInfo == null) { return }
        if (GameDataCenter.item == null) { return }

        let power = GameDataCenter.zhanLi.getTotalZhanLi(GameDataCenter.sevBack);
        let clubName = GameDataCenter.sevBack?.club?.a?.name ?? "";
        let level = GameDataCenter.sevBack?.userInfo?.a?.level ?? 1;
        let sid = GameDataCenter.sevBack?.userInfo?.a?.sid;
        let itemNum = GameDataCenter.item.getItemCount(ConstItem.gem);
        let roleData = {
            ingot: itemNum, //剩余游戏代币 
            playerid: GameDataCenter.user.uuid, //角色ID
            factionname: clubName,//帮派名称
            viplevel: "0",//VIP等级
            servername: GameDataCenter.user.serverName,//区服名称
            playerlevel: level,//角色等级
            serverid: sid,//区服ID
            playername: GameDataCenter.user.nickName,//角色名称
        };

        var roleDataJson = JSON.stringify(roleData);
        Sdk.uploadRoleData(roleDataJson, function (result) {
            if (result.code != 0) {
                console.log("上报失败，失败原因：" + result.msg);
            } else {
                //上报成功
            }
        });

    }

    logout(): void {
        Sdk.logout(function (result) {
            if (result.code != 0) {
                console.log("退出失败，失败原因：" + result.msg);
            } else {
                //退出成功
                GameDataCenter.plat.instance.restart()
            }
        })
    }

    //打开浏览器打开链接
    openUrl(url: string) {

    }
}