package com.mints.goodmoney.ui.activitys

import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import com.mints.goodmoney.R
import com.mints.goodmoney.ad.video.VedioAdingManager
import com.mints.goodmoney.common.Constant
import com.mints.goodmoney.manager.TTPreLoadExpressManager
import com.mints.goodmoney.mvp.model.VedioAdingBean
import com.mints.goodmoney.mvp.presenters.AwardPresenter
import com.mints.goodmoney.mvp.views.AwardView
import com.mints.goodmoney.ui.activitys.base.BaseActivity
import com.mints.goodmoney.ui.widgets.countdowntimer.CountDownTimerSupport
import com.mints.goodmoney.ui.widgets.countdowntimer.OnCountDownTimerListener
import com.mints.goodmoney.utils.SoundPoolUtil
import com.mints.goodmoney.utils.SpanUtils
import com.mints.goodmoney.utils.Utils
import kotlinx.android.synthetic.main.activity_award.*
import java.math.BigDecimal
import java.util.*

/**
 * 描述：奖励界面
 * 作者：孟崔广
 * 时间：2020/10/09 15:47
 */
class AwardActivity : BaseActivity(), AwardView, View.OnClickListener {

    private lateinit var vedioAdingManager: VedioAdingManager
    private val awardPresenter by lazy { AwardPresenter() }
    private var mTimer: CountDownTimerSupport? = null
    private var curCoin = 0 //传入金币
    private var extraId = ""//传入key
    private var carrierType = ""//传入载体
    private var loadVedioFailCount = 0 // 视频失败次数

    override fun getContentViewLayoutID() = R.layout.activity_award

    override fun isApplyKitKatTranslucency() = false

    override fun toggleOverridePendingTransition() = true

    override fun getOverridePendingTransitionMode() = TransitionMode.SCALE

    override fun initViewsAndEvents() {
        awardPresenter.attachView(this)

        vedioAdingManager = VedioAdingManager.getInstance(this)

        initExpress()
        initDataView()
        initListener()
    }

    private fun initDataView() {
        // 金币声音
        try {
            SoundPoolUtil.getInstance().getGoldVoice()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        // 获取按键栏
        Utils.hideBottomUIMenu(this)
        // 开启3秒倒计时
        startTime()

        when (carrierType) {
            Constant.SHAREFRIEND_COMPLETE_1, Constant.SHAREFRIEND_COMPLETE_2,
            Constant.SHAREFRIEND_COMPLETE_3, Constant.SHAREFRIEND_COMPLETE_4,
            Constant.SHAREFRIEND_COMPLETE_5, Constant.SHAREFRIEND_COMPLETE_6,
            Constant.CARRIER_GAME_ONLINE -> {
                val vo = HashMap<String, Any>()
                vo["carrierType"] = carrierType
                awardPresenter.reportAddCoinMsg(vo)

                tvAwardContent.setText(curCoin.toString() + "金币已到账")
                tvAwardNext.setText("我知道了")
            }
            Constant.CARRIER_HOMEVEDIO -> {
                val vo = HashMap<String, Any>()
                vo["carrierType"] = carrierType
                awardPresenter.reportAddCoinMsg(vo)

                tvAwardContent.setText(curCoin.toString() + "金币已到账")
                tvAwardNext.setText("看视频赚${extraId}金币")

                carrierType = Constant.CARRIER_HOMEVEDIO_DOUBLE
            }
            Constant.CARRIER_SMALLHOMEVEDIO -> {
                val vo = HashMap<String, Any>()
                vo["carrierType"] = carrierType
                awardPresenter.reportAddCoinMsg(vo)

                tvAwardContent.setText(curCoin.toString() + "金币已到账")
                tvAwardNext.setText("看视频赚${extraId}金币")

                carrierType = Constant.CARRIER_SMALLHOMEVEDIO_DOUBLE
            }
            Constant.CHALLENGE_SHAREFRIEND -> {
                val vo = HashMap<String, Any>()
                vo["carrierType"] = carrierType
                awardPresenter.reportAddCoinMsg(vo)

                tvAwardContent.setText(curCoin.toString() + "金币已到账")
                tvAwardNext.setText("金币翻倍")

                carrierType = Constant.CARRIER_CHALLENGE_SHAREFRIEND_DOUBLE
            }
            Constant.CARRIER_NEW_USER -> {
                tvAwardContent.setText("新人红包")
                tvAwardNext.setText("我知道了")
                tvAwardHint.setVisibility(View.VISIBLE)
                tvAwardHint.setText(curCoin.toString() + "金币已到账")
            }
            Constant.CARRIER_OFFLINE_DOUBLE -> {
                tvAwardContent.setText("离线收益奖励" + curCoin + "金币")
                tvAwardNext.setText("金币翻倍")
            }
            Constant.CARRIER_ZHANGYUE -> {
                tvAwardContent.setText("阅读奖励" + curCoin + "金币")
            }
            Constant.CARRIER_SIGNIN_HOMEPAGE_AWARD -> {
                tvAwardContent.setText("签到奖励" + curCoin + "金币")
            }
            Constant.CARRIER_GAME -> {
                if (curCoin > 0) {
                    tvAwardContent.setText("游戏奖励" + curCoin + "金币")
                } else {
                    tvAwardContent.setText("很遗憾,游戏试玩不足3秒")
                }
                tvAwardNext.setText("我知道了")
            }
            Constant.CARRIER_SIGNIN_HOMEPAGE_CARD,
            Constant.CARRIER_CHALLENGE_TURN, Constant.CARRIER_CHALLENGE_CARD,
            Constant.CARRIER_WALK_BUBBLE,
            Constant.CARRIER_WALK, Constant.CARRIER_HOMEWATER -> {
                tvAwardContent.setText("看视频领取" + curCoin + "金币")
            }
            else -> {
                tvAwardContent.setText(curCoin.toString() + "金币已到账")
            }
        }
    }

    override fun finish() {
        super.finish()
        //关闭窗体动画显示
        overridePendingTransition(0, R.anim.scale_out)
    }

    override fun getBundleExtras(extras: Bundle?) {
        super.getBundleExtras(extras)
        extras?.let {
            curCoin = it.getInt(Constant.MAIN_CUR_COIN, 0)
            extraId = it.getString(Constant.MAIN_EXTRA_ID, "")
            carrierType = it.getString(Constant.MAIN_CARRIER_TYPE, "")
        }
    }

    override fun onResume() {
        super.onResume()

        awardPresenter.getCoinMsg()
    }

    override fun onDestroy() {
        super.onDestroy()

        mTimer?.stop()
        mTimer = null

        try {
            TTPreLoadExpressManager.getInstance().loadTtFrameLayout()
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }

        vedioAdingManager?.setVedioAdingListener(null)
        vedioAdingManager.onDestory()

        awardPresenter.detachView()
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        return if (keyCode == KeyEvent.KEYCODE_BACK) {
            true
        } else super.onKeyDown(keyCode, event)
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.ivAwardBack -> {
                finish()
            }
            R.id.tvAwardNext -> {
                when (carrierType) {
                    // 只有看视频才能领金币
                    Constant.CARRIER_CHALLENGE_SHAREFRIEND_DOUBLE,
                    Constant.CARRIER_OFFLINE_DOUBLE, Constant.CARRIER_SIGNIN_HOMEPAGE_CARD,
                    Constant.CARRIER_CHALLENGE_TURN, Constant.CARRIER_CHALLENGE_CARD,
                    Constant.CARRIER_WALK_BUBBLE, Constant.CARRIER_HOMEVEDIO_DOUBLE,
                    Constant.CARRIER_SMALLHOMEVEDIO_DOUBLE,
                    Constant.CARRIER_WALK, Constant.CARRIER_HOMEWATER -> {
                        awardVedio()
                    }
                    else -> {
                        finish()
                    }
                }
            }
        }
    }

    /**
     * 获取激励视频
     */
    private fun awardVedio() {
        if (vedioAdingManager.getVedioFinishFlag()) {
            showToast("今日视频已看完，请明天再来吧")
            return
        }

        showLoading("加载中...")

        val bean = VedioAdingBean()
        bean.setCarrierType(carrierType)
        bean.setCurCoin(curCoin)
        bean.setExtraId(extraId)

        loadVedio(vedioAdingManager, bean, true)
    }

    /**
     * 加载激励视频
     */
    private fun loadVedio(vedioAdingManager: VedioAdingManager, bean: VedioAdingBean, isFirstLoad: Boolean) {
        vedioAdingManager.setVedioAdingListener(object : VedioAdingManager.VedioAdingListener {
            override fun vedioAdingListenerError(adType: String) {
                showToast("加载超时，请休息一下")
                hideLoading()
            }

            override fun vedioAdingListenerFail(adType: String) {
                loadVedioFailCount++
                if (loadVedioFailCount >= 2) {
                    hideLoading()
                    showToast("加载失败，请稍后重试!")
                } else {
                    loadVedio(vedioAdingManager, bean, false)
                }
            }

            override fun vedioAdingListenerSuccess(adType: String) {
                hideLoading()
                vedioAdingSuccess(adType)
            }
        })
        if (isFirstLoad) {
            // 首页按权重加载
            vedioAdingManager.loadAding(this, bean)
        } else {
            // 失败按优先级加载
            vedioAdingManager.loadFailAding(this, bean)
        }
    }


    private fun initListener() {
        tvAwardNext.setOnClickListener(this)
        ivAwardBack.setOnClickListener(this)
    }

    /**
     * 弹窗倒计时
     */
    private fun startTime() {
        mTimer = CountDownTimerSupport(3000L, 1000L)
        mTimer?.setOnCountDownTimerListener(object : OnCountDownTimerListener {
            override fun onTick(millisUntilFinished: Long) {
                if (!this@AwardActivity.isFinishing) {
                    tvAwardBack?.setText("${millisUntilFinished / 1000}")
                }
            }

            override fun onFinish() {
                if (!this@AwardActivity.isFinishing) {
                    ivAwardBack?.setVisibility(View.VISIBLE)
                    tvAwardBack?.setVisibility(View.GONE)
                }
            }
        })
        mTimer?.start()
    }


    override fun getUserTaskMsgSuc(coin: Int) {
        val sumCoin = coin.toString()
        val allcoinBig = BigDecimal(sumCoin)
        val rateBig = BigDecimal("10000")
        val cashStr = allcoinBig.divide(rateBig).setScale(2, BigDecimal.ROUND_DOWN).toString()

        tvAwardCash.setText(
                SpanUtils()
                        .append("我的金币").setFontSize(40).setForegroundColor(resources.getColor(R.color.black_text))
                        .append(sumCoin).setFontSize(40).setForegroundColor(resources.getColor(R.color.main_mints))
                        .append("≈").setFontSize(40).setForegroundColor(resources.getColor(R.color.black_text))
                        .append("" + cashStr).setFontSize(40).setForegroundColor(resources.getColor(R.color.main_mints))
                        .append("元").setFontSize(40).setForegroundColor(resources.getColor(R.color.black_text))
                        .create()
        )
    }

    /**
     * 随机广告完成回调
     */
    private fun setAdFinshLayout() {
        if (!isFinishing) {
            tvAwardContent.text = "奖励金币已发放"
            tvAwardNext.visibility = View.GONE
            tvAwardHint.visibility = View.GONE
        }
    }

    /**
     * 广告返回结果
     */
    private fun vedioAdingSuccess(adType: String) {
        setAdFinshLayout()
    }

    private fun initExpress() {
        try {
            if (flAwardAd != null) {
                flAwardAd.removeAllViews()
                flAwardAd.addView(TTPreLoadExpressManager.getInstance().ttFrameLayout)
            }
        } catch (e: Exception) {

        }
    }
}