package com.ym.game.view

import android.annotation.SuppressLint
import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.os.CountDownTimer
import android.util.Log
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import com.ym.admodule.config.AdManager
import com.ym.admodule.listener.ZXADVideoListener
import com.ym.game.listener.IDialogViewCloseCallback
import com.ym.game.contract.TurntableContract
import com.ym.game.presenter.TurntablePresenter
import com.ym.library.net.BaseObserver
import com.ym.library.net.RxSchedulers
import com.ym.library.rxbus.RxBusConstant
import com.ym.library.rxbus.RxBusUtil
import com.ym.library.rxbus.Subscribe
import com.ym.library.rxbus.ThreadMode
import com.ym.ddhy.R
import com.ym.library.listener.IAdVideoListener
import com.ym.library.module.StatusEntity
import com.ym.library.module.TurntableEntity
import com.ym.library.net.GameApiClient
import com.ym.library.utils.*


/**
 *Craeted by ${junqi.li}
 *Craeted by 2020/9/10
 */
object TurntableDialog : TurntableUtils(), TurntableContract.View {
    private var TAG = "Turntable"
    private var mListener: IDialogViewCloseCallback? = null
    private var isStartAnim = true
    private var isUpdate = false

    private var context: Activity? = null
    private var mDialog: Dialog? = null

    private var mLotteryResult: TurntableEntity.Turntable? = null
    private var turntables: TurntableEntity? = null
    private var tvTurntableCount: TextView? = null
    private var tvTime: TextView? = null
    private var btnTurntableLottery: ImageView? = null
    private var ivTurntableBg: ImageView? = null
    private var btnCountdown: ImageView? = null
    private var mPresenter: TurntablePresenter? = null
    private var timeTask: CountDownTimer? = null

    //初始化转盘动画 需要提现初始化 避免问题
    fun initTurntableAnim() {
        initAnim()
    }

    /**
     *幸运转盘
     */
    fun showTurntable(context: Activity?, mListener: IDialogViewCloseCallback) {
        if (context == null) {
            return
        }
        this.context = context
        EventUtils.onEvent("show_lucky_turntable", "幸运转盘")
//        ToponManager.initNativeAd((context as Activity), AdID.AD_LUCKY_TURNTABLE_BIGIMAGE)
//        ToponManager.initRewardAd((context as Activity), AdID.AD_LUCKY_TURNTABLE_VIDEO)
        mPresenter = TurntablePresenter(this)
        mPresenter?.getTurntableList()
        RxBusUtil.getDefault().register(this)
        mDialog = Dialog(context, R.style.UpdateVersionCompatDialogTheme75)
        val mDialogView =
            MainDialog.showBottomDialog(
                R.layout.dialog_turntable,
                context,
                mDialog!!,
                0,
                Gravity.CENTER
            )

        ivTurntableBg = mDialogView?.findViewById<ImageView>(R.id.iv_turntable_bg)
        tvTurntableCount = mDialogView?.findViewById<TextView>(R.id.tv_main_turntable_count)
        btnTurntableLottery = mDialogView?.findViewById<ImageView>(R.id.btn_turntable_lottery)
        btnCountdown = mDialogView?.findViewById<ImageView>(R.id.btn_turntable_lottery_countdown)
        tvTime = mDialogView?.findViewById<TextView>(R.id.tv_main_turntable_time)
        btnTurntableLottery?.addClickScale()
        btnTurntableLottery?.setOnClickListener {
            if (Utils.isFastClick2()) {
                if (turntables?.showVideo == 0 && turntables?.countDownSecond!! <=0) {
                    //开启转盘
                    EventUtils.onEvent("click_lucky_turntable_lottery", "幸运转盘抽奖")
                    btnTurntableLottery?.isEnabled = false
                    isStartAnim = true
                    mPresenter?.getTurntableLotteryResult()
                } else if (turntables?.showVideo == 1) {
                    //看广告 结束调用转盘结果接口 刷新列表 并开启转盘动画
                    EventUtils.onEvent("click_lucky_turntable_lottery_look_video", "幸运转盘抽奖视频")
                    showAd()
                }
            }
        }

        btnCountdown?.setOnClickListener {
            //倒计时
            Utils.showToast(context, "抽奖次数已用完，倒计时结束后再来吧~")
        }
        mDialogView?.findViewById<ImageView>(R.id.iv_turntable_close).setOnClickListener {
            //            RxBusUtil.getDefault().send(RxBusConstant.RX_MAIN_UPDATE_HOME_INFO)
            mDialog?.dismiss()
            timeTask?.cancel()
            mListener.onCloseViewSuccess(true);
            RxBusUtil.getDefault().unregister(this)
        }

        mDialog?.setOnCancelListener {
            timeTask?.cancel()
            RxBusUtil.getDefault().unregister(this)
        }


        mDialog?.setCanceledOnTouchOutside(false)
        mDialog?.setCancelable(false)
        if (context.isFinishing){
            return
        }
        mDialog?.show()
    }

    private fun showAd() {
        AdManager.playRewardAd(
            ADConfig.AD_REWARD_VIDIO,
            "turntable_lottery",
            (context as Activity),
            object : ZXADVideoListener {
                override fun onAdClose() {
                    getVideoAcceleratorsReceive3();
                    reset()
                    btnTurntableLottery?.isEnabled = false
                    isStartAnim = true
                    isUpdate = true
                }

                override fun onAdShow() {
                    Utils.showToast(context, "看完视频可获得奖励")
                }

                override fun onAdVideoBarClick() {

                }

                override fun onError(errorMsg: String?) {
//                    getVideoAcceleratorsReceive3();
                    reset()
                    btnTurntableLottery?.isEnabled = false
                    isStartAnim = true
                    isUpdate = true
                }

                override fun onSuccess() {
                }
            })
    }

    /**
     * 获取转盘数据
     */
    @SuppressLint()
    @Subscribe(code = RxBusConstant.RX_MAIN_TURNTABLE_LOTTERYED, threadMode = ThreadMode.MAIN)
    fun updateTurntableLotteryed() {
        LogUtils.i(TAG, "获取转盘数据")
        mPresenter?.getTurntableList()
    }

    //转盘结果
    override fun turntableLotteryResult(data: TurntableEntity.Turntable) {
        mLotteryResult = data
        if (isStartAnim) {
            if (ivTurntableBg != null) {
                startAnim(data.id, ivTurntableBg!!)
            }
        }
//        if (isUpdate) {
//            //看视频后刷新状态
//            mPresenter?.getTurntableList()
//            isUpdate = false
//        }
    }

    //转盘列表
    override fun turntableListResult(data: TurntableEntity) {
        turntables = data
        initView(data)
    }

    fun initView(data: TurntableEntity) {
        tvTurntableCount?.text = "剩余次数: ${data.lotteryNum}"
        //免费抽奖
        if (data.showVideo == 0 && data.countDownSecond != null && data.countDownSecond!! <=0) {
            tvTime?.visibility = View.GONE
            btnCountdown?.visibility = View.GONE
            btnTurntableLottery?.visibility = View.VISIBLE
            btnTurntableLottery?.setBackgroundResource(R.mipmap.icon_free)
        } else {
            //看视频抽奖
            if (data.showVideo == 1) {
                tvTime?.visibility = View.GONE
                btnCountdown?.visibility = View.GONE
                btnTurntableLottery?.visibility = View.VISIBLE
                btnTurntableLottery?.setBackgroundResource(R.mipmap.icon_look_ad)
            } else if (data.countDownSecond != null && data.countDownSecond!! > 0) {
                //倒计时
                tvTime?.visibility = View.VISIBLE
                btnCountdown?.visibility = View.VISIBLE
                btnTurntableLottery?.visibility = View.GONE
                timeTask = startTimeTask(data.countDownSecond!!)

            }
        }
    }


    //开启计时器
    fun startTimeTask(time: Int): CountDownTimer? {
        LogUtils.i(TAG, "${time}")
        return object : CountDownTimer(time.toLong() * 1000 + 1000, 1000) {
            override fun onTick(millisUntilFinished: Long) {
                tvTime?.text = formatTime((millisUntilFinished / 1000).toInt())
            }

            override fun onFinish() {
                mPresenter?.getTurntableList()
            }
        }.start()
    }

    //动画结束
    override fun animEnd() {
        LogUtils.i(TAG, "转盘结束" + "剩余次数: ${mLotteryResult?.lotteryNum}")
        reset()
        mPresenter?.getTurntableList()
        isStartAnim = false
        btnTurntableLottery?.isEnabled = true
        tvTurntableCount?.text = "剩余次数: ${mLotteryResult?.lotteryNum}"

        RxBusUtil.getDefault().send(RxBusConstant.RX_MAIN_UPDATE_HOME_INFO)
        var type = mLotteryResult?.awardType
        if (type != null) {
            if (type != 6) {
                MainDialog.showgetWaterDrop(
                    context, type,
                    "lottery",
                    mLotteryResult?.awardNum ?: 0,
                    mLotteryResult?.extJson
                )
            }
        }

//        if (mLotteryResult?.awardType == 1) {

//        } else {
//            MainDialog.receiveBox(
//                (context as Activity),
//                2,
//                mLotteryResult?.awardNum!!,
//                View.OnClickListener {
//                    mDialog?.dismiss()
//                    RxBusUtil.getDefault().send(RxBusConstant.RX_MAIN_ACTIVITY_TAB, 1)//跳转兑换商店
//                })
//        }
    }

    fun formatTime(time: Int): String? {
        val hh = time / 3600
        val mm = (time - 3600 * hh) / 60
        val ss = time - 3600 * hh - 60 * mm
        val sb = StringBuilder()
        sb.append(hh.toString() + "时")
        if (mm < 10) {
            sb.append("0" + mm + "分")
        } else {
            sb.append(mm.toString() + "分")
        }
        if (ss < 10) {
            sb.append("0" + ss + "秒")
        } else {
            sb.append(ss.toString() + "秒")
        }
        return sb.toString()
    }


    //恢复开始的状态
    private fun reset() {
        ivTurntableBg?.setImageResource(R.mipmap.icon_zhuanpan_bg)
    }

    /**
     * 添加点击缩放效果
     */
    fun View.addClickScale(scale: Float = 0.9f, duration: Long = 150) {
        this.setOnTouchListener { _, event ->
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    this.animate().scaleX(scale).scaleY(scale).setDuration(duration).start()
                }
                MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                    this.animate().scaleX(1f).scaleY(1f).setDuration(duration).start()
                }
            }
            // 点击事件处理，交给View自身
            this.onTouchEvent(event)
        }
    }
    //看视频领上报
    fun getVideoAcceleratorsReceive3() {
        GameApiClient.gameApi.adVideoReport()
            .compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<StatusEntity>() {
                override fun onSuccess(result: StatusEntity?) {
                    Log.d("wxw", "看视频上报 Success")
                    mPresenter?.getTurntableLotteryResult()
                }

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