/**
游戏名称:逍遥仙（淘宝）
小程序ID:
 */
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, 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";
export default class PlatformTaoBao extends PlatformBase {
    sdk: any;
    gameActivityController: any;
    RewardedVideoAd: any;
    constructor() {
        super()
        this.AdXiaDanSuc = false;//初始化
        // 切换到前台
        const listener = function (res) {
            // console.log("-----tb.onShow 回调触发111:", res)
            console.log("-----tb.onShow 回调触发222:", this.AdXiaDanSuc)
            // if (this.AdXiaDanSuc) {
            this.AdXiaDanSuc = false
            console.log("有广告任务，发起奖励请求")
            // GameDataCenter.adVideo.onTaoBaoXiadanSucc() // 向服务端请求奖励
            // }

            this.dealQuery(res)
            GameDataCenter.audio.resumeMusic()

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

            EventMng.emit(GameEvent.ON_SHOW_APP)
        }
        my.onShow((res) => {
            console.log("-----tb.onShow 回调触发:", res)
            // if (this.AdXiaDanSuc) {
            //     this.AdXiaDanSuc = false
            //     console.log("有广告任务，发起奖励请求")
            //     //连续请求5次
            //     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.adVideo.onTaoBaoXiadanSucc() // 向服务端请求奖励
            //     }, 1000)
            // }

            this.dealQuery(res)
            GameDataCenter.audio.resumeMusic()

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

            EventMng.emit(GameEvent.ON_SHOW_APP)
        });
        // my.offShow(listener)
        const hideListener = function (res) {
            console.log("-----tb.onHide 回调触发:", res)
            // GameDataCenter.plat.instance.reportRole(ReportRoleType.offline)
            // this.dealQuery(res)
            GameDataCenter.audio.stopAllEffects()
            GameDataCenter.audio.pauseMusic()
        }
        my.onHide((res) => {
            console.log("-----tb.onHide 回调触发:", res)
            // GameDataCenter.plat.instance.reportRole(ReportRoleType.offline)
            // this.dealQuery(res)
            GameDataCenter.audio.stopAllEffects()
            GameDataCenter.audio.pauseMusic()
        });
        // my.offHide(hideListener);
        //该方法不支持ide
        // my.setPreferredFramesPerSecond(30);

        my.setKeepScreenOn({
            keepScreenOn: true
        })
        if (my.getUpdateManager) {
            const updateManager = my.getUpdateManager()

            updateManager.onCheckForUpdate(function (res) {
                //请求完新版本信息的回调
                console.log(res.hasUpdate)
            })

            updateManager.onUpdateReady(function () {
                my.confirm({
                    title: '更新提示',
                    content: '新版本已经准备好，是否重启应用？',
                    success: function (res) {
                        if (res.confirm) {
                            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                            updateManager.applyUpdate()
                        }
                    }
                })
            })
        }
        // 初始化并获取sdk实例
        if (my.tb.getInteractiveSDK) {
            this.sdk = my.tb.getInteractiveSDK(); //调用此函数即可初始化SDK
            // 获取运营活动控制器
            this.gameActivityController = this.sdk.getGameActivityController({
                bizCode: 'xiaoyaoxiannew1',//请申请
            });
        }
    }

    showLoginView(): void {
        console.log("淘宝小游戏平台静默登录")
        EventMng.emit(LoadEvent.LOAD_PROGRESS, 0.25, "login")
        my.getSystemInfo({
            success: (res) => {
                console.log(`systemInfo: ${JSON.stringify(res)}`);
                if (res["platform"] == "Android") {
                    GameDataCenter.plat.instance.deviceOS = PlatFormDevType.android;
                } else {
                    GameDataCenter.plat.instance.deviceOS = PlatFormDevType.ios;
                }
            }
        });
        // async function GetOpenId() {
        // let result
        //     try {
        //     result = await window['cloud'].application.httpRequest({
        //         //不需要完整域名，只需要接口访问路径即可
        //         'path': '/welcome',
        //         'method': 'GET',
        //         'headers': {},
        //         'params': {},
        //         'body':{},
        //         //cloudAppId填写开启本地调试的云应用ID,否则会调到云端
        //         'exts': { "cloudAppId": "55088", "timeout": 4000 }
        //     });
        //     } catch (error) {
        //         console.log(error)
        //     }
        // }
        my.authorize({
            scopes: 'scope.userInfo',
            success: (res: any) => {
                console.log("淘宝授权：" + JSON.stringify(res))
                EventMng.emit(LoadEvent.LOAD_PROGRESS, 0.75, "login")
                // GetOpenId().then(res => { 
                // console.log("openId == ",res) 
                let code = res.accessToken.accessToken;
                console.log("淘宝静默登录成功")
                let tagInfo = this.sdk.getChannelTag();
                console.log('ChannelTag', tagInfo);
                let params: PlayerLoginPram = {
                    pid: Config.pid,
                    param: [code]
                }
                GameController.network.send(PlayerLogin.url, params, (result: SevBack) => {
                    console.log("后段验证返回")
                    EventMng.emit(LoadEvent.LOAD_PROGRESS, 1, "login")
                    if (result.type == 1 && result.platBack) {
                        this.openId = result.platBack.openid
                        this.loginParams = [result.platBack.token, JSON.stringify(tagInfo)]
                        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)
                        }
                    }
                    // 获取用户设置信息
                    console.log("获取用户设置信息")
                    my.getSetting({
                        withSubscriptions: true,
                        success(res) {
                            console.log("获取用户设置信息 回调:", res)
                            if (res.authSetting && res.authSetting["scope.userInfo"]) {
                                // 已授权
                                console.log("已授权")
                                GameDataCenter.plat.instance.hasAuthUserInfo = true
                            }
                        }
                    })
                })
                // })

            },
            fail: (res: any) => {
                // UIHelp.ShowTips("授权失败，请点击右上角的三个点，开启授权后重新登录")
                EventMng.emit(LoadEvent.LOAD_PROGRESS, 0.75, "login")
                // GetOpenId().then(res => { 
                // console.log("openId == ",res) 
                // let code = res.accessToken.accessToken;
                console.log("淘宝静默登录成功")
                let tagInfo = this.sdk.getChannelTag();
                console.log('ChannelTag', tagInfo);
                let params: PlayerLoginPram = {
                    pid: Config.pid,
                    param: []
                }
                GameController.network.send(PlayerLogin.url, params, (result: SevBack) => {
                    console.log("后段验证返回")
                    EventMng.emit(LoadEvent.LOAD_PROGRESS, 1, "login")
                    if (result.type == 1 && result.platBack) {
                        this.openId = result.platBack.openid
                        this.loginParams = [result.platBack.token, JSON.stringify(tagInfo)]
                        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)
                        }
                    }
                    // 获取用户设置信息
                    console.log("获取用户设置信息")
                    my.getSetting({
                        withSubscriptions: true,
                        success(res) {
                            console.log("获取用户设置信息 回调:", res)
                            if (res.authSetting && res.authSetting["scope.userInfo"]) {
                                // 已授权
                                console.log("已授权")
                                GameDataCenter.plat.instance.hasAuthUserInfo = true
                            }
                        }
                    })
                })
                // })
            }
        });
    }

    private dealQuery(res) {
        if (res.scene) {
            GameDataCenter.plat.queryparams.scene = res.scene
        }
        let shareInfo = this.sdk.getShareInfo();
        if (shareInfo['inviter']) {
            GameDataCenter.plat.queryparams.inviter = shareInfo['inviter']
        }
        if (shareInfo['sharer']) {
            GameDataCenter.plat.queryparams.sharer = shareInfo['sharer']
        }
        EventMng.emit(PlatEvent.ON_SCENE_CHANGED)
    }

    pay(orderId: string, order10cs: string, param: PayProductParam): void {
        my.tb.virtualTrade({
            itemId: param.productId,
            outOrderId: orderId,
            success(res) {
                // do something
                console.log("====== :", res)
                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)
            },
            fail(errData) {
                // do something
                console.log("======支付失败:", errData)
                UIHelp.ShowTips("支付失败")
            }
        })
    }

    // 打开客服窗口
    openService() {
        // 打开客服窗口
        if (my.tb.openMessage) {
            my.tb.openMessage({ sellerNick: "摩西游戏化旗舰店" })
        }
    }

    // showRewardAd(adId: string, kid: string, order11Id: string): void {
    //     if (gameMethod.isEmpty(adId)) {
    //         UIHelp.ShowTips("暂无广告配置")
    //         return
    //     }
    //     // 获取任务控制器
    //     let taskController = this.sdk.getTaskController({
    //         materialId: '33002', //请找淘宝PD协助申请
    //         materialCode: '6dZEr8Pk2xOTdGGIeUlUQUb' //请找淘宝PD协助申请
    //     });
    //     taskController.getTaskList()
    //     .then(res => {
    //         console.log("taskList:"+JSON.stringify(res))
    //         let taskList = res.main
    //         //找到对应的任务类型，直接触发
    //         let targetTask = null;
    //         for (let key in taskList) {
    //             if (Object.prototype.hasOwnProperty.call(taskList, key)) {
    //                 let taskInfo = taskList[key];
    //                 if (taskInfo.consumeType == adId) {
    //                     targetTask = taskInfo
    //                     break;
    //                 }
    //             }
    //         }
    //         if (targetTask != null) {
    //             if (targetTask.count >= targetTask.maxCount) {
    //                 UIHelp.ShowTips("当前任务奖励已达领取上限")
    //                 return
    //             }
    //             taskController.executeTask(targetTask.id)
    //             .then(res => {
    //                 this.AdXiaDanSuc = true;
    //                 console.log("executeTask succ:"+JSON.stringify(res))
    //             })
    //             .catch(err => {
    //                 UIHelp.ShowTips("淘宝任务执行异常")
    //                 console.log(err)
    //             });
    //         } else {
    //             UIHelp.ShowTips("找不到对应的广告类型")
    //         }
    //     })
    //     .catch(err => {
    //         UIHelp.ShowTips("淘宝任务获取列表异常")
    //         console.log(err)
    //     });
    // }

    showRewardAd(adId: string, kid: string, order11Id: string): void {
        if (gameMethod.isEmpty(adId)) {
            UIHelp.ShowTips(`${kid}暂无广告配置`)
            return
        }
        // 小游戏
        if (gameMethod.isEmpty(this.RewardedVideoAd)) {
            this.RewardedVideoAd = my.createRewardedAd({ adUnitId: adId });
        }

        let isLoaded = true;
        // 按钮或者自定义事件触发
        const invoke = () => {
            if (isLoaded) {
                this.RewardedVideoAd
                    .show()
                    .then(() => {
                        console.log("广告显示成功");
                        // 展示成功清除 
                        isLoaded = false
                        // this.RewardedVideoAd.offLoad(loadCallback)
                    })
                    .catch((err) => {
                        console.log("广告组件出现问题", err);
                        // 再次重试加载一次          
                        this.RewardedVideoAd
                            .load()
                            .then(() => {
                                console.log("手动加载成功");
                                invoke()
                            });
                    })
            } else {
                console.log('广告没加载完成');
            }
        }
        invoke();
        // const loadCallback = (res) => {
        //     console.log('loadCallback:', res);
        //     isLoaded = true;
        //     invoke();
        // }
        // 完成广告回回调  
        const completeCallback = (res) => {
            console.log('completeCallback', res);
            // this.AdXiaDanSuc = true;
            GameDataCenter.adVideo.onTaoBaoXiadanSucc();
            // 在合适的时机去释放监听
            // RewardedVideoAd.offLoad(loadCallback)
            // this.RewardedVideoAd.offComplete(completeCallback)
            // this.RewardedVideoAd.offClose(closeCallback)
            // this.RewardedVideoAd.offError(errorCallback)
        }
        // 完成广告或者未完成广告，关闭广告会回调  
        const closeCallback = (res) => {
            console.warn('closeCallbak', res)
        }
        // 广告接口报错的回调 
        const errorCallback = (e) => {
            console.error('errorCallback', e)
        }
        // 监听广告的事件
        // this.RewardedVideoAd.onLoad(loadCallback)
        this.RewardedVideoAd.onClose(closeCallback)
        this.RewardedVideoAd.onComplete(completeCallback)
        this.RewardedVideoAd.onError(errorCallback)
    }
    reportRoleData(actionName: string, type: Number = 1) {
        if (type == 1) {
            try {
                this.sdk.reportExposure({ actionName: actionName });
            } catch (e) {
                console.error(e);
            }
        } else {
            try {
                this.sdk.reportClick({ actionName: actionName });
            } catch (e) {
                console.error(e);
            }
        }


    }
    //检测新人组件是否开启
    checkGameActivityController(cb: (isOpen: boolean) => {}) {
        if (gameMethod.isEmpty(this.gameActivityController)) {
            cb(false)
        }
        this.gameActivityController.getInfo().then((res) => {
            console.log("checkGameActivityController res=>", res)
            // if (res.showModule) {
            //     let params: UserSetZjPram = {
            //     }
            //     GameController.network.send(UserSetZj.url, params, (result: SevBack) => {

            //     })
            // }
            cb(res.showModule)
        }).catch((err) => {
            console.error("checkGameActivityController err:", err);
        });
    }
    //淘宝新人组件
    openGameActivityController() {
        if (gameMethod.isEmpty(this.gameActivityController)) {
            UIHelp.ShowTips("淘宝新人组件初始化失败")
            return
        }
        // 释放监听
        this.gameActivityController.offViewClose(() => {

        });
        this.gameActivityController.getInfo().then((res) => {
            console.log("getInfo=>", res);
            if (!gameMethod.isEmpty(this.gameActivityController) && res.showModule) {
                this.gameActivityController.openView().then((res) => {
                    console.log("openView=>", res);
                    // 增加监听
                    this.gameActivityController.onViewClose(() => {

                    });
                }).catch((err) => {
                    console.error("openGameActivityController err:", err);
                });
            } else {
                UIHelp.ShowTips("无法打开新人组件")
            }
        }).catch((err) => {
            console.error(err);
        });
    }
    //淘宝用户关键行为上报
    reportUserAction(actionId: number) {
        console.log("reportUserAction actionId=>", actionId);
        this.sdk.reportScene({
            sceneId: 401,
            timestamp: Date.now(),
            costTime: 2000,
            extra: {
                raw: actionId
            }
        });
    }
}