package com.gh.gamecenter.gamecollection.square

import android.animation.Animator
import android.animation.TimeInterpolator
import android.animation.ValueAnimator
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.view.animation.AccelerateDecelerateInterpolator
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.gh.common.util.DirectUtils
import com.gh.common.util.NewLogUtils
import com.gh.gamecenter.databinding.GameCollectionSquareAmwayItemBinding
import com.gh.gamecenter.entity.AmwayCommentEntity
import java.lang.ref.WeakReference

class GameCollectionAmwayViewHolder(var binding: GameCollectionSquareAmwayItemBinding) :
    RecyclerView.ViewHolder(binding.root) {

    private val mAdapter = GameCollectionAmwayAdapter(binding.root.context)
    private val mLooperHandle = LooperHandle(this)
    private val mSlideLooperKey = 333
    private val mLifecycleObserver = object : DefaultLifecycleObserver {
        override fun onResume(owner: LifecycleOwner) {
            super.onResume(owner)
            startAutoPlay()
        }

        override fun onPause(owner: LifecycleOwner) {
            super.onPause(owner)
            stopAutoPlay()
        }
    }

    fun bindAmway(amwayList: List<AmwayCommentEntity>, viewModel: GameCollectionSquareViewModel) {
        mAdapter.setAmwayList(amwayList)
        binding.amwayVp.run {
            if (adapter is GameCollectionAmwayAdapter) return
            isUserInputEnabled = false
            adapter = mAdapter
            orientation = ViewPager2.ORIENTATION_VERTICAL
            startAutoPlay()
        }
        binding.root.setOnClickListener {
            NewLogUtils.logClickGameCollectionAmway(GameCollectionSquareViewModel.getOrderChineseByName(viewModel.view))
            DirectUtils.directToAmway(binding.root.context)
            NewLogUtils.logEnterGameCollectionAmway()
        }
    }

    private fun scrollToNextPage() {
        if (mAdapter.getRealCount() == 0) return
        val next = binding.amwayVp.currentItem + 1
        binding.amwayVp.setCurrentItem(next, 1000)
    }

    private fun startAutoPlay() {
        if (mAdapter.getRealCount() <= 1) return
        stopAutoPlay()
        mLooperHandle.sendEmptyMessageDelayed(mSlideLooperKey, AMWAY_LOOP_TIME)
    }

    private fun stopAutoPlay() {
        mLooperHandle.removeMessages(mSlideLooperKey)
    }

    fun onViewAttach(lifecycle: Lifecycle) {
        lifecycle.addObserver(mLifecycleObserver)
    }

    fun onViewDetach(lifecycle: Lifecycle) {
        lifecycle.removeObserver(mLifecycleObserver)
    }

    fun ViewPager2.setCurrentItem(
        item: Int,
        duration: Long,
        interpolator: TimeInterpolator = AccelerateDecelerateInterpolator(),
        pagePxHeight: Int = height
    ) {
        val pxToDrag: Int = pagePxHeight * (item - currentItem)
        val animator = ValueAnimator.ofInt(0, pxToDrag)
        var previousValue = 0
        animator.addUpdateListener { valueAnimator ->
            val currentValue = valueAnimator.animatedValue as Int
            val currentPxToDrag = (currentValue - previousValue).toFloat()
            fakeDragBy(-currentPxToDrag)
            previousValue = currentValue
        }
        animator.addListener(object : Animator.AnimatorListener {
            override fun onAnimationStart(animation: Animator) {
                beginFakeDrag()
            }

            override fun onAnimationEnd(animation: Animator) {
                endFakeDrag()
            }

            override fun onAnimationCancel(animation: Animator) {}
            override fun onAnimationRepeat(animation: Animator) {}
        })
        animator.interpolator = interpolator
        animator.duration = duration
        animator.start()
    }

    companion object {
        // 安利墙卡片轮播时间
        const val AMWAY_LOOP_TIME = 5000L
    }

    class LooperHandle(viewHolder: GameCollectionAmwayViewHolder) : Handler(
        Looper.getMainLooper()
    ) {
        private val mWeakReference: WeakReference<GameCollectionAmwayViewHolder> = WeakReference(viewHolder)

        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            val viewHolder = mWeakReference.get()
            if (viewHolder != null && msg.what == viewHolder.mSlideLooperKey) {
                viewHolder.scrollToNextPage()
                viewHolder.startAutoPlay()
            }
        }
    }
}