package com.adealink.weparty.module.playmate.event

import android.os.Handler
import android.os.Looper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.adealink.frame.statistics.BaseStatEvent
import com.adealink.weparty.R

abstract class PlaymateListEventReporter {

    private val handler = Handler(Looper.getMainLooper())
    private val reportRunnables = mutableMapOf<RecyclerView, Runnable>()

    /**
     * 注册RecyclerView进行事件上报
     * @param recyclerView 要监听的RecyclerView
     * @param delayMillis 滑动停止后延迟上报的时间（默认300毫秒）
     */
    fun register(recyclerView: RecyclerView, delayMillis: Long = 300L) {
        // 移除已存在的监听器
        unregister(recyclerView)

        val scrollListener = object : RecyclerView.OnScrollListener() {
            private var scrollRunnable: Runnable? = null

            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)

                when (newState) {
                    RecyclerView.SCROLL_STATE_IDLE -> {
                        // 滑动停止，延迟上报
                        scheduleReport(recyclerView, delayMillis)
                    }

                    RecyclerView.SCROLL_STATE_DRAGGING,
                    RecyclerView.SCROLL_STATE_SETTLING -> {
                        // 滑动中，取消之前的延迟上报
                        cancelScheduledReport(recyclerView)
                    }
                }
            }
        }

        recyclerView.addOnScrollListener(scrollListener)
        recyclerView.setTag(R.id.recycler_view_event_reporter, scrollListener)


        val adapter = recyclerView.adapter
        if (adapter == null) {
            throw IllegalStateException("recyclerView adapter is null")
        }
        adapter.registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() {
            override fun onChanged() {
                super.onChanged()
                checkAndReportInitialItems(adapter.itemCount, recyclerView)
            }

            override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
                super.onItemRangeInserted(positionStart, itemCount)
                checkAndReportInitialItems(adapter.itemCount, recyclerView)
            }
        })
    }

    private var isFirstLoad = true
    private fun checkAndReportInitialItems(itemCount: Int, recyclerView: RecyclerView) {
        if (isFirstLoad && itemCount > 0) {
            isFirstLoad = false
            // 延迟上报，确保视图已经创建
            handler.postDelayed({
                reportImmediately(recyclerView)
            }, 150)
        }
    }

    /**
     * 取消注册RecyclerView
     */
    fun unregister(recyclerView: RecyclerView) {
        val listener = recyclerView.getTag(R.id.recycler_view_event_reporter)
                as? RecyclerView.OnScrollListener

        listener?.let {
            recyclerView.removeOnScrollListener(it)
            recyclerView.setTag(R.id.recycler_view_event_reporter, null)
        }

        cancelScheduledReport(recyclerView)
    }

    /**
     * 立即上报当前可视Item的事件（可用于页面销毁时调用）
     */
    fun reportImmediately(recyclerView: RecyclerView) {
        reportVisibleItems(recyclerView)
        cancelScheduledReport(recyclerView)
    }

    private fun scheduleReport(recyclerView: RecyclerView, delayMillis: Long) {
        // 取消之前可能存在的延迟任务
        cancelScheduledReport(recyclerView)

        val runnable = Runnable {
            reportVisibleItems(recyclerView)
            reportRunnables.remove(recyclerView)
        }

        reportRunnables[recyclerView] = runnable
        handler.postDelayed(runnable, delayMillis)
    }

    private fun cancelScheduledReport(recyclerView: RecyclerView) {
        reportRunnables[recyclerView]?.let { runnable ->
            handler.removeCallbacks(runnable)
            reportRunnables.remove(recyclerView)
        }
    }

    private fun reportVisibleItems(recyclerView: RecyclerView) {
        val layoutManager = recyclerView.layoutManager as? LinearLayoutManager ?: return

        // 获取当前可视范围内的Item数量
        val firstVisibleItem = layoutManager.findFirstVisibleItemPosition()
        val lastVisibleItem = layoutManager.findLastVisibleItemPosition()

        if (firstVisibleItem == RecyclerView.NO_POSITION ||
            lastVisibleItem == RecyclerView.NO_POSITION
        ) {
            return
        }

        // 上报每个可视Item的事件
        val events = mutableListOf<BaseStatEvent>()
        for (i in firstVisibleItem..lastVisibleItem) {
            val viewHolder = recyclerView.findViewHolderForAdapterPosition(i)
            if (viewHolder != null && viewHolder.itemView.isShown) {
                val event = getReportEvent(viewHolder, viewHolder.layoutPosition) ?: return
                events.add(event)
            }
        }
        reportEvent(events)
    }

    abstract fun getReportEvent(viewHolder: RecyclerView.ViewHolder, position: Int): BaseStatEvent?

    abstract fun reportEvent(events: List<BaseStatEvent>)


}
