package com.gh.gamecenter.home.custom.floatview

import android.content.Context
import android.net.Uri
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.therouter.TheRouter
import com.gh.common.exposure.ExposureManager
import com.gh.common.exposure.ExposureTraceUtils
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.constant.RouteConsts
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.common.view.WrapContentDraweeView
import com.gh.gamecenter.core.provider.IDirectProvider
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.feature.entity.PageLocation
import com.gh.gamecenter.feature.entity.WelcomeDialogEntity
import com.gh.gamecenter.feature.exposure.ExposureEvent
import com.gh.gamecenter.feature.exposure.ExposureType
import com.gh.gamecenter.feature.provider.ILinkDirectUtilsProvider
import com.gh.gamecenter.feature.entity.FloatingWindowEntity
import com.gh.gamecenter.feature.databinding.LayoutFloatingWindowItemBinding
import com.gh.gamecenter.home.custom.adapter.CustomBaseChildAdapter

class CustomFloatingWindowViewAdapter(
    context: Context,
    private var mCallback: Callback
) : CustomBaseChildAdapter<FloatingWindowEntity, CustomFloatingWindowViewAdapter.FloatingWindowItemViewHolder>(context) {
    var pageLocation: PageLocation? = null

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

    override fun getItemCount(): Int = if (dataList.size <= 1) dataList.size else Int.MAX_VALUE

    override fun onBindViewHolder(holder: FloatingWindowItemViewHolder, position: Int) {
        val realPosition = position % dataList.size

        val windowEntity = dataList[realPosition]

        val iv = holder.binding.imageIv
        val closeView = holder.binding.closeIv

        if (windowEntity.pushType == "always") {
            closeView.visibility = View.GONE
        } else {
            closeView.enlargeTouchArea(5)
            closeView.setOnClickListener {
                // 很丑陋，但暂时先这样处理
                _dataList.removeAt(realPosition)
                notifyDataSetChanged()
                mCallback.onItemDismissClickedCallback(realPosition)

                if (dataList.isEmpty()) {
                    mCallback.onDataListEmptyCallback()
                }

                SensorsBridge.trackSuspendedWindowClick(
                    "收起",
                    "关闭",
                    "自定义页面",
                    bottomTab = pageLocation?.bottomTab ?: "",
                    multiTabId = pageLocation?.severalTabPageId ?: "",
                    multiTabName = pageLocation?.severalTabPageName ?: "",
                    position = pageLocation?.tabPosition ?: -1,
                    tabContent = pageLocation?.tabContent ?: "",
                    customPageId = pageLocation?.pageId ?: "",
                    customPageName = pageLocation?.pageName ?: "",
                    linkId = windowEntity.link.link ?: "",
                    linkType = windowEntity.link.type ?: "",
                    linkText = windowEntity.link.text ?: "",
                )
            }
        }

        // 限制最大宽度为 256dp，后续根据图片大小进行处理
        iv.setTag(ImageUtils.TAG_TARGET_WIDTH, 256F.dip2px())
        // 添加加载回调，避免网络差出现图片没有但是有关闭按钮的情况
        iv.registerLoadingCallback(object : WrapContentDraweeView.LoadingCallback {
            override fun loaded() {
                if (windowEntity.pushType != "always") {
                    closeView.visibility = View.VISIBLE
                }
            }
        })
        iv.setMaxAndMinSizeLimit(64, 48)
        iv.setSubsampleSize(4)
        ImageUtils.display(iv, windowEntity.image)

        // 预加载需要展开的大图到本地，避免执行展开动画时图片为空
        if (windowEntity.expandable) {
            ImageUtils.prefetchToDiskCache(
                windowEntity.expandedImage)
        }

        holder.binding.imageIv.setOnClickListener {
            if (windowEntity.expandable) {
                windowEntity.link.icon = windowEntity.expandedImage

                windowEntity.link.floatingWindowId = windowEntity.id
                mCallback.onItemExpandCallback(windowEntity.link)

                SensorsBridge.trackSuspendedWindowClick(
                    "收起",
                    "展开",
                    "自定义页面",
                    bottomTab = pageLocation?.bottomTab ?: "",
                    multiTabId = pageLocation?.severalTabPageId ?: "",
                    multiTabName = pageLocation?.severalTabPageName ?: "",
                    position = pageLocation?.tabPosition ?: -1,
                    tabContent = pageLocation?.tabContent ?: "",
                    customPageId = pageLocation?.pageId ?: "",
                    customPageName = pageLocation?.pageName ?: "",
                    linkId = windowEntity.link.link ?: "",
                    linkType = windowEntity.link.type ?: "",
                    linkText = windowEntity.link.text ?: "",
                )
            } else {
                val directUtils = TheRouter.get(ILinkDirectUtilsProvider::class.java)
                if (windowEntity.link.type == EntranceConsts.HOST_WEB
                    || windowEntity.link.type == EntranceConsts.HOST_WEB_INURL
                    || windowEntity.link.type == EntranceConsts.HOST_WEB_AL
                ) {
                    val uri = Uri.parse(windowEntity.link.link)
                        .buildUpon()
                        .appendQueryParameter(Constants.URL_QUERY_FROM_FLOATING_WINDOW, "true")
                        .build()
                    windowEntity.link.link = uri.toString()
                }
                val clickEvent = ExposureEvent.createEvent(
                    GameEntity().apply { sequence = position },
                    source = windowEntity.link.traceEvent?.source ?: emptyList(),
                    event = ExposureType.CLICK,
                    eTrace = ExposureTraceUtils.appendTrace(windowEntity.link.traceEvent)
                )
                if (windowEntity.link.type != "game") {
                    ExposureManager.log(clickEvent)
                }
                directUtils?.directToLinkPage(it.context, windowEntity.link, "右下角悬浮窗", "", clickEvent)
                SensorsBridge.trackSuspendedWindowClick(
                    "收起",
                    "跳转",
                    "自定义页面",
                    bottomTab = pageLocation?.bottomTab ?: "",
                    multiTabId = pageLocation?.severalTabPageId ?: "",
                    multiTabName = pageLocation?.severalTabPageName ?: "",
                    position = pageLocation?.tabPosition ?: -1,
                    tabContent = pageLocation?.tabContent ?: "",
                    customPageId = pageLocation?.pageId ?: "",
                    customPageName = pageLocation?.pageName ?: "",
                    linkId = windowEntity.link.link ?: "",
                    linkType = windowEntity.link.type ?: "",
                    linkText = windowEntity.link.text ?: "",
                )
            }
        }
    }

    class FloatingWindowItemViewHolder(val binding: LayoutFloatingWindowItemBinding) :
        RecyclerView.ViewHolder(binding.root)

    interface Callback {
        fun onItemExpandCallback(entity: WelcomeDialogEntity)

        fun onItemDismissClickedCallback(position: Int)

        fun onDataListEmptyCallback()
    }

}