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

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import androidx.core.view.ViewCompat
import com.gh.common.exposure.ExposureManager
import com.gh.common.exposure.ExposureTraceUtils
import com.gh.common.util.LogUtils
import com.gh.common.util.NewLogUtils
import com.gh.gamecenter.common.entity.LinkEntity
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.utils.PageSwitchDataHelper
import com.gh.gamecenter.databinding.ItemHomeRecommendListItemCustomBinding
import com.gh.gamecenter.entity.HomeRecommend
import com.gh.gamecenter.feature.exposure.ExposureEvent
import com.gh.gamecenter.feature.exposure.ExposureType
import com.gh.gamecenter.home.custom.viewholder.CustomHomeRecommendItemViewHolder.Companion.MAX_SPAN_COUNT
import org.json.JSONException
import org.json.JSONObject

/**
 * @author : liujiarui
 * date : 2023/3/23
 * description :
 */
class CustomHomeRecommendItemGridAdapter(
    private val listener: OnEventListener,
) : BaseAdapter() {

    private val dataList = arrayListOf<HomeRecommend>()
    private var exposureEventList: List<ExposureEvent>? = null
    private var spanCount = MAX_SPAN_COUNT

    fun submitList(data: List<HomeRecommend>, spanCount: Int, trackEventList: List<ExposureEvent>?) {
        exposureEventList = trackEventList
        this.spanCount = spanCount
        dataList.clear()
        dataList.addAll(data)
        notifyDataSetChanged()
    }

    override fun getCount() = dataList.size

    override fun getItem(position: Int) = dataList[position]

    override fun getItemId(position: Int): Long {
        return dataList[position].linkId.hashCode().toLong()
    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        val data = dataList.getOrNull(position)
        val binding: ItemHomeRecommendListItemCustomBinding
        if (convertView == null) {
            binding = ItemHomeRecommendListItemCustomBinding
                .inflate(LayoutInflater.from(parent.context), parent, false)
            binding.root.tag = binding
        } else {
            binding = convertView.tag as ItemHomeRecommendListItemCustomBinding
        }
        if (data != null) {
            ImageUtils.display(binding.iconIv, data.image)
            binding.nameTv.text = data.name
            binding.nameTv.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(binding.root.context))
            // 当金刚区一排需要展示五个时，就算后台返回了引导文案，最右边 itemView 仍然会出现显示不全的情况，所以这里将此种情况的引导文案隐藏
            val isRightmost = spanCount == MAX_SPAN_COUNT && (position + 1) % MAX_SPAN_COUNT == 0
            binding.tvBubble.goneIf(!data.isShowGuide || isRightmost) {
                binding.tvBubble.text = data.guide.text
            }
        }

        ViewCompat.setElevation(binding.root, 999F - position)
        initEvent(binding, position)
        return binding.root
    }

    private fun initEvent(binding: ItemHomeRecommendListItemCustomBinding, position: Int) {
        //点击事件上报
        binding.root.setDebouncedClickListener {
            val recommend = dataList[position]

            LogUtils.logRecommendClick(
                "首页",
                recommend.name,
                recommend.linkType,
                recommend.linkText,
                recommend.linkId,
                position
            )

            val trackEvent = JSONObject()
            try {
                trackEvent.put("position", position)
                trackEvent.put("Recommended_location_name", recommend.name)
                trackEvent.put("location", "首页")
            } catch (e: JSONException) {
                e.printStackTrace()
            }
            SensorsBridge.trackEvent("RecommendedLocationClick", trackEvent)

            if (recommend.linkType == "common_collection") {
                NewLogUtils.logAccessToCommonCollectionDetail(recommend.linkId, recommend.linkText, "首页推荐入口")
            }
            PageSwitchDataHelper.pushCurrentPageData(
                hashMapOf(
                    Pair(
                        PageSwitchDataHelper.PAGE_BUSINESS_TYPE,
                        "首页-推荐位"
                    )
                )
            )
            exposureEventList?.getOrNull(position)?.let {
                val clickEvent = ExposureEvent(
                    payload = it.payload,
                    source = it.source,
                    eTrace = ExposureTraceUtils.appendTrace(it),
                    event = ExposureType.CLICK
                )
                if (recommend.transformLinkEntity().type != "game") {
                    ExposureManager.log(clickEvent)
                }
            }
            listener.navigateToLinkPage(
                recommend.transformLinkEntity(),
                "金刚区",
                exposureEventList?.getOrNull(position)
            )
        }
    }

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