package com.ym.game.presenter

import android.app.Activity
import android.text.TextUtils
import android.util.Log
import android.view.View
import com.ym.game.contract.GameContract
import com.ym.game.contract.PuzzleContract
import com.ym.game.listener.IDialogViewCloseCallback
import com.ym.game.view.MainDialog
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.utils.AdPreference
import com.ym.xynt.UserInfoEntity

/**
 * @author (wangXuewei)
 * @datetime 2021-02-04 14:58 GMT+8
 * @detail :
 */
class GamePresenter : GameContract.Presenter {

    var mView: GameContract.View
    var act: Activity

    constructor(mView: GameContract.View, activity: Activity) {
        this.mView = mView
        this.act = activity
    }

    override 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")
                        SettingPreference.saveUserInfo(result)
                        SettingPreference.setTrackId(result.gaodeTrackId ?: 0L)
                        SettingPreference.setTerminalId(result.gaodeTerminalId ?: 0L)
                        AdPreference.setUid(uid)
                    }
                }

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

    //获取游戏配置
    override fun getGameConfig() {
        GameApiClient.gameApi.getGameConfig().compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<GameConfigValueEntity>() {
                override fun onSuccess(result: GameConfigValueEntity) {
                    mView.gameConfigResult(result)
                }

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

                }
            })
    }

    //兑换商店
    override fun getDuiHuanShop() {
        GameApiClient.gameApi.getDuiHuanShop().compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<List<GameDuiHuanShopEntity>>() {
                override fun onSuccess(result: List<GameDuiHuanShopEntity>) {
                    mView.gameDuihuanShopResult(result)
                }

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

                }
            })
    }

    //地块列表
    override fun getLandList(from: Int) {
        GameApiClient.gameApi.getListLand().compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<List<LandListEntity>>() {
                override fun onSuccess(result: List<LandListEntity>?) {
                    mView.gameLandListResult("{\"landList\":" + Utils.obj2Str(result) + "}", from)
                }

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

                }
            })
    }

    //首页信息
    override fun getHomeInfo() {
        GameApiClient.gameApi.getGameHomeInfo().compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<HomeInfoEntity>() {
                override fun onSuccess(result: HomeInfoEntity?) {
                    mView.gameHomeInfoResult(Utils.obj2Str(result))
                }

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

                }
            })
    }

    override fun getCleanBug(landId: Int) {
        GameApiClient.gameApi.getCleanBug(landId).compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<LandListEntity>() {
                override fun onSuccess(result: LandListEntity?) {
                    mView.gameCleanBugResult(Utils.obj2Str(result))
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                    if (code.equals("600")) {
                        checkVideoStatus(2, "CLEAR_BUG_REWARD", landId, 0)
                    }
                }
            })
    }

    override fun getRewardLand(landId: Int) {
        GameApiClient.gameApi.getRewardLand(landId).compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<LandListEntity>() {
                override fun onSuccess(result: LandListEntity?) {
                    mView.gameRewardLandResult(Utils.obj2Str(result))
                }

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

                }
            })
    }

    override fun getPlantLand(landId: Int, plantId: Int) {
        GameApiClient.gameApi.getPlantLand(landId, plantId)
            .compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<LandListEntity>() {
                override fun onSuccess(result: LandListEntity?) {
                    mView.gamePlantLandResult(Utils.obj2Str(result))
                }

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

                }
            })
    }

    override fun getLockLand(landId: Int) {
        GameApiClient.gameApi.getUnLockLand(landId).compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<LandListEntity>() {
                override fun onSuccess(result: LandListEntity?) {
                    mView.gameLockLandResult(Utils.obj2Str(result))
                }

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

                }
            })
    }

    override fun getUseAccelerators(landId: Int) {
        GameApiClient.gameApi.getUseAccelerators(landId).compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<LandListEntity>() {
                override fun onSuccess(result: LandListEntity?) {
                    mView.gameUseAcceleratorsResult(Utils.obj2Str(result))
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                    if (code.equals("600")) {
                        checkVideoStatus(1, "ACCELERATORS_REWARD", landId, 0)
                    }
                }
            })
    }

    override fun getUseFertilize() {
        GameApiClient.gameApi.getUseFertilize().compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<Any>() {
                override fun onSuccess(result: Any?) {
                    mView.gameUseFertilizeResult(Utils.obj2Str(result))
                }

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

                }
            })
    }

    override fun getCurrentOrder() {
        GameApiClient.gameApi.getCurrentOrder().compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<List<OrderListEntity>>() {
                override fun onSuccess(result: List<OrderListEntity>?) {
                    mView.gameCurrentOrderResult("{\"orderList\":" + Utils.obj2Str(result) + "}")
                }

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

                }
            })
    }

    override fun getFlyBox(type: Int) {
        //1 花仙
        if (type == 1) {
            checkVideoStatus(4, "VIDEO_FAIRY", 0, 0)
        }
        //2 宝箱
        if (type == 2) {
            checkVideoStatus(3, "BOX_REWARD", 0, 0)
        }


    }

    //type 1 加速剂不足 2 杀虫剂不足 3 4开宝箱 5 施肥加速
    fun checkVideoStatus(type: Int, slot: String, landId: Int,time:Int) {
        GameApiClient.gameApi.getVideoStatus(slot).compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<StatusEntity>() {
                override fun onSuccess(result: StatusEntity?) {
                    if (result != null) {
                        if (result.status == 1) {
                            if (type == 1) {
                                mView.gameWaterNotEnough(result?.playNum!!, landId)
                            }
                            if (type == 2) {
                                mView.gameCleanBugNotEnough(result?.playNum!!, landId)
                            }
                            if (type == 3 || type == 4) {
                                AdUtils.playRewardAd(act, slot, object : IAdVideoListener {
                                    override fun onAdClose() {
                                        OpenFlyBox(type)
                                    }

                                    override fun onError(errorMsg: String?) {

                                    }
                                })
                            }
                            if (type == 5) {
                                MainDialog.showDialogCloud(
                                    act,
                                    time,
                                    result.playNum,
                                    View.OnClickListener {
                                        AdUtils.playRewardAd(
                                            act,
                                            "cloud_acceleration_click",
                                            object : IAdVideoListener {
                                                override fun onAdClose() {
                                                    getUseFertilize();
                                                }

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

                        } else {
                            ToastUtils.showTextToast("${result?.msg}");
                        }
                    }
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                    if (code.equals("105")) {
                        ToastUtils.showTextToast("$errorMsg");
                    }
                }
            })
    }

    //看视频领取加速剂
    fun videoByAccelerator(landId: Int) {
        GameApiClient.gameApi.getVideoAcceleratorsReceive()
            .compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<StatusEntity>() {
                override fun onSuccess(result: StatusEntity?) {
                    //使用加速剂
                    getUseAccelerators(landId)
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                    ToastUtils.showTextToast(code + errorMsg);
                }
            })

    }

    //看视频领取杀虫剂
    fun videoByCleanBug(landId: Int) {
        GameApiClient.gameApi.getVideoCleanBugReceive().compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<StatusEntity>() {
                override fun onSuccess(result: StatusEntity?) {
                    //使用杀虫剂
                    getCleanBug(landId)
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                    ToastUtils.showTextToast(code + errorMsg);
                }
            })

    }


    fun OpenFlyBox(type: Int) {
        GameApiClient.gameApi.getopenBox(type - 2)
            .compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<FlyBoxEntity>() {
                override fun onSuccess(result: FlyBoxEntity?) {
                    Log.d("wxw", "看视频领取宝箱" + Utils.obj2Str(result))
                    if (result != null) {
                        var type = result.rewardType
                        if (type != null) {
                            MainDialog.showopenBox(
                                act, type,
                                "宝箱奖励",
                                result.rewardNum ?: 0,
                                result,
                                object : IDialogViewCloseCallback {
                                    override fun onCloseViewSuccess(isSuccess: Boolean) {

                                    }
                                }
                            )
                            getHomeInfo()
                        }
                    }
                }

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

    //是否可以施肥
    fun getCanUseFood(min: Int) {
        GameApiClient.gameApi.getCanUseFer().compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<StatusEntity>() {
                override fun onSuccess(result: StatusEntity?) {
                    //
                    if (result != null) {
                        if (result.status == 1) {
                            checkVideoStatus(5, "FERTILIZE_REWARD", 0, min);

                        } else {
                            ToastUtils.showTextToast(result.msg);
                        }
                    }

                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                    ToastUtils.showTextToast(code + errorMsg);
                }
            })
    }

}