package com.gh.gamecenter.video.detail

import android.app.Activity
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.airbnb.lottie.LottieAnimationView
import com.gh.common.exposure.IExposable
import com.gh.common.util.DownloadItemUtils
import com.gh.common.util.LogUtils
import com.gh.common.videolog.VideoRecordUtils
import com.gh.download.cache.ExoCacheManager
import com.gh.gamecenter.R
import com.gh.gamecenter.adapter.viewholder.GameViewHolder
import com.gh.gamecenter.common.base.activity.BaseActivity
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.exposure.ExposureSource
import com.gh.gamecenter.common.utils.ImageUtils
import com.gh.gamecenter.common.utils.goneIf
import com.gh.gamecenter.common.utils.putWidgetBusinessName
import com.gh.gamecenter.common.utils.safelyGetInRelease
import com.gh.gamecenter.core.utils.MtaHelper
import com.gh.gamecenter.entity.VideoEntity
import com.gh.gamecenter.eventbus.EBDownloadStatus
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.feature.exposure.ExposureEvent
import com.gh.gamecenter.feature.view.DownloadButton
import com.gh.gamecenter.game.GameAndPosition
import com.halo.assistant.HaloApp
import com.lightgame.download.DownloadEntity
import com.shuyu.gsyvideoplayer.builder.GSYVideoOptionBuilder
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack
import com.shuyu.gsyvideoplayer.utils.OrientationUtils
import com.shuyu.gsyvideoplayer.video.base.GSYVideoView

class VideoAdapter(
    private val mFragment: Fragment,
    private val mRecyclerView: RecyclerView,
    private val mRefreshLayout: SwipeRefreshLayout,
    private val mViewModel: VideoDetailContainerViewModel,
    private val mBasicExposureSourceList: ArrayList<ExposureSource>
) : RecyclerView.Adapter<RecyclerView.ViewHolder>(), IExposable {

    var videoList = arrayListOf<VideoEntity>()
    var isVisible = false//fragment是否可见

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val params =
            RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.MATCH_PARENT)
        val view = DetailPlayerView(mFragment.requireContext()).apply {
            layoutParams = params
        }
        view.setFragment(mFragment)
        return object : RecyclerView.ViewHolder(view) {}
    }

    override fun getItemCount(): Int = videoList.size

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val videoView = (holder.itemView as DetailPlayerView)
        videoView.resetProgressAndTime()//重置进度条，避免进度复用
        videoView.findViewById<View>(R.id.placeholderView)?.goneIf(!mViewModel.isHomeVideo)
        val video = videoList.safelyGetInRelease(position)
        video?.let {
            val mOrientationUtils = OrientationUtils(mFragment.requireContext() as Activity, videoView)
            mOrientationUtils.isEnable = false
            videoView.setViewModel(mViewModel)
            GSYVideoOptionBuilder()
                .setIsTouchWiget(false)
                .setUrl(it.url)
                .setRotateViewAuto(false)
                .setCacheWithPlay(true)
                .setRotateWithSystem(false)
                .setReleaseWhenLossAudio(true)
//                .setLockLand(true)
                .setLooping(false)
                .setShowFullAnimation(false)
                .setVideoAllCallBack(object : GSYSampleCallBack() {
                    override fun onQuitFullscreen(url: String?, vararg objects: Any) {
                        mOrientationUtils.backToProtVideo()
                        videoView.hideAllButton(false)
                        videoView.recordMta("全屏播放-退出全屏")
                        MtaHelper.onEvent(
                            "视频详情",
                            "全屏播放-退出全屏",
                            "${videoList[position].title}（${videoList[position].id}）"
                        )
                        videoView.uploadVideoStreamingPlaying("全屏播放-退出全屏")
                    }
                })
                .build(videoView)

            videoView.updateViewDetail(it)
            videoView.updateThumb(it.getThumb())
            videoView.updateMuteStatus()
            videoView.fullscreenButton.setOnClickListener {
                if (mRefreshLayout.isRefreshing) return@setOnClickListener
                if (mOrientationUtils.isLand == 0) {
                    videoView.recordMta("进入全屏")
                    MtaHelper.onEvent("视频详情", "进入全屏", "${videoList[position].title}（${videoList[position].id}）")
                    videoView.uploadVideoStreamingPlaying("全屏")
                }
                videoView.hideAllButton(true)
                mOrientationUtils.resolveByClick()
                val fullVideoPlayer =
                    videoView.startWindowFullscreen(mFragment.requireContext(), true, true) as? DetailPlayerView
                fullVideoPlayer?.observeVolume(mFragment.requireContext() as AppCompatActivity)
                fullVideoPlayer?.setViewModel(mViewModel)
                fullVideoPlayer?.hideAllButton(true)
                fullVideoPlayer?.updateViewDetail(videoList[position])
                fullVideoPlayer?.updateMuteStatus()
                // 进入全屏后直接播放
                if (fullVideoPlayer?.currentState == GSYVideoView.CURRENT_STATE_PAUSE) {
                    fullVideoPlayer.setCurrentPosition(videoView.getCurrentPosition())
                    fullVideoPlayer.onVideoResume(false)
                }
            }

            videoView.isNeedShowWifiTip = HaloApp.get(Constants.SHOULD_SHOW_VIDEO_MOBILE_WARNING, false) as Boolean?
                ?: false

            if (it.watched && !it.isFirstBind) {
                if (position == 0) {
                    videoView.watchedContainer.visibility = View.VISIBLE
                    videoView.watchedTv.text = "暂无关注up主动态，前往 “推荐” 查看更多视频"
                } else {
                    if (position - 1 >= 0 && !videoList[position - 1].watched) {
                        videoView.watchedContainer.visibility = View.VISIBLE
                        videoView.watchedTv.text = "上次看到这里，前往 “推荐” 查看更多视频"
                    } else {
                        videoView.watchedContainer.visibility = View.GONE
                    }
                }
            } else {
                videoView.watchedContainer.visibility = View.GONE
            }
            it.isFirstBind = true
        }

        if (position == mViewModel.startPosition && isVisible) {
            if (position + 2 <= videoList.size - 1) {//预加载视频
                ExoCacheManager.preload(videoList[position + 1].url)
                ExoCacheManager.preload(videoList[position + 2].url)
                ImageUtils.picasso.load(videoList[position + 1].getThumb()).fetch()
                ImageUtils.picasso.load(videoList[position + 2].getThumb()).fetch()
            } else if (position + 1 <= videoList.size - 1) {
                ExoCacheManager.preload(videoList[position + 1].url)
                ImageUtils.picasso.load(videoList[position + 1].getThumb()).fetch()
            }
            videoView.observeVolume(mFragment.requireContext() as AppCompatActivity)
            videoView.startButton.performClick()
            mViewModel.addHistoryRecord(videoList[position])
            VideoRecordUtils.log(videoList[position].id)
        }
        if (position == mViewModel.startPosition) {
            LogUtils.uploadVideoStreamingPlaying(
                "开始播放-入口进入", "", mViewModel.path,
                mViewModel.entranceDetail, videoList[position].id, mViewModel.uuid, 0.0, 0, 0, "play"
            )
        }

        setDownloadButton(videoView, position)
    }

    private fun setDownloadButton(videoView: DetailPlayerView?, position: Int) {
        videoList[position].game?.let { game ->
            val multiTv = videoView?.findViewById<TextView>(R.id.multiVersionDownloadTv)
            val downloadTipsLottie = videoView?.findViewById<LottieAnimationView>(R.id.downloadTipsLottie)
            videoView?.findViewById<DownloadButton>(R.id.download_btn)?.run {
                val btn = this
                val exposureEvent = generateExposure(game)
                game.exposureEvent = exposureEvent
                putWidgetBusinessName("视频Tab右下角游戏")
                DownloadItemUtils.setOnClickListener(mFragment.requireContext(),
                    this,
                    game,
                    0,
                    this@VideoAdapter,
                    mViewModel.path,
                    sourceEntrance = "视频流",
                    location = BaseActivity.mergeEntranceAndPath(mViewModel.path, "视频详情"),
                    traceEvent = exposureEvent
                ) {
                    when (btn.text) {
                        "下载" -> {
                            videoView.recordMta("下载游戏")
                            MtaHelper.onEvent(
                                "视频详情",
                                "下载游戏",
                                "${videoList[position].title}（${videoList[position].id}）"
                            )
                        }

                        "预约" -> {
                            videoView.recordMta("预约游戏")
                            MtaHelper.onEvent(
                                "视频详情",
                                "预约游戏",
                                "${videoList[position].title}（${videoList[position].id}）"
                            )
                        }
                    }
                    videoView.uploadVideoStreamingPlaying("点击下载按钮", btn.text.toString())
                }
                DownloadItemUtils.updateItem(
                    mFragment.requireContext(),
                    game,
                    GameViewHolder(videoView).apply {
                        gameDownloadBtn = this@run
                        gameDownloadTips = downloadTipsLottie
                        multiVersionDownloadTv = multiTv
                    }
                )
            }
        }
    }

    private fun generateExposure(gameEntity: GameEntity): ExposureEvent {
        val exposureSourceList = arrayListOf<ExposureSource>()

        when {
            mViewModel.isHomeVideo -> {
                exposureSourceList.addAll(mBasicExposureSourceList)
                exposureSourceList.add(ExposureSource("视频流"))
            }
            mViewModel.entrance.contains("首页-游戏") -> {
                exposureSourceList.add(ExposureSource("新首页"))
                exposureSourceList.add(ExposureSource("游戏"))
            }
            mViewModel.path.contains("首页-轮播图") -> {
                exposureSourceList.add(ExposureSource("新首页"))
                exposureSourceList.add(ExposureSource("轮播图"))
            }
            mViewModel.path.contains("游戏详情") -> exposureSourceList.add(ExposureSource("游戏详情"))
            mViewModel.path.contains("推荐入口") -> exposureSourceList.add(ExposureSource("问答", "推荐入口"))
            else -> exposureSourceList.add(ExposureSource("其他"))
        }

        exposureSourceList.add(ExposureSource("视频详情"))

        return ExposureEvent.createEvent(gameEntity, exposureSourceList)
    }

    fun notifyItemByDownload(download: DownloadEntity) {
        for (i in 0 until videoList.size) {
            val videoEntity = videoList.safelyGetInRelease(i)
            if (videoEntity?.game?.id == download.gameId) {
                val holder = mRecyclerView.findViewHolderForAdapterPosition(i)
                setDownloadButton(holder?.itemView as? DetailPlayerView, i)
            }
        }
    }

    fun notifyItemByDownload(position: Int) {
        val holder = mRecyclerView.findViewHolderForAdapterPosition(position)
        setDownloadButton(holder?.itemView as? DetailPlayerView, position)
    }

    fun notifyItemAndRemoveDownload(status: EBDownloadStatus) {
        val data = getGameEntityByPackage(status.packageName)
        for (gameAndPosition in data) {
            if (gameAndPosition.entity != null && gameAndPosition.entity.name == status.name) {
                gameAndPosition.entity.getEntryMap().remove(status.platform)
            }
            val holder = mRecyclerView.findViewHolderForAdapterPosition(gameAndPosition.position)
            setDownloadButton(holder?.itemView as? DetailPlayerView, gameAndPosition.position)
        }
    }

    fun getGameEntityByPackage(packageName: String): List<GameAndPosition> {
        val positionList = ArrayList<GameAndPosition>()
        val positionMap = mViewModel.positionAndPackageMap
        for (key in positionMap.keys) {
            if (key.contains(packageName)) {
                val position = positionMap[key]!!
                if (position >= videoList.size) return arrayListOf()
                val game = videoList[position].game
                if (game != null) {
                    positionList.add(GameAndPosition(game, position))
                }
            }
        }
        return positionList
    }

    fun onBackPressed(videoView: DetailPlayerView?): Boolean {
        if (videoView?.getCurrentIsFullscreen() == true) {
            videoView.getVideoAllCallBack().onQuitFullscreen("")
        }
        if (CustomManager.backFromWindowFull(mFragment.requireContext(), "detail_${mViewModel.uuid}")) {
            return true
        }
        return false
    }

    override fun getEventByPosition(pos: Int): ExposureEvent? {
        return videoList[pos].game?.exposureEvent
    }

    override fun getEventListByPosition(pos: Int): List<ExposureEvent>? {
        return null
    }
}