package com.gh.gamecenter.gamedetail.detail.viewholder

import android.graphics.Typeface
import android.view.ViewGroup
import android.view.ViewGroup.MarginLayoutParams
import androidx.constraintlayout.widget.ConstraintSet
import androidx.core.view.isVisible
import androidx.core.view.updateLayoutParams
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.util.DirectUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.utils.ExtraTagHandler
import com.gh.gamecenter.databinding.*
import com.gh.gamecenter.feature.view.DownloadButton
import com.gh.gamecenter.gamedetail.GameDetailViewModel
import com.gh.gamecenter.gamedetail.entity.GameDetailComprehensivePanelItem
import com.gh.gamecenter.gamedetail.entity.GameDetailComprehensivePanelItem.Companion.FUNCTION_TYPE_ONE_LINE_ONE_POINT
import com.gh.gamecenter.gamedetail.entity.GameDetailComprehensivePanelItem.Companion.SHOW_TYPE_PART
import com.gh.gamecenter.gamedetail.entity.GameDetailComprehensivePanelItem.ContentData
import com.gh.gamecenter.gamedetail.entity.GameDetailData
import splitties.views.topPadding

class GameDetailComprehensivePanelItemViewHolder(
    val binding: ItemGameDetailComprehensivePanelBinding,
    downloadBtn: DownloadButton?,
    viewModel: GameDetailViewModel
) : BaseGameDetailItemViewHolder(binding.root, downloadBtn, viewModel) {
    override fun bindView(data: GameDetailData) {
        super.bindView(data)
        val entity = data.linkComprehensive ?: return
        val dataList = entity.data ?: return
        binding.run {
            root.topPadding = if (entity.showName) 0 else 16F.dip2px()
            panelRv.background = com.gh.gamecenter.common.R.drawable.bg_shape_f8_radius_8.toDrawable(context)
            titleTv.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(context))
            titleTv.goneIf(!entity.showName) {
                titleTv.text = entity.name
            }
            if (panelRv.adapter !is ComprehensivePanelAdapter) {
                panelRv.isNestedScrollingEnabled = false
                (panelRv.itemAnimator as DefaultItemAnimator).supportsChangeAnimations = false
                panelRv.layoutManager = LinearLayoutManager(context)
                panelRv.adapter = ComprehensivePanelAdapter(dataList)
            } else {
                if (sequence != panelRv.tag) {
                    (panelRv.adapter as? ComprehensivePanelAdapter)?.dataList = dataList
                }
                panelRv.adapter?.run { notifyItemRangeChanged(0, itemCount) }
            }
            panelRv.tag = sequence
        }
    }

    inner class ComprehensivePanelAdapter(var dataList: List<GameDetailComprehensivePanelItem>) :
        RecyclerView.Adapter<RecyclerView.ViewHolder>() {
        override fun getItemViewType(position: Int): Int {
            val data = dataList[position]
            return when (data.type) {
                GameDetailComprehensivePanelItem.TYPE_FUNCTION -> ITEM_FUNCTION
                GameDetailComprehensivePanelItem.TYPE_FAQ -> ITEM_FAQ
                else -> ITEM_DECLARATION
            }
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            return when (viewType) {
                ITEM_FUNCTION -> ComprehensivePanelFunctionViewHolder(parent.toBinding())
                ITEM_FAQ -> ComprehensivePanelFAQViewHolder(parent.toBinding())
                else -> ComprehensivePanelDeclarationViewHolder(parent.toBinding())
            }
        }

        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            val data = dataList.getOrNull(position) ?: return
            if (holder is ComprehensivePanelFunctionViewHolder) {
                holder.binding.run {
                    root.updateLayoutParams<MarginLayoutParams> {
                        topMargin = if (position == 0) 0 else 8F.dip2px()
                    }
                    titleIv.goneIf(!data.showTitle)
                    titleTv.goneIf(!data.showTitle) {
                        titleTv.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(context))
                        titleTv.text = data.title
                    }
                    val contentData = data.data ?: return
                    holder.showPart = data.functionType == FUNCTION_TYPE_ONE_LINE_ONE_POINT && data.showType == SHOW_TYPE_PART
                    expandTv.isVisible = viewModel.comprehensivePanelExpandBtnStatusMap.getOrPut("${sequence}${position}") { holder.showPart && contentData.size > data.showRowNum }
                    expandTv.text = if (holder.isExpand) "收起" else "全部"
                    expandTv.setOnClickListener { _ ->
                        holder.isExpand = !holder.isExpand
                        (recyclerView.adapter as? ComprehensivePanelFunctionAdapter)?.dataList =
                            if (holder.showPart && !holder.isExpand) {
                                contentData.take(data.showRowNum)
                            } else {
                                contentData
                            }
                        recyclerView.adapter?.notifyDataSetChanged()
                        expandTv.text = if (holder.isExpand) "收起" else "全部"
                    }
                    val spanCount = if (data.functionType == FUNCTION_TYPE_ONE_LINE_ONE_POINT) 1 else 2
                    val finalContentData = if (holder.showPart && !holder.isExpand) {
                        contentData.take(data.showRowNum)
                    } else {
                        contentData
                    }
                    if (recyclerView.adapter !is ComprehensivePanelFunctionAdapter) {
                        recyclerView.isNestedScrollingEnabled = false
                        (recyclerView.itemAnimator as DefaultItemAnimator).supportsChangeAnimations = false
                        recyclerView.layoutManager = GridLayoutManager(context, spanCount)
                        recyclerView.adapter = ComprehensivePanelFunctionAdapter(data, finalContentData, holder)
                    } else {
                        (recyclerView.layoutManager as? GridLayoutManager)?.spanCount = spanCount
                        (recyclerView.adapter as? ComprehensivePanelFunctionAdapter)?.run {
                            dataList = finalContentData
                            notifyDataSetChanged()
                        }
                    }
                }
            }
            if (holder is ComprehensivePanelFAQViewHolder) {
                holder.binding.run {
                    root.updateLayoutParams<MarginLayoutParams> {
                        topMargin = if (position == 0) 0 else 16F.dip2px()
                        bottomMargin = if (position == itemCount - 1) 0 else if (data.showTitle) 12F.dip2px() else 8F.dip2px()
                    }
                    titleIv.goneIf(!data.showTitle)
                    titleTv.goneIf(!data.showTitle) {
                        titleTv.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(context))
                        titleTv.text = data.title
                    }
                    val contentData = data.data ?: return
                    if (recyclerView.adapter !is ComprehensivePanelFAQAdapter) {
                        recyclerView.isNestedScrollingEnabled = false
                        (recyclerView.itemAnimator as DefaultItemAnimator).supportsChangeAnimations = false
                        recyclerView.layoutManager = LinearLayoutManager(context)
                        recyclerView.adapter = ComprehensivePanelFAQAdapter(data.title, contentData)
                    } else {
                        (recyclerView.adapter as? ComprehensivePanelFAQAdapter)?.run {
                            dataList = contentData
                            notifyDataSetChanged()
                        }
                    }
                }
            }
            if (holder is ComprehensivePanelDeclarationViewHolder) {
                holder.binding.run {
                    root.updateLayoutParams<MarginLayoutParams> {
                        topMargin = if (position == 0) 0 else 12F.dip2px()
                    }
                    titleIv.goneIf(!data.showTitle)
                    titleTv.goneIf(!data.showTitle) {
                        titleTv.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(context))
                        titleTv.text = data.title
                    }
                    declarationTv.setTextColor(com.gh.gamecenter.common.R.color.text_tertiary.toColor(context))
                    declarationTv.setTextWithInterceptingInternalUrl(
                        data.declaration.dropFontColorInDarkMode(declarationTv.context)
                            .fromHtmlCompat(PicassoImageGetter(declarationTv), ExtraTagHandler())
                    )
                }
            }
        }

        override fun getItemCount(): Int = dataList.size
    }

    inner class ComprehensivePanelFunctionAdapter(
        private val gameDetailComprehensivePanelItem: GameDetailComprehensivePanelItem,
        var dataList: List<ContentData>,
        private val parentViewHolder: ComprehensivePanelFunctionViewHolder
    ) :
        RecyclerView.Adapter<ComprehensivePanelFunctionItemViewHolder>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ComprehensivePanelFunctionItemViewHolder =
            ComprehensivePanelFunctionItemViewHolder(parent.toBinding())

        override fun getItemCount(): Int = dataList.size

        override fun onBindViewHolder(holder: ComprehensivePanelFunctionItemViewHolder, position: Int) {
            val data = dataList.getOrNull(position) ?: return
            holder.binding.numberIv.goneIf(dataList.size < 2) {
                holder.binding.numberIv.setImageResource(R.drawable.bg_game_detail_comprehensive_panel_function_number)
            }
            holder.binding.numberTv.run {
                goneIf(dataList.size < 2) {
                    setTextColor(com.gh.gamecenter.common.R.color.text_aw_primary.toColor(context))
                    setTypeface(Typeface.createFromAsset(context.assets, Constants.DIN_FONT_PATH))
                    text = (position + 1).toString()
                }
            }
            holder.binding.contentTv.run {
                setTextColor(com.gh.gamecenter.common.R.color.text_secondary.toColor(context))
                maxLines = if (parentViewHolder.showPart && !parentViewHolder.isExpand) 1 else Int.MAX_VALUE
                text = data.text
                post {
                    if (layout == null) return@post

                    val hasEllipsize = layout.getEllipsisCount(0) > 0
                    if (parentViewHolder.showPart && hasEllipsize && !parentViewHolder.binding.expandTv.isVisible) {
                        parentViewHolder.binding.expandTv.isVisible = true
                        viewModel.comprehensivePanelExpandBtnStatusMap["${sequence}${parentViewHolder.bindingAdapterPosition}"] = true
                    }

                    // 计算最后一行是否有足够位置放下 全部/收起 按钮
                    if (position == itemCount - 1) {
                        val lastLine = layout.lineCount - 1
                        val lastLineString = text.substring(layout.getLineStart(lastLine), layout.getLineEnd(lastLine))
                        val distanceToEnd = width - paint.measureText(lastLineString)
                        val showExpandInTheLastLine = distanceToEnd >= parentViewHolder.binding.expandTv.width
                        ConstraintSet().apply {
                            clone(parentViewHolder.binding.root)
                            clear(parentViewHolder.binding.expandTv.id, ConstraintSet.TOP)
                            clear(parentViewHolder.binding.expandTv.id, ConstraintSet.BOTTOM)
                            if (showExpandInTheLastLine) {
                                connect(parentViewHolder.binding.expandTv.id, ConstraintSet.BOTTOM, parentViewHolder.binding.recyclerView.id, ConstraintSet.BOTTOM)
                            } else {
                                connect(parentViewHolder.binding.expandTv.id, ConstraintSet.TOP, parentViewHolder.binding.recyclerView.id, ConstraintSet.BOTTOM)
                                connect(parentViewHolder.binding.expandTv.id, ConstraintSet.BOTTOM, ConstraintSet.PARENT_ID, ConstraintSet.BOTTOM)
                            }
                        }.applyTo(parentViewHolder.binding.root)
                    }
                }
            }
            holder.binding.root.setOnClickListener { _ ->
                data.link?.let {
                    DirectUtils.directToLinkPage(context, it, "游戏详情-功能说明", "")
                    SensorsBridge.trackGameDetailModuleClick(
                        gameId,
                        gameName,
                        gameType,
                        "组件内容",
                        moduleType,
                        "功能说明",
                        sequence,
                        gameDetailComprehensivePanelItem.title,
                        position + 1,
                        it.type,
                        it.link,
                        it.text,
                        gameStatus
                    )
                }
            }
        }
    }

    inner class ComprehensivePanelFAQAdapter(private val subModuleName: String, var dataList: List<ContentData>) :
        RecyclerView.Adapter<ComprehensivePanelFAQItemViewHolder>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ComprehensivePanelFAQItemViewHolder =
            ComprehensivePanelFAQItemViewHolder(parent.toBinding())

        override fun getItemCount(): Int = dataList.size

        override fun onBindViewHolder(holder: ComprehensivePanelFAQItemViewHolder, position: Int) {
            val data = dataList.getOrNull(position) ?: return
            holder.binding.root.updateLayoutParams<MarginLayoutParams> {
                topMargin = if (position == 0) 0 else 8F.dip2px()
            }
            holder.binding.root.background = R.drawable.bg_shape_ui_surface_radius_4_item_style.toDrawable(context)
            holder.binding.contentTv.run {
                setTextColor(com.gh.gamecenter.common.R.color.text_secondary.toColor(context))
                text = data.text
            }
            holder.binding.arrowIv.goneIf(data.link == null) {
                holder.binding.arrowIv.setImageResource(R.drawable.ic_auxiliary_arrow_right_8)
            }
            holder.binding.root.setOnClickListener { _ ->
                data.link?.let {
                    DirectUtils.directToLinkPage(context, it, "游戏详情-功能说明", "")
                    SensorsBridge.trackGameDetailModuleClick(
                        gameId,
                        gameName,
                        gameType,
                        "组件内容",
                        moduleType,
                        "功能说明",
                        sequence,
                        subModuleName,
                        position + 1,
                        it.type,
                        it.link,
                        it.text,
                        gameStatus
                    )
                }
            }
        }
    }

    inner class ComprehensivePanelFunctionViewHolder(val binding: ItemGameDetailComprehensivePanelRvBinding) :
        RecyclerView.ViewHolder(binding.root) {
        var showPart: Boolean = false
        var isExpand = false
            get() = viewModel.comprehensivePanelExpandTextStatusMap.getOrPut("${sequence}${bindingAdapterPosition}") { !showPart }
            set(value) {
                viewModel.comprehensivePanelExpandTextStatusMap["${sequence}${bindingAdapterPosition}"] = value
                field = value
            }
    }

    inner class ComprehensivePanelFAQViewHolder(val binding: ItemGameDetailComprehensivePanelRvBinding) :
        RecyclerView.ViewHolder(binding.root)

    inner class ComprehensivePanelDeclarationViewHolder(val binding: ItemGameDetailComprehensivePanelDeclarationBinding) :
        RecyclerView.ViewHolder(binding.root)

    inner class ComprehensivePanelFunctionItemViewHolder(val binding: ItemGameDetailComprehensivePanelFunctionBinding) :
        RecyclerView.ViewHolder(binding.root)

    inner class ComprehensivePanelFAQItemViewHolder(val binding: ItemGameDetailComprehensivePanelFaqBinding) :
        RecyclerView.ViewHolder(binding.root)

    companion object {
        const val ITEM_FUNCTION = 0
        const val ITEM_FAQ = 1
        const val ITEM_DECLARATION = 2
    }
}