package com.gh.gamecenter.home.custom.adapter

import android.content.Context
import android.graphics.drawable.GradientDrawable
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.exposure.ExposureManager
import com.gh.common.exposure.ExposureTraceUtils
import com.gh.gamecenter.common.base.BaseRecyclerViewHolder
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.entity.ExposureEntity
import com.gh.gamecenter.common.entity.LinkEntity
import com.gh.gamecenter.common.json.json
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.utils.PageSwitchDataHelper
import com.gh.gamecenter.core.utils.SPUtils
import com.gh.gamecenter.databinding.ItemGameNavigationCustomBinding
import com.gh.gamecenter.entity.GameNavigationEntity
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.feature.exposure.ExposureEvent
import com.gh.gamecenter.feature.exposure.ExposureType
import com.gh.gamecenter.feature.exposure.IExposureProvider

class CustomGameNavigationAdapter(
    context: Context,
    private val listener: OnEventListener,
) : CustomBaseChildAdapter<GameNavigationEntity, CustomGameNavigationAdapter.GameNavigationViewHolder>(context) {

    private var recordMap = SPUtils.getMap(Constants.SP_GAME_NAVIGATION)
    private var exposureEventList: List<ExposureEvent>? = null

    fun setData(data: List<GameNavigationEntity>, trackEventList: List<ExposureEvent>?) {
        exposureEventList = trackEventList
        submitList(data)
    }

    override fun getKey(t: GameNavigationEntity): String {
        return t.id
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): GameNavigationViewHolder {
        return GameNavigationViewHolder(parent.toBinding())
    }

    override fun onBindViewHolder(holder: GameNavigationViewHolder, position: Int) {
        // 是否显示小红点
        var isShowHint = false
        val entity = dataList[position]
        holder.exposureEvent = exposureEventList?.getOrNull(position)
        ImageUtils.display(holder.binding.navigationView, entity.image)
        holder.binding.navigationNameTv.text = if (entity.isShowEntryName) {
            entity.entryName
        } else {
            ""
        }
        val isFirstLine = position < 4
        if (entity.isShowBubble && isFirstLine) {
            isShowHint = false
            showGuide(entity, holder.binding)
        } else {
            holder.binding.flBubbleContainer.goneIf(true)
            if (entity.hint) {
                val record = recordMap[entity.id]
                if (record == null) {
                    isShowHint = true
                    holder.binding.redHintIv.visibility = View.VISIBLE
                } else {
                    val split = record.split(divider)//时间戳|点击次数
                    val updateTime = split[0].toLong()
                    val count = split[1].toInt()
                    //判断是否更新过
                    if (updateTime == entity.time?.update) {
                        isShowHint = false
                        holder.binding.redHintIv.visibility = View.GONE
                    } else {
                        val currentTime = System.currentTimeMillis() / 1000
                        val isGone = currentTime !in entity.hintStartTime..entity.hintEndTime || count >= 2
                        holder.binding.redHintIv.goneIf(isGone)
                        isShowHint = !isGone
                    }
                }
            } else {
                isShowHint = false
                holder.binding.redHintIv.visibility = View.GONE
            }
        }

        holder.itemView.setOnClickListener {
            entity.linkEntity?.let {
                if (isShowHint) {
                    val record = recordMap[entity.id]
                    if (record == null) {
                        recordMap[entity.id] = "${entity.time?.update}${divider}1"
                    } else {
                        val split = record.split(divider)
                        val updateTime = split[0].toLong()
                        var count = split[1].toInt()
                        recordMap[entity.id] = "${updateTime}${divider}${++count}"
                    }
                    SPUtils.setMap(Constants.SP_GAME_NAVIGATION, recordMap)
                    notifyItemChanged(position)
                }
                PageSwitchDataHelper.pushCurrentPageData(
                    hashMapOf(
                        Pair(PageSwitchDataHelper.PAGE_BUSINESS_TYPE, "板块-内容列表->导航栏"),
                        Pair(PageSwitchDataHelper.PAGE_BUSINESS_ID, "${""}->${entity.id}"),
                        Pair(PageSwitchDataHelper.PAGE_BUSINESS_NAME, "")
                    )
                )

                SensorsBridge.trackEvent("NavigationClick", json {
                    "position" to position
                    "Navigation_name" to entity.entryName
                    "Navigation_id" to entity.id
                    "block_name" to ""
                    "block_id" to ""
                })
                val exposureEvent = exposureEventList?.getOrNull(position)
                if (exposureEvent != null) {
                    val clickEvent = ExposureEvent.createEvent(
                        GameEntity(
                            containerId = entity.id,
                            containerType = ExposureEntity.NAVIGATION_ID
                        ),
                        exposureEvent.source,
                        ExposureTraceUtils.appendTrace(exposureEvent),
                        ExposureType.CLICK
                    )
                    if (it.type != "game") {
                        ExposureManager.log(clickEvent)
                    }
                }
                listener.navigateToLinkPage(it, "导航栏", exposureEvent)
            }
        }
    }

    private fun showGuide(entity: GameNavigationEntity, binding: ItemGameNavigationCustomBinding) {
        binding.flBubbleContainer.goneIf(false)
        binding.tvBubble.text = entity.guide.text
        binding.tvBubble.setTextColor(entity.guide.textColorInt)

        val gradientDrawable =
            (binding.tvBubble.background as? GradientDrawable) ?: GradientDrawable()
        gradientDrawable.cornerRadii =
            floatArrayOf(
                8F.dip2px().toFloat(),
                8F.dip2px().toFloat(),
                8F.dip2px().toFloat(),
                8F.dip2px().toFloat(),
                2F.dip2px().toFloat(),
                2F.dip2px().toFloat(),
                2F.dip2px().toFloat(),
                2F.dip2px().toFloat()
            )
        gradientDrawable.setStroke(1F.dip2px(), entity.guide.borderColorInt)
        gradientDrawable.setColor(entity.guide.backgroundColorInt)
        binding.tvBubble.background = gradientDrawable
    }

    companion object {
        const val divider = "|"
    }

    class GameNavigationViewHolder(val binding: ItemGameNavigationCustomBinding) :
        BaseRecyclerViewHolder<RecyclerView.ViewHolder>(binding.root), IExposureProvider {

        var exposureEvent: ExposureEvent? = null

        override fun provideExposureData(): ExposureEvent? {
            return exposureEvent?.getFreshExposureEvent()
        }
    }

    interface OnEventListener {
        fun navigateToLinkPage(link: LinkEntity, text: String, exposureEvent: ExposureEvent?)
    }
}