package com.gh.gamecenter.gamedetail.detail.viewholder

import android.view.Gravity
import android.view.View.MeasureSpec
import android.view.ViewGroup
import android.view.ViewGroup.MarginLayoutParams
import android.view.ViewTreeObserver
import androidx.core.view.updateLayoutParams
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.util.NewLogUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.utils.TimeUtils
import com.gh.gamecenter.databinding.ItemGameDetailMoreBinding
import com.gh.gamecenter.databinding.ItemGameDetailRecyclerViewBinding
import com.gh.gamecenter.databinding.ItemGameDetailServerBinding
import com.gh.gamecenter.feature.entity.ServerCalendarEntity
import com.gh.gamecenter.feature.view.DownloadButton
import com.gh.gamecenter.gamedetail.GameDetailViewModel
import com.gh.gamecenter.gamedetail.detail.adapter.GameLatestServiceAdapter
import com.gh.gamecenter.gamedetail.entity.GameDetailData
import com.gh.gamecenter.gamedetail.fuli.kaifu.ServersCalendarActivity

class GameDetailServerItemViewHolder(
    val binding: ItemGameDetailRecyclerViewBinding,
    downloadBtn: DownloadButton?,
    viewModel: GameDetailViewModel
) : BaseGameDetailItemViewHolder(binding.root, downloadBtn, viewModel) {
    override fun bindView(data: GameDetailData) {
        super.bindView(data)
        val entity = data.linkServer ?: return
        binding.run {
            titleTv.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(context))
            moreTv.setTextColor(com.gh.gamecenter.common.R.color.text_theme.toColor(context))
            moreTv.setDrawableEnd(R.drawable.ic_auxiliary_arrow_right_text_theme_12.toDrawable(context))
            titleTv.text = "游戏开服"
            moreTv.goneIf(entity.calendar.isEmpty()) {
                moreTv.text = "更多"
                moreTv.setOnClickListener {
                    SensorsBridge.trackGameDetailModuleClick(
                        gameId,
                        gameName,
                        gameType,
                        "右上角",
                        moduleType,
                        "游戏开服",
                        sequence,
                        gameStatus = gameStatus
                    )
                    val intent = ServersCalendarActivity.getIntent(
                        context,
                        viewModel.game!!,
                        entity,
                        viewModel.meLiveData.value
                    )
                    context.startActivity(intent)
                    viewModel.game?.let {
                        NewLogUtils.logGameDetailOpenListClick(it.name ?: "", it.id, "更多")
                    }
                }
            }
            if (entity.calendar.isNotEmpty()) {
                if (recyclerView.adapter !is ServerItemAdapter) {
                    recyclerView.isNestedScrollingEnabled = false
                    (recyclerView.itemAnimator as DefaultItemAnimator).supportsChangeAnimations = false
                    recyclerView.layoutManager = LinearLayoutManager(context)
                    recyclerView.adapter = ServerItemAdapter(entity.calendar)
                } else {
                    recyclerView.adapter?.run { notifyItemRangeChanged(0, itemCount) }
                }
            }
        }
    }

    inner class ServerItemAdapter(val dataList: ArrayList<ServerCalendarEntity>) :
        RecyclerView.Adapter<RecyclerView.ViewHolder>() {
        private val showItemCount: Int = 3
        private val maxItemCount: Int = 10
        private var isExpand = false
        private var expandEntities = arrayListOf<ServerCalendarEntity>()
        private var shrinkEntities = arrayListOf<ServerCalendarEntity>()

        init {
            expandEntities.clear()
            expandEntities.addAll(dataList.take(maxItemCount))
            //举例：当前时间为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条
            shrinkEntities.clear()
            val currentHour = TimeUtils.getCurrentHour()
            dataList.forEach {
                val hour = TimeUtils.getFormatTime(it.getTime(), "HH").toInt()
                if (hour > currentHour && shrinkEntities.size < showItemCount) {
                    shrinkEntities.add(it)
                }
            }
            //判断不足3条，向前补齐
            if (shrinkEntities.size < showItemCount) {
                if (shrinkEntities.isEmpty()) {
                    shrinkEntities.addAll(dataList.takeLast(showItemCount))
                } else {
                    val firstIndex = dataList.indexOf(shrinkEntities[0])
                    for (index in dataList.size - 1 downTo 0) {
                        if (index < firstIndex && shrinkEntities.size < showItemCount) {
                            shrinkEntities.add(0, dataList[index])
                        }
                    }
                }
            }

        }

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

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder =
            if (viewType == ITEM_SERVER) ServerItemViewHolder(parent.toBinding()) else MoreViewHolder(parent.toBinding())

        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            if (holder is ServerItemViewHolder) {
                val entity = if (expandEntities.size > showItemCount) {
                    if (isExpand) expandEntities.safelyGetInRelease(position) else
                        shrinkEntities.safelyGetInRelease(position)
                } else {
                    expandEntities.safelyGetInRelease(position)
                } ?: return
                holder.binding.root.updateLayoutParams<MarginLayoutParams> { topMargin = if (position == 0) 0 else 8F.dip2px() }
                holder.binding.timeTv.setDrawableStart(R.drawable.ic_game_detail_server)
                holder.binding.timeTv.setTextColor(com.gh.gamecenter.common.R.color.text_secondary.toColor(context))
                holder.binding.timeTv.text = TimeUtils.getFormatDate(entity.getTime())
                holder.binding.serviceNameTv.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(context))
                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.START
                        } else {
                            holder.binding.serviceNameTv.gravity = Gravity.END
                        }
                    }
                })
            }
            if (holder is MoreViewHolder) {
                holder.binding.arrowIv.rotation = if (isExpand) 180f else 0f
                holder.itemView.setOnClickListener {
                    isExpand = !isExpand
                    notifyDataSetChanged()
                    viewModel.game?.let {
                        NewLogUtils.logGameDetailOpenListClick(it.name ?: "", it.id, "展开")
                    }
                }
            }
        }

        override fun getItemCount(): Int = if (expandEntities.size > showItemCount) {
            if (isExpand) expandEntities.size + 1 else showItemCount + 1
        } else expandEntities.size
    }

    inner class ServerItemViewHolder(val binding: ItemGameDetailServerBinding) :
        RecyclerView.ViewHolder(binding.root)

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

    companion object {
        const val ITEM_MORE = 0
        const val ITEM_SERVER = 1
    }
}