package com.gh.gamecenter.home.custom.viewholder

import android.animation.TimeInterpolator
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.OnScrollListener
import androidx.recyclerview.widget.RecyclerView.SCROLL_STATE_IDLE
import com.gh.gamecenter.R
import com.gh.gamecenter.common.view.stacklayoutmanager2.StackAnimation2
import com.gh.gamecenter.common.view.stacklayoutmanager2.StackLayoutManagerV2
import com.gh.gamecenter.core.runOnIoThread
import com.gh.gamecenter.databinding.RecyclerFoldSlideLargeImageCustomBinding
import com.gh.gamecenter.home.custom.CustomPageViewModel
import com.gh.gamecenter.home.custom.IGameChangedNotifier
import com.gh.gamecenter.home.custom.adapter.CustomFoldSlideLargeImageItemAdapter
import com.gh.gamecenter.home.custom.eventlistener.SubjectEventHelper
import com.gh.gamecenter.home.custom.model.CustomPageItem
import com.gh.gamecenter.home.custom.model.CustomSubjectItem

/**
 * 游戏专题-折叠滑动大图
 */
class CustomFoldSlideLargeImageViewHolder(
    viewModel: CustomPageViewModel,
    val binding: RecyclerFoldSlideLargeImageCustomBinding
) : BaseCustomViewHolder(viewModel, binding.root) {

    override val childEventHelper by lazy(LazyThreadSafetyMode.NONE) {
        SubjectEventHelper(viewModel)
    }

    private val layoutManager by lazy {
        StackLayoutManagerV2(214, 310, CustomFoldSlideLargeImageLayoutAnimation())
    }

    private val adapter by lazy {
        CustomFoldSlideLargeImageItemAdapter(itemView.context, childEventHelper)
    }

    override val gameChangedNotifier: IGameChangedNotifier
        get() = adapter

    private var topViewHolder: CustomFoldSlideLargeImageItemAdapter.ImageItemViewHolder? = null

    private val onScrollListener = object : OnScrollListener() {
        override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
            if (newState == SCROLL_STATE_IDLE) {
                updateTopViewHolder(layoutManager.selectedPosition)
            }
        }

        override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
            super.onScrolled(recyclerView, dx, dy)
            if (dy == 0) {
                updateTopViewHolder(layoutManager.selectedPosition)
            }
        }
    }

    private var isInit = true

    init {
        binding.recyclerView.isNestedScrollingEnabled = false
        layoutManager.setOnItemSelectedListener(object : StackLayoutManagerV2.OnStackListener {
            override fun onSelectedPositionChanged(position: Int) {
                updateTopViewHolder(position)
            }

            override fun onScrollStateChanged(isScrolling: Boolean) = Unit
        })
    }

    private fun updateTopViewHolder(position: Int) {
        val viewHolder = binding.recyclerView.findViewHolderForAdapterPosition(position)
        if (topViewHolder != viewHolder) {
            topViewHolder?.dismissBubble()
        }
        if (viewHolder is CustomFoldSlideLargeImageItemAdapter.ImageItemViewHolder) {
            topViewHolder = viewHolder
            viewHolder.showBubble()
        }
    }

    override fun bindView(item: CustomPageItem) {
        super.bindView(item)
        if (item is CustomSubjectItem) {

            setSubjectTitle(binding.layoutTitle, item, childEventHelper)

            runOnIoThread(isLightWeightTask = true) {
                item.data.data?.forEachIndexed { index, game ->
                    fillExposureAndReportAd(game, index, item)
                }
            }

            if (binding.recyclerView.adapter == null) {
                binding.recyclerView.layoutManager = layoutManager
                binding.recyclerView.adapter = adapter
            }
            adapter.setData(item)

            if (isInit) {
                isInit = false
                binding.recyclerView.scrollToPosition(adapter.getInitPosition())
            }
        }
    }

    override fun onViewAttach(parent: RecyclerView?) {
        parent?.addOnScrollListener(onScrollListener)
    }

    override fun onViewDetach(parent: RecyclerView?) {
        parent?.removeOnScrollListener(onScrollListener)
        // 取消气泡与倒计时
        topViewHolder?.dismissBubble()
    }

    class CustomFoldSlideLargeImageLayoutAnimation : StackAnimation2 {
        private val alphaInterceptor = TimeInterpolator { x ->
            x * x * x * x
        }

        override fun layoutAnimations(child: View, layoutPosition: Int, layoutManager: StackLayoutManagerV2) {
            // 相邻卡片间透明度差距变化
            val alphaSpace = 1f / layoutManager.visibleCount
            val alpha: Float
            var scale = 1f
            if (layoutPosition == layoutManager.selectedPosition) {
                alpha = 1 - alphaInterceptor.getInterpolation(layoutManager.scrollPercent)
            } else {
                alpha =
                    1 - (layoutPosition - layoutManager.selectedPosition) * alphaSpace + alphaSpace * layoutManager.scrollPercent
                scale =
                    1 - (layoutPosition - layoutManager.selectedPosition) * 0.1f + 0.1f * layoutManager.scrollPercent
            }
            child.findViewById<View>(R.id.cl_container)?.alpha = alpha
            child.pivotY = child.measuredHeight / 2f
            child.pivotX = child.width.toFloat()
            child.scaleX = scale
            child.scaleY = scale
        }

    }
}