package com.ym.game

import android.annotation.SuppressLint
import android.app.Dialog
import android.content.*
import android.os.Bundle
import android.os.Handler
import android.os.IBinder
import android.text.TextUtils
import android.util.Log
import android.view.View
import com.umeng.analytics.MobclickAgent
import com.ym.xynt.UserInfoEntity
import com.ym.game.activity.WxLoginActivity
import com.ym.game.contract.GameContract
import com.ym.game.listener.IDialogViewCloseCallback
import com.ym.game.notif.NotificationService
import com.ym.game.presenter.GamePresenter
import com.ym.game.presenter.WareHousePresenter
import com.ym.game.view.*
import com.ym.library.MyConstant
import com.ym.library.down.UpdateVersionManager
import com.ym.library.listener.IAdVideoListener
import com.ym.library.module.*
import com.ym.library.net.*
import com.ym.library.utils.*
import com.ym.modulecommon.AppliContext
import com.ym.modulecommon.utils.AdPreference
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, GameContract.View {
    private var mOrderString = "";
    private val mContext = AppliContext.get()
    private var mRefreshLoginObservable: Observable<String>? = null
    private var mPresenter: GamePresenter? = null

    @SuppressLint("CheckResult")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        EventUtils.onEvent("tab_imp", "幸运农田")
        if (SettingPreference.getIsShowGuide()) {
            SettingPreference.setIsShowGuide(false)
        }
        mPresenter = GamePresenter(this,this);
        mPresenter?.getUserInfo()
        mRefreshLoginObservable = RxBus.get().register("refresh_login", String::class.java)
        TurntableDialog.initTurntableAnim()
        mRefreshLoginObservable?.observeOn(AndroidSchedulers.mainThread())?.subscribe({
            when (it) {
                "not_login" -> {
                    AdPreference.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)
                    }
                }
            }
        }, {

        })
        openNotif()
    }

    override fun onDestroy() {
        if (scc != null) {
            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)
        EventUtils.onEvent(
            "page_status",
            Utils.obj2Str(ReportEntity(MyConstant.ReportSessionId, "GameActivity", "onResume"))
        )
    }

    override fun onPause() {
        super.onPause()
        MobclickAgent.onPause(this)
        EventUtils.onEvent(
            "page_status",
            Utils.obj2Str(ReportEntity(MyConstant.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() {
//        EventUtils.onEvent("setting_click")
        JumpUtils.jumpSettingActivity()
//        JumpUtils.jumpUserInfoActivity()
    }

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

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

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

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

        if (!isWelfareclick) {
            isWelfareclick = true
            MainLooper.get()?.post(Runnable {
                WelfarePopupwindow().init(this@GameActivity, this@GameActivity)
            })
            MainLooper.get()?.postDelayed(Runnable {
                isWelfareclick = false
            }, 2000)
        }

    }

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

    /**
     * 大富翁
     */
    fun onMonopolyClick() {
        MainLooper.get()?.post(Runnable {

            JumpUtils.h5NormalJump(
                "免费领奖",
                NetConfig.H5.CONFIRMURL,
                false,
                act
            )
            //CashExchangeDialog.showCashExchage(this, this)
//                PuzzleDialog.showPuzzleDialog(this, this)

        })
    }

    //幸运刮卡
    fun onClickLuckyCard() {
        JumpUtils.h5Jump(
            "幸运刮卡",
            NetConfig.H5.guaguakaurl,
            false,
            act
        )
    }

    //邀请有奖
    fun onClickInvite() {
        JumpUtils.h5NormalJump(
            "邀请赚钱",
            NetConfig.H5.InviteFriendsurl,
            false,
            act
        )
    }

    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)
                }
            }
        })

    }

    /**
     * 领金币
     */
    var isCoinclick = false
    fun getCoin() {
        if (!isCoinclick) {
            isCoinclick = true
            MainLooper.get()?.post(Runnable {
                SiginDropsPopupwindow().init(this@GameActivity, this@GameActivity)
            })
            MainLooper.get()?.postDelayed(Runnable {
                isCoinclick = false
            }, 2000)
        }
    }

    var isDailyclick = false

    //天天提现
    fun onClickDailyCash() {
        if (!isDailyclick) {
            isDailyclick = true
            MainLooper.get()?.post(Runnable {
                DailyCashWithdrawPopupWindow().init(this@GameActivity, this@GameActivity)
            })
            MainLooper.get()?.postDelayed(Runnable {
                isDailyclick = false
            }, 2000)
        }
    }


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




    /**
     * 点击底部拆红包看视频
     */
    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 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", "")
    }

    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 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,
                        false,
                        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?) {
                        }
                    })

            })
        })
    }

    //展示仓库弹窗
    fun showWareHouseDialog() {
        MainLooper.get()?.post(Runnable {
            if (Utils.isFastClick2()) {
                WareHouseDialog.showWareHouse(this)
            }
        })
    }

    //获得加速剂弹窗
    fun showjiasu(getnum: Int, num: Int) {
        MainLooper.get()?.post(Runnable {
            MainDialog.showAccelerator(this, getnum, num, View.OnClickListener {

                callUnity("Form_land", "onVideoAcceleratorReceive", "")
            })
        })
    }

    //======================================Unity调用Android=======================

    /**
     * 点击飞行宝箱看视频 1 花仙 2 宝箱
     */
    fun clickOpenBox(type:Int) {
        mPresenter?.getFlyBox(type)
    }

    //看视频解锁地块
    fun lookAdVideoUnLockLand(landId: Int) {
        AdUtils.playRewardAd(
            this@GameActivity,
            "UNLOCK_LAND",
            object : IAdVideoListener {
                override fun onAdClose() {
                    getUnLockFruit(landId)
                }

                override fun onError(errorMsg: String?) {

                }
            })
    }
    fun getGameConfig() {
        mPresenter?.getGameConfig()
    }

    fun getHomeInfo() {
        mPresenter?.getHomeInfo()
    }

    //施肥
    fun allUseFood(){
        mPresenter?.getCanUseFood(config?.gameValue?.fertilizeReduceMinute!!)
//        callUnity("LandList", "OnUseFoodSuccess","")
    }

    /**
     * 获取地块列表
     * */
    fun getListLandNew(from: Int) {
        Log.d("wxw", "from${from}")
        mPresenter?.getLandList(from)
    }

    fun getOrderList() {
        mPresenter?.getCurrentOrder()
    }

    fun getCleanBug(landId: Int) {
        mPresenter?.getCleanBug(landId)
    }

    fun getRewardFruit(landId: Int) {
        mPresenter?.getRewardLand(landId)
    }

    fun getPlantFruit(landId: Int, plantId: Int) {
        Log.d("wxw", "landId${landId}plantId${plantId}")
        mPresenter?.getPlantLand(landId, plantId)
    }

    fun getUnLockFruit(landId: Int) {
        mPresenter?.getLockLand(landId)
    }

    fun getUseAccelera(landId: Int) {
        mPresenter?.getUseAccelerators(landId)
    }

    //=========================================Unity调用Android=====================
    private var config: GameConfigValueEntity? = null;

    //游戏配置
    override fun gameConfigResult(result: GameConfigValueEntity) {
        config = result
        callUnity("Canvas", "loadGameConfigSuccess", Utils.obj2Str(result))
    }

    override fun gameDuihuanShopResult(result: List<GameDuiHuanShopEntity>) {

    }

    //地块列表
    override fun gameLandListResult(result: String, from: Int) {
        Log.d("wxw", "gameLandListResult" + result)
        if (from == 1) {
            callUnity("Canvas", "loadLandListSuccess", result)
        } else {
            callUnity("LandList", "ResetGameData", result)
        }
    }

    override fun gameHomeInfoResult(result: String) {
        Log.d("wxw", "gameHomeInfoResult" + result)
        callUnity("TitleView", "OnHomeInfoData", result)
    }

    override fun gameCleanBugResult(result: String) {
        Log.d("wxw", "gameCleanBugResult" + result)
        callUnity("LandList", "OnCleanBugSuccess", result)
    }

    override fun gameRewardLandResult(result: String) {
        Log.d("wxw", "gameRewardLandResult" + result)
        callUnity("LandList", "OnRewardSuccess", result)
        getOrderList()
    }

    override fun gamePlantLandResult(result: String) {
        Log.d("wxw", "gamePlantLandResult" + result)
        callUnity("LandList", "OnPlantSuccess", result)
    }

    override fun gameLockLandResult(result: String) {
        Log.d("wxw", "gameLockLandResult" + result)
//        callUnity("LandList", "OnLockLandSuccess", result)
        getListLandNew(2);
    }

    override fun gameUseAcceleratorsResult(result: String) {
        Log.d("wxw", "gameUseAcceleratorsResult" + result)
        callUnity("LandList", "OnUseWaterSuccess", result)
        getHomeInfo()
    }

    override fun gameUseFertilizeResult(result: String) {
        Log.d("wxw", "gameUseFertilizeResult" + result)
        callUnity("LandList", "OnUseFoodSuccess","")
        callUnity("LandList", "ResetGameData", result)
        getHomeInfo()
    }

    override fun gameWaterNotEnough(playNum: Int, landId: Int) {
        MainDialog.showAccelerator(
            this,
            config?.gameValue?.rewardAcceleratorsByVideo!!,
            playNum,
            View.OnClickListener {
//                callUnity("Form_land", "onVideoAcceleratorReceive", "")
                AdUtils.playRewardAd(act,"ACCELERATORS_REWARD",object :IAdVideoListener{
                    override fun onAdClose() {
                        mPresenter?.videoByAccelerator(landId)
                    }

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

    override fun gameCleanBugNotEnough(playNum: Int, landId: Int) {
        MainDialog.showCleanBug(
            this,
            config?.gameValue?.rewardClearBugByVideo!!,
            playNum,
            View.OnClickListener {
//                callUnity("Form_land", "onVideoAcceleratorReceive", "")
                AdUtils.playRewardAd(act,"CLEAR_BUG_REWARD",object :IAdVideoListener{
                    override fun onAdClose() {
//                        callUnity("Form_land", "onVideoAcceleratorReceive", "")
                        mPresenter?.videoByCleanBug(landId)
                    }

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

    override fun gameCurrentOrderResult(result: String) {
        Log.d("wxw", "gameCurrentOrderResult" + result)
        callUnity("Order", "SetOrderListData", result)
    }

    override fun gameFlyBoxResult(result: FlyBoxEntity) {
        MainLooper.get()?.post(Runnable {
            MainDialog.showGetBox(this, 1, View.OnClickListener {
//                if (flyBoxIsClick) {
//                    flyBoxIsClick = false
//                    AdUtils.playRewardAd(this, "box_click", object : IAdVideoListener {
//                        override fun onAdClose() {
//                            flyBoxIsClick = true
//                            getFlyBoxReceive()
//                        }
//
//                        override fun onError(errorMsg: String?) {
//                            flyBoxIsClick = true
//                        }
//                    })
//                }
//                    Utils.showToast(AppliContext.get(), "今日次数已用完，明天再来吧～")
            })
        })
    }
}