/**
 * haituoh5版本 sdk配置
 * 

微信内跳转入口是

在main.js的最上面
window.__zero__ = {
    "packageID": "101",
}
在onStart初始化sdk

引入SDK:在html中添加一个script标签就可以了
    <!-- // H5引入方舟SDK -->
    <script type="text/javascript" src="htkSdk_xxxxx.js"></script>
    <script >
        hitalkOpenSDK.init(function(res){//初始化sdk
            if(res.retCode!=0){
                    console.log("初始化失败")
                    return
            } 
            console.log("初始化成功")
            //调用登录接口
        },{gameId:319});  //向海拓申请获得
    </script>
    <!-- 开启vConsole -->
    <!-- <script src="https://unpkg.com/vconsole@latest/dist/vconsole.min.js"></script>
    <script>
    // VConsole 默认会挂载到 `window.VConsole` 上
    var vConsole = new window.VConsole();
    </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, InGame, PayProductParam, ReportRoleType } 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";

export default class PlatformHaiTuoH5 extends PlatformBase {
    isGoPay: boolean
    mint: Mint;
    constructor() {
        super()
        cc.game.on(cc.game.EVENT_SHOW, () => {

        })
        window['DHMiniH5SDK'].setSwitchAccountNotification(function (callbackData) {
            console.log("SwitchAccount data=>", JSON.stringify(callbackData))
            window['DHMiniH5SDK'].logout(() => {

            })
        });
        window['DHMiniH5SDK'].setLogoutNotification(() => {
            GameDataCenter.sevBack = null
            Config.inGame = InGame.no
            // this.restart()
            cc.game.restart()
        })
        //防沉迷
        if (window['DHMiniH5SDK'].isDhApp) {
            console.log("注册防沉迷强制下线监听")
            window['DHMiniH5SDK'].gamePreventAddiction((reponse) => {
                // 在被强制下线后的回调函数中，理论上游戏应按如下步骤执行相关操作：
                // 第一步，清除当前登录的账号角色等信息
                // 第二步，重回游戏起始页
                // 第三步，再次调用 sdk.login 接口以拉起登录窗口
                console.log("触发防沉迷强制下线，游戏重启")
                let cb = () => {
                    GameDataCenter.sevBack = null
                    Config.inGame = InGame.no
                    // this.restart()
                    cc.game.restart()
                }
                UIHelp.ShowDialog({
                    content: "根据国家新闻出版署 《关于防止未成年人沉迷网络游戏的通知》、《关于进一步严格管理切实防止未成年人沉迷网络游戏的通知》的要求，您已超出今日健康体验时限，游戏将强制退出。",
                    title: "防沉迷调整通知",
                    txtConfirm: "我知道了",
                    onlyConfirm: true,
                    cbConfirm: cb
                })
            });
        }
    }
    showLoginView(): void {
        console.log("MiniH5初始化&登录SDK")
        EventMng.emit(LoadEvent.LOAD_PROGRESS, 0.25, "login")
        let packageInfo = Gamecfg.packageInfo.getItem(Config.pid)
        var productCode = packageInfo.params[0];        //QuickSDK后台自动分配 
        var productKey = packageInfo.params[1];        //QuickSDK后台自动分配
        try {
            window['DHMiniH5SDK'].login((result: any) => {
                console.log("login data=", JSON.stringify(result))
                // EventMng.emit(LoadEvent.LOAD_MESSAGE, JSON.stringify(result))
                if (result.code == 0) {
                    let data = result.data
                    EventMng.emit(LoadEvent.LOAD_PROGRESS, 0.75, "login")
                    let params: PlayerLoginPram = {
                        pid: Config.pid,
                        param: [data.accountId, data.loginType, data.token]
                    }
                    setTimeout(() => {
                        //电魂sdk漏斗打点
                        if (window['DHMiniH5SDK']) {
                            window['DHMiniH5SDK'].analytics.log({
                                eventId: "420000::GAME_CLIENT_LOGIN_START",
                                subEventId: "0",
                                logLevel: "d",
                                logContent: "游戏客户端开始请求登录游戏服",
                                accountId: window['DHMiniH5SDK'].userInfo.accountId
                            }, params => {
                                console.log(params);
                            });
                        }
                        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()
                                //电魂sdk漏斗打点
                                if (window['DHMiniH5SDK']) {
                                    window['DHMiniH5SDK'].analytics.log({
                                        eventId: "450000::GAME_CLIENT_LOGIN_SUCCESS",
                                        subEventId: "0",
                                        logLevel: "d",
                                        logContent: "游戏客户端登录成功",
                                        accountId: window['DHMiniH5SDK'].userInfo.accountId
                                    }, params => {
                                        console.log(params);
                                    });
                                }
                            } else {
                                console.log("PlayerLogin.url 返回数据异常")
                                if (gameMethod.isEmpty(result.win) || gameMethod.isEmpty(result.win.msgOut)) {
                                    GameDataCenter.plat.showErrDialog(GameErrCode.errGamePlatLogin)
                                }
                            }
                        })
                    }, 1000)
                } else {
                    UIHelp.ShowTips("登录失败")
                    // GameDataCenter.plat.instance.restart()
                }
            })
        } catch (error) {
            UIHelp.ShowTips("----" + error)
            // UIHelp.ShowDialog({ content: error })
        }

    }

    pay(orderId: string, order10cs: string, param: PayProductParam): void {
        this.isGoPay = true
        let serverList = Object.values(GameDataCenter.login.playerInfo?.qufuList || {});
        let serverName = GameDataCenter.user.userInfo?.sid
        for (const iterator of serverList) {
            if (iterator.sid == GameDataCenter.user.userInfo?.sid) {
                serverName = iterator.name
                break
            }
        }
        let payData = {
            serverId: parseInt(GameDataCenter.user.userInfo?.sid),
            serverName: serverName,
            roleId: parseInt(GameDataCenter.user.userInfo?.uuid),
            roleName: GameDataCenter.user.userInfo?.name,
            roleLevel: GameDataCenter.user.userInfo?.level,
            productId: param.productId,
            productName: param.productName,
            productNum: 1,
            price: param.price * 100,
            currencyType: "CNY",
            cpOrderId: orderId,
            areaId: Config.pid,
            areaName: Config.pid,
            memo: orderId
        }
        console.log("拉取支付的参数：", JSON.stringify(payData))
        window['DHMiniH5SDK'].payment(payData, (response) => {
            if (response.code == 0) { // 支付成功
                window['DHMiniH5SDK'].analytics.pay({
                    accountId: window['DHMiniH5SDK'].userInfo.accountId,
                    roleId: window['DHMiniH5SDK'].userInfo.accountId,
                    roleLevel: GameDataCenter.sevBack.userInfo?.a?.level,
                    orderId: orderId,
                    itemId: param.productId,
                    payAmount: param.price
                }, params => {
                    console.log(params);
                });
                //电魂sdk漏斗打点
                if (window['DHMiniH5SDK']) {
                    window['DHMiniH5SDK'].analytics.log({
                        eventId: "510000::GAME_CLIENT_PAY_SUCCESS",
                        subEventId: "0",
                        logLevel: "d",
                        logContent: "发放支付道具至玩家",
                        accountId: window['DHMiniH5SDK'].userInfo.accountId
                    }, params => {
                        console.log(params);
                    });
                }
                this.isGoPay = false

            } else { // 其他，支付失败

            }
        });
    }
    // 上报角色数据
    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
        let type = ""
        switch (event) {
            case ReportRoleType.create:
                isCreateRole = true
                type = "CREATE_ROLE"
                //电魂sdk漏斗打点
                if (window['DHMiniH5SDK']) {
                    window['DHMiniH5SDK'].analytics.log({
                        eventId: "450001::GAME_CLIENT_CREATING_A_ROLE",
                        subEventId: "0",
                        logLevel: "d",
                        logContent: "游戏客户端创角成功",
                        accountId: window['DHMiniH5SDK'].userInfo.accountId
                    }, params => {
                        console.log(params);
                    });
                }
                // window['DHMiniH5SDK'].analytics.register({accountId: window['DHMiniH5SDK'].userInfo.accountId}, params => {
                //     console.log(params);
                //   });
                break;
            case ReportRoleType.levelup:
                type = "LEVEL_UP"
                level++
                break;
            case ReportRoleType.offline:

                break;
            case ReportRoleType.online:
                type = "LOGIN_GAME"
                break;
            case ReportRoleType.other:

                break;
            default:
                break;
        }
        let power = 1;
        if (gameMethod.isEmpty(GameDataCenter.sevBack)) {
            power = 1
        } else {
            let eps = gameMethod.ep_all(GameDataCenter.sevBack);
            let power1 = gameMethod.ep_power(0, eps);
            power = power1
        }
        let serverName = GameDataCenter.user.getServerNameBySid(GameDataCenter.sevBack.userInfo?.a?.sid) || GameDataCenter.sevBack.userInfo?.a?.sid;
        var roleInfo = {
            type: type,
            isCreateRole: isCreateRole,
            roleCreateTime: GameDataCenter.sevBack.userInfo?.a?.regtime,
            uid: GameDataCenter.plat.instance.openId,
            username: GameDataCenter.sevBack.userInfo?.a?.name,
            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);

        window['DHMiniH5SDK'].analytics.uploadRoleInfo({
            type: type,
            isCreateRole: isCreateRole, // 仅创建角色时传true,更新信息时传false
            roleCreateTime: GameDataCenter.sevBack.userInfo?.a?.regtime, // 角色创建时间，时间戳精确到秒
            serverId: parseInt(GameDataCenter.sevBack.userInfo?.a?.sid), // 角色所在游戏服务器ID
            serverName: serverName, // 角色所在游戏服务器名称
            roleId: parseInt(GameDataCenter.sevBack.userInfo?.a?.uuid), // 角色ID
            roleName: GameDataCenter.sevBack.userInfo?.a?.name, // 角色名
            roleLevel: level, // 角色等级
            roleBalance: 0, // 角色游戏内货币余额
            vipLevel: 1, // 角色VIP等级
            partyId: 0, // 公会/社团ID
            partyName: '无', // 公会/社团名称
            rolePower: power, // 角色战力
            partyRoleId: 1, // 角色在帮派中的ID
        }, (response) => {
            console.log(response);
        });
    }
    openService() {
        if (window['DHMiniH5SDK'].isDhApp) {
            window['DHMiniH5SDK'].service({
                roleId: parseInt(GameDataCenter.sevBack.userInfo?.a?.uuid),
                nickname: GameDataCenter.sevBack.userInfo?.a?.name,
                level: GameDataCenter.sevBack.userInfo?.a?.level
            });
        }
    }
    checkMsg(str: string, cb: Function): void {
        cb()
    }
}