/**
17玩 SDK

 */

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 { GameEvent, LoadEvent, PlatEvent } from "../data/const/EventConst";
import { AD_VIDEO_KEY, ConstItem, GameErrCode, 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 NativeManager from "../utils/NativeManager";
import PlatformBase from "./PlatformBase";
export default class PlatformWan17 extends PlatformBase {
    rewardVideo: any
    adId: string;
    constructor() {
        super()
        window["NativeNotify"] = {
            //native平台回调
            OnNativeNotify: function (eventType, eventDataString) {
                try {
                    console.log("NativeNotify OnNativeNotify eventType:" + eventType + ",eventDataString:" + eventDataString);
                    let dataDict = JSON.parse(eventDataString);
                    if (eventType == "17WanLogin") { //17登录
                        if (dataDict.status == "0") {
                            EventMng.emit(LoadEvent.LOAD_PROGRESS, 0.75, "login")
                            let params: PlayerLoginPram = {
                                pid: Config.pid,
                                param: [dataDict.accountid, dataDict.sessionid]
                            }
                            // if (dataDict.status != 0) {
                            //     GameDataCenter.plat.showErrDialog(GameErrCode.errPlatLogin)
                            //     return
                            // }
                            setTimeout(() => {
                                GameController.network.send(PlayerLogin.url, params, (result: SevBack) => {
                                    console.log("后段验证返回", JSON.stringify(result))
                                    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("后端验证成功", GameDataCenter.plat.instance.openId)

                                        // // 加载广告组件
                                        //GameDataCenter.plat.instance.initRewardedVideoAd(AD_VIDEO_KEY.welChest)
                                        // 获取邀请者uuid
                                        let inviter = ""
                                        GameDataCenter.plat.instance.login(inviter)
                                    } else {
                                        console.log("PlayerLogin.url 返回数据异常")
                                        if (gameMethod.isEmpty(result.win) || gameMethod.isEmpty(result.win.msgOut)) {
                                            GameDataCenter.plat.showErrDialog(GameErrCode.errGamePlatLogin)
                                        }
                                    }
                                })
                            }, 1000)
                        } else if (dataDict.status == "1") {
                            //玩家取消登录，显示登录按钮
                            EventMng.emit(LoadEvent.SHOW_LOGIN_BTN)
                        } else if (dataDict.status == "2") {
                            //玩家注销，退出游戏
                            GameDataCenter.plat.instance.restart()
                        }
                        else {
                            GameDataCenter.plat.showErrDialog(GameErrCode.errPlatLogin)
                        }

                    } else if (eventType == "17WanPay") {  //17支付
                        if (dataDict.status == 0) {
                            //充值成功
                            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)
                        } else if (dataDict.status == 1) {
                            //充值失败

                        } else {
                            //待审核中

                        }
                    } else if (eventType == "17WanShare") {  //17分享

                    } else if (eventType == "17WanAdReward") {  //广告
                        GameDataCenter.adVideo.onXiadanSucc() // 改成直接调用,不回调了
                    } else if (eventType == "17WanAdLoad") {  //广告加载完成
                        console.log("17WanAdLoad adUnitId:", this.adId)
                        if (!gameMethod.isEmpty(this.adId)) {
                            NativeManager.CallToNative("On17ShowAd", [{ "Name": "sceneId", "Value": this.adId }], "")
                        }
                    }
                    else if (eventType == "17WanChannel") {  //获取渠道名称
                        //GameDataCenter.plat.instance.channel = dataDict.channel
                    }
                    else if (eventType == "getClipboardText") {
                        //EventMng.emit(duihuanEvent.GetText, dataDict.msg);
                    }
                    else {
                        console.log("NativeNotify OnNativeNotify not find eventType: " + eventType);
                    }
                }
                catch (error) {
                    console.log("NativeNotify OnNativeNotify error: " + error.stack);
                }
            },
        }
    }

    showLoginView(): void {
        console.log("平台sdk初始化...")
        EventMng.emit(LoadEvent.LOAD_PROGRESS, 0.25, "login")
        let packageInfo = Gamecfg.packageInfo.getItem(Config.pid)
        NativeManager.CallToNative("On17WanInit", {}, "")
    }
    // 上报用户信息
    reportUserInfo(res) {
        console.log("上报用户信息", res)
    }
    // 上报角色数据
    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 sceneValue = 0;
        if (event == ReportRoleType.create) {
            sceneValue = 1;
        } else if (event == ReportRoleType.levelup) {
            sceneValue = 2;
        }
        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 sex = GameDataCenter.sevBack.userInfo?.a?.sex;
        let exp = GameDataCenter.sevBack.actJingJie?.a?.exp;
        let iscz = GameDataCenter.sevBack.userInfo?.a?.iscz ?? 0;
        let regtime = GameDataCenter.sevBack.userInfo?.a?.regtime;
        let userInfo17 = {
            ingot: "",//游戏余额
            playerId: GameDataCenter.user.uuid,//角色ID
            factionName: clubName,//帮派
            vipLevel: "0",
            serverName: GameDataCenter.user.serverName,
            playerLevel: level,
            serverId: sid,
            playerName: GameDataCenter.user.nickName,
            campId: "",//阵营
            roleSex: sex,
            careerId: "",
            experience: exp,
            coin: itemNum,
            payment: iscz,
            roleCTime: regtime,
            sceneValue: sceneValue,
        }
        NativeManager.CallToNative("On17WanOutInGame", [{ "Name": "userInfo", "Value": JSON.stringify(userInfo17) }], "")
    }
    pay(orderId: string, order10cs: string, param: PayProductParam): void {
        let packageInfo = Gamecfg.packageInfo.getItem(Config.pid)
        let feePoint = order10cs;
        let payUrl: string = packageInfo.wayhttp + "player/pay/" + Config.pid
        NativeManager.CallToNative("On17WanPay", [{ "Name": "orderId", "Value": orderId }, { "Name": "url", "Value": payUrl }, { "Name": "sum", "Value": param.price.toString() }, { "Name": "feePoint", "Value": feePoint }, { "Name": "desc", "Value": param.productDesc }], "")
        //17玩 xiao7特殊处理，调支付就开始轮询，降低支付到账延迟
        // if (Config.paySuccAdokId != null) {
        //     clearInterval(Config.paySuccAdokId)
        //     Config.paySuccAdokId = null
        // }
        // Config.paySuccAdokIndex = 0
        // Config.paySuccAdokId = setInterval(() => {
        //     Config.paySuccAdokIndex++
        //     if (Config.paySuccAdokIndex >= 20) {
        //         clearInterval(Config.paySuccAdokId)
        //         Config.paySuccAdokId = null
        //     }
        //     GameDataCenter.time.sendAdok()
        // }, 1000)

    }

    initRewardedVideoAd(adkey: AD_VIDEO_KEY) {
        // GameDataCenter.plat.instance.adUnitId = GameDataCenter.adVideo.getAdUnitID(adkey)
        // NativeManager.CallToNative("On17LoadAd",[{"Name":"sceneId", "Value":GameDataCenter.plat.instance.adUnitId}],"")
    }
    showRewardAd(adId: string, kid: string, order11Id: string): void {
        this.adId = adId;
        NativeManager.CallToNative("On17ShowAd", [{ "Name": "sceneId", "Value": this.adId }], "")
    }
    //打开浏览器打开链接
    openUrl(url: string) {
        NativeManager.CallToNative("OnOpenBrowser", [{ "Name": "url", "Value": url }], "")
    }
    //看运营提供什么 提供手Q链接就用这个 ， 提供网址链接就用浏览器打开
    addQQ(url: string) {
        NativeManager.CallToNative("OnAddQQ", [{ "Name": "url", "Value": url }], "")
    }
    joinQQGroup(url: string, cb?: Function) {
        NativeManager.CallToNative("OnJoinQQGroup", [{ "Name": "url", "Value": url }], "")
        if (cb) {
            cb();
        }
    }
    getChannel() {
        NativeManager.CallToNative("OnGetChannel", [], "")
    }
    share(title: string, imageUrl: string, query: string, contents?: string, hashtag_ids?: string, app_id?: string, group_label_id?: string): void {
        let data = {
            "title": title,
            "imageUrl": imageUrl,
            "query": query,
            "contents": contents,
            "hashtag_ids": hashtag_ids,
            "app_id": app_id,
            "group_label_id": group_label_id,
        }
        //NativeManager.CallToNative("OnShare2Tap",[{"Name":"data", "Value":JSON.stringify(data)}],"")//直接分享 (不存网图到本地)
        NativeManager.CallToNative("OnSaveUrlImg", [{ "Name": "data", "Value": JSON.stringify(data) }], "")// 存图并分享 (存图到本地再拉起分享)
    }
    getClipboardText(): void {
        NativeManager.CallToNative("getClipboardText", {}, "");
    }
    reShowLogInView(): void {
        NativeManager.CallToNative("On17WanLogin", {}, "");
    }

}