package com.gh.gamecenter.gamedetail.desc

import android.app.Activity
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.util.LibaoUtils
import com.gh.common.util.NewLogUtils
import com.gh.gamecenter.LibaoDetailActivity
import com.gh.gamecenter.R
import com.gh.gamecenter.common.callback.OnListClickListener
import com.gh.gamecenter.common.utils.copyTextAndToast
import com.gh.gamecenter.common.utils.fromHtml
import com.gh.gamecenter.common.utils.toBinding
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.entity.LibaoEntity
import com.gh.gamecenter.login.user.UserManager

class GameLibaoAdapter(
    val context: Context,
    val libaos: ArrayList<LibaoEntity>,
    val gameName: String,
    val gameId: String,
) :
    RecyclerView.Adapter<RecyclerView.ViewHolder>() {
    var mIsExpand = false
    private val mShowItemCount: Int = 3//最多展示多少个礼包
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return if (viewType == LIBAO_ITEM) {
            LibaoViewHolder(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]
                val isTypeCopy = libaoEntity.receiveMethod == "copy"

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

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

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

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

                        initProgressUI(libaoEntity, holder)
                    } else {
                        when (libaoEntity.status) {
                            "ling" -> {
                                holder.binding.libaoSchedulePb.visibility = View.VISIBLE
                                holder.binding.remainingTv.visibility = View.VISIBLE
                                holder.binding.libaoCodeTv.visibility = View.GONE

                                initProgressUI(libaoEntity, holder)
                            }
                            "linged", "repeatLing", "repeatLinged" -> {
                                holder.binding.libaoSchedulePb.visibility = View.GONE
                                holder.binding.remainingTv.visibility = View.GONE
                                holder.binding.libaoCodeTv.visibility = View.VISIBLE

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

                }

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

                        NewLogUtils.logGameDetailGiftClick(gameName, gameId, "礼包详情")
                    }
                }
            }
            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, "展开")
                }
            }
        }
    }

    private fun initProgressUI(libaoEntity: LibaoEntity, holder: LibaoViewHolder) {
        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
                }
            }
            holder.binding.remainingTv.text = "剩余${count}%"
            holder.binding.libaoSchedulePb.progress = count
        }
    }

    class LibaoViewHolder(var binding: ItemGameLibaoBinding) : RecyclerView.ViewHolder(binding.root)
    class MoreViewHolder(var binding: ItemGameDetailMoreBinding) : RecyclerView.ViewHolder(binding.root)

    companion object {
        const val MORE = 0
        const val LIBAO_ITEM = 1
    }
}