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

import android.content.Context
import android.graphics.PorterDuff
import android.graphics.PorterDuffColorFilter
import android.view.Gravity
import android.view.ViewGroup
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.DefaultUrlHandler
import com.gh.common.util.DirectUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.WebActivity
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.utils.ExtraTagHandler
import com.gh.gamecenter.core.utils.TimeUtils
import com.gh.gamecenter.databinding.ItemGameDetailInfoBinding
import com.gh.gamecenter.databinding.SubItemGameDetailInfoBinding
import com.gh.gamecenter.feature.entity.GameInfo
import com.gh.gamecenter.feature.view.DownloadButton
import com.gh.gamecenter.gamedetail.GameDetailViewModel
import com.gh.gamecenter.gamedetail.dialog.GameInfoDialogFragment
import com.gh.gamecenter.gamedetail.dialog.GamePermissionDialogFragment
import com.gh.gamecenter.gamedetail.entity.GameDetailData
import com.gh.gamecenter.gamedetail.entity.GameDetailInfo

class GameDetailInfoItemViewHolder(
    val binding: ItemGameDetailInfoBinding,
    downloadBtn: DownloadButton?,
    viewModel: GameDetailViewModel
) :
    BaseGameDetailItemViewHolder(binding.root, downloadBtn, viewModel) {
    override fun bindView(data: GameDetailData) {
        super.bindView(data)
        val entity = data.linkInfo ?: return
        binding.run {
            container.background = R.drawable.bg_shape_f8_radius_8.toDrawable(context)
            titleTv.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(context))
            moreTv.setTextColor(com.gh.gamecenter.common.R.color.text_theme.toColor(context))
            moreTv.setDrawableEnd(R.drawable.ic_auxiliary_arrow_right_text_theme_12.toDrawable(context))
            titleTv.text = entity.name
            divider1.setBackgroundColor(com.gh.gamecenter.common.R.color.ui_divider.toColor(context))

            bindStaticInfo(context, entity, viewModel, privacyPolicyTv, permissionsTv, requestUpdateTv, desTv) {
                SensorsBridge.trackGameDetailModuleClick(
                    gameId,
                    gameName,
                    gameType,
                    "组件内容",
                    moduleType,
                    entity.name,
                    sequence,
                    it,
                    gameStatus = gameStatus
                )
            }

            divider2.goneIf(entity.des.isEmpty()) {
                divider2.setBackgroundColor(com.gh.gamecenter.common.R.color.ui_divider.toColor(context))
            }
            moreTv.setOnClickListener {
                GameInfoDialogFragment.show(context, viewModel.game, entity)
                SensorsBridge.trackGameDetailModuleClick(
                    gameId,
                    gameName,
                    gameType,
                    "右上角",
                    moduleType,
                    entity.name,
                    sequence,
                    gameStatus = gameStatus
                )
            }

            if (gameInfoRv.adapter !is InfoItemAdapter) {
                val normalTypeKeys = normalTypeNameMap.keys
                val showFirstList = entity.fields.filter { normalTypeKeys.contains(it.name) && it.isFirst }.sortedBy { it.order }
                gameInfoRv.isNestedScrollingEnabled = false
                (gameInfoRv.itemAnimator as DefaultItemAnimator).supportsChangeAnimations = false
                gameInfoRv.layoutManager = LinearLayoutManager(context)
                gameInfoRv.adapter = InfoItemAdapter(showFirstList)
            } else {
                gameInfoRv.adapter?.run { notifyItemRangeChanged(0, itemCount) }
            }
        }
    }

    inner class InfoItemAdapter(val dataList: List<GameDetailInfo.InfoItem>) :
        RecyclerView.Adapter<RecyclerView.ViewHolder>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder =
            InfoItemViewHolder(parent.toBinding()) {
                SensorsBridge.trackGameDetailModuleClick(
                    gameId,
                    gameName,
                    gameType,
                    "组件内容",
                    moduleType,
                    itemData?.linkInfo?.name,
                    sequence,
                    gameStatus = gameStatus
                )
            }

        override fun getItemCount(): Int = dataList.size

        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            val data = dataList.getOrNull(position) ?: return
            if (holder is InfoItemViewHolder) {
                holder.bindInfoItem(context, data)
            }
        }
    }

    class InfoItemViewHolder(val binding: SubItemGameDetailInfoBinding, private val onClickAction: (() -> Unit)? = null) : RecyclerView.ViewHolder(binding.root) {
        fun bindInfoItem(context: Context, data: GameDetailInfo.InfoItem) {
            binding.run {
                nameTv.setTextColor(com.gh.gamecenter.common.R.color.text_tertiary.toColor(context))
                infoTv.setTextColor(if (data.name == TYPE_ICP) com.gh.gamecenter.common.R.color.text_theme.toColor(context) else com.gh.gamecenter.common.R.color.text_secondary.toColor(context))
                actionTv.setTextColor(com.gh.gamecenter.common.R.color.text_theme.toColor(context))
                nameTv.text = if (data.name == TYPE_CONTACT) data.text else normalTypeNameMap[data.name]
                infoTv.text = when (data.name) {
                    TYPE_INTERNET -> if (data.value == "yes") "是" else "否"
                    TYPE_UPDATE_TIME -> data.value.toLongOrNull()?.let { TimeUtils.getFormatTime(it) }
                    else -> data.value
                }
                actionTv.goneIf(data.name != TYPE_CONTACT) {
                    val actionString = if (data.type == "qq") ACTION_CONTACT else if (data.key.isNotEmpty()) ACTION_JOIN else ACTION_COPY
                    actionTv.text = actionString
                    actionTv.setOnClickListener {
                        when (actionString) {
                            ACTION_CONTACT -> {
                                if (ShareUtils.isQQClientAvailable(context)) {
                                    DirectUtils.directToQqConversation(context, data.value)
                                } else {
                                    data.value.copyTextAndToast("已复制")
                                }
                            }

                            ACTION_JOIN -> {
                                if (ShareUtils.isQQClientAvailable(context)) {
                                    DirectUtils.directToQqGroup(context, data.key)
                                } else {
                                    data.value.copyTextAndToast("已复制")
                                }
                            }

                            ACTION_COPY -> {
                                data.value.copyTextAndToast("已复制")
                            }
                        }
                    }
                }
                infoTv.post {
                    val width = infoTv.width - infoTv.compoundPaddingLeft - infoTv.compoundPaddingRight
                    if (infoTv.paint.measureText(infoTv.text.toString()) > width) {
                        infoTv.gravity = Gravity.CENTER_VERTICAL
                        infoTv.isSelected = true
                    }
                }
                infoTv.setOnClickListener {
                    when (data.name) {
                        TYPE_ICP -> {
                            DirectUtils.directToExternalBrowser(context, context.getString(com.gh.gamecenter.common.R.string.icp_url))
                        }
                        else -> {
                            infoTv.marqueeAgain()
                        }
                    }
                    onClickAction?.invoke()
                }
            }
        }
    }

    companion object {
        const val TYPE_PRIVACY_POLICY = "privacy_policy_url"
        const val TYPE_PERMISSIONS = "permissions"
        const val TYPE_REQUEST_UPDATE = "request_update_status"

        const val TYPE_INTERNET = "internet_app"
        const val TYPE_ICP = "ICP"
        const val TYPE_DEVELOPER = "developer"
        const val TYPE_PUBLISHER = "publisher"
        const val TYPE_MANUFACTURER = "manufacturer"
        const val TYPE_VERSION = "version"
        const val TYPE_UPDATE_TIME = "update_time"
        const val TYPE_RECOMMEND_AGE = "recommend_age"
        const val TYPE_CREDIT_CODE = "credit_code"
        const val TYPE_SIZE = "size"
        const val TYPE_SUPPLIER = "supplier"
        const val TYPE_CONTACT = "qq/qq_qun"

        const val ACTION_COPY = "复制"
        const val ACTION_JOIN = "加入"
        const val ACTION_CONTACT = "添加"

        // 固定信息类型
        val staticTypeNameMap = mapOf(
            TYPE_PRIVACY_POLICY to "隐私政策",
            TYPE_PERMISSIONS to "权限及用途",
            TYPE_REQUEST_UPDATE to "版本求更新"
        )

        val normalTypeNameMap = mapOf(
            TYPE_INTERNET to "联网App",
            TYPE_ICP to "ICP备案号",
            TYPE_DEVELOPER to "开发者",
            TYPE_PUBLISHER to "发行商",
            TYPE_MANUFACTURER to "厂商",
            TYPE_VERSION to "当前版本",
            TYPE_UPDATE_TIME to "更新时间",
            TYPE_RECOMMEND_AGE to "适龄等级",
            TYPE_CREDIT_CODE to "统一社会信用代码",
            TYPE_SIZE to "游戏大小",
            TYPE_SUPPLIER to "供应商",
            TYPE_CONTACT to ""
        )

        fun bindStaticInfo(
            context: Context,
            entity: GameDetailInfo,
            viewModel: GameDetailViewModel,
            privacyPolicyTv: TextView,
            permissionsTv: TextView,
            requestUpdateTv: TextView,
            desTv: TextView,
            onClickAction: ((String) -> Unit)? = null
        ) {
            val privacyPolicyInfo = entity.fields.find { it.name == TYPE_PRIVACY_POLICY }
            privacyPolicyTv.goneIf(privacyPolicyInfo == null) {
                privacyPolicyTv.setTextColor(com.gh.gamecenter.common.R.color.text_secondary.toColor(context))
                privacyPolicyTv.setDrawableEnd(R.drawable.ic_auxiliary_arrow_right_8.toDrawable(context)?.apply {
                    colorFilter = PorterDuffColorFilter(com.gh.gamecenter.common.R.color.text_secondary.toColor(context), PorterDuff.Mode.SRC_ATOP)
                })
                privacyPolicyTv.setOnClickListener {
                    privacyPolicyInfo?.value?.let {
                        if (!DefaultUrlHandler.transformNormalScheme(context, it, "隐私政策", "")) {
                            val intent = WebActivity.getIntent(context, it, "隐私政策", false, false)
                            context.startActivity(intent)
                        }
                    }
                    onClickAction?.invoke("隐私政策")
                }
            }

            val permissionsInfo = entity.fields.find { it.name == TYPE_PERMISSIONS }
            permissionsTv.goneIf(permissionsInfo == null) {
                permissionsTv.setTextColor(com.gh.gamecenter.common.R.color.text_secondary.toColor(context))
                permissionsTv.setDrawableEnd(R.drawable.ic_auxiliary_arrow_right_8.toDrawable(context)?.apply {
                    colorFilter = PorterDuffColorFilter(com.gh.gamecenter.common.R.color.text_secondary.toColor(context), PorterDuff.Mode.SRC_ATOP)
                })
                permissionsTv.setOnClickListener {
                    var version = ""
                    var manufacturerType = ""
                    var manufacturer = ""
                    var privacyPolicyUrl = ""
                    entity.fields.forEach {
                        when (it.name) {
                            TYPE_DEVELOPER, TYPE_PUBLISHER, TYPE_MANUFACTURER -> {
                                manufacturerType = it.name
                                manufacturer = it.value
                            }
                            TYPE_VERSION -> version = it.value
                            TYPE_PRIVACY_POLICY -> privacyPolicyUrl = it.value
                        }
                    }
                    val gameInfo = GameInfo(
                        version = version,
                        manufacturerType = manufacturerType,
                        manufacturer = manufacturer,
                        privacyPolicyUrl = privacyPolicyUrl,
                        permissions = permissionsInfo?.permissions
                    )
                    GamePermissionDialogFragment.show(context as AppCompatActivity, viewModel.game, gameInfo)
                    onClickAction?.invoke("权限及用途")
                }
            }

            val requestUpdateInfo = entity.fields.find { it.name == TYPE_REQUEST_UPDATE }
            requestUpdateTv.goneIf(requestUpdateInfo == null || requestUpdateInfo.value == "off") {
                requestUpdateTv.setTextColor(com.gh.gamecenter.common.R.color.text_theme.toColor(context))
                requestUpdateTv.setDrawableEnd(R.drawable.ic_auxiliary_arrow_right_8.toDrawable(context)?.apply {
                    colorFilter = PorterDuffColorFilter(com.gh.gamecenter.common.R.color.text_theme.toColor(context), PorterDuff.Mode.SRC_ATOP)
                })
                requestUpdateTv.setOnClickListener {
                    DialogHelper.showDialog(
                        context, "版本求更新", "如果游戏上线了新版本，您可以提交申请，让小助手尽快更新版本喔！",
                        "提交申请", "取消", {
                            viewModel.sendSuggestion()
                        }, extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true)
                    )
                    onClickAction?.invoke("版本求更新")
                }
            }

            desTv.goneIf(entity.des.isEmpty()) {
                desTv.setTextWithInterceptingInternalUrl(
                    entity.des.dropFontColorInDarkMode(desTv.context)
                        .fromHtmlCompat(PicassoImageGetter(desTv), ExtraTagHandler())
                )
            }
        }
    }
}