package com.duben.microtribe.ui.activitys

import android.app.Dialog
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import android.view.View
import com.daimajia.androidanimations.library.Techniques
import com.daimajia.androidanimations.library.YoYo
import com.duben.microtribe.R
import com.duben.microtribe.ad.AdManager
import com.duben.microtribe.ad.AdStatusListener
import com.duben.microtribe.ad.NoPreAdManager
import com.duben.microtribe.common.Constant
import com.duben.microtribe.mvp.model.NineListBean
import com.duben.microtribe.mvp.model.NineShowBean
import com.duben.microtribe.mvp.presenters.NinePresenter
import com.duben.microtribe.mvp.views.NineView
import com.duben.microtribe.ui.activitys.base.BaseActivity
import com.duben.microtribe.ui.widgets.DialogListener
import com.duben.microtribe.ui.widgets.NineContinueDialog
import com.duben.microtribe.utils.AppPreferencesManager
import com.duben.microtribe.utils.SplitArrayUtils
import com.duben.microtribe.utils.rxutil.CommonRxTask
import com.duben.microtribe.utils.rxutil.RxjavaUtil
import com.duben.library.utils.nodoubleclick.AntiShake
import kotlinx.android.synthetic.main.activity_nine.*

/**
 * 描述：9宫格手机
 * 作者：孟崔广
 */
class NineActivity : BaseActivity(), View.OnClickListener, NineView {

    companion object {
        val IS_AD_SHOW = "IS_AD_SHOW"
    }

    private val ninePresenter by lazy { NinePresenter() }
    private var yoyo: YoYo.YoYoString? = null
    val luckyIndexMap: MutableMap<Int, String> = HashMap()
    private var nineShowBean: NineShowBean? = null
    var carrierType = Constant.CARRIERTYPE_NINE
    var isAdShow = false

    override fun getContentViewLayoutID() = R.layout.activity_nine

    override fun isApplyKitKatTranslucency() = false

    override fun toggleOverridePendingTransition() = true

    override fun getOverridePendingTransitionMode() = TransitionMode.SCALE

    override fun getBundleExtras(extras: Bundle?) {
        super.getBundleExtras(extras)
        extras?.let {
            isAdShow = it.getBoolean(IS_AD_SHOW, false)
        }
    }

    override fun initViewsAndEvents() {
        ninePresenter.attachView(this)
        ninePresenter.getTurnIphoneMsg()

        initData()
        initListener()

        btn_action?.postDelayed({
            yoyo = YoYo.with(Techniques.Pulse).duration(1000).repeat(-1).playOn(btn_action)
        }, 200)
    }

    override fun onResume() {
        super.onResume()
//        ninePresenter.showTurn()
    }

    override fun onDestroy() {
        super.onDestroy()
        marqueeView?.startFlipping()
        ninePresenter.detachView()
        yoyo?.stop()
        yoyo = null
    }

    private fun initListener() {
        btn_action.setOnClickListener(this)
        rl_lucky.setOnClickListener(this)
        iv_nine_back.setOnClickListener(this)
    }

    override fun finish() {
        super.finish()
        overridePendingTransition(0, R.anim.scale_out)
    }

    override fun onClick(v: View) {
        if (AntiShake.check(v.id)) return

        when (v.id) {
            R.id.iv_nine_back -> {
                finish()
            }
            R.id.btn_action, R.id.rl_lucky -> {
                if (luckyIndexMap.size == 0) {
                    showToast("界面初始异常，请重新进入")
                    return
                }

                if (isAdShow) {
                    luckyAward()
                } else {
                    if (nineShowBean != null) {
                        if (nineShowBean!!.complete >= nineShowBean!!.need) {
                            luckyAward()
                        } else {
                            val bundle = Bundle()
                            bundle.putInt(NineKnowActivity.COMPLETE, nineShowBean!!.complete)
                            bundle.putInt(NineKnowActivity.NEED, nineShowBean!!.need)
                            readyGoThenKill(NineKnowActivity::class.java, bundle)
                        }
                    }
                }
            }
        }
    }

    override fun unlockSuc() {
//        ninePresenter.showTurn()

        if (isAdShow) {
            if (nineShowBean != null) {
                if (nineShowBean!!.need - nineShowBean!!.complete-1>0) {
                    showContinueDialog()
                }
            }
        }
    }

    override fun getTurnIphoneMsgSuc(data: NineListBean) {
        lucky_panel2.setImgArray(data.list)
        initLuckyIndexForPid(data.list)

        if (TextUtils.isEmpty(data.rule)) {
            ll_nine_rule.visibility = View.GONE
        } else {
            ll_nine_rule.visibility = View.VISIBLE
            tv_nine_rule.text = data.rule
        }
    }

    private fun initLuckyIndexForPid(list: List<NineListBean.NineBean>) {
        if (list != null && list.size > 0) {
            for (i in 0 until list.size) {

                luckyIndexMap.put(i, list.get(i).pid ?: i.toString())
            }
        }
    }

    override fun toTurnSuc(data: NineListBean.NineBean) {
        Handler(Looper.getMainLooper()).postDelayed({
            startNine(data)
        }, 500)
    }

    override fun showTurnSuc(data: NineShowBean) {
        nineShowBean = data
        if (TextUtils.equals(
                carrierType,
                Constant.CARRIERTYPE_NINE3
            ) && data.complete >= data.need
        ) {
            carrierType = Constant.CARRIERTYPE_NINE
            ninePresenter.toTurn()
        }
        // 展示 5/20
        if (isAdShow) {
            tv_nine_count.visibility = View.VISIBLE
            tv_nine_count.text = "${data.complete}/${data.need}次"
            btn_action.setBackgroundResource(R.mipmap.ic_luckly_btn)
        } else {
            btn_action.setBackgroundResource(R.mipmap.ic_lucky_vedio)
            tv_nine_count.visibility = View.GONE
        }
    }

    private fun luckyAward() {
        if (nineShowBean != null) {
            if (nineShowBean!!.complete >= nineShowBean!!.need) {
                carrierType = Constant.CARRIERTYPE_NINE3
            }
        }
        AdManager.instance.showAd(this, carrierType,
            object : AdStatusListener {
                var canFail = false
                override fun adSuccess() {
                    canFail = true
                }

                override fun adFail() {
                    if (canFail) return

                    NoPreAdManager.loadVideoAd(
                        this@NineActivity,
                        carrierType, object : AdStatusListener {
                            override fun adFail() {
                                carrierType = Constant.CARRIERTYPE_NINE
                                showToast("广告太火爆了，请稍候再试")
                            }

                            override fun adSuccess() {
                            }

                            override fun adClose(vo: HashMap<String, Any>?) {
                                vo?.let {
                                    ninePresenter.unlock(vo)
                                }
                            }
                        })
                }

                override fun adClose(vo: HashMap<String, Any>?) {
                    vo?.let {
                        ninePresenter.unlock(vo)
                    }
                }

            })

    }

    fun startNine(data: NineListBean.NineBean) {
        if (data.pid == null) {
            showToast("产品未配置")
            return
        }

        if (!lucky_panel2.isGameRunning) {
            lucky_panel2.startGame()

            RxjavaUtil.executeRxTask(object : CommonRxTask<String>("") {
                override fun doInIOThread() {
                    Thread.sleep(3000)
                }

                override fun doInUIThread() {
                    if (this@NineActivity.isFinishing) {
                        return
                    }

                    val index = getLuckyIndex(data.pid)
                    lucky_panel2.tryToStop(index)

                    Handler(Looper.getMainLooper()).postDelayed({
                        val bundle = Bundle()
                        bundle.putString(NinePayActivity.PID, data.pid)
                        bundle.putString(NinePayActivity.TITLE, data.title)
                        bundle.putString(NinePayActivity.TYPE, data.type)
                        readyGoThenKill(NinePayActivity::class.java, bundle)
                    }, 1500)
                }
            })
        }
    }

    private fun getLuckyIndex(pid: String): Int {
        if (luckyIndexMap.size > 0) {
            for ((key, value) in luckyIndexMap) {
                if (TextUtils.equals(pid, value)) {
                    return key
                }
            }
        }

        return 0
    }

    private fun initData() {
        val messages = ArrayList<String>()
        messages.add("恭喜用户183******66抽中 终身会员")
        messages.add("恭喜用户177******34抽中 +1年会员")
        messages.add("恭喜用户134******49抽中 +14天会员")
        messages.add("恭喜用户159******51抽中 +3天会员")
        messages.add("恭喜用户150******87抽中 +7天会员")
        messages.add("恭喜用户134******65抽中 +5天会员")
        messages.add("恭喜用户183******40抽中 +30天会员")
        messages.add("恭喜用户131******08抽中 +7天会员")
        messages.add("恭喜用户177******65抽中 +1年会员")
        messages.add("恭喜用户180******39抽中 +3天会员")
        messages.add("恭喜用户150******43抽中 +14天会员")
        messages.add("恭喜用户152******05抽中 终身会员")
        messages.add("恭喜用户133******87抽中 +7天会员")
        messages.add("恭喜用户151******64抽中 +14天会员")
        marqueeView.startWithList(SplitArrayUtils.getRandomList(messages) as List<Nothing>?)
    }

    // 继续观看逻辑
    private fun showContinueDialog() {
        nineShowBean?.let {
            NineContinueDialog(
                this@NineActivity,
                it.need - it.complete - 1,
                object : DialogListener() {
                    override fun onClick(dialog: Dialog?, v: View?) {
                        super.onClick(dialog, v)
                        dialog?.dismiss()
                        luckyAward()
                    }
                }).show()
        }
    }
}