package com.ym.game

import android.annotation.SuppressLint
import android.app.Dialog
import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.content.pm.ActivityInfo
import android.os.Bundle
import android.os.IBinder
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.view.WindowManager
import com.bx.adsdk.AdSdk
import com.game.luckyfarm.UnityPlayerActivity
import com.gyf.immersionbar.ImmersionBar
import com.umeng.analytics.MobclickAgent
import com.ym.ddhy.R
import com.ym.game.activity.WxLoginActivity
import com.ym.game.listener.IDialogViewCloseCallback
import com.ym.game.notif.NotificationService
import com.ym.game.view.*
import com.ym.library.Constant
import com.ym.library.down.UpdateVersionManager
import com.ym.library.listener.IAdVideoListener
import com.ym.library.module.*
import com.ym.library.net.ApiClient
import com.ym.library.net.BaseObserver
import com.ym.library.net.GameApiClient
import com.ym.library.net.RxSchedulers
import com.ym.library.utils.*
import com.ym.modulecommon.AppliContext
import com.ym.modulecommon.module.UserInfoEntity
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import org.jetbrains.anko.act
import java.lang.reflect.Method

/**
 * @author (wangXuewei)
 * @datetime 2020-10-09 22:09 GMT+8
 * @detail :
 */
class GameActivity : UnityPlayerActivity(), IDialogViewCloseCallback {
    private var mOrderString = "";
    private val mContext = AppliContext.get()
    private var mRefreshLoginObservable: Observable<String>? = null

    @SuppressLint("CheckResult")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
//        StatusBarUtils.transportStatus(this, resources.getColor(R.color.transparent))
//        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT // 禁用横屏
//        window.addFlags(WindowManager.LayoutParams.FLAG_SECURE) //禁止截屏
        EventUtils.onEvent("tab_imp", "多多花园")
        if (SettingPreference.getIsShowGuide()) {
            SettingPreference.setIsShowGuide(false)
        }
        mRefreshLoginObservable = RxBus.get().register("refresh_login", String::class.java)
        TurntableDialog.initTurntableAnim()
        getUserInfo()
        checkUpdateApp()
        mRefreshLoginObservable?.observeOn(AndroidSchedulers.mainThread())?.subscribe({
            when (it) {
                "not_login" -> {
                    com.ym.modulecommon.utils.SettingPreference.setToken("")
                    try {
                        val intent = Intent(this, WxLoginActivity::class.java)
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                        AppliContext.get().startActivity(intent)
                    } catch (e: java.lang.Exception) {
                    }
                }
                "open_notif" -> {
                    openNotif()
                }
                "close_notif" -> {
                    if(scc!=null){
                        unbindService(scc)
                    }
                }
            }
        }, {

        })

//        //小满上报
//        if (Constant.isReportXiaoman) {
//            AdSdk.exposure("2773", com.ym.modulecommon.utils.SettingPreference.getToken())
//            Constant.isReportXiaoman = false
//        }
        openNotif()

        AdUtils.loadNextCacheRewardVideoAd(this)
        AdUtils.loadFeedCacheAdToCache(this)
    }

    override fun onDestroy() {
        unbindService(scc)
        super.onDestroy()
        if (mRefreshLoginObservable != null) {
            RxBus.get().unregister("refresh_login", mRefreshLoginObservable!!)//页面销毁的时候要执行 反注册
        }

    }

    private fun checkUpdateApp() {
        val updateVersionManager = UpdateVersionManager(this)
        updateVersionManager?.checkUpdate(false)
    }

    override fun onResume() {
        super.onResume()
        MobclickAgent.onResume(this)
        Log.d("I/Unity", "onResume")
        EventUtils.onEvent(
            "page_status",
            Utils.obj2Str(ReportEntity(Constant.ReportSessionId, "GameActivity", "onResume"))
        )
    }

    override fun onPause() {
        super.onPause()
        MobclickAgent.onPause(this)
        EventUtils.onEvent(
            "page_status",
            Utils.obj2Str(ReportEntity(Constant.ReportSessionId, "GameActivity", "onPause"))
        )
    }


    /**
     * 调用Unity的方法
     * @param gameObjectName    调用的GameObject的名称
     * @param functionName      方法名
     * @param args              参数
     * @return                  调用是否成功
     */
    fun callUnity(
        gameObjectName: String?,
        functionName: String?,
        args: String?
    ): Boolean {
        try {
            val classtype =
                Class.forName("com.unity3d.player.UnityPlayer")
            val method: Method = classtype.getMethod(
                "UnitySendMessage",
                String::class.java,
                String::class.java,
                String::class.java
            )
            if (args != null) {
                method.invoke(classtype, gameObjectName, functionName, args)
            } else {
                method.invoke(classtype, gameObjectName, functionName)
            }
            return true
        } catch (e: Exception) {
        }
        return false
    }

    //头像跳转
    fun onclickHead() {
        JumpUtils.jumpSettingActivity()
    }

    /**
     * 小满入口
     */
    fun gotoXiaoManActivity() {
        EventUtils.onEvent("XiaoManClick", "小满入口点击");
        JumpUtils.jumpXiaomanActivity("天天领现金")
    }

    /**
     * 跳转提现页
     */
    fun gotoWithdrawPage(type: Int) {
        if (type == 1) {
            JumpUtils.h5Jump("跳转提现页", Constant.Param.WithDraw2, false, act)
        } else {
            JumpUtils.h5Jump("跳转提现页", Constant.Param.WithDraw, false, act)
        }
    }

    /**
     * 上榜赚钱
     */
    fun ranklistClick() {
        //JumpUtils.h5Jump("上榜赚钱", Constant.Param.RankList)
        JumpUtils.h5Jump("排行榜", Constant.Param.RankList, false, act)
    }

    /**
     * 每日福利
     */
    fun oneveryDayWelfareClick() {
        Log.d("wxw", "每日福利")
//        JumpUtils.h5Jump("每日福利", Constant.Param.WelfareCenter, false, act)
        JumpUtils.jumpWelfareActivity()
    }

    /**
     * 打卡提现
     */
    fun clockInMakeMoney() {
        Log.d("wxw", "打卡提现")
//        JumpUtils.h5Jump("打卡提现", Constant.Param.PunchRecord, false, act)
        JumpUtils.jumpClockInWithdrawActivity()
    }

    /**
     * 拼图红包
     */
    fun onPuzzleClick() {
        Log.d("wxw", "拼图红包")
        MainLooper.get()?.post(Runnable {
            if (Utils.isFastClick2()) {
                //CashExchangeDialog.showCashExchage(this, this)
                PuzzleDialog.showPuzzleDialog(this, this)
            }
        })
    }

    private var isclick = false

    /**
     * 兑换现金
     */
    fun cashExchange() {
        if (!isclick) {
            isclick = true
            MainLooper.get()?.post(Runnable {
                CashExchangeDialog.showCashExchage(this, this)
            })
            MainLooper.get()?.postDelayed(Runnable {
                isclick = false
            }, 2000)
        }

    }

    /**
     * 幸运转盘
     */
    fun luckyTurntable() {
        this.runOnUiThread(object : Runnable {
            override fun run() {
                if (Utils.isFastClick()) {
                    TurntableDialog.showTurntable(this@GameActivity, this@GameActivity)
                }
            }
        })

    }

    /**
     * 领金币
     */
    fun getCoin() {
        this.runOnUiThread(object : Runnable {
            override fun run() {
                SiginDropsPopupwindow().init(this@GameActivity, this@GameActivity)
            }
        })
    }

    /**
     * 领加速剂
     */
    fun getSpeedWater() {
        this.runOnUiThread(object : Runnable {
            override fun run() {
                SpeedWaterPopupWindow().init(this@GameActivity, this@GameActivity)
            }
        })
    }

    /**
     * 点击飞行宝箱看视频
     */
    var flyBoxIsClick = true
    fun adFlyBox() {
        if (flyBoxIsClick) {
            flyBoxIsClick = false
            AdUtils.playRewardAd(this, "box_click", object : IAdVideoListener {
                override fun onAdClose() {
                    flyBoxIsClick = true
                    getFlyBoxReceive()
                }

                override fun onError(errorMsg: String?) {
                    flyBoxIsClick = true
                }
            })
        }
    }


    /**
     * 点击底部拆红包看视频
     */
    var flyBoxIsClick2 = true
    fun adRedPackPlan() {
        if (flyBoxIsClick2) {
            flyBoxIsClick2 = false
            AdUtils.playRewardAd(this, "bottom_open_red_envelope_click", object : IAdVideoListener {
                override fun onAdClose() {
                    flyBoxIsClick2 = true
                    getRedPackPlanReceive();
                }

                override fun onError(errorMsg: String?) {
                    flyBoxIsClick2 = true
                }
            })
        }

    }

    /**
     *  获取首页信息
     */
    fun getHomeInfo(callback: IUnitySendMessageCallback?) {
        GameApiClient.gameApi.getGameHomeInfo().compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<HomeInfoEntity>() {
                override fun onSuccess(result: HomeInfoEntity?) {
                    Log.d("wxw", "获取首页信息" + Utils.obj2Str(result))
                    callback?.onHomeSuccess(true, Utils.obj2Str(result))
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                    Log.d("wxw", "获取首页信息 error")
                    callback?.onHomeSuccess(false, errorMsg + "")
                }
            })
    }

    /**
     * 获取地块列表
     * */
    fun getListLand(callback: IUnitySendMessageCallback?) {
//        GameApiClient.gameApi.getListLand().compose(RxSchedulers.observableIO2Main())
//            .subscribe(object : BaseObserver<NewLandListEntity>() {
//                override fun onSuccess(result: NewLandListEntity?) {
//                    Log.d("wxw", "地块列表" + "{\"landList\":" + Utils.obj2Str(result) + "}")
//                    callback?.onFarmLandListSuccess(
//                        true,
//                        "{\"landList\":" + Utils.obj2Str(result) + "}"
//                    )
//                }
//
//                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
//                    Log.d("wxw", "地块列表 error")
//                    callback?.onFarmLandListSuccess(false, "LandError")
//                }
//            })
    }

    /**
     * 获取地块列表
     * */
    fun getListLandNew(from: Int) {
        Log.d("Wxw", "初始化地块列表成功$from")
        GameApiClient.gameApi.getListLand().compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<NewLandListEntity>() {
                override fun onSuccess(result: NewLandListEntity?) {
                    var json = Utils.obj2Str(result)
                    Log.d("Wxw", "初始化地块列表成功$from$json")
                    if (from == 1) {
                        callUnity("Canvas", "loadLandListSuccess", json)
                    }
                    if (from == 2) {
                        callUnity("Form_land", "sycnLandListSuccess", json)
                    }
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                    Log.d("Wxw", "初始化地块列表失败$from")
                }
            })
    }

    fun getGuide(callback: IUnitySendMessageCallback?) {
        GameApiClient.gameApi.getGuide().compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<GuideEntity>() {
                override fun onSuccess(result: GuideEntity?) {
                    callback?.onGetGuideSuccess(
                        true,
                        Utils.obj2Str(result)
                    )
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                    callback?.onFarmLandListSuccess(false, "GuideError")
                }
            })
    }


    fun onGetRedPackList(callback: IUnitySendMessageCallback?) {
//        callUnity("RedPackList", "redPackListDataUpdate", "")
        GameApiClient.gameApi.getRedPackList()
            .compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<List<RedPackListEntity>>() {
                override fun onSuccess(result: List<RedPackListEntity>?) {
                    if (result != null) {
                        Log.d(
                            "wxw",
                            "redPack===" + "{\"redPackList\":" + Utils.obj2Str(result) + "}"
                        )
                        callback?.onRedPackListSuccess(
                            true,
                            "{\"redPackList\":" + Utils.obj2Str(result) + "}"
                        )
                    }
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                    callback?.onRedPackListSuccess(
                        false,
                        "红包列表失败"
                    )
                }
            })
    }


    fun onRedPackReceive(redPackId: Int, moneyNum: String) {
        Log.d("wxw", "redId" + redPackId + "moneyNum" + moneyNum)
        GameApiClient.gameApi.getRedPackReceive(redPackId)
            .compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<RedPackReceiveEntity>() {
                override fun onSuccess(result: RedPackReceiveEntity?) {
                    if (result != null) {
                        callUnity("RedPackList", "redPackListDataUpdate", "")
                        callUnity("TitleView", "getHomeInfo", "")
                        GameEvent("show_receive_redPack_dialog_success", "展示红包领取弹窗成功")
                        //签到双倍领取弹窗显示
                        MainDialog.getTaskRewardDialog(
                            act,
                            "+${moneyNum}",
                            View.OnClickListener {
                                GameEvent("click_receive_redPack_double", "点击六倍领取")
                                Log.d("wxw", "签到翻倍广告点击")
                                AdUtils.playRewardAd(
                                    this@GameActivity,
                                    "receive_redPack_double_click",
                                    object : IAdVideoListener {
                                        override fun onAdClose() {
                                            onRedPackAwardReceive(result.doubleX.multipleSid)
                                        }

                                        override fun onError(errorMsg: String?) {
                                        }
                                    })
                            })
                    }
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                    GameEvent("show_receive_redPack_dialog_fail", "展示红包领取弹窗失败")
                }
            })
    }

    fun onRedPackAwardReceive(doubleId: String) {
        Log.d("wxw", "double" + doubleId)
        GameApiClient.gameApi.getRedPackAwardReceive(doubleId)
            .compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<RedPackDoubleReceiveEntity>() {
                override fun onSuccess(result: RedPackDoubleReceiveEntity?) {
                    if (result != null) {
                        GameEvent("show_receive_redPack_double_success", "六倍领取成功")
//                        var allMoneyNum =
//                            "总共获得奖励+${result.rewardContentList[0].totalRewardNum / 100.toDouble()}元";
//                        ToastUtil.showImageToas(act, allMoneyNum)
//                        callUnity("RedPackList", "redPackListDataUpdate", "")
                        MainDialog.showgetWaterDrop(
                            act,
                            4,
                            "redPack_double",
                            result.rewardContentList[0].totalRewardNum,
                            null
                        )
                    }
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                    GameEvent("show_receive_redPack_double_fail", "六倍领取失败")
                }
            })
    }


    /**
     * 云朵加速
     * */
    var cloudIsClick = true
    fun getCloudSpeed(callback: IUnitySendMessageCallback?) {
        Log.d("wxw", "云朵加速")
        if (cloudIsClick) {
            cloudIsClick = false
            AdUtils.playRewardAd(
                this@GameActivity,
                "cloud_acceleration_click",
                object : IAdVideoListener {
                    override fun onAdClose() {
                        cloudIsClick = true
                        GameApiClient.gameApi.getCloudSpeed()
                            .compose(RxSchedulers.observableIO2Main())
                            .subscribe(object : BaseObserver<StatusEntity>() {
                                override fun onSuccess(result: StatusEntity?) {
                                    Log.d("wxw", "云朵加速" + Utils.obj2Str(result))
                                    callback?.onCloudSpeedSuccess(true, Utils.obj2Str(result))
                                }

                                override fun onFailure(
                                    e: Throwable?,
                                    code: String?,
                                    errorMsg: String?
                                ) {
                                    Log.d("wxw", "云朵加速 error")
                                    callback?.onCloudSpeedSuccess(false, errorMsg + "")
                                }
                            })
                    }

                    override fun onError(errorMsg: String?) {
                        cloudIsClick = true
                    }
                })
        }
    }

    //解锁地块
    fun getUnlockLand(callback: IUnitySendMessageCallback?, id: Int, type: Int) {
        Log.d("wxw", "解锁地块 id" + id + "type" + type)//同步
//        GameApiClient.gameApi.getUnlockLand(id, type).compose(RxSchedulers.observableIO2Main())
//            .subscribe(object : BaseObserver<StatusEntity>() {
//                override fun onSuccess(result: StatusEntity?) {
//                    result?.id = id
//                    result?.type = type
//                    Log.d("wxw", "解锁地块" + Utils.obj2Str(result))
//                    callback?.onLandUnLockSuccess(true, Utils.obj2Str(result))
//                }
//
//                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
//                    Log.d("wxw", "解锁地块 error")
//                    callback?.onLandUnLockSuccess(false, errorMsg + "")
//                }
//            })
    }

    //解锁地块本地同步服务端 解锁地块传1 种植种子传2 收获果实传3 解锁倒计时4
    fun getUnlockLandNew(id: Int, type: Int, time: Int) {
        Log.d("wxw", "解锁地块 id" + id + "type" + type + "time" + time)//同步
        GameApiClient.gameApi.getUnlockLand(id, type, time)
            .compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<StatusEntity>() {
                override fun onSuccess(result: StatusEntity?) {
                    Log.d("wxw", "同步解锁地块")
                    getListLandNew(2);
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                    Log.d("wxw", "同步解锁地块 error")
                }
            })
    }

    //看视频除虫
    fun lookAdVideoCleanWorm(id: Int) {
        this.runOnUiThread(object : Runnable {
            override fun run() {
                MainDialog.showDialogWorm(this@GameActivity, View.OnClickListener {
                    AdUtils.playRewardAd(
                        this@GameActivity,
                        "CleanWorm",
                        object : IAdVideoListener {
                            override fun onAdClose() {
                                getUnlockLandNew(id, 4, 0)
                            }

                            override fun onError(errorMsg: String?) {

                            }
                        })
                })

            }
        })


    }


    fun seedNotEnoughDialog(id: Int, seedPrice: Int, seedVideoNum: Int) {
        this.runOnUiThread(object : Runnable {
            override fun run() {
                MainDialog.showDialogSeedNotEnough(this@GameActivity, id, seedPrice, seedVideoNum,
                    View.OnClickListener {
                        //买种子
                        callUnity("Form_land", "onBuySeed", "")
                    }, View.OnClickListener {
                        //看视频领取种子
                        callUnity("Form_land", "onVideoSeedReceive", "")
                    })

            }
        })
    }


    //看视频解锁地块
    fun lookAdVideoUnLockLand() {
        AdUtils.playRewardAd(
            this@GameActivity,
            "unlockLand",
            object : IAdVideoListener {
                override fun onAdClose() {
                    callUnity("Form_land", "lookAdVideoUnLockLandSuccess", "")
                }

                override fun onError(errorMsg: String?) {

                }
            })
    }

    //加速剂
    fun getUseAccelerators(callback: IUnitySendMessageCallback?, id: Int) {
        GameApiClient.gameApi.getUseAccelerators(id).compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<StatusEntity>() {
                override fun onSuccess(result: StatusEntity?) {
                    Log.d("wxw", "加速剂" + Utils.obj2Str(result))
                    callback?.onUseAcceleratorsSuccess(true, Utils.obj2Str(result))
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                    Log.d("wxw", "加速剂 error")
                    callback?.onUseAcceleratorsSuccess(false, errorMsg + "")
                }
            })
    }

    //加速剂
    fun getUseAcceleratorsSync(id: Int) {
        GameApiClient.gameApi.getUseAccelerators(id).compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<StatusEntity>() {
                override fun onSuccess(result: StatusEntity?) {
                    Log.d("wxw", "加速剂同步" + Utils.obj2Str(result))
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                    Log.d("wxw", "加速剂同步 error")
                }
            })
    }

    //金币购买种子
    fun getBuySeed(id: Int, time: Int) {
        Log.d("wxw", "金币购买种子id" + id + "time" + time);
        GameApiClient.gameApi.getBuySeed(id, time).compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<StatusEntity>() {
                override fun onSuccess(result: StatusEntity?) {
                    Log.d("wxw", "金币购买种子" + Utils.obj2Str(result))
//                    callback?.onBuySeedSuccess(true, Utils.obj2Str(result))
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                    Log.d("wxw", "金币购买种子 error")
//                    callback?.onBuySeedSuccess(false, errorMsg + "")
                }
            })
    }

    //仓库
    fun getWareHouseData(callback: IUnitySendMessageCallback?, id: Int) {
//        startActivity(Intent(this,HomeWareActivity::class.java))
        GameApiClient.gameApi.getWareHouseData(id).compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<List<LandListEntity>>() {
                override fun onSuccess(result: List<LandListEntity>?) {
                    Log.d("wxw", "仓库" + "{\"landList\":" + Utils.obj2Str(result) + "}")
                    callback?.onHomeWareListSuccess(
                        true,
                        "{\"landList\":" + Utils.obj2Str(result) + "}"
                    )
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                    Log.d("wxw", "仓库 error")
                    callback?.onHomeWareListSuccess(false, errorMsg + "")
                }
            })
    }

    fun jumpOrderDialog() {
        if (mOrderString != null && !mOrderString.equals("")) {

        }

    }

    //订单数据
    fun getOrderData(callback: IUnitySendMessageCallback?) {
        GameApiClient.gameApi.getHomeWList().compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<List<HomeListEntity>>() {
                override fun onSuccess(result: List<HomeListEntity>?) {
                    mOrderString = Utils.obj2Str(result)
                    Log.d("wxw", "订单数据" + Utils.obj2Str(result))
                    callback?.onOrderListSuccess(
                        true,
                        "{\"homeList\":" + Utils.obj2Str(result) + "}"
                    )
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                    Log.d("wxw", "订单数据 error")
                    callback?.onOrderListSuccess(false, errorMsg + "")
                }
            })
    }

    //订单领取
    fun getOrderReceive(callback: IUnitySendMessageCallback?) {
        GameApiClient.gameApi.getOrderReceive().compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<StatusEntity>() {
                override fun onSuccess(result: StatusEntity?) {
                    Log.d("wxw", "订单领取" + Utils.obj2Str(result))
                    callback?.onOrderReceiveSuccess(true, Utils.obj2Str(result))
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                    Log.d("wxw", "订单领取 error")
                    callback?.onOrderReceiveSuccess(false, errorMsg + "")
                }
            })
    }

    //看视频领取种子
    var videoSeedClick = true
    fun getVideoSeedReceive(callback: IUnitySendMessageCallback?, id: Int) {
//        if (videoSeedClick) {
//            videoSeedClick = false
//            AdUtils.playRewardAd(
//                this@GameActivity,
//                "receive_seed_click",
//                object : IAdVideoListener {
//                    override fun onAdClose() {
//                        videoSeedClick = true
//                        GameApiClient.gameApi.getVideoSeedReceive(id)
//                            .compose(RxSchedulers.observableIO2Main())
//                            .subscribe(object : BaseObserver<StatusEntity>() {
//                                override fun onSuccess(result: StatusEntity?) {
//                                    result?.id = id
//                                    Log.d("wxw", "看视频领取种子" + Utils.obj2Str(result))
//                                    callback?.onIncrVideoSeedSuccess(true, Utils.obj2Str(result))
//                                }
//
//                                override fun onFailure(
//                                    e: Throwable?,
//                                    code: String?,
//                                    errorMsg: String?
//                                ) {
//                                    Log.d("wxw", "看视频领取种子 error")
//                                    callback?.onIncrVideoSeedSuccess(false, errorMsg + "")
//                                }
//                            })
//                    }
//
//                    override fun onError(errorMsg: String?) {
//                        videoSeedClick = true
//                    }
//                })
//        }
    }

    //看视频领取种子 本地处理  新
    fun getVideoSeedReceiveNew(id: Int, time: Int) {
        if (videoSeedClick) {
            videoSeedClick = false
            AdUtils.playRewardAd(
                this@GameActivity,
                "receive_seed_click",
                object : IAdVideoListener {
                    override fun onAdClose() {
                        videoSeedClick = true
                        GameApiClient.gameApi.getVideoSeedReceive(id, time)
                            .compose(RxSchedulers.observableIO2Main())
                            .subscribe(object : BaseObserver<StatusEntity>() {
                                override fun onSuccess(result: StatusEntity?) {
                                    Log.d("wxw", "看视频领取种子同步" + Utils.obj2Str(result))
                                    callUnity(
                                        "Form_land",
                                        "onVideoSeedReceiveSuccess",
                                        "" + (id - 1)
                                    )
                                }

                                override fun onFailure(
                                    e: Throwable?,
                                    code: String?,
                                    errorMsg: String?
                                ) {
                                    Log.d("wxw", "看视频领取种子同步 error")
                                }
                            })
                    }

                    override fun onError(errorMsg: String?) {
                        videoSeedClick = true
                    }
                })
        }
    }


    var videoJiasuClick = true

    //看视频领取加速剂
    fun getVideoAcceleratorsReceive(callback: IUnitySendMessageCallback?, id: Int) {
        if (videoJiasuClick) {
            videoJiasuClick = false
            AdUtils.playRewardAd(
                this@GameActivity,
                "accelerator_receive_click",
                object : IAdVideoListener {
                    override fun onAdClose() {
                        videoJiasuClick = true
                        GameApiClient.gameApi.getVideoAcceleratorsReceive(id)
                            .compose(RxSchedulers.observableIO2Main())
                            .subscribe(object : BaseObserver<StatusEntity>() {
                                override fun onSuccess(result: StatusEntity?) {
                                    result?.id = id
                                    Log.d("wxw", "看视频领取加速剂" + Utils.obj2Str(result))
                                    callback?.onIncrVideoAcceleratorsSuccess(
                                        true,
                                        Utils.obj2Str(result)
                                    )
                                }

                                override fun onFailure(
                                    e: Throwable?,
                                    code: String?,
                                    errorMsg: String?
                                ) {
                                    Log.d("wxw", "看视频领取加速剂 error")
                                    callback?.onIncrVideoAcceleratorsSuccess(false, errorMsg + "")
                                }
                            })
                    }

                    override fun onError(errorMsg: String?) {
                        videoJiasuClick = true
                    }
                })
        }

    }

    fun getFlyBoxReceive() {
        GameApiClient.gameApi.getopenBox()
            .compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<FlyBoxEntity>() {
                override fun onSuccess(result: FlyBoxEntity?) {
                    Log.d("wxw", "看视频领取宝箱" + Utils.obj2Str(result))

                    if (result != null) {
                        var type = result.type
                        if (type != null) {
                            MainDialog.showopenBox(
                                this@GameActivity, type,
                                "宝箱奖励",
                                result.awardNum ?: 0,
                                result,
                                this@GameActivity
                            )
                        }
                    }
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                    Log.d("wxw", "看视频领取宝箱 error")
                }
            })
    }

    fun getRedPackPlanReceive() {
        GameApiClient.gameApi.getOpenPlantBox()
            .compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<FlyBoxEntity>() {
                override fun onSuccess(result: FlyBoxEntity?) {
                    Log.d("wxw", "底部拆红包" + Utils.obj2Str(result))
                    if (result != null) {
                        var type = result.type
                        if (type != null) {
                            MainDialog.showopenBox(
                                this@GameActivity, type,
                                "拆红包",
                                result.awardNum ?: 0,
                                result,
                                this@GameActivity
                            )
                        }
                    }
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                    Log.d("wxw", "底部拆红包 error")
                }
            })
    }


    fun GameEvent(keyName: String, valueName: String) {
        EventUtils.onEvent(keyName, valueName);
    }

    override fun onCloseViewSuccess(isSuccess: Boolean) {
        //关闭view
        Log.e("MXL", "CLOSE")
        callUnity("TitleView", "getHomeInfo", "")
        callUnity("GameManager", "getCardList", "")
    }

    fun getUserInfo() {
        EventUtils.onEvent("SplashPresenter_getUserInfo")
        ApiClient.userApi.getUserInfo().compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<UserInfoEntity>() {
                override fun onSuccess(result: UserInfoEntity) {
                    val uid = result.uid
                    if (TextUtils.isEmpty(uid)) {
                        EventUtils.onEvent("SplashPresenter_getUserInfo_fail")
                    } else {
                        EventUtils.onEvent("SplashPresenter_getUserInfo_success")
                        com.ym.modulecommon.utils.SettingPreference.saveUserInfo(result)
                        SettingPreference.setTrackId(result.gaodeTrackId ?: 0L)
                        SettingPreference.setTerminalId(result.gaodeTerminalId ?: 0L)
                        com.ym.modulecommon.utils.SettingPreference.setUid(uid)
                    }
                }

                override fun onFailure(e: Throwable, code: String?, errorMsg: String?) {
                    EventUtils.onEvent("SplashPresenter_getUserInfo_fail")
                }
            })
    }

    //检查云朵加速
    fun checkCloud(callback: IUnitySendMessageCallback?) {
        GameApiClient.gameApi.getGameCloudCheck().compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<GuideEntity>() {
                override fun onSuccess(result: GuideEntity?) {
                    callback?.onGetCheckCloud(
                        true,
                        Utils.obj2Str(result)
                    )
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                    callback?.onGetCheckCloud(false, "CloudError")
                }
            })
    }


    private var myNotifService: NotificationService? = null
    private var scc: ServiceConnection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName, service: IBinder) {
            val myBinder: NotificationService.MyBinder =
                service as NotificationService.MyBinder
            myNotifService = myBinder.getService()
        }

        override fun onServiceDisconnected(name: ComponentName) {}
    }

    //打开通知栏
    private fun openNotif() {
        if (SettingPreference.getNotice()) {
            val intent = Intent(this, NotificationService::class.java)
            bindService(intent, scc as ServiceConnection, BIND_AUTO_CREATE)
        }
    }

    //卡片收集
    fun addCard(callback: IUnitySendMessageCallback?) {
        GameApiClient.gameApi.addCard().compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<AddCardEntity>() {
                override fun onSuccess(result: AddCardEntity?) {
                    mOrderString = Utils.obj2Str(result)
                    Log.d("wxw", "收集卡片" + Utils.obj2Str(result))
                    callback?.onAddCardSuccess(true, Utils.obj2Str(result))
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                    Log.d("wxw", "收集卡片 error")
                    callback?.onAddCardSuccess(false, errorMsg + "")
                }
            })
    }

    //查询卡片角标
    fun getCardList(callback: IUnitySendMessageCallback?) {
        GameApiClient.gameApi.getCollectCard().compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<PuzzleEntity>() {
                override fun onSuccess(result: PuzzleEntity?) {
                    mOrderString = Utils.obj2Str(result)
                    Log.d("wxw", "查询卡片角标" + Utils.obj2Str(result))
                    callback?.onGetCardList(true, Utils.obj2Str(result))
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                    Log.d("wxw", "查询卡片角标 error")
                    callback?.onGetCardList(false, errorMsg + "")
                }
            })
    }

    //
    fun duihuan(id: Int, jine: String) {
        GameApiClient.gameApi.dowd(id).compose(
            RxSchedulers.observableIO2Main()
        ).subscribe(object : BaseObserver<ExchangeEntity>() {
            override fun onSuccess(result: ExchangeEntity?) {
                if (result != null) {
                    callUnity("reward_list_bg", "getTitleOrderListData", "")
                    MainDialog?.showWithDraw(
                        this@GameActivity,
                        result?.status ?: 0,
                        result?.title ?: "",
                        result?.reason ?: "",
                        result?.buttonText ?: "",
                        result?.buttonStatus ?: 0,
                        id,
                        result?.type,
                        jine,
                        true,
                        Dialog(this@GameActivity)
                    )
                }
            }

            override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {

                Utils.showToast(mContext, "" + errorMsg)
            }
        })
    }

    fun showCloudDialog(speedtime: Int, sppedtimes: Int) {
        MainLooper.get()?.post(Runnable {
            // CashExchangeDialog.showCashExchage(this, this)
            MainDialog.showDialogCloud(this, speedtime, sppedtimes, View.OnClickListener {
                AdUtils.playRewardAd(
                    this@GameActivity,
                    "cloud_acceleration_click",
                    object : IAdVideoListener {
                        override fun onAdClose() {

                            GameApiClient.gameApi.getCloudSpeed()
                                .compose(RxSchedulers.observableIO2Main())
                                .subscribe(object : BaseObserver<StatusEntity>() {
                                    override fun onSuccess(result: StatusEntity?) {
                                        Log.d("wxw", "云朵加速" + Utils.obj2Str(result))
                                        // callback?.onCloudSpeedSuccess(true, Utils.obj2Str(result))
                                        callUnity("Form_land", "showCloudSpeedAnim", "")
                                        getListLandNew(2)
                                    }

                                    override fun onFailure(
                                        e: Throwable?,
                                        code: String?,
                                        errorMsg: String?
                                    ) {
                                        Log.d("wxw", "云朵加速 error")
                                        //callback?.onCloudSpeedSuccess(false, errorMsg + "")
                                    }
                                })
                        }

                        override fun onError(errorMsg: String?) {
                            cloudIsClick = true
                        }
                    })

            })
        })
    }

    fun showWareHouseDialog() {
        MainLooper.get()?.post(Runnable {
            if (Utils.isFastClick2()) {
                WareHouseDialog.showWareHouse(this)
            }
        })
    }

}