package com.duben.microtribe.video.csj

import android.app.Dialog
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import com.airbnb.lottie.LottieAnimationView
import com.airbnb.lottie.LottieComposition
import com.airbnb.lottie.LottieCompositionFactory
import com.airbnb.lottie.LottieDrawable
import com.bytedance.sdk.dp.*
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.ExpressAdCallback
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.IndexList
import com.duben.microtribe.mvp.model.NineShowBean
import com.duben.microtribe.mvp.model.VedioBean
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.ui.widgets.DialogListener
import com.duben.microtribe.ui.widgets.VideoEpisodeDialog
import com.duben.microtribe.ui.widgets.VipCountDialog
import com.duben.microtribe.utils.AppPreferencesManager
import com.duben.microtribe.utils.SpanUtils
import com.duben.microtribe.utils.UIUtils
import com.duben.library.utils.GlideUtils
import com.duben.library.utils.nodoubleclick.AntiShake
import com.duben.microtribe.common.AppConfig
import com.duben.microtribe.mvp.model.VipBean
import com.duben.microtribe.ui.widgets.DetailAdDialog
import kotlinx.android.synthetic.main.drama_activity_api_detail.*
import kotlinx.android.synthetic.main.drama_activity_api_detail.iv_lucky_gif
import kotlinx.android.synthetic.main.drama_activity_api_detail.ll_lucky
import kotlinx.android.synthetic.main.drama_activity_api_detail.tv_lucky_status

/**
 *  @author Assen
 *  @date 2023/7/6
 *  @desc
 */
class DramaApiDetailActivity : BaseActivity(), VideoEpisodeAdapter.OnEpisodeClickListener,
    VideoView, View.OnClickListener {

    companion object {
        private const val TAG = "DramaApiDetailActivity"

        var outerDrama: DPDrama? = null
    }

    private val videoPresenter by lazy { VideoPresenter() }

    private var mVipFlag = UserManager.getInstance().vipFlag

    private var dpWidget: IDPWidget? = null
    private var isInited = false
    private var drama: DPDrama? = null
    private var tipList: ArrayList<String>? = null
    private var orderTagsList: ArrayList<String>? = null
    private var isLuckyShow = false

    private var unlockCallback: IDPDramaListener.Callback? = null

    private var mInitUnlockIndex = 0

    //可免费观看的最大集数
    private var mUnlockIndexMap = mutableMapOf<Long, Int>()

    // 已经解锁的集数
    private var mHasUnlockIndexMap = mutableMapOf<Long, MutableList<Int>>()

    private var blockView: View? = null
    private var unlockBtn: Button? = null
    private var leaveBtn: ImageView? = null
    private var vipBtn: Button? = null

    private var lastIndex = 1

    private var enableInfiniteScroll = true
    private var enableCustomReport = false

    private var hideLeftTopTips = false

    private var hideMore = true

    private var freeSet = 5
    private var lockSet = 2

    private var isThirdId = false
    private var isPlayNext = false


    private var mode = DPDramaDetailConfig.SPECIFIC_DETAIL

    private var mVedioBean: VedioBean? = null

    private var mCurrentIndex = 0
    private var currentDramaIndex = 0

    private var detailAdDialog: DetailAdDialog? = null


    override fun getBundleExtras(extras: Bundle?) {
        val json = extras?.getString(Constant.VEDIO_BEAN)
        isThirdId = extras?.getBoolean(Constant.VEDIO_THIRD, false) == true
        isPlayNext = extras?.getBoolean(Constant.VEDIO_NEXT, false) == true

        mVedioBean = Gson().fromJson(json, VedioBean::class.java)
        orderTagsList = mVedioBean?.orderTags

        freeSet = mVedioBean!!.unlockIndex
        lockSet = if (mVedioBean!!.adGiveVedioNum == 0) 1 else mVedioBean!!.adGiveVedioNum
        hideLeftTopTips = true
        mode = DPDramaDetailConfig.SPECIFIC_DETAIL
        enableInfiniteScroll = false
        enableCustomReport = false

        super.getBundleExtras(extras)
    }

    override fun getContentViewLayoutID() = R.layout.drama_activity_api_detail

    override fun initViewsAndEvents() {
        videoPresenter.attachView(this)
        mVedioBean?.let { videoPresenter.getIndexList(it.thirdId, true) }
        videoPresenter.getVipProducts()
        if (!UserManager.getInstance().vipFlag) {
            ExpressManager.instance.preLoadAd()
        }

        fm_bottom.setOnClickListener {
            if (AntiShake.check(it.id)) return@setOnClickListener
            showEpisodeDialog()
        }

        blockView = findViewById<LinearLayout>(R.id.block_view)
        blockView?.isClickable = true
        unlockBtn = findViewById(R.id.unlock)
        leaveBtn = findViewById(R.id.leave)
        vipBtn = findViewById(R.id.vip)

        if (UserManager.getInstance().newFlag) {
            // 匹配
            vipBtn!!.visibility = View.VISIBLE
        } else {
            // 未匹配
            vipBtn!!.visibility = View.GONE
        }

        blockView?.visibility = View.GONE

        drama = outerDrama
        drama?.let {
            if (isPlayNext) mVedioBean!!.seeIndex + 1
            it.index = mVedioBean!!.seeIndex
            mCurrentIndex = mVedioBean!!.seeIndex
            mInitUnlockIndex = mVedioBean!!.unlockIndex
            mUnlockIndexMap[it.id] = mInitUnlockIndex
            mHasUnlockIndexMap[it.id] = arrayListOf(mInitUnlockIndex)
            title_tv.text = it.title
            if (mVedioBean!!.completeStatus == 0) {
                episode_tv.text = String.format("共%d集 已完结", it.total)
            } else {
                episode_tv.text = String.format("共%d集 更新中", it.total)
            }
            info_tv.text = String.format("第%d集", mVedioBean!!.seeIndex)
            if (!UserManager.getInstance().newFlag) {

                unlock.text = String.format("观看激励视频")
                unlock.visibility = View.VISIBLE

            } else {
                unlock.visibility = View.GONE
            }

            tv_title.text =
                if (AppConfig.firstVipPrice == 0.0) "解锁后续剧集" else "${AppConfig.firstVipPrice}元解锁后续剧集"


            if (mVedioBean!!.collect == 0) {
                setCollectImage(zan_iv)
            } else {
                setCancelCollectImage(zan_iv)
            }
            zan_num_tv.text = mVedioBean!!.hot
        }
        ll_collect.setOnClickListener(this)
        ll_lucky.setOnClickListener(this)

        if (DPSdk.isStartSuccess()) {
            init()
        }
    }

    override fun isApplyKitKatTranslucency() = true

    private fun init() {
        if (isInited) {
            return
        }
        initWidget()

        dpWidget?.let { widget ->
            supportFragmentManager.beginTransaction().replace(R.id.fl_container, widget.fragment)
                .commit()

            leaveBtn?.setOnClickListener {
                finish()
            }
            vipBtn?.setOnClickListener {
                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)
            }
        }

        isInited = true
    }

    private fun initWidget() {
        drama?.let { drama ->
            dpWidget = DPSdk.factory().createDramaDetail(
                DPWidgetDramaDetailParams.obtain()
                    .detailConfig(
                        DPDramaDetailConfig.obtain(mode)
                            .bottomOffset(20)
                            .infiniteScrollEnabled(enableInfiniteScroll)
                            .hideLeftTopTips(hideLeftTopTips, null)
                            .showCellularToast(true)
                            .hideMore(hideMore)
                            .listener(dramaListener)
                            .adListener(dramaAdListener)
                            .setCustomReport(enableCustomReport) { context, id ->
                                // 举报
                            }
                    )
                    .id(drama.id)
                    .index(drama.index)
//                    .currentDuration(currentDuration)
            )
        }
    }

    override fun onDestroy() {
        dpWidget?.destroy()
        ExpressManager.instance.destroy()
        super.onDestroy()
    }

    override fun onResume() {
        super.onResume()

//        videoPresenter.showTurn()

        if (mVipFlag != UserManager.getInstance().vipFlag && UserManager.getInstance().vipFlag) {
            // 重置状态
            resetData()
        }

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

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

    private val dramaAdListener: IDPAdListener = object : IDPAdListener() {
        override fun onDPAdRequest(map: Map<String?, Any?>) {
            Log.d(TAG, "onDPAdRequest map =  $map")
        }

        override fun onDPAdRequestSuccess(map: Map<String?, Any?>) {
            Log.d(TAG, "onDPAdRequestSuccess map = $map")
        }

        override fun onDPAdRequestFail(code: Int, msg: String?, map: Map<String?, Any?>) {
            Log.d(TAG, "onDPAdRequestFail map = $map")
        }

        override fun onDPAdFillFail(map: Map<String?, Any?>) {
            Log.d(TAG, "onDPAdFillFail map = $map")
        }

        override fun onDPAdShow(map: Map<String?, Any?>) {
            Log.d(TAG, "onDPAdShow map = $map")
        }

        override fun onDPAdPlayStart(map: Map<String?, Any?>) {
            Log.d(TAG, "onDPAdPlayStart: map = $map")
        }

        override fun onDPAdPlayPause(map: Map<String?, Any?>) {
            Log.d(TAG, "onDPAdPlayPause map = $map")
        }

        override fun onDPAdPlayContinue(map: Map<String?, Any?>) {
            Log.d(TAG, "onDPAdPlayContinue map = $map")
        }

        override fun onDPAdPlayComplete(map: Map<String?, Any?>) {
            Log.d(TAG, "onDPAdPlayComplete map = $map")
        }

        override fun onDPAdClicked(map: Map<String?, Any?>) {
            Log.d(TAG, "onDPAdClicked map = $map")
        }
    }

    private var dramaListener: IDPDramaListener = object : IDPDramaListener() {

        override fun onDPSeekTo(position: Int, time: Long) {
            super.onDPSeekTo(position, time)
            Log.d(TAG, "onDPSeekTo:")
        }

        override fun onDPPageChange(position: Int, map: MutableMap<String, Any>?) {
            super.onDPPageChange(position, map)
            Log.d(TAG, "onDPPageChange:" + map?.toString())
        }

        override fun onDPVideoPlay(map: MutableMap<String, Any>?) {
            super.onDPVideoPlay(map)
            Log.d(TAG, "onDPVideoPlay:" + map?.toString())
            (map?.get("index") as? Int?)?.let {
                lastIndex = it
            }
        }

        override fun onDPVideoPause(map: MutableMap<String, Any>?) {
            super.onDPVideoPause(map)
            Log.d(TAG, "onDPVideoPause:" + map?.toString())
        }

        override fun onDPVideoContinue(map: MutableMap<String, Any>?) {
            super.onDPVideoContinue(map)
            Log.d(TAG, "onDPVideoContinue:" + map?.toString())
        }

        override fun onDPVideoCompletion(map: MutableMap<String, Any>?) {
            super.onDPVideoCompletion(map)
            Log.d(TAG, "onDPVideoCompletion:" + map?.toString())
        }

        override fun onDPVideoOver(map: MutableMap<String, Any>?) {
            super.onDPVideoOver(map)
            Log.d(TAG, "onDPVideoOver:" + map?.toString())
        }

        override fun onDPClose() {
            super.onDPClose()
            Log.d(TAG, "onDPClose")
        }

        override fun onDPRequestStart(map: MutableMap<String, Any>?) {
            super.onDPRequestStart(map)
            Log.d(TAG, "onDPRequestStart:" + map?.toString())
        }

        override fun onDPRequestFail(code: Int, msg: String?, map: MutableMap<String, Any>?) {
            super.onDPRequestFail(code, msg, map)
            Log.d(TAG, "onDPRequestFail:" + map?.toString())
        }

        override fun onDPRequestSuccess(list: MutableList<MutableMap<String, Any>>?) {
            super.onDPRequestSuccess(list)
            list?.forEach {
                Log.d(TAG, "onDPRequestSuccess:$it")
            }
        }

        override fun isNeedBlock(
            drama: DPDrama?,
            index: Int,
            map: MutableMap<String, Any>?
        ): Boolean {
            drama ?: return false
            Log.d(TAG, "isNeedBlock: index = $index")
            val unlockIndex = mUnlockIndexMap[drama.id] ?: mInitUnlockIndex
            val hasUnlockList = mHasUnlockIndexMap[drama.id] ?: mutableListOf()
            Log.d(
                TAG,
                "isNeedBlock: index = $index" + " " + unlockIndex + "s" + drama.id + mHasUnlockIndexMap +
                        " --- " + (index > unlockIndex && hasUnlockList.contains(index).not())
            )

            info_tv.text = String.format("第%d集", index)
            mCurrentIndex = index
            showVipCountDialog(index - 1)
            localShowLucky(index - 1)

            val needBlock = index > unlockIndex && hasUnlockList.contains(index).not()
            if (!needBlock) {
                blockView?.visibility = View.GONE
                // 上送视频信息，若未解锁不上送
                if (mCurrentIndex <= mVedioBean!!.unlockIndex) {
                    mVedioBean!!.seeIndex = index
                    mVedioBean!!.orderTags = orderTagsList
                    LocalVedioManager.commitVedio(mVedioBean!!)
                }
            }

            return needBlock
        }

        override fun showAdIfNeeded(
            drama: DPDrama?,
            callback: Callback?,
            map: MutableMap<String, Any>?
        ) {
            super.showAdIfNeeded(drama, callback, map)
            drama ?: return
            Log.d(TAG, "showAdIfNeeded:" + map?.toString())
            blockView?.visibility = View.VISIBLE
            unlockCallback = callback
            currentDramaIndex = dpWidget?.currentDramaIndex!!
            // 展示广告
            val unlockText = String.format(
                    "解锁%s·第%d-%d集",
                    drama.title,
                    mInitUnlockIndex + 1,
                    mInitUnlockIndex + lockSet
            )
            AppConfig.detailDialogUnlockText = unlockText

            if (!UserManager.getInstance().newFlag) {

                tv_title.text = unlockText

            } else {
                tv_title.text =
                    if (AppConfig.firstVipPrice == 0.0) "解锁后续剧集" else "${AppConfig.firstVipPrice}元解锁后续剧集"

            }

            showAdView()

            dpWidget?.let { widget ->
                unlockBtn?.setOnClickListener {
                    val carrierType = Constant.CARRIERTYPE_CSJ_VEDIO
                    AdManager.instance.showAd(this@DramaApiDetailActivity, carrierType,
                        object : AdStatusListener {
                            var canFail = false
                            override fun adSuccess() {
                                canFail = true
                            }

                            override fun adFail() {
                                if (canFail) return

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

                                        override fun adSuccess() {
                                        }

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

                                            // 更新解锁集数
                                            for (i in 1 until lockSet) {
                                                val hasUnlockList: MutableList<Int> =
                                                    mHasUnlockIndexMap[drama.id]
                                                        ?: mutableListOf()
                                                hasUnlockList.add(widget.currentDramaIndex + i)
                                                mHasUnlockIndexMap[drama.id] = hasUnlockList
                                            }
                                            mInitUnlockIndex = mUnlockIndexMap[drama.id]!! + lockSet
                                            mUnlockIndexMap[drama.id] =
                                                mUnlockIndexMap[drama.id]!! + lockSet
                                            mVedioBean!!.unlockIndex = mInitUnlockIndex

                                            // 播放当前集
                                            mVedioBean!!.seeIndex = mCurrentIndex
                                            mVedioBean!!.orderTags = orderTagsList
                                            LocalVedioManager.commitVedio(mVedioBean!!)

                                            blockView?.visibility = View.GONE
                                            callback?.onDramaRewardArrived() // 解锁当前集
                                        }
                                    })
                            }

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

                                // 更新解锁集数
                                for (i in 1 until lockSet) {
                                    val hasUnlockList: MutableList<Int> =
                                        mHasUnlockIndexMap[drama.id] ?: mutableListOf()
                                    hasUnlockList.add(widget.currentDramaIndex + i)
                                    mHasUnlockIndexMap[drama.id] = hasUnlockList
                                }
                                mInitUnlockIndex = mUnlockIndexMap[drama.id]!! + lockSet
                                mUnlockIndexMap[drama.id] = mUnlockIndexMap[drama.id]!! + lockSet
                                mVedioBean!!.unlockIndex = mInitUnlockIndex
                                blockView?.visibility = View.GONE

                                // 播放当前集
                                mVedioBean!!.seeIndex = mCurrentIndex
                                mVedioBean!!.orderTags = orderTagsList
                                LocalVedioManager.commitVedio(mVedioBean!!)
                                callback?.onDramaRewardArrived() // 解锁当前集
                            }
                        })
                }
            }
        }

        override fun onDramaSwitch(map: MutableMap<String, Any>?) {
            super.onDramaSwitch(map)
            Log.d(TAG, "onDramaSwitch:" + map?.toString())
            val title = map?.get("title") as? String?
            val total = map?.get("total") as? Int?
            episode_tv.text = String.format("共%d集 已完结", total)
        }

        override fun onDramaGalleryClick(map: MutableMap<String, Any>?) {
            super.onDramaGalleryClick(map)
            map?.let {
                Log.d(TAG, "onDramaGalleryClick: $it")
            }
        }

        override fun onDramaGalleryShow(map: MutableMap<String, Any>?) {
            super.onDramaGalleryShow(map)
            map?.let {
                Log.d(TAG, "onDramaGalleryShow: $it")
            }
        }

        override fun onRewardDialogShow(map: MutableMap<String, Any>?) {
            super.onRewardDialogShow(map)
            map?.let {
                Log.d(TAG, "onRewardDialogShow: $it")
            }
        }

        override fun onUnlockDialogAction(action: String?, map: MutableMap<String, Any>?) {
            super.onUnlockDialogAction(action, map)
            map?.let {
                Log.d(TAG, "onUnlockDialogAction: action=$action map=$it")
            }
        }
    }

    private var dialog: VideoEpisodeDialog? = null

    private fun showEpisodeDialog() {
        if (mVedioBean == null && 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?.setOnEpisodeClickListener(this)
        val index = if (mCurrentIndex == 0) 0 else mCurrentIndex - 1
        dialog?.setCurrentIndex(index)
        dialog?.show()
    }

    override fun onEpisodeClick(position: Int) {
        dialog?.dismiss()
        if (position + 1 > mInitUnlockIndex) {
            dpWidget?.let { widget ->
                widget.currentDramaIndex = mInitUnlockIndex + 1
            }
            return
        }
        dpWidget?.let { widget ->
            widget.currentDramaIndex = position + 1
        }
    }

    override fun getIndexListSuc(indexList: IndexList) {
        tipList = indexList.tip
    }

    override fun getIndexListFail() {

    }

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

    override fun collectFail() {

    }

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

    override fun cancelCollectFail() {

    }

    override fun unlockSuc(indexList: IndexList) {

    }

    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
        }

        localShowLucky(mCurrentIndex - 1)
    }

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

    private fun playCollectAnim(view: LottieAnimationView) {
        val lottieDrawable = LottieDrawable()
        LottieCompositionFactory.fromAsset(context, "home_collect.json")
            .addListener { result: LottieComposition? ->
                lottieDrawable.setImagesAssetsFolder("images/")
                lottieDrawable.composition = result
                lottieDrawable.loop(false)
                lottieDrawable.playAnimation()
            }
        view.setImageDrawable(lottieDrawable)
    }

    private fun playCancelCollectAnim(view: LottieAnimationView) {
        val lottieDrawable = LottieDrawable()
        LottieCompositionFactory.fromAsset(context, "home_cancel_collect.json")
            .addListener { result: LottieComposition? ->
                lottieDrawable.setImagesAssetsFolder("images/")
                lottieDrawable.composition = result
                lottieDrawable.loop(false)
                lottieDrawable.playAnimation()
            }
        view.setImageDrawable(lottieDrawable)
    }

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

        when (v?.id) {
            R.id.ll_collect -> {
                if (mVedioBean!!.collect == 0) {
                    if (isThirdId) {
                        videoPresenter.collect("" + mVedioBean!!.thirdId)
                    } else {
                        videoPresenter.collect("" + mVedioBean!!.vedioId)
                    }
                } else {
                    if (isThirdId) {
                        videoPresenter.cancelCollect("" + mVedioBean!!.thirdId)
                    } else {
                        videoPresenter.cancelCollect("" + mVedioBean!!.vedioId)
                    }
                }
            }
            R.id.ll_lucky -> {
                readyGo(NineActivity::class.java)
            }
            else -> {}
        }
    }

    private fun showVipCountDialog(position: Int) {
        if (position == 0 || mVedioBean!!.tipMaxIndex == 0 || mVedioBean!!.tipMaxIndex - 1 < position) return
        VipCountDialog(this, mVedioBean!!, tipList)
            .setOnDialogDismiss(object : VipCountDialog.OnDialogDismiss {
                override fun onDialogDismiss() {}
            })
            .show()
    }

    private fun localShowLucky(position: Int) {
        val localLucky = AppPreferencesManager.get()
            .getBoolean(Constant.LUCKY_FLAG, false)
        if (mVedioBean != null && (isLuckyShow || localLucky)) {
            if (position > mVedioBean!!.unlockIndex - 1) {
                // 解锁界面
                ll_lucky.visibility = View.GONE
            } else {
                // 超过免费剧
                if (position >= mVedioBean!!.freeIndex) {
                    ll_lucky.visibility = View.VISIBLE
                    context?.let {
                        GlideUtils.loadRoundImageViewGif(
                            it,
                            R.drawable.ic_nine,
                            iv_lucky_gif
                        )
                    }
                } else {
                    ll_lucky.visibility = View.GONE
                }
            }
        }
    }

    private fun setCollectImage(view: LottieAnimationView) {
        val lottieDrawable = LottieDrawable()
        LottieCompositionFactory.fromAsset(context, "home_collect.json")
            .addListener { result: LottieComposition? ->
                lottieDrawable.setImagesAssetsFolder("images/")
                lottieDrawable.composition = result
            }
        view.setImageDrawable(lottieDrawable)
    }

    private fun setCancelCollectImage(view: LottieAnimationView) {
        val lottieDrawable = LottieDrawable()
        LottieCompositionFactory.fromAsset(context, "home_cancel_collect.json")
            .addListener { result: LottieComposition? ->
                lottieDrawable.setImagesAssetsFolder("images/")
                lottieDrawable.composition = result
            }
        view.setImageDrawable(lottieDrawable)
    }

    private fun resetData() {
        if (UserManager.getInstance().vipFlag) {
            mVedioBean?.let {

                //解锁全部集数
                it.unlockIndex = it.vedioTotal
                it.tipMaxIndex = 0
                mInitUnlockIndex = it.vedioTotal
                //设置弹框集数为0
                it.adGiveVedioNum = 0

                mUnlockIndexMap = mutableMapOf()
                mHasUnlockIndexMap = mutableMapOf()

                drama?.let {
                    // 更新解锁集数
                    for (i in 0 until mInitUnlockIndex) {
                        val hasUnlockList: MutableList<Int> = mutableListOf()
                        hasUnlockList.add(i + 1)
                        mHasUnlockIndexMap[it.id] = hasUnlockList
                    }
                    mUnlockIndexMap[it.id] = mInitUnlockIndex
                    mUnlockIndexMap[it.id] = mUnlockIndexMap[it.id]!!
                    mVedioBean!!.unlockIndex = mInitUnlockIndex
                }

                // 播放当前集
                mVedioBean!!.seeIndex = mCurrentIndex
                mVedioBean!!.orderTags = orderTagsList
                LocalVedioManager.commitVedio(mVedioBean!!)

                if (block_view?.visibility == View.VISIBLE) {
                    blockView?.visibility = View.GONE
                    //解锁当前集
                    dpWidget?.let { widget ->
                        unlockCallback?.onDramaRewardArrived()
                    }
                }
            }
        }
    }

    private fun showAdView() {
        if (UserManager.getInstance().vipFlag) return

        ExpressManager.instance.getAdView(object : ExpressAdCallback {
            override fun loadSuccess(adView: FrameLayout?) {
                adView?.let {
                    UIUtils.removeFromParent(it)
                    fl_ad.removeAllViews()
                    fl_ad.addView(it)
                }
            }

            override fun renderSuccess(adView: FrameLayout?): Boolean {
                adView?.let {
                    UIUtils.removeFromParent(it)
                    fl_ad.removeAllViews()
                    fl_ad.addView(it)
                }

                ExpressManager.instance.preLoadAd()
                return false
            }

            override fun loadFail() {
            }

        })
    }

    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 -> {
                        val carrierType = Constant.CARRIERTYPE_CSJ_VEDIO
                        AdManager.instance.showAd(this@DramaApiDetailActivity, carrierType,
                            object : AdStatusListener {
                                var canFail = false
                                override fun adSuccess() {
                                    canFail = true
                                }

                                override fun adFail() {
                                    if (canFail) return

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

                                            override fun adSuccess() {
                                            }

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

                                                // 更新解锁集数
                                                for (i in 1 until lockSet) {
                                                    val hasUnlockList: MutableList<Int> =
                                                        mHasUnlockIndexMap[drama?.id]
                                                            ?: mutableListOf()
                                                    hasUnlockList.add(currentDramaIndex + i)
                                                    mHasUnlockIndexMap[drama!!.id] = hasUnlockList
                                                }
                                                mInitUnlockIndex =
                                                    mUnlockIndexMap[drama?.id]!! + lockSet
                                                mUnlockIndexMap[drama!!.id] =
                                                    mUnlockIndexMap[drama!!.id]!! + lockSet
                                                mVedioBean!!.unlockIndex = mInitUnlockIndex

                                                // 播放当前集
                                                mVedioBean!!.seeIndex = mCurrentIndex
                                                mVedioBean!!.orderTags = orderTagsList
                                                LocalVedioManager.commitVedio(mVedioBean!!)

                                                blockView?.visibility = View.GONE
                                                unlockCallback?.onDramaRewardArrived() // 解锁当前集
                                            }
                                        })
                                }

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

                                    // 更新解锁集数
                                    for (i in 1 until lockSet) {
                                        val hasUnlockList: MutableList<Int> =
                                            mHasUnlockIndexMap[drama!!.id] ?: mutableListOf()
                                        hasUnlockList.add(currentDramaIndex + i)
                                        mHasUnlockIndexMap[drama!!.id] = hasUnlockList
                                    }
                                    mInitUnlockIndex = mUnlockIndexMap[drama!!.id]!! + lockSet
                                    mUnlockIndexMap[drama!!.id] =
                                        mUnlockIndexMap[drama!!.id]!! + lockSet
                                    mVedioBean!!.unlockIndex = mInitUnlockIndex
                                    blockView?.visibility = View.GONE

                                    // 播放当前集
                                    mVedioBean!!.seeIndex = mCurrentIndex
                                    mVedioBean!!.orderTags = orderTagsList
                                    LocalVedioManager.commitVedio(mVedioBean!!)
                                    unlockCallback?.onDramaRewardArrived() // 解锁当前集
                                }
                            })

                        detailAdDialog?.dismiss()
                    }
                }
            }
        })
        detailAdDialog!!.show()
    }
}