package com.gh.gamecenter.gamedetail.desc

import android.content.Context
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View.MeasureSpec
import android.view.ViewGroup
import android.view.ViewTreeObserver
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.util.NewLogUtils
import com.gh.gamecenter.core.utils.TimeUtils
import com.gh.gamecenter.common.utils.safelyGetInRelease
import com.gh.gamecenter.common.utils.toBinding
import com.gh.gamecenter.databinding.ItemGameDetailLatestServiceBinding
import com.gh.gamecenter.databinding.ItemGameDetailMoreBinding
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.feature.entity.ServerCalendarEntity

class GameLatestServiceAdapter(
    val context: Context,
    val gameEntity: GameEntity?,
    val datas: ArrayList<ServerCalendarEntity>
) :
    RecyclerView.Adapter<RecyclerView.ViewHolder>() {
    private val mShowItemCount: Int = 3
    private val mMaxItemCount: Int = 10
    private var mIsExpand = false
    private var mExpandEntities = arrayListOf<ServerCalendarEntity>()
    private var mShrinkEntities = arrayListOf<ServerCalendarEntity>()

    init {
        mExpandEntities.clear()
        mExpandEntities.addAll(datas.take(mMaxItemCount))
        //举例：当前时间为9点
        //全部开服                 展示的3条
        //7、8、9、10              8、9、10
        //7、8、9、10、11、12、13  10、11、12
        //6、7、8、9               7、8、9
        //获取未来最靠近当前时间的3条
        mShrinkEntities.clear()
        val currentHour = TimeUtils.getCurrentHour()
        datas.forEach {
            val hour = TimeUtils.getFormatTime(it.getTime(), "HH").toInt()
            if (hour > currentHour && mShrinkEntities.size < mShowItemCount) {
                mShrinkEntities.add(it)
            }
        }
        //判断不足3条，向前补齐
        if (mShrinkEntities.size < mShowItemCount) {
            if (mShrinkEntities.isEmpty()) {
                mShrinkEntities.addAll(datas.takeLast(mShowItemCount))
            } else {
                val firstIndex = datas.indexOf(mShrinkEntities[0])
                for (index in datas.size - 1 downTo 0) {
                    if (index < firstIndex && mShrinkEntities.size < mShowItemCount) {
                        mShrinkEntities.add(0, datas[index])
                    }
                }
            }
        }

    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return if (viewType == SERVICE_ITEM) {
            GameLatestServiceViewHolder(parent.toBinding())
        } else {
            MoreViewHolder(ItemGameDetailMoreBinding.inflate(LayoutInflater.from(context), parent, false))
        }
    }

    override fun getItemViewType(position: Int): Int {
        return if (mExpandEntities.size > mShowItemCount) {
            if (position == itemCount - 1) MORE else SERVICE_ITEM
        } else {
            SERVICE_ITEM
        }
    }

    override fun getItemCount(): Int {
        return if (mExpandEntities.size > mShowItemCount) {
            if (mIsExpand) mExpandEntities.size + 1 else mShowItemCount + 1
        } else mExpandEntities.size
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (holder is GameLatestServiceViewHolder) {
            val entity = if (mExpandEntities.size > mShowItemCount) {
                if (mIsExpand) mExpandEntities.safelyGetInRelease(position) else
                    mShrinkEntities.safelyGetInRelease(position)
            } else {
                mExpandEntities.safelyGetInRelease(position)
            } ?: return
            holder.binding.timeTv.text = TimeUtils.getFormatDate(entity.getTime())
            holder.binding.serviceNameTv.text = "${entity.getNote()} ${entity.remark}"

            holder.binding.serviceNameTv.viewTreeObserver.addOnGlobalLayoutListener(object :
                ViewTreeObserver.OnGlobalLayoutListener {
                override fun onGlobalLayout() {
                    holder.binding.serviceNameTv.viewTreeObserver.removeOnGlobalLayoutListener(this)

                    holder.binding.serviceNameTv.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED)
                    val measuredWidth = holder.binding.serviceNameTv.measuredWidth
                    val width = holder.binding.serviceNameTv.width
                    if (measuredWidth > width) {
                        holder.binding.serviceNameTv.isSelected = true
                        holder.binding.serviceNameTv.gravity = Gravity.LEFT
                    } else {
                        holder.binding.serviceNameTv.gravity = Gravity.RIGHT
                    }
                }
            })
        } else if (holder is MoreViewHolder) {
            holder.binding.arrowIv.rotation = if (mIsExpand) 180f else 0f
            holder.itemView.setOnClickListener {
                mIsExpand = !mIsExpand
                notifyDataSetChanged()
                gameEntity?.let {
                    NewLogUtils.logGameDetailOpenListClick(it.name ?: "", it.id, "展开")
                }
            }
        }
    }

    class GameLatestServiceViewHolder(var binding: ItemGameDetailLatestServiceBinding) :
        RecyclerView.ViewHolder(binding.root)

    class MoreViewHolder(var binding: ItemGameDetailMoreBinding) : RecyclerView.ViewHolder(binding.root)

    companion object {
        const val MORE = 0
        const val SERVICE_ITEM = 1
    }
}