/**
游戏名称:遮天
SDK文档：
https://client2.hhycdk.com/docs/sdkDocs.html?target_id=4e81bdd1-aaf0-46d8-9b3a-50769becbe1b
gameId = 319 测试秘钥 = 1d5c5fcb80934b4886cc8a7c61366664 正式秘钥 = fa62a8cbd24941ec83edaf89799a1c4b zoneKey = ztxm_wxml snKey = s218
小程序ID:wx38c033079c5d7490
 */

// 导入crypto-js的md5加密功能
import * as CryptoJS from 'crypto-js';
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, 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 { md5 } from "../utils/md5";
import ThinkingDataMgr from '../utils/ThinkingDataMgr';
export default class PlatformHaiTuoMini extends PlatformBase {
    rewardVideo: any
    constructor() {
        super()
        // wx.getLaunchOptionsSync(res => {
        //     this.dealQuery(res)
        //     setTimeout(() => {
        //         let str = ""
        //         for (const key in res.query) {
        //             str += key + "=" + res.query[key]
        //         }
        //         let data: DialogParams = {
        //             content: "内容:" + str
        //         }
        //         UIHelp.ShowDialog(data)
        //     }, 3000);
        // })
        // 屏幕常亮
        wx.setKeepScreenOn({
            keepScreenOn: true
        })
        // 热启动,或唤醒时触发
        wx.onShow(res => {
            this.dealQuery(res)
            GameDataCenter.audio.resumeMusic()

            // IOS系统,在后台切回时似乎回失去常亮功能,这里再调用一次
            wx.setKeepScreenOn({
                keepScreenOn: true
            })

            EventMng.emit(GameEvent.ON_SHOW_APP)
            console.log("-----wx.onShow 回调触发:", res)
        })
        // 切到后台时触发
        wx.onHide(res => {
            GameDataCenter.audio.stopAllEffects()
            GameDataCenter.audio.pauseMusic()
        })
        // 加载广告组件
        wx.showShareMenu({
            withShareTicket: false,
            menus: ['shareAppMessage', 'shareTimeline']
        })
        // 小程序更新机制 https://developers.weixin.qq.com/minigame/dev/guide/runtime/update-mechanism.html
        const updateManager = wx.getUpdateManager()
        updateManager.onCheckForUpdate(function (res) {
            // 请求完新版本信息的回调
            console.log("请求完新版本信息的回调", res.hasUpdate)
        })
        updateManager.onUpdateReady(function () {
            wx.showModal({
                title: '更新提示',
                content: '新版本已经准备好，是否重启应用？',
                success(res) {
                    if (res.confirm) {
                        // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                        updateManager.applyUpdate()
                    }
                }
            })
        })
        updateManager.onUpdateFailed(function () {
            // 新版本下载失败
        })
    }

    private dealQuery(res) {
        if (res.scene) {
            GameDataCenter.plat.queryparams.scene = res.scene
        }
        if (res.query['inviter']) {
            GameDataCenter.plat.queryparams.inviter = res.query['inviter']
        }
        if (res.query['sharer']) {
            GameDataCenter.plat.queryparams.sharer = res.query['sharer']
        }
        console.log("-----sharer-----", GameDataCenter.plat.queryparams.sharer)
        EventMng.emit(PlatEvent.ON_SCENE_CHANGED)
    }

    showLoginView(): void {
        console.log("平台sdk初始化...")
        let opts = wx.getLaunchOptionsSync()
        EventMng.emit(LoadEvent.LOAD_PROGRESS, 0.25, "login")
        let packageInfo = Gamecfg.packageInfo.getItem(Config.pid)
        window['hitalkOpenSDK'].init((res: any) => {
            let sysInfo = wx.getSystemInfoSync();
            GameDataCenter.plat.instance.deviceOS = sysInfo?.platform
            console.log("----当前运行平台信息:", JSON.stringify(sysInfo))
            console.log("----当前运行平台:", GameDataCenter.plat.instance.deviceOS)
            // do something
            console.log("----初始化回调:", res)
            if (res.retCode != 0) {
                console.log("初始化失败")
                return
            }
            console.log("初始化成功")
            window['hitalkOpenSDK'].resetConfig(true)// true:正式服; false:测试服
            //调用登录接口
            EventMng.emit(LoadEvent.LOAD_PROGRESS, 0.5, "login")
            window['hitalkOpenSDK'].login((res: any) => {
                if (res.retCode === 0) {
                    console.log('fingerPlayer登录成功: res=>' + JSON.stringify(res));

                    //可以全局获取的参数
                    Config.wxOpenId = window['hitalkOpenSDK'].openId //用户唯一标识
                    Config.wxSign = res.data.sign //签名
                    EventMng.emit(LoadEvent.LOAD_PROGRESS, 0.75, "login")
                    let params: PlayerLoginPram = {
                        pid: Config.pid,
                        param: [res.data.openId, res.data.timestamp, res.data.sign, JSON.stringify(res.data?.snUserInfoJson)]
                    }
                    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)

                            // 获取邀请者uuid
                            let inviter = ""
                            if (wx.getEnterOptionsSync) {
                                let obj = wx.getEnterOptionsSync()
                                if (obj.query && obj.query['inviter']) {
                                    inviter = obj.query['inviter']
                                }
                            }
                            this.login(inviter)
                        } else {
                            console.log("PlayerLogin.url 返回数据异常")
                            if (gameMethod.isEmpty(result.win) || gameMethod.isEmpty(result.win.msgOut)) {
                                GameDataCenter.plat.showErrDialog(GameErrCode.errGamePlatLogin)
                            }
                        }
                    })
                } else {
                    console.log('fingerPlayer登录失败: res=>' + JSON.stringify(res));
                    //注意:调用登录接口失败后,需要跳转游戏页面显示重新登录的按钮
                    UIHelp.ShowDialog({
                        content: "登录授权失败，请重新登录",
                        onlyConfirm: true,
                        cbConfirm: () => {
                            GameDataCenter.plat.instance.restart()
                        }
                    })
                }

                // 获取用户设置信息
                console.log("获取用户设置信息")
                wx.getSetting({
                    withSubscriptions: true,
                    success(res) {
                        console.log("获取用户设置信息 回调:", res)
                        if (res.authSetting && res.authSetting["scope.userInfo"]) {
                            // 已授权
                            console.log("已授权")
                            GameDataCenter.plat.instance.hasAuthUserInfo = true
                        }
                        // 整理订阅消息
                        if (res.subscriptionsSetting && res.subscriptionsSetting.itemSettings) {
                            GameDataCenter.subscribe.recordSubscribeAlwaysSettings(res.subscriptionsSetting.itemSettings)
                        }
                    }
                })
            })
            wx.onShareAppMessage(function () {
                return {
                    title: "",
                    imageUrl: "",
                    query: `state=${""}`
                }
            })
            wx.showShareMenu({
                menus: ['shareAppMessage', 'shareTimeline']
            })
        }, { gameId: parseInt(packageInfo.params[0]), zoneKey: packageInfo.params[1], snKey: packageInfo.params[2] })
    }
    // 上报用户信息
    reportUserInfo(res) {
    }
    // 上报角色数据
    reportRole(event: ReportRoleType): void {
        //统一由服务端上报
        return
        if (GameDataCenter.sevBack == null) { return }
        if (GameDataCenter.sevBack.userInfo?.a == null) { return }
        console.log("上报角色数据:" + event + ",uuid:" + GameDataCenter.sevBack.userInfo?.a?.uuid)
        let onlineTime = 0
        if (GameDataCenter.time.onlineTime > 0) {
            onlineTime = GameDataCenter.time.sevTime - GameDataCenter.time.onlineTime
        }
        let roleTypeStr = 3
        if (event == ReportRoleType.create) {
            roleTypeStr = 2
        } else if (event == ReportRoleType.levelup) {
            roleTypeStr = 4
        }
        let param = {
            "areaId": GameDataCenter.sevBack.userInfo?.a?.sid,
            "areaName": GameDataCenter.user.serverName,
            "roleId": GameDataCenter.sevBack.userInfo?.a?.uuid,
            "roleName": GameDataCenter.sevBack.userInfo?.a?.name,
            "roleLevel": GameDataCenter.sevBack.userInfo?.a?.level,
            "vipGrade": 0,
            "createRoleTime": GameDataCenter.sevBack.userInfo?.a?.regtime,
            "createTime": GameDataCenter.time.sevTime,
            "moneyNum": GameDataCenter.sevBack.userInfo?.a?.iscz,
            "rolePower": 0,
            "roleTurnup": 0,
            "sign": Config.wxSign
        }
        //验证
        let str: string = ""
        str += "&areaId=" + param["areaId"]
        str += "&areaName=" + param["areaName"]
        str += "&createRoleTime=" + param["createRoleTime"]
        str += "&createTime=" + param["createTime"]
        str += "&moneyNum=" + param["moneyNum"]
        str += "&roleId=" + param["roleId"]
        str += "&roleLevel=" + param["roleLevel"]
        str += "&roleName=" + param["roleName"]
        str += "&rolePower=" + param["rolePower"]
        str += "&roleTurnup=" + param["roleTurnup"]
        str += "&vipGrade=" + param["vipGrade"]
        str += "fa62a8cbd24941ec83edaf89799a1c4b"
        // console.log("md5 str => ", str)
        let _sign = md5(str).toUpperCase();
        param.sign = _sign
        window['hitalkOpenSDK'].gameReport(roleTypeStr, param, (res: any) => {
            console.log("角色数据上报:" + JSON.stringify(res));
            if (res.retCode == 0) {
                //上报成功
            }
            //上报失败
        })
    }
    pay(orderId: string, order10cs: string, param: PayProductParam): void {
        window['hitalkOpenSDK'].isGamePay({}, function (res: any) {
            //true:开启(默认值),false:关闭支付
            console.log('是否开启支付功能:' + res)
            if (res) {
                //开启支付功能
                let packageInfo = Gamecfg.packageInfo.getItem(Config.pid)
                let price = param.price * 100
                let startPaydata = {
                    'gameId': parseInt(packageInfo.params[0]), //	游戏唯一标识
                    'snKey': packageInfo.params[2], //	包唯一码
                    'openId': window['hitalkOpenSDK'].openId, //用户唯一标识
                    'roleId': GameDataCenter.sevBack.userInfo?.a?.uuid, //	角色Id
                    'roleName': GameDataCenter.sevBack.userInfo?.a?.name, //角色名称
                    'roleLevel': GameDataCenter.sevBack.userInfo?.a?.level, //角色等级
                    'vipGrade': 0, //VIP等级
                    'areaId': GameDataCenter.sevBack.userInfo?.a?.sid,   // 区服id,合服之后传旧的areaId,与数据上报的区服ID相同
                    'areaName': GameDataCenter.sevBack.userInfo?.a?.sid, // 区服名称
                    'productId': param.productId, // 商品ID
                    'productName': param.productName,   // 商品名称
                    'productDescribe': param.productDesc,   // 商品描述
                    'amount': price, // 商品金额(单位:分)
                    'gameOrderNo': orderId, // 游戏方支付订单号
                    'timestamp': GameDataCenter.time.sevTime,   // 时间戳,单位:秒
                    'extension': "", //透传字段,支付回调时会原样返回,默认值:""
                    'callbackUrl': order10cs,   // 支付回调地址 
                    'sign': ""   // 签名信息
                }
                //验证
                let str: string = ""
                str += "amount=" + startPaydata["amount"]
                str += "&areaId=" + startPaydata["areaId"]
                str += "&areaName=" + startPaydata["areaName"]
                str += "&callbackUrl=" + startPaydata["callbackUrl"]
                if (!gameMethod.isEmpty(startPaydata["extension"])) {
                    str += "&extension=" + startPaydata["extension"]
                }
                str += "&gameId=" + startPaydata["gameId"]
                str += "&gameOrderNo=" + startPaydata["gameOrderNo"]
                str += "&openId=" + startPaydata["openId"]
                str += "&productDescribe=" + startPaydata["productDescribe"]
                str += "&productId=" + startPaydata["productId"]
                str += "&productName=" + startPaydata["productName"]
                str += "&roleId=" + startPaydata["roleId"]
                str += "&roleLevel=" + startPaydata["roleLevel"]
                str += "&roleName=" + startPaydata["roleName"].trim()
                str += "&snKey=" + startPaydata["snKey"]
                str += "&timestamp=" + startPaydata["timestamp"]
                str += "&vipGrade=" + startPaydata["vipGrade"]
                str += "fa62a8cbd24941ec83edaf89799a1c4b"
                console.log("md5 str => ", str)
                let _sign = md5(str).toUpperCase();
                startPaydata.sign = _sign
                console.log("startPaydata=>", JSON.stringify(startPaydata))
                window['hitalkOpenSDK'].gamePay(startPaydata, (res: any) => {
                    console.log('支付:' + JSON.stringify(res))
                    if (res.retCode = 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 {
                        UIHelp.ShowTips("支付异常，请联系客服")
                        //异常上报服务端
                        if (window["sendClientErr"]) {
                            window["sendClientErr"]([JSON.stringify(res)])
                        }
                    }
                })
            } else {
                //不开启支付功能
                UIHelp.ShowTips("未开启支付，无需支付")
            }
        })

    }

    checkMsg(str: string, cb: Function): void {
        //由服务端校验
        cb()
        // var switchs = window['hitalkOpenSDK'].switchStatus //获取功能开关状态
        // //是否实现敏感字校验功能
        // //true:由客户端校验敏感字,false:由服务端接口校验敏感字
        // if (switchs.contentCheck && switchs.contentCheck.status) {
        //     // 需要
        //     //调用敏感字校验接口
        //     var params = {
        //         scene: 2,//内容应用场景值(1:创角，2:聊天(默认)，3:家族改名，4:家族公告)
        //         content: str
        //     }
        //     window['hitalkOpenSDK'].gameExtraAction("contentCheck", params, function (res) {
        //         if (res.retCode == 0) {
        //             //校验通过
        //             cb()
        //         } else {
        //             //校验失败
        //             UIHelp.ShowTips("输入文字带有敏感词,请重新输入")
        //         }
        //     })
        // } else {
        //     // 不需要
        //     UIHelp.ShowTips("未开通敏感词检测")
        //     cb()
        // }

    }
    // 打开客服窗口
    openService() {
        var switchs = window['hitalkOpenSDK'].switchStatus //获取功能开关状态
        //是否显示客服功能
        if (switchs.customerService) {
            // 显示客服功能
            // 打开客服窗口
            window['hitalkOpenSDK'].gameExtraAction("customerService", {}, function (res) {
                //返回结果
            });
        } else {
            // 隐藏游戏内客服按钮
            UIHelp.ShowTips("未开通客服功能")
        }

    }
    // 订阅消息
    setSubscribe(tmplIds: string[], ids: string[]) {
        var switchs = window['hitalkOpenSDK'].switchStatus //获取功能开关状态
        //是否显示客服功能
        //判断渠道是否有订阅功能
        if (switchs.subscribe) {
            //长期订阅状态,该功能暂时关闭,需达到条件才能开启
            var subscribeStatus = switchs.subscribe.status //长期订阅状态(暂停使用);  true:已订阅  false:未订阅
            var oneStatus = switchs.subscribe.oneStatus//一次性订阅状态;   true:已订阅  false:未订阅

            //一次性订阅功能判断,当调用subscribe订阅接口时为true时判断
            if (oneStatus) {
                //用户订阅状态为true要进行的操作
                //比如:当用户订阅状态为true时,隐藏"订阅"图标/或者"勾选"订阅功能
            } else {
                //用户订阅状态为false要进行的操作
            }
            wx["showModal"]({
                title: "提示",
                content: "请授权开启服务通知",
                showCancel: true,
                success: function (res) {
                    if (res.confirm) {
                        //当(未订阅)用户点击"订阅"按钮,主动订阅时调用
                        var params = {
                            type: 0,  //0:长期订阅  1:一次性订阅 (默认传入)
                            tmplIds: tmplIds //订阅模板ID 数组
                        }
                        window['hitalkOpenSDK'].gameExtraAction("subscribe", params, function (res) {
                            console.log("===订阅接口回调===", res)
                            if (res.retCode == 0) {
                                //表示订阅成功
                                GameDataCenter.subscribe.setLastSubscribeTime(tmplIds)
                                let acceptList: string[] = []
                                let NoAcceptList: string[] = []
                                tmplIds.forEach((element, index) => {
                                    if (res?.data?.indexOf(element) >= 0) {
                                        acceptList.push(ids[index])
                                    } else {
                                        NoAcceptList.push(ids[index])
                                    }
                                });
                                if (acceptList.length > 0) {
                                    GameDataCenter.subscribe.sendSubscribe(acceptList)
                                }
                                if (NoAcceptList.length > 0) {
                                    GameDataCenter.subscribe.sendSubscribeCancle(NoAcceptList)
                                }
                            } else {
                                //表示订阅失败
                                GameDataCenter.subscribe.sendSubscribeCancle(tmplIds)
                            }
                        });
                    } else if (res.cancel) {
                        console.log('用户点击取消');
                        // 用户点击取消后的逻辑处理
                        //表示订阅失败
                        GameDataCenter.subscribe.sendSubscribeCancle(tmplIds)
                    }
                }

            })

        } else {
            //表示该渠道没有订阅功能,游戏不能显示订阅相关功能
            UIHelp.ShowTips("未开通订阅功能")
        }

    }
    showRewardAd(adId: string, kid: string, order11Id: string): void {
        var switchs = window['hitalkOpenSDK'].switchStatus //获取功能开关状态
        //是否需要激励视频功能
        if (switchs.videoAd) {
            //数数上报
            let properties = {
                "ad_platform": "微信小游戏",
                "ad_id": adId,
                "ad_type": "激励视频",
                "ad_placement_name": "home_feed",
                "ad_placement_id": order11Id,
                "current_page": kid,
                // "ad_ecpm": 0
            }
            ThinkingDataMgr.TDTrack("ad_request", properties)
            // 开启激励视频功能
            //播放视频功能    
            var params = {
                adUnitId: adId//不同位置的广告ID,需要游戏传入
            }
            window['hitalkOpenSDK'].gameExtraAction("videoAd", params, function (res) {
                let isSuc = res.retCode == 0 ? true : false
                //数数上报
                let properties = {
                    "ad_platform": "微信小游戏",
                    "ad_id": adId,
                    "ad_type": "激励视频",
                    "ad_placement_name": "home_feed",
                    "ad_placement_id": order11Id,
                    "current_page": kid,
                    // "ad_ecpm": 0,
                    "is_filled_success": isSuc,
                    "error_detail_info": JSON.stringify(res),
                    "error_detail_code": res.retCode
                }
                ThinkingDataMgr.TDTrack("ad_response", properties)
                if (res.retCode == 0) {
                    //表示播放视频成功,游戏内给玩家发放奖励
                    GameDataCenter.adVideo.onXiadanSucc()
                    //数数上报
                    let properties = {
                        "ad_platform": "微信小游戏",
                        "ad_id": adId,
                        "ad_type": "激励视频",
                        "ad_placement_name": "home_feed",
                        "ad_placement_id": order11Id,
                        "current_page": kid,
                        // "ad_ecpm": 0,
                        // "ad_app_name": "未知"
                    }
                    ThinkingDataMgr.TDTrack("ad_show", properties)
                } else {
                    //表示播放视频失败,不发奖励
                    //数数上报
                    let properties = {
                        "ad_platform": "微信小游戏",
                        "ad_id": adId,
                        "ad_type": "激励视频",
                        "ad_placement_name": "home_feed",
                        "ad_placement_id": order11Id,
                        "current_page": kid,
                        // "ad_ecpm": 0,
                        // "ad_app_name": "未知",
                        // "ad_duration": 30,
                        // "ad_play_duration": 15,
                        "is_complete_play": false
                    }
                    ThinkingDataMgr.TDTrack("ad_close", properties)
                }
            });
        } else {
            // 关闭激励视频功能

            UIHelp.ShowTips("未开通视频广告")
        }

    }
    // 分享上报
    resportShareEvent() {
        console.log("分享上报")
        // window["hitalkOpenSDK"].addShareInfo({
        //     data: {
        //         to_target: 'wx'
        //     }
        // }).then(res => {
        //     console.log("分享结果:", res)
        // })
    }
}