/**
 * 变态版h5版本 sdk配置
 * 

微信内跳转入口是

在main.js的最上面
window.__zero__ = {
    "packageID": "1101",
}

在main.js的onStart加上
cc.assetManager.downloader.appendTimeStamp = true
开启资源时间戳（暂时不需要，影响玩家体验）

  解决网页白边的问题 放在html的body里
  <style> 
    body {
     display:block;
     margin:0px;
    }
  </style>
  //解决网页缓存的问题（暂时的）
    
    var getQuery2 = function (name) {
      var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
      var r = window.location.search.substr(1).match(reg);
      if (r != null) return decodeURIComponent(r[2]);
      return null;
    }
    var main = function () {
      var _time = parseInt(getQuery2("time") || "0");
      var _curTime = new Date().getTime();
      if (!_time) { 
        window.location.replace('https://cdnjyxy.happilygame.com/webMobile/index.html?time=' + _curTime);//注意要换对应的专服链接
        return;
      }
    }
    main();
引入SDK:在html中添加一个script标签就可以了
<script src="https://sdkapi.happilygame.com/static/lib/pp/libQuickSDK_v2.js"></script>
 */
import Mint from "../utils/mintFilter/index";
import Gamecfg from "../common/gameCfg";
import { gameMethod } from "../common/gameMethod";
import { PlayerLogin, PlayerLoginPram } from "../common/Xyc";
import { SevBack } from "../common/Xys";
import Config from "../Config";
import { LoadEvent } from "../data/const/EventConst";
import { GameErrCode, PayProductParam, ReportRoleType, PlatFormDevType } from "../data/const/TypeConst";
import GameDataCenter from "../data/GameDataCenter";
import GameController from "../GameController";
import UIHelp from "../logic/ui/UIHelp";
import EventMng from "../manager/EventMng";
import PlatformBase from "./PlatformBase";
import HttpRequest from "../network/HttpRequest";

export default class PlatformQuickH5 extends PlatformBase {
    isGoPay: boolean
    mint: Mint;
    username: ""
    channelId: string
    constructor() {
        super()
        cc.game.on(cc.game.EVENT_SHOW, () => {
            if (this.isGoPay) {
                this.isGoPay = false
                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();
        })
        QuickSDK.setSwitchAccountNotification(function (callbackData) {
            console.log("SwitchAccount data=>", JSON.stringify(callbackData))
            GameController.clear()
            cc.game.restart()
        });
        QuickSDK.setLogoutNotification(() => {
            GameController.clear()
            cc.game.restart()
        })
    }
    showLoginView(): void {
        console.log("初始化&登录SDK")
        EventMng.emit(LoadEvent.LOAD_PROGRESS, 0.25, "login")
        try {
            let localStorage = cc.sys.localStorage.getItem(`model_login`);
            let localData = {};
            if (!gameMethod.isEmpty(localStorage)) {
                localData = JSON.parse(localStorage);
            }
            let policyAgree = localData["policy_agree"];
            if (!gameMethod.isEmpty(policyAgree) && policyAgree == "1") {
                this.SdkInitLogin();
            } else {
                QuickSDK.showPrivace((retMsg: any) => {
                    console.log("privace data=>", JSON.stringify(retMsg))
                    if (retMsg?.status) {
                        this.SdkInitLogin();
                    } else {
                        QuickSDK.callExtFunction("exit", {});
                    }
                })
            }
        } catch (error) {
            UIHelp.ShowTips("----" + error)
        }
    }

    SdkInitLogin() {
        let packageInfo = Gamecfg.packageInfo.getItem(Config.pid)
        var productCode = packageInfo.params[0];        //QuickSDK后台自动分配 
        var productKey = packageInfo.params[1];        //QuickSDK后台自动分配
        let isNative = false
        this.isMiniClient();//设置登录平台
        QuickSDK.init(productCode, productKey, isNative, () => {
            console.log("初始化成功")
            setTimeout(() => {
                QuickSDK.login((result: any) => {
                    console.log("login data=", JSON.stringify(result))
                    // EventMng.emit(LoadEvent.LOAD_MESSAGE, JSON.stringify(result))
                    if (result.status) {
                        let data = result.data
                        this.username = data.username
                        this.channelId = data.channelId.toString()
                        EventMng.emit(LoadEvent.LOAD_PROGRESS, 0.75, "login")
                        let params: PlayerLoginPram = {
                            pid: Config.pid,
                            param: [data.uid, data.token, data.channelId]
                        }
                        setTimeout(() => {
                            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) {
                                    this.openId = result.platBack.openid
                                    this.loginParams = [result.platBack.token]
                                    console.log("后端验证成功", this.openId)
                                    this.login()
                                } else {
                                    console.log("PlayerLogin.url 返回数据异常")
                                    if (gameMethod.isEmpty(result.win) || gameMethod.isEmpty(result.win.msgOut)) {
                                        GameDataCenter.plat.showErrDialog(GameErrCode.errGamePlatLogin)
                                    }
                                }
                            })
                        }, 1000)
                    } else {
                        UIHelp.ShowTips("登录失败")
                    }
                })
            }, 1000)
        })
    }

    pay(orderId: string, order10cs: string, param: PayProductParam): void {
        let packageInfo = Gamecfg.packageInfo.getItem(Config.pid)
        var productCode = packageInfo.params[0];        //QuickSDK后台自动分配 
        let serverName = GameDataCenter.user.getServerNameBySid(GameDataCenter.sevBack?.userInfo?.a?.sid) || GameDataCenter.sevBack.userInfo.a.sid;
        let orderInfo = {
            productCode: productCode,
            uid: GameDataCenter.plat.instance.openId,
            username: this.username,
            userRoleId: GameDataCenter.sevBack.userInfo.a.uuid,
            userRoleName: GameDataCenter.sevBack.userInfo.a.name,
            serverId: parseInt(GameDataCenter.sevBack.userInfo.a.sid),
            userServer: serverName,
            userLevel: GameDataCenter.sevBack.userInfo.a.level,
            cpOrderNo: orderId,
            amount: param.price,
            subject: param.productName,
            desc: param.productName,//param.productDesc,
            callbackUrl: '',
            extrasParams: order10cs,
            goodsId: param.productId,
            count: 1,
            quantifier: '个',
        }

        var orderInfoJson = JSON.stringify(orderInfo);
        this.isGoPay = true
        QuickSDK.pay(orderInfoJson, (payStatusObject: any) => {
            console.log("创建订单成功:", JSON.stringify(payStatusObject))
            this.isGoPay = false
            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)
        })
        this.dealYanChi();
    }

    // 充值延迟到账，前端只能循环处理
    dealYanChi() {
        if (Config.paySuccAdokId != null) {
            clearInterval(Config.paySuccAdokId)
            Config.paySuccAdokId = null
        }
        Config.paySuccAdokIndex = 0
        Config.paySuccAdokId = setInterval(() => {
            Config.paySuccAdokIndex++
            if (Config.paySuccAdokIndex >= 15) {
                clearInterval(Config.paySuccAdokId)
                Config.paySuccAdokId = null
                this.isGoPay = false
            }
            GameDataCenter.time.sendAdok()
        }, 1000)
    }
    // 上报角色数据
    reportRole(event: ReportRoleType): void {
        // • 初始化成功后调⽤. • 进⼊区服、创⻆、⻆⾊等级更新、战⼒更新时调⽤.
        if (GameDataCenter.sevBack == null) { return }
        if (GameDataCenter.sevBack.userInfo == null) { return }
        console.log("上报角色数据:", event)
        let onlineTime = 0
        if (GameDataCenter.time.onlineTime > 0) {
            onlineTime = GameDataCenter.time.sevTime - GameDataCenter.time.onlineTime
        }
        let isCreateRole = false
        let level = GameDataCenter.sevBack.userInfo.a.level
        switch (event) {
            case ReportRoleType.create:
                isCreateRole = true
                break;
            case ReportRoleType.levelup:
                break;
            case ReportRoleType.offline:

                break;
            case ReportRoleType.online:

                break;
            case ReportRoleType.other:

                break;
            default:
                break;
        }
        let power = GameDataCenter.sevBack.userInfo.a.power;
        let serverName = GameDataCenter.user.getServerNameBySid(GameDataCenter.sevBack.userInfo.a.sid) || GameDataCenter.sevBack.userInfo.a.sid;

        if (this.channelId == "4804" || this.channelId == "4771") {
            //专服1-混A上报角色需要加密
            let roleInfo6 = {
                uid: GameDataCenter.plat.instance.openId,
                username: this.username,
                serverId: GameDataCenter.sevBack.userInfo.a.sid,
                serverName: serverName,
                userRoleId: GameDataCenter.sevBack.userInfo.a.uuid,
                userRoleName: GameDataCenter.sevBack.userInfo.a.name,
                userRoleLevel: level,
                vipLevel: 0,
                gameRolePower: power,
                channel_role_sign: "",
                isCreateRole: isCreateRole,
                roleCreateTime: GameDataCenter.sevBack.userInfo.a.regtime,
                userRoleBalance: 0,
                partyId: 0,
                partyName: '无',
            };
            let verifyStr = "uid=" + roleInfo6.uid + "&username=" + roleInfo6.username + "&serverId=" + roleInfo6.serverId + "&serverName=" + roleInfo6.serverName + "&userRoleId=" + roleInfo6.userRoleId + "&userRoleName=" + roleInfo6.userRoleName + "&userRoleLevel=" + roleInfo6.userRoleLevel + "&vipLevel=" + roleInfo6.vipLevel + "&gameRolePower=" + roleInfo6.gameRolePower + "&key="
            // console.log("verifyStr:",verifyStr)
            let url = Gamecfg.packageInfo.getItem(Config.pid).wayhttp + "player/sbVerify"
            HttpRequest.POST(url, {}, { str: verifyStr }, (result: any) => {
                console.log("player/sbVerify=>", result)
                roleInfo6.channel_role_sign = result.sign
                var roleInfoJson6 = JSON.stringify(roleInfo6);
                // set_userinfo 设置⻆⾊基本信息，如头像、昵称
                QuickSDK.uploadGameRoleInfo(roleInfoJson6, () => {

                })
            })
        } else {
            let roleInfo = {
                isCreateRole: isCreateRole,
                roleCreateTime: GameDataCenter.sevBack.userInfo.a.regtime,
                uid: GameDataCenter.plat.instance.openId,
                username: this.username,
                serverId: GameDataCenter.sevBack.userInfo.a.sid,
                serverName: serverName,
                userRoleName: GameDataCenter.sevBack.userInfo.a.name,
                userRoleId: GameDataCenter.sevBack.userInfo.a.uuid,
                userRoleBalance: 0,
                vipLevel: 1,
                userRoleLevel: level,
                gameRolePower: power,
                partyId: 0,
                partyName: '无',
            };

            var roleInfoJson = JSON.stringify(roleInfo);
            // set_userinfo 设置⻆⾊基本信息，如头像、昵称
            QuickSDK.uploadGameRoleInfo(roleInfoJson, () => {

            })
        }
    }
    checkMsg(str: string, cb: Function): void {
        cb()
    }

    restart(force?: boolean) {
        QuickSDK.logout(() => {

        })
    }

    openUrl(url: string) {
        QuickSDK.callUrl(url);
    }

    /**
     * 是否微端
     */
    isMiniClient() {
        //UA: Mozilla/5.0 (iPhone; CPU iPhone OS 17_6_1 like MacoS X) AppleWebKit/605.1.15(KHTML, like Gecko)Mobile/15E148
        //    Mozilla/5.0 (iPhone; CPU iPhone 0S 17_6_1 like Mac OS X)AppleWebKit/605.1.15(KHTML, like Gecko) obile/15E148 color:gray".match(/\(i[^;]+;( U;)?CPU.+Mac OS X
        let u = navigator.userAgent;
        let isAndroid = u.indexOf("Android") > -1 || u.indexOf("Adr") > -1;
        if (isAndroid) {
            GameDataCenter.plat.instance.deviceOS = PlatFormDevType.androidH5
        }
        let isIos = u.indexOf("iPhone") > -1 && u.indexOf("Safari") == -1;
        if (isIos) {
            GameDataCenter.plat.instance.deviceOS = PlatFormDevType.iosH5
        }
        if (cc.sys.os == cc.sys.OS_IOS) {
            GameDataCenter.plat.instance.deviceOS = PlatFormDevType.iosH5
        }
        return isAndroid || isIos;
    }
}