package com.gh.gamecenter.gamedetail.detail.adapter

import android.app.Activity
import android.content.Context
import android.util.SparseArray
import android.view.View
import android.view.ViewGroup
import android.view.ViewGroup.MarginLayoutParams
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.constraintlayout.widget.ConstraintSet
import androidx.core.util.forEach
import androidx.core.view.updateLayoutParams
import androidx.recyclerview.widget.RecyclerView
import com.facebook.drawee.view.SimpleDraweeView
import com.gh.gamecenter.ImageViewerActivity
import com.gh.gamecenter.common.base.BaseRecyclerViewHolder
import com.gh.gamecenter.common.utils.ImageUtils
import com.gh.gamecenter.common.utils.dip2px
import com.gh.gamecenter.common.utils.toBinding
import com.gh.gamecenter.common.utils.toastInInternalRelease
import com.gh.gamecenter.databinding.ItemGameCoverGalleryBinding
import com.gh.gamecenter.databinding.ItemGameCoverVideoBinding
import com.gh.gamecenter.gamedetail.GameDetailViewModel
import com.gh.gamecenter.gamedetail.detail.GameDetailFragment
import com.gh.gamecenter.gamedetail.entity.CoverEntity
import com.gh.gamecenter.gamedetail.video.GameDetailScrollCalculatorHelper
import com.gh.gamecenter.gamedetail.video.TopVideoView
import com.lightgame.adapter.BaseRecyclerAdapter
import com.shuyu.gsyvideoplayer.builder.GSYVideoOptionBuilder
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack
import com.shuyu.gsyvideoplayer.utils.OrientationUtils

class GameDetailCoverAdapter(
    context: Context,
    private val fragment: GameDetailFragment,
    private val viewModel: GameDetailViewModel,
    private val scrollCalculatorHelper: GameDetailScrollCalculatorHelper,
    private val showOrHideCoverFilter: ((Boolean) -> Unit)
) : BaseRecyclerAdapter<RecyclerView.ViewHolder>(context) {

    private var coverRecyclerView: RecyclerView? = null
    private var coverList = arrayListOf<CoverEntity>()
    private var isSingleGallery = false
    private var hasSetFixedHeight = false
    private val imageUrlList = arrayListOf<String>()
    private val imageViewArray = SparseArray<SimpleDraweeView>()

    fun submitList(data: List<CoverEntity>) {
        imageUrlList.clear()
        coverList = ArrayList(data)
        isSingleGallery = coverList.count { it.gallery != null } == 1
        coverList.mapNotNullTo(imageUrlList) { it.gallery?.url }
        notifyDataSetChanged()
    }

    override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
        super.onAttachedToRecyclerView(recyclerView)
        coverRecyclerView = recyclerView
    }

    override fun getItemViewType(position: Int): Int {
        val coverEntity = coverList.getOrNull(position)
        return when {
            coverEntity?.video != null -> ITEM_VIDEO
            else -> ITEM_GALLERY
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return when (viewType) {
            ITEM_VIDEO -> GameDetailCoverVideoItemViewHolder(parent.toBinding())
            else -> GameDetailCoverGalleryItemViewHolder(parent.toBinding())
        }
    }

    override fun getItemCount(): Int = coverList.size

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        coverList.getOrNull(position)?.let {
            if (holder is GameDetailCoverVideoItemViewHolder) {
                bindVideoItem(holder, it, position)
            }
            if (holder is GameDetailCoverGalleryItemViewHolder) {
                bindGalleryItem(holder, it, position)
            }
        }
    }

    private fun bindVideoItem(holder: GameDetailCoverVideoItemViewHolder, entity: CoverEntity, position: Int) {
        if (position == viewModel.defaultCoverEntity?.index && !hasSetFixedHeight) {
            holder.binding.root.post {
                coverRecyclerView?.updateLayoutParams<ViewGroup.LayoutParams> { height = holder.binding.root.height }
                hasSetFixedHeight = true
            }
        }

        val topVideo = entity.video ?: return
        val orientationUtils = OrientationUtils(mContext as Activity, holder.binding.player)
        orientationUtils.isEnable = false
        GSYVideoOptionBuilder()
            .setIsTouchWigetFull(false)
            .setIsTouchWiget(false)
            .setRotateViewAuto(false)
            .setShowFullAnimation(false)
            .setSeekRatio(1F)
            .setUrl(topVideo.url)
            .setCacheWithPlay(true)
            .setShowPauseCover(true)
            .setReleaseWhenLossAudio(false)
            .setAutoFullWithSize(true)
            .setDismissControlTime(5000)
            .setVideoAllCallBack(object : GSYSampleCallBack() {
                override fun onClickStartIcon(url: String?, vararg objects: Any?) {
                    scrollCalculatorHelper.currentPlayer = holder.binding.player
                }

                override fun onClickResume(url: String?, vararg objects: Any?) {
                    scrollCalculatorHelper.currentPlayer = holder.binding.player
                }

                override fun onQuitFullscreen(url: String?, vararg objects: Any) {
                    orientationUtils.backToProtVideo()
                    holder.binding.player.uploadVideoStreamingPlaying("退出全屏")
                }
            })
            .build(holder.binding.player)

        holder.binding.player.viewModel = viewModel
        holder.binding.player.showOrHideCoverFilter = showOrHideCoverFilter
        holder.binding.player.scrollCalculatorHelper = scrollCalculatorHelper
        holder.binding.player.video = topVideo
        holder.binding.player.updateThumb(topVideo.poster)

        holder.binding.player.fullscreenButton.setOnClickListener {
            val horizontalVideoView =
                holder.binding.player.startWindowFullscreen(mContext, true, true) as? TopVideoView
            if (horizontalVideoView == null) {
                toastInInternalRelease("全屏失败，请向技术人员提供具体的操作步骤")
                return@setOnClickListener
            }
            orientationUtils.resolveByClick()
            horizontalVideoView.uuid = holder.binding.player.uuid
            horizontalVideoView.viewModel = viewModel
            horizontalVideoView.video = topVideo
            horizontalVideoView.updateThumb(topVideo.poster)
            horizontalVideoView.violenceUpdateMuteStatus()
            holder.binding.player.uploadVideoStreamingPlaying("开始播放")
            holder.binding.player.uploadVideoStreamingPlaying("点击全屏")
        }

        holder.binding.player.observeVolume(fragment)
    }

    private fun bindGalleryItem(holder: GameDetailCoverGalleryItemViewHolder, entity: CoverEntity, position: Int) {
        val imageUrl = entity.gallery?.url ?: ""
        val isLastItem = position == coverList.lastIndex
        val imageWidth = (entity.gallery?.width ?: return).toInt()
        val imageHeight = (entity.gallery?.height ?: return).toInt()
        val isLandscape = imageWidth >= imageHeight
        val ratio = imageWidth / imageHeight.toFloat()
        ConstraintSet().also {
            it.clone(holder.binding.root)
            it.setDimensionRatio(holder.binding.galleryIv.id, if (isLandscape) "h,16:9" else "")
        }.applyTo(holder.binding.root)
        holder.binding.root.updateLayoutParams<MarginLayoutParams> {
            width = if (isLandscape || isSingleGallery) ViewGroup.LayoutParams.MATCH_PARENT else ViewGroup.LayoutParams.WRAP_CONTENT
            height = if (isLandscape) ViewGroup.LayoutParams.WRAP_CONTENT else PORTRAIT_IMAGE_HEIGHT_DP.dip2px()
            rightMargin = if (isLandscape || isSingleGallery || isLastItem) 8F.dip2px() else 0
        }
        holder.binding.galleryIv.updateLayoutParams<ConstraintLayout.LayoutParams> {
            width = if (isLandscape) 0 else (PORTRAIT_IMAGE_HEIGHT_DP.dip2px() * ratio).toInt()
            height = if (isLandscape) 0 else PORTRAIT_IMAGE_HEIGHT_DP.dip2px()
        }
        if (position == viewModel.defaultCoverEntity?.index && !hasSetFixedHeight) {
            holder.binding.root.post {
                coverRecyclerView?.updateLayoutParams<ViewGroup.LayoutParams> { height = holder.binding.root.height }
                hasSetFixedHeight = true
            }
        }
        holder.binding.galleryIv.setTag(ImageUtils.TAG_TARGET_WIDTH, imageWidth)
        ImageUtils.display(holder.binding.galleryIv, imageUrl)
        imageViewArray[entity.galleryIndex] = holder.binding.galleryIv
        holder.binding.root.setOnClickListener {
            val imageViewList = arrayListOf<View>()
            imageViewArray.forEach { _, value -> imageViewList.add(value) }
            val intent = ImageViewerActivity.getIntent(
                mContext,
                imageUrlList,
                entity.galleryIndex,
                imageViewList,
                "游戏详情-视频/图片区域"
            )
            mContext.startActivity(intent)
        }
    }

    companion object {
        const val ITEM_VIDEO = 0
        const val ITEM_GALLERY = 1

        private const val PORTRAIT_IMAGE_HEIGHT_DP = 280F
    }

    class GameDetailCoverVideoItemViewHolder(val binding: ItemGameCoverVideoBinding) :
        BaseRecyclerViewHolder<Any>(binding.root)

    class GameDetailCoverGalleryItemViewHolder(val binding: ItemGameCoverGalleryBinding) :
        BaseRecyclerViewHolder<Any>(binding.root)
}