package com.duben.microtribe.video.tx.newrecommend

import android.app.Dialog
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.View
import androidx.core.content.ContextCompat
import com.google.gson.Gson
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.ad.express.ExpressManager
import com.duben.microtribe.common.Constant
import com.duben.microtribe.manager.LocalVedioManager
import com.duben.microtribe.manager.UserManager
import com.duben.microtribe.mvp.model.*
import com.duben.microtribe.mvp.model.IndexList.VedioEpisodeBean
import com.duben.microtribe.mvp.presenters.VideoPresenter
import com.duben.microtribe.mvp.views.VideoView
import com.duben.microtribe.ui.activitys.NineActivity
import com.duben.microtribe.ui.activitys.VipActivity
import com.duben.microtribe.ui.activitys.base.BaseActivity
import com.duben.microtribe.ui.adapter.VideoEpisodeAdapter
import com.duben.microtribe.utils.AppPreferencesManager
import com.duben.microtribe.utils.SpanUtils
import com.duben.microtribe.video.tx.VideoModel
import com.duben.library.utils.GlideUtils
import com.duben.library.utils.nodoubleclick.AntiShake
import com.duben.microtribe.common.AppConfig
import com.duben.microtribe.ui.widgets.DetailAdDialog
import com.duben.microtribe.ui.widgets.DialogListener
import com.duben.microtribe.ui.widgets.VideoEpisodeDialog
import kotlinx.android.synthetic.main.activity_new_tx_video.*

/**
 * 推荐剧集二级页
 */
class NewTxVideoActivity : BaseActivity(), View.OnClickListener, VideoView,
    VideoEpisodeAdapter.OnEpisodeClickListener, NewTxVideoAdapter.OnCustomChildClickListener {

    private var mVipFlag = UserManager.getInstance().vipFlag

    private var mAllData = arrayListOf<VedioEpisodeBean>()

    private var dialog: VideoEpisodeDialog? = null
    private var detailAdDialog: DetailAdDialog? = null

    private val videoPresenter by lazy { VideoPresenter() }

    private var mVedioBean: VedioBean? = null
    private var indexBean: IndexList? = null
    private var orderTagsList: ArrayList<String>? = null

    private var playIndex = 1
    private var vedioAdPosition=0

    override fun getContentViewLayoutID() = R.layout.activity_new_tx_video

    override fun initViewsAndEvents() {
        videoPresenter.attachView(this)
        videoPresenter.getVipProducts()
        mVedioBean?.let { videoPresenter.getIndexList("" + it.vedioId) }
        initView()
    }

    override fun getBundleExtras(extras: Bundle?) {
        val json = extras?.getString(Constant.VEDIO_BEAN)
        mVedioBean = Gson().fromJson(json, VedioBean::class.java)
        mVedioBean?.isRecommendVedio = true
        orderTagsList = mVedioBean?.orderTags
        super.getBundleExtras(extras)
    }

    override fun isApplyKitKatTranslucency() = false

    override fun onResume() {
        super.onResume()
        new_super_short_video_view.resume()

//        videoPresenter.showTurn()

        if (mVipFlag != UserManager.getInstance().vipFlag && UserManager.getInstance().vipFlag) {
            // 重置状态
            playIndex = new_super_short_video_view.currentPosition
            mVedioBean?.let { videoPresenter.getIndexList("" + it.vedioId) }
        }

        // vip界面返回弹出广告弹窗
        if (AppConfig.showVipAdDialog && !UserManager.getInstance().vipFlag) {
            Handler(Looper.getMainLooper()).postDelayed({
                adDialog()
                AppConfig.showVipAdDialog = false
            }, 300)
        }
    }

    override fun onPause() {
        super.onPause()
        new_super_short_video_view.pause()
    }

    override fun onDestroy() {
        new_super_short_video_view.onDestroy()
        super.onDestroy()
        new_super_short_video_view.releasePlayer()

        ExpressManager.instance.destroy()
        videoPresenter.detachView()
    }

    private fun initView() {
        if (!UserManager.getInstance().vipFlag) {
            ExpressManager.instance.preLoadAd()
        }

        episode_tv.text = String.format(
            "共%d集  %s",
            mVedioBean?.vedioTotal,
            if (mVedioBean?.completeStatus == 0) "已完结" else "更新中"
        )

        new_super_short_video_view.setOnCustomChildClickListener(this)
        new_super_short_video_view.setOnPageChangeListener {
            if (new_super_short_video_view.isAdPosition(it) || new_super_short_video_view.isLuckPosition(
                    it
                )
            ) {
//                fm_bottom.visibility = View.GONE
                new_super_short_video_view.pause()
                return@setOnPageChangeListener
            }

//            fm_bottom.visibility = View.VISIBLE

            // videoIndex -> seeIndex
            val data = new_super_short_video_view.data
            if (data.size > it && data[it].itemType == MULTI_ITEM_1) {
                mVedioBean!!.seeIndex = data[it].video!!.vedioIndex
                mVedioBean!!.orderTags = orderTagsList
                mVedioBean!!.isRecommendVedio = true
                LocalVedioManager.commitVedio(mVedioBean!!)
            }
        }

        fm_bottom.setOnClickListener(this)
        close_iv.setOnClickListener(this)
        ll_lucky.setOnClickListener(this)
    }

    override fun onClick(v: View?) {
        if (AntiShake.check(v?.id)) return
        when (v?.id) {
            R.id.close_iv -> finish()
            R.id.fm_bottom -> showEpisodeDialog()
            R.id.ll_lucky -> readyGo(NineActivity::class.java)
            else -> {}
        }
    }

    private fun showEpisodeDialog() {
        if (dialog != null && dialog!!.isShowing) return

        val vedioBean = VedioBean()
        mVedioBean?.let {
            vedioBean.title = it.title
            vedioBean.vedioTotal = it.vedioTotal
            vedioBean.unlockIndex = it.unlockIndex
            vedioBean.seeIndex = it.seeIndex
        }

        dialog = VideoEpisodeDialog(this, vedioBean, object : DialogListener() {
            override fun onClick(dialog: Dialog?, v: View?) {
                super.onClick(dialog, v)
                dialog?.dismiss()
            }
        })
        dialog?.setCurrentIndex(new_super_short_video_view.realSeeIndex)
        dialog?.setOnEpisodeClickListener(this)
        dialog?.show()
    }

    override fun getIndexListSuc(indexList: IndexList) {
        // 处理推荐页跳转自动播放下一集逻辑
        mVedioBean = indexList.vedioMsg
        playIndex = mVedioBean!!.seeIndex - 1
        mVedioBean?.isRecommendVedio = true
        indexBean = indexList
        mAllData.clear()
        mAllData.addAll(indexList.list)

        new_super_short_video_view.loadData(mVedioBean, getAdapterData(), playIndex)
    }

    override fun getIndexListFail() {

    }

    override fun collectSuc() {
    }

    override fun collectFail() {

    }

    override fun cancelCollectSuc() {
    }

    override fun cancelCollectFail() {
    }

    override fun unlockSuc(indexList: IndexList) {
    }

    override fun unlockFail() {
    }

    override fun showTurnSuc(data: NineShowBean) {
        AppPreferencesManager.get()
            .put(Constant.LUCKY_FLAG, data.isShow)

        if (!data.isShow || UserManager.getInstance().vipFlag) {
            ll_lucky.visibility = View.GONE
            return
        } else {
            ll_lucky.visibility = View.VISIBLE
            context?.let { GlideUtils.loadRoundImageViewGif(it, R.drawable.ic_nine, iv_lucky_gif) }
        }

        val complete = data.complete
        val need = data.need
        if (complete >= need) {
            tv_lucky_status.text = SpanUtils()
                .append("可领取")
                .setForegroundColor(ContextCompat.getColor(this, R.color.apk_uninstalled))
                .create()
        } else {
            tv_lucky_status.text = SpanUtils()
                .append(complete.toString())
                .setForegroundColor(ContextCompat.getColor(this, R.color.red))
                .append("/")
                .append(need.toString())
                .create()
        }
    }

    override fun getVipProductSuc(data: VipBean) {
        if (data.list != null && data.list.size > 0) {
            AppConfig.firstVipPrice = data.list.get(0).price
        }
    }

    override fun onEpisodeClick(position: Int) {
        dialog?.dismiss()
        val data = new_super_short_video_view.data
        if (position >= mVedioBean!!.unlockIndex) {
            new_super_short_video_view.onItemClick(data.size - 1)
            return
        }

        val readPosition = getRealPosition(position + 1)
//        val readPosition = position

        new_super_short_video_view.onItemClick(readPosition)
    }

    private fun getAdapterData(): MutableList<VideoMultiItemEntity4> {
        val data = mutableListOf<VideoMultiItemEntity4>()
        for (i in 0 until mAllData.size) {
            val item = mAllData[i]
            data.add(
                i,
                VideoMultiItemEntity4(MULTI_ITEM_1, item, VideoModel(item.vedioUrl), VEDIO3DOS_FREE)
            )
        }
        if (mVedioBean!!.unlockIndex < mVedioBean!!.vedioTotal) {
            val item =
                VideoMultiItemEntity4(
                    MULTI_ITEM_2,
                    mAllData[0],
                    VideoModel(mAllData[0].vedioUrl),
                    VEDIO3DOS_PAY
                )
            data.add(item)
        }
        return data
    }

    override fun onCustomChildClick(view: View, position: Int) {
        vedioAdPosition=position
        when (view.id) {
            R.id.ll_collect -> {
                // 无收藏
            }
            R.id.leave -> {
                // 返回
                finish()
            }
            R.id.unlock -> {
                // 看广告解锁
                showAd()
            }
            R.id.vip -> {
                // 开通VIP
                val bundle = Bundle()
                bundle.putString(VipActivity.VEDIO_ID, mVedioBean!!.vedioId.toString())
                bundle.putString(VipActivity.THIRD_ID, mVedioBean!!.thirdId)
                bundle.putBoolean(VipActivity.IS_RECOMMEND, true)
                bundle.putBoolean(VipActivity.IS_DETAIL, true)
                readyGo(VipActivity::class.java, bundle)
            }

            else -> {}
        }
    }

    private fun showAd() {
        val carrierType = Constant.CARRIERTYPE_TX_VEDIO
        AdManager.instance.showAd(this, carrierType,
            object : AdStatusListener {
                var canFail = false
                override fun adSuccess() {
                    canFail = true
                }

                override fun adFail() {
                    if (canFail) return

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

                            override fun adSuccess() {
                            }

                            override fun adClose(vo: HashMap<String, Any>?) {
                                updateEpisodeData(vedioAdPosition, vo)
                            }
                        })
                }

                override fun adClose(vo: HashMap<String, Any>?) {
                    updateEpisodeData(vedioAdPosition, vo)
                }
            })
    }

    private fun updateEpisodeData(position: Int, vo: HashMap<String, Any>?) {
        vo?.let {
            // 解锁剧集
            vo["vedioId"] = mVedioBean!!.vedioId
            vo["num"] = (position + 1)
            videoPresenter.unlock(vo)
        }

        if (position >= mAllData.size) return
        new_super_short_video_view.updateData(position)
    }

    // 用于点击匹配当前剧集对应的具体下标
    private fun getRealPosition(position: Int): Int {
        var readPosition = position
        val data = new_super_short_video_view.data
        if (data != null && data.size > 0) {
            for (i in 0 until data.size) {
                if (data[i].itemType == MULTI_ITEM_1) {
                    if (data[i].video!!.vedioIndex == position) {
                        readPosition = i
                        break
                    }
                }
            }
        }
        return readPosition
    }

    private fun adDialog() {
        detailAdDialog = DetailAdDialog(context, object : DialogListener() {
            override fun onClick(v: View) {
                if (AntiShake.check(v.id)) return

                when (v.id) {
                    R.id.iv_detail_ad_next -> {
                        showAd()
                        detailAdDialog?.dismiss()
                    }
                }
            }
        })
        detailAdDialog!!.show()
    }
}