package com.gh.gamecenter.floatingwindow

import android.net.Uri
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.therouter.TheRouter
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.common.view.WrapContentDraweeView
import com.gh.gamecenter.feature.entity.FloatingWindowEntity
import com.gh.gamecenter.feature.provider.ILinkDirectUtilsProvider
import com.gh.gamecenter.feature.databinding.LayoutFloatingWindowItemBinding

class FloatingWindowViewAdapter(
    private var mGameId: String,
    private var mGameName: String,
    private var mLocation: String,
    private var mDataList: ArrayList<FloatingWindowEntity> = arrayListOf(),
    private var mCallback: Callback
) : RecyclerView.Adapter<FloatingWindowViewAdapter.FloatingWindowItemViewHolder>() {

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

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

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

        val windowEntity = mDataList[realPosition]

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

        // 记录曝光
        val exposureEvent = FloatingWindowManager.logExposure(mGameId, windowEntity.id)

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

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

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

                LogUtils.logFloatingWindowClicked(
                    action = "关闭悬浮窗",
                    windowId = windowEntity.id,
                    source = if (mGameId.isEmpty()) "首页" else "游戏详情",
                    gameId = mGameId,
                    gameName = mGameName,
                    linkId = windowEntity.link.link ?: "",
                    linkType = windowEntity.link.type ?: "",
                    linkText = windowEntity.link.text ?: ""
                )
                SensorsBridge.trackSuspendedWindowClick(
                    "收起",
                    "关闭",
                    mLocation,
                    gameId = mGameId,
                    gameName = mGameName,
                    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)

        holder.binding.imageIv.setOnClickListener {
            val directUtils = TheRouter.get(ILinkDirectUtilsProvider::class.java)

            // 仅页面为首页-推荐，且可展开为大图时才执行回调
            if (windowEntity.expandable && mGameId.isEmpty()) {
                mCallback.onItemExpandCallback(realPosition)
                return@setOnClickListener
            }

            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()
            }

            directUtils?.directToLinkPage(it.context, windowEntity.link, "右下角悬浮窗", "", exposureEvent)

            LogUtils.logFloatingWindowClicked(
                action = "点击悬浮窗跳转页面",
                windowId = windowEntity.id,
                source = if (mGameId.isEmpty()) "首页" else "游戏详情",
                gameId = mGameId,
                gameName = mGameName,
                linkId = windowEntity.link.link ?: "",
                linkType = windowEntity.link.type ?: "",
                linkText = windowEntity.link.text ?: ""
            )
            SensorsBridge.trackSuspendedWindowClick(
                "收起",
                "跳转",
                mLocation,
                gameId = mGameId,
                gameName = mGameName,
                linkId = windowEntity.link.link ?: "",
                linkType = windowEntity.link.type ?: "",
                linkText = windowEntity.link.text ?: ""
            )
        }
    }

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

    interface Callback {
        fun onItemExpandCallback(position: Int)

        fun onItemDismissClickedCallback(position: Int)

        fun onDataListEmptyCallback()
    }

}