package com.duben.microtribe.video.tx

import android.app.Dialog
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.View
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.draw.DrawExpressManager
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.adapter.TxVideoAdapter
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.*
import kotlinx.android.synthetic.main.activity_tx_video.*

class TxVideoActivity : BaseActivity(), View.OnClickListener, VideoView,
    VideoEpisodeAdapter.OnEpisodeClickListener, TxVideoAdapter.OnCustomChildClickListener {

    private var mVipFlag = UserManager.getInstance().vipFlag

    var videos = ArrayList<VedioEpisodeBean>()

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

    private val videoPresenter by lazy { VideoPresenter() }

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

    private var isPlayNext = false
    private var playIndex = 1

    override fun getContentViewLayoutID() = R.layout.activity_tx_video

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

        videoPresenter.getVipProducts()

    }

    override fun getBundleExtras(extras: Bundle?) {
        val json = extras?.getString(Constant.VEDIO_BEAN)
        isPlayNext = extras?.getBoolean(Constant.VEDIO_NEXT, false) == true
        mVedioBean = Gson().fromJson(json, VedioBean::class.java)
        orderTagsList = mVedioBean?.orderTags
        if (isPlayNext) {
            mVedioBean?.let {
                it.recommendIndex = it.recommendIndex + 1
            }
        }
        super.getBundleExtras(extras)
    }

    override fun isApplyKitKatTranslucency() = false

    override fun onResume() {
        super.onResume()
        super_short_video_view.resume()
//        videoPresenter.showTurn()

        if (mVipFlag != UserManager.getInstance().vipFlag && UserManager.getInstance().vipFlag) {
            // 重置状态
            isPlayNext = false
            playIndex = 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()
        super_short_video_view.pause()
    }

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

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

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

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

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

            fm_bottom.visibility = View.VISIBLE

            val readIndex = getRealIndex(it)
//            showVipCountDialog(readIndex)
            localShowLucky(readIndex)

            // videoIndex -> seeIndex
            val data = super_short_video_view.data
            if (data.size > it && data[it].itemType == MULTI_ITEM_1) {
                mVedioBean!!.seeIndex = data[it].video!!.vedioIndex
                mVedioBean!!.orderTags = orderTagsList
                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

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

    override fun getIndexListSuc(indexList: IndexList) {
        // 处理推荐页跳转自动播放下一集逻辑
        if (isPlayNext) {
            playIndex = mVedioBean!!.recommendIndex - 1
            if (playIndex >= mVedioBean!!.unlockIndex - 1) {
                playIndex = mVedioBean!!.unlockIndex - 1
            }
        } else {
            playIndex = mVedioBean!!.seeIndex - 1
        }
        if (playIndex > mVedioBean!!.vedioTotal || playIndex <= 0) playIndex = 0

        tipList = indexList.tip
        mVedioBean = indexList.vedioMsg
        indexBean = indexList
        videos.clear()
        videos.addAll(indexList.list)

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

    override fun getIndexListFail() {

    }

    override fun collectSuc() {
        mVedioBean!!.collect = 1
    }

    override fun collectFail() {

    }

    override fun cancelCollectSuc() {
        mVedioBean!!.collect = 0
    }

    override fun cancelCollectFail() {
    }

    override fun unlockSuc(indexList: IndexList) {
        videos.addAll(indexList.list)
        mVedioBean!!.unlockIndex = videos.size
        super_short_video_view.loadMoreData(getAdapterData())
    }

    override fun unlockFail() {
    }

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

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

            // 匹配
//            ll_lucky.visibility = View.VISIBLE
        } else {
            // 未匹配
//            ll_lucky.visibility = View.GONE
        }
    }

    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 = super_short_video_view.data
        if (position >= mVedioBean!!.unlockIndex) {
            super_short_video_view.onItemClick(data.size - 1)
//            super_short_video_view.onItemClick(mVedioBean!!.unlockIndex)
            return
        }

        val readPosition = getRealPosition(position + 1)

        super_short_video_view.onItemClick(readPosition)
//        Handler(Looper.getMainLooper()).postDelayed({
//            showVipCountDialog(position + 1)
//            localShowLucky(position + 1)
//        }, 300)
    }

    private fun getAdapterData(): MutableList<VideoMultiItemEntity> {
        val data = mutableListOf<VideoMultiItemEntity>()
        if (videos.size > 0) {
            for (video in videos) {
                val item = VideoMultiItemEntity(MULTI_ITEM_1, video, VideoModel(video.vedioUrl))
                data.add(item)
            }
            if (mVedioBean!!.unlockIndex < mVedioBean!!.vedioTotal) {
                val item =
                    VideoMultiItemEntity(MULTI_ITEM_2, videos[0], VideoModel(videos[0].vedioUrl))
                data.add(item)
            }
        }
        return data
    }

    override fun onCustomChildClick(view: View, position: Int) {
        when (view.id) {
            R.id.ll_collect -> {
                // 收藏
                mVedioBean?.let {
                    if (it.collect == 0) {
                        videoPresenter.collect("" + it.vedioId)
                    } else {
                        videoPresenter.cancelCollect("" + it.vedioId)
                    }
                }
            }
            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_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@TxVideoActivity,
                        carrierType, object : AdStatusListener {
                            override fun adFail() {
                                showToast("广告太火爆了，请稍候再试")
                            }

                            override fun adSuccess() {
                            }

                            override fun adClose(vo: HashMap<String, Any>?) {
                                vo?.let {
                                    vo["vedioId"] = mVedioBean!!.vedioId
                                    videoPresenter.unlock(vo)
                                }
                            }
                        })
                }

                override fun adClose(vo: HashMap<String, Any>?) {
                    vo?.let {
                        vo["vedioId"] = mVedioBean!!.vedioId
                        videoPresenter.unlock(vo)
                    }
                }

            })
    }

    /**
     * @param index 当前下标的集数
     */
    private fun showVipCountDialog(index: Int) {
        if (isFinishing) return

        if (mVedioBean!!.tipMaxIndex == 0 ||
            index == 1 ||
            mVedioBean!!.tipMaxIndex < index ||
            index > mVedioBean!!.unlockIndex
        ) {
            return
        }

        VipCountDialog(this, mVedioBean!!, tipList)
            .setOnDialogDismiss(object : VipCountDialog.OnDialogDismiss {
                override fun onDialogDismiss() {}
            })
            .show()

    }

    /**
     * @param index 当前下标的集数
     */
    private fun localShowLucky(index: Int) {
        val localLucky = AppPreferencesManager.get()
            .getBoolean(Constant.LUCKY_FLAG, false)

        if (isLuckyShow || localLucky) {
            ll_lucky.visibility = View.VISIBLE
            context?.let { GlideUtils.loadRoundImageViewGif(it, R.drawable.ic_nine, iv_lucky_gif) }

        } else {
            ll_lucky.visibility = View.GONE
        }

//        if (mVedioBean != null && (isLuckyShow || localLucky)) {
//            if (index > mVedioBean!!.unlockIndex) {
//                // 解锁界面
//                ll_lucky.visibility = View.GONE
//            } else {
//                // 超过免费剧
//                if (index > mVedioBean!!.freeIndex) {
//                    ll_lucky.visibility = View.VISIBLE
//                } else {
//                    ll_lucky.visibility = View.GONE
//                }
//            }
//        }
    }

    // 获取当前下标真正代表的集数
    private fun getRealIndex(position: Int): Int {
        var readIndex = position
        val data = super_short_video_view.data
        if (data != null && data.size > 0) {
            if (data[position].itemType == MULTI_ITEM_1) {
                readIndex = data[position].video!!.vedioIndex
            }
        }
        return readIndex
    }

    // 用于点击匹配当前剧集对应的具体下标
    private fun getRealPosition(position: Int): Int {
        var readPosition = position
        val data = 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()
    }
}