package com.gh.gamecenter.gamedetail.detail.adapter

import android.app.Activity
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.ViewGroup.MarginLayoutParams
import android.widget.LinearLayout
import androidx.core.view.forEach
import androidx.core.view.isVisible
import androidx.core.view.updateLayoutParams
import androidx.recyclerview.widget.RecyclerView
import com.facebook.drawee.drawable.ScalingUtils
import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder
import com.facebook.drawee.generic.RoundingParams
import com.facebook.drawee.view.SimpleDraweeView
import com.gh.common.util.LibaoUtils
import com.gh.common.util.NewLogUtils
import com.gh.gamecenter.ImageViewerActivity
import com.gh.gamecenter.common.databinding.RefreshFooterviewBinding
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.utils.MtaHelper
import com.gh.gamecenter.core.utils.SpanBuilder
import com.gh.gamecenter.databinding.ItemGameDetailMoreBinding
import com.gh.gamecenter.databinding.ItemGameLibaoBinding
import com.gh.gamecenter.feature.entity.LibaoEntity
import com.gh.gamecenter.gamedetail.detail.viewholder.BaseGameDetailItemViewHolder.GameDetailModuleTrackData
import com.gh.gamecenter.libao.LibaoDetailActivity
import com.gh.gamecenter.login.user.UserManager

class GameLibaoAdapter(
    val context: Context,
    var libaos: ArrayList<LibaoEntity>,
    val gameName: String,
    val gameId: String,
    showExpandIcon: Boolean = true,
    private val trackData: GameDetailModuleTrackData? = null,
    private val getGameStatus: (() -> String)? = null
) :
    RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    private var mIsExpand = false
    private val mShowItemCount: Int = if (showExpandIcon) 3 else Int.MAX_VALUE // 最多展示多少个礼包

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return when(viewType) {
            LIBAO_ITEM -> LibaoViewHolder(parent.toBinding())
            FOOTER_ITEM -> FooterViewHolder(parent.toBinding())
            else -> MoreViewHolder(ItemGameDetailMoreBinding.inflate(LayoutInflater.from(context), parent, false))
        }
    }

    override fun getItemViewType(position: Int): Int {
        return if (libaos.size > mShowItemCount) {
            if (!mIsExpand) {
                if (position == mShowItemCount) MORE else LIBAO_ITEM
            } else {
                if (position == libaos.size) MORE else LIBAO_ITEM
            }
        } else {
            LIBAO_ITEM
        }
    }

    override fun getItemCount(): Int {
        return if (libaos.size > mShowItemCount) {
            if (mIsExpand) libaos.size + 1 else mShowItemCount + 1
        } else {
            libaos.size
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when (holder) {
            is LibaoViewHolder -> {
                val libaoEntity = libaos[position]
                holder.bindItem(context, this, gameId, gameName, libaoEntity, trackData, getGameStatus)
            }
            is MoreViewHolder -> {
                holder.binding.arrowIv.rotation = if (mIsExpand) 180f else 0f
                holder.itemView.setOnClickListener {
                    if (!mIsExpand) MtaHelper.onEvent("游戏详情_新", "游戏礼包_展开", gameName)
                    mIsExpand = !mIsExpand
                    notifyDataSetChanged()
                    NewLogUtils.logGameDetailGiftClick(gameName, gameId, "展开")
                }
            }
            is FooterViewHolder -> {
                holder.binding.footerviewHint.setTextColor(com.gh.gamecenter.common.R.color.text_instance.toColor(context))
                holder.binding.footerviewHint.text = "没有更多内容了"
                holder.binding.footerviewLoading.isVisible = false
            }
        }
    }

    class LibaoViewHolder(var binding: ItemGameLibaoBinding) : RecyclerView.ViewHolder(binding.root) {
        fun bindItem(
            context: Context,
            adapter: RecyclerView.Adapter<*>,
            gameId: String,
            gameName: String,
            libaoEntity: LibaoEntity,
            gameDetailModuleTrackData: GameDetailModuleTrackData? = null,
            getGameStatus: (() -> String)? = null
        ) {
            val position = bindingAdapterPosition
            binding.root.updateLayoutParams<MarginLayoutParams> { topMargin = if (position == 0) 0 else 8F.dip2px() }
            binding.root.background = com.gh.gamecenter.common.R.drawable.bg_shape_f8_radius_8.toDrawable(context)
            binding.libaoNameTv.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(context))
            binding.contentTv.setTextColor(com.gh.gamecenter.common.R.color.text_tertiary.toColor(context))
            binding.remainingTv.setTextColor(com.gh.gamecenter.common.R.color.text_theme.toColor(context))
            binding.libaoCodeTv.setTextColor(com.gh.gamecenter.common.R.color.text_secondary.toColor(context))

            binding.libaoNameTv.text = libaoEntity.name
            binding.contentTv.text = libaoEntity.content?.fromHtml()

            binding.horizontalScrollView.goneIf(libaoEntity.materials.isEmpty()) {
                if (binding.imagesContainer.tag == libaoEntity.id) {
                    binding.imagesContainer.forEach { view ->
                        if (view is SimpleDraweeView) {
                            view.hierarchy.roundingParams = RoundingParams().apply {
                                setCornersRadius(4F.dip2px().toFloat())
                                setOverlayColor(com.gh.gamecenter.common.R.color.ui_container_1.toColor(context))
                            }
                        }
                    }
                    return@goneIf
                }
                binding.imagesContainer.removeAllViews()
                val imageViewList = arrayListOf<View>()
                libaoEntity.materials.forEachIndexed { index, material ->
                    binding.imagesContainer.addView(SimpleDraweeView(context).apply {
                        val roundingParams = RoundingParams().apply {
                            setCornersRadius(4F.dip2px().toFloat())
                            setOverlayColor(com.gh.gamecenter.common.R.color.ui_container_1.toColor(context))
                        }
                        hierarchy = GenericDraweeHierarchyBuilder(resources)
                            .setFadeDuration(500)
                            .setRoundingParams(roundingParams)
                            .setPlaceholderImage(com.gh.gamecenter.common.R.drawable.occupy, ScalingUtils.ScaleType.FIT_XY)
                            .build()
                        ImageUtils.display(this, material.img)
                    }.apply {
                        imageViewList.add(this)
                        setOnClickListener {
                            context.startActivity(ImageViewerActivity.getIntent(context, libaoEntity.getMaterialImgList(), index, imageViewList, null))
                        }
                    }, LinearLayout.LayoutParams(24F.dip2px(), 24F.dip2px()).apply {
                        setMargins(if (index != 0) 16F.dip2px() else 8F.dip2px(), 0, 0, 0)
                    })
                }
                binding.imagesContainer.tag = libaoEntity.id
            }

            val isTypeCopy = libaoEntity.receiveMethod == "copy"
            if (isTypeCopy) {
                // 类型为复制，不需要登录也能直接领取
                binding.libaoSchedulePb.visibility = View.GONE
                binding.remainingTv.visibility = View.GONE
                binding.libaoCodeTv.visibility = View.VISIBLE

                val text = "兑换码：${libaoEntity.code}"
                binding.libaoCodeTv.text = SpanBuilder(text).color(
                    binding.root.context,
                    4,
                    text.length,
                    com.gh.gamecenter.common.R.color.text_theme
                ).build()
                binding.copyLibaoCodeIv.visibility = View.VISIBLE
                binding.copyLibaoCodeIv.setOnClickListener {
                    binding.receiveTv.performClick()
                }
            } else if (libaoEntity.universal || libaoEntity.status == "check") {
                //通用码礼包/或者还未添加礼包码时，不显示进度条，显示礼包码
                binding.libaoSchedulePb.visibility = View.GONE
                binding.remainingTv.visibility = View.GONE
                binding.libaoCodeTv.visibility = View.VISIBLE
                binding.copyLibaoCodeIv.visibility = View.GONE

                if (!UserManager.getInstance().isLoggedIn) {
                    binding.libaoCodeTv.text = "礼包码：-"
                } else {
                    when (libaoEntity.status) {
                        "linged", "repeatLing", "repeatLinged", "taoed", "repeatTao", "repeatTaoed" -> {
                            val size = libaoEntity.me?.userDataLibaoList?.size ?: 0
                            val code = libaoEntity.me?.userDataLibaoList?.get(size - 1)?.code ?: ""
                            val text = "礼包码：$code"
                            binding.libaoCodeTv.text = SpanBuilder(text).color(
                                binding.root.context,
                                4,
                                text.length,
                                com.gh.gamecenter.common.R.color.text_theme
                            ).build()
                            binding.copyLibaoCodeIv.visibility = View.VISIBLE
                            binding.copyLibaoCodeIv.setOnClickListener {
                                code.copyTextAndToast("$code 复制成功")
                            }
                        }
                        else -> {
                            binding.libaoCodeTv.text = "礼包码：-"
                        }
                    }
                }
            } else {
                if (!UserManager.getInstance().isLoggedIn) {
                    binding.libaoSchedulePb.visibility = View.VISIBLE
                    binding.remainingTv.visibility = View.VISIBLE
                    binding.libaoCodeTv.visibility = View.GONE
                    binding.copyLibaoCodeIv.visibility = View.GONE

                    initProgressUI(libaoEntity)
                } else {
                    when (libaoEntity.status) {
                        "linged", "repeatLing", "repeatLinged", "taoed", "repeatTao", "repeatTaoed" -> {
                            binding.libaoSchedulePb.visibility = View.GONE
                            binding.remainingTv.visibility = View.GONE
                            binding.libaoCodeTv.visibility = View.VISIBLE

                            val size = libaoEntity.me?.userDataLibaoList?.size ?: 0
                            val code = libaoEntity.me?.userDataLibaoList?.get(size - 1)?.code ?: ""
                            val text = "礼包码：$code"
                            binding.libaoCodeTv.text = SpanBuilder(text).color(
                                binding.root.context,
                                4,
                                text.length,
                                com.gh.gamecenter.common.R.color.text_theme
                            ).build()
                            binding.copyLibaoCodeIv.visibility = View.VISIBLE
                            binding.copyLibaoCodeIv.setOnClickListener {
                                code.copyTextAndToast("$code 复制成功")
                            }
                        }
                        else -> {
                            binding.libaoSchedulePb.visibility = View.VISIBLE
                            binding.remainingTv.visibility = View.VISIBLE
                            binding.libaoCodeTv.visibility = View.GONE
                            binding.copyLibaoCodeIv.visibility = View.GONE

                            initProgressUI(libaoEntity)
                        }
                    }
                }

            }

//                LibaoUtils.setLiBaoBtnStatusRound(holder.binding.receiveTv, libaoEntity,true, context)
            LibaoUtils.initLibaoBtn(
                context,
                binding.receiveTv,
                libaoEntity,
                false,
                null,
                true,
                "游戏详情",
                "礼包列表页"
            ) {
                adapter.notifyItemChanged(position)
            }
            if (!libaoEntity.packageName.isNullOrEmpty()) {
                binding.receiveTv.setOnClickListener {
                    val intent = LibaoDetailActivity.getIntent(context, libaoEntity, true, "游戏详情")
                    if (it.context is Activity) {
                        (it.context as Activity).startActivityForResult(intent, LIBAO_REQUEST)
                    }
                }
            }
            itemView.setOnClickListener {
                if (isTypeCopy) {
                    // do nothing
                } else {
                    val intent = LibaoDetailActivity.getIntent(context, libaoEntity, "游戏详情")
                    if (it.context is Activity) {
                        (it.context as Activity).startActivityForResult(intent, LIBAO_REQUEST)
                    }

                    NewLogUtils.logGameDetailGiftClick(gameName, gameId, "礼包详情")
                    if (gameDetailModuleTrackData != null && getGameStatus != null) {
                        SensorsBridge.trackGameDetailModuleClick(
                            gameDetailModuleTrackData.gameId,
                            gameDetailModuleTrackData.gameName,
                            gameDetailModuleTrackData.gameType,
                            "组件内容",
                            gameDetailModuleTrackData.moduleType,
                            gameDetailModuleTrackData.moduleName,
                            gameDetailModuleTrackData.sequence,
                            libaoEntity.name,
                            position + 1,
                            "libao",
                            libaoEntity.id,
                            libaoEntity.name,
                            getGameStatus()
                        )
                    }
                }
            }
        }

        private fun initProgressUI(libaoEntity: LibaoEntity) {
            val total = libaoEntity.total
            val available = libaoEntity.available
            if (total != 0) {
                val availablePercent = (available) / total.toFloat() * 100
                val count = when {
                    availablePercent >= 1F -> {
                        availablePercent.toInt()
                    }
                    availablePercent == 0F -> {
                        0
                    }
                    else -> {
                        1
                    }
                }
                binding.remainingTv.text = "剩余${count}%"
                binding.libaoSchedulePb.progress = count
            }
        }
    }
    class MoreViewHolder(var binding: ItemGameDetailMoreBinding) : RecyclerView.ViewHolder(binding.root)
    class FooterViewHolder(var binding: RefreshFooterviewBinding) : RecyclerView.ViewHolder(binding.root)

    companion object {
        const val MORE = 0
        const val LIBAO_ITEM = 1
        const val FOOTER_ITEM = 2

        const val LIBAO_REQUEST = 100
    }
}