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

import android.content.Context
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.lifecycle.LifecycleOwner
import com.gh.common.constant.Config
import com.gh.common.util.DirectUtils
import com.gh.common.util.NewFlatLogUtils
import com.gh.gamecenter.ShellActivity
import com.gh.gamecenter.ShellActivity.Type
import com.gh.gamecenter.WebActivity
import com.gh.gamecenter.common.entity.LinkEntity
import com.gh.gamecenter.common.exposure.ExposureSource
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.common.view.TextBannerView
import com.gh.gamecenter.core.utils.TimeUtils
import com.gh.gamecenter.databinding.ItemGameDetailContentCardSingleBinding
import com.gh.gamecenter.databinding.LayoutGameDetailContentCardBinding
import com.gh.gamecenter.feature.entity.MeEntity
import com.gh.gamecenter.feature.exposure.ExposureEvent
import com.gh.gamecenter.feature.view.DownloadButton
import com.gh.gamecenter.gamedetail.GameDetailViewModel
import com.gh.gamecenter.gamedetail.entity.CardBackground
import com.gh.gamecenter.gamedetail.entity.ContentCardEntity
import com.gh.gamecenter.gamedetail.entity.ContentCardEntity.Companion.TYPE_ARCHIVE
import com.gh.gamecenter.gamedetail.entity.ContentCardEntity.Companion.TYPE_BBS
import com.gh.gamecenter.gamedetail.entity.ContentCardEntity.Companion.TYPE_GIFT
import com.gh.gamecenter.gamedetail.entity.ContentCardEntity.Companion.TYPE_RELATED_VERSION
import com.gh.gamecenter.gamedetail.entity.ContentCardEntity.Companion.TYPE_SERVER
import com.gh.gamecenter.gamedetail.entity.ContentCardEntity.Companion.TYPE_TOOLKIT
import com.gh.gamecenter.gamedetail.entity.ContentCardEntity.Companion.TYPE_ZONE
import com.gh.gamecenter.gamedetail.entity.GameDetailData
import com.gh.gamecenter.gamedetail.entity.GameDetailTabEntity
import com.gh.gamecenter.gamedetail.fuli.kaifu.ServersCalendarActivity
import com.gh.gamecenter.gamedetail.libao.LibaoListFragment
import com.gh.gamecenter.livedata.Event
import com.gh.gamecenter.newsdetail.NewsDetailActivity
import kotlin.math.abs

class GameDetailContentCardSingleItemViewHolder(
    val binding: ItemGameDetailContentCardSingleBinding,
    downloadBtn: DownloadButton?,
    viewModel: GameDetailViewModel,
    private val lifecycleOwner: LifecycleOwner,
) : BaseGameDetailItemViewHolder(binding.root, downloadBtn, viewModel) {

    override fun bindView(data: GameDetailData) {
        super.bindView(data)
        val contentCardEntity = data.linkContentCard?.first() ?: return
        binding.run {
            bindContentCard(
                lifecycleOwner,
                viewModel,
                contentCardEntity,
                data.cardBackground,
                firstCardContainer,
                baseTrackData.apply { supSequence = 0 }
            ) { gameStatus }
        }
    }

    companion object {
        fun bindContentCard(
            lifecycleOwner: LifecycleOwner,
            viewModel: GameDetailViewModel,
            contentCardEntity: ContentCardEntity,
            cardBackground: CardBackground?,
            itemBinding: LayoutGameDetailContentCardBinding,
            trackData: GameDetailModuleTrackData,
            getGameStatus: () -> String
        ) {
            with(itemBinding) {
                val context = root.context
                if (contentCardEntity.id == root.tag) {
                    if (contentBannerView.isVisible) contentBannerView.updateView()
                    cardBackground?.colorTransparent?.let {
                        root.setRoundedColorBackgroundByColorInt(
                            it.RGBAToARGB().hexStringToIntColor(),
                            8F
                        )
                    } ?: run {
                        root.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))
                    contentTv.setTextColor(com.gh.gamecenter.common.R.color.text_tertiary.toColor(context))

                    return@with
                }

                root.tag = contentCardEntity.id
                cardBackground?.colorTransparent?.let {
                    root.setRoundedColorBackgroundByColorInt(
                        it.RGBAToARGB().hexStringToIntColor(),
                        8F
                    )
                }
                titleTv.text = contentCardEntity.title
                ImageUtils.display(iconIv, contentCardEntity.icon)

                val showContentTv =
                    contentCardEntity.showDes && (contentCardEntity.des.isNotEmpty() || contentCardEntity.link.type == TYPE_GIFT)
                contentTv.visibleIf(showContentTv) {
                    contentTv.text =
                        if (contentCardEntity.link.type == TYPE_GIFT && contentCardEntity.des.isEmpty()) "${contentCardEntity.libao?.total}个游戏礼包" else contentCardEntity.des
                    contentTv.setTextColor(com.gh.gamecenter.common.R.color.text_tertiary.toColor(context))
                }

                val showContentBannerView =
                    contentCardEntity.showDes && contentCardEntity.link.type == TYPE_SERVER && contentCardEntity.server != null && contentCardEntity.des.isEmpty()
                contentBannerView.goneIf(!showContentBannerView) {
                    val server = contentCardEntity.server ?: return@goneIf
                    val nowTime = System.currentTimeMillis()
                    var timeDiff = 0L
                    var closestIndex = 0
                    val bannerTextDataList = server.calendar.mapIndexed { index, serverCalendarEntity ->
                        val diff = abs(nowTime - serverCalendarEntity.getTime() * 1000L)
                        if (diff < timeDiff || index == 0) {
                            timeDiff = diff
                            closestIndex = index
                        }
                        val serverTime =
                            if (TimeUtils.isToday(serverCalendarEntity.getTime()))
                                serverCalendarEntity.getFormatTime("今天 HH:mm")
                            else if (TimeUtils.isTomorrow(serverCalendarEntity.getTime()))
                                serverCalendarEntity.getFormatTime("明天 HH:mm")
                            else
                                serverCalendarEntity.getFormatTime("MM-dd HH:mm")
                        TextBannerView.BannerTextData("${serverTime ?: ""} ${serverCalendarEntity.type}")
                    }
                    contentBannerView.setDataList(bannerTextDataList, closestIndex)
                    contentBannerView.startBannerLoop()
                }

                val showRedDot = contentCardEntity.redDot != 0 && viewModel.shouldShowContentCardRedDot(contentCardEntity)
                redDotTv.goneIf(!showRedDot) {
                    redDotTv.text = contentCardEntity.redDot.toString()
                }

                val showNewTag = contentCardEntity.link.type == TYPE_ARCHIVE && contentCardEntity.archive != null && contentCardEntity.showNewTag
                newIv.goneIf(!showNewTag)

                root.setOnClickListener {
                    NewFlatLogUtils.logGameDetailGameContentCardClick(
                        contentCardEntity.title ?: "",
                        viewModel.game?.name ?: "",
                        viewModel.game?.id ?: "",
                        contentCardEntity.link.type ?: "",
                        contentCardEntity.link.link ?: "",
                        contentCardEntity.link.text ?: ""
                    )
                    SensorsBridge.trackGameDetailModuleClick(
                        gameId = trackData.gameId,
                        gameName = trackData.gameName,
                        gameType = trackData.gameType,
                        contentType = "组件内容",
                        moduleType = trackData.moduleType,
                        moduleName = trackData.moduleName,
                        sequence = trackData.sequence,
                        linkText = contentCardEntity.link.text ?: "",
                        linkType = contentCardEntity.link.type ?: "",
                        linkId = contentCardEntity.id,
                        gameStatus = getGameStatus()
                    )

                    val dialog = contentCardEntity.dialog
                    if (dialog != null) {// 展示内容卡片提示弹窗
                        DialogHelper.showDialog(
                            context = context,
                            title = dialog.title ?: "",
                            content = dialog.body ?: "",
                            confirmText = context.getString(com.gh.gamecenter.common.R.string.confirm),
                            cancelText = context.getString(com.gh.gamecenter.common.R.string.cancel),
                            confirmClickCallback = {
                                jumpToContentCardLink(context, contentCardEntity, viewModel, redDotTv)
                            }
                        )
                    } else {
                        jumpToContentCardLink(context, contentCardEntity, viewModel, redDotTv)
                    }
                }

                viewModel.contentCardClickedLiveData.observe(lifecycleOwner) {
                    if (it.peekContent() == contentCardEntity.link.type) {
                        it.getContentWithHandled()?.let { root.performClick() }
                    }
                }
            }
        }

        fun jumpToContentCardLink(context: Context, contentCardEntity: ContentCardEntity, viewModel: GameDetailViewModel, redDotTv: TextView) {
            val path = "游戏详情->内容卡片"
            when (contentCardEntity.link.type) {
                TYPE_GIFT,
                TYPE_ARCHIVE -> {
                    if (contentCardEntity.link.type == TYPE_GIFT) {
                        viewModel.markContentCardRedDot(contentCardEntity)
                        redDotTv.isVisible = false
                    }

                    val type = if (contentCardEntity.link.type == TYPE_GIFT) GameDetailTabEntity.TYPE_GIFT else GameDetailTabEntity.TYPE_ARCHIVE
                    val tabList = viewModel.gameDetailTabListLiveData.value?.data
                    if (tabList?.find { it.type == type } != null) {
                        viewModel.performTabSelected(type)
                    } else if (contentCardEntity.link.type == TYPE_GIFT) {
                        val bundle = LibaoListFragment.getBundle(viewModel.game, false)
                        context.startActivity(ShellActivity.getIntent(context, Type.SIMPLE_LIBAO_LIST, bundle))
                    } else if (contentCardEntity.link.type == TYPE_ARCHIVE) {
                        DirectUtils.directToCloudArchive(context, viewModel.game?.id ?: "", viewModel.game?.name ?: "", "", "游戏详情页-内容卡片")
                    }
                }

                TYPE_SERVER -> {
                    if (viewModel.game != null && contentCardEntity.server != null) {
                        viewModel.markContentCardRedDot(contentCardEntity)
                        redDotTv.isVisible = false
                        context.startActivity(
                            ServersCalendarActivity.getIntent(
                                context,
                                viewModel.game!!, contentCardEntity.server!!,
                                viewModel.meLiveData.value ?: MeEntity()
                            )
                        )
                    }
                }

                TYPE_RELATED_VERSION -> {
                    viewModel.scrollToListPositionLiveData.postValue(Event(LinkEntity(type = GameDetailData.TYPE_RELATED_GAME)))
                }

                TYPE_ZONE -> {
                    if (contentCardEntity.zoneTab && viewModel.game?.zone != null && viewModel.game?.zone!!.style == "link") {
                        context.startActivity(
                            WebActivity.getIntent(
                                context,
                                viewModel.game?.zone!!.link,
                                true
                            )
                        )
                    }
                }

                TYPE_BBS -> {
                    val funcBbs = contentCardEntity.funcBbs
                    funcBbs?.let {
                        DirectUtils.directForumDetail(context, it.link, path)
                    }
                }

                TYPE_TOOLKIT -> {
                    if (contentCardEntity.toolkit.isNotEmpty()) {
                        contentCardEntity.toolkit.safelyGetInRelease(0)?.let {
                            val url = it.url
                            if (url != null && url.contains(Config.URL_ARTICLE)) {
                                val newsId = url.substring(url.lastIndexOf("/") + 1, url.length - 5) // 5: ".html"
                                val intent = NewsDetailActivity.getIntentById(context, newsId, path)
                                context.startActivity(intent)
                            } else {
                                context.startActivity(
                                    WebActivity.getWebByCollectionTools(
                                        context,
                                        it,
                                        false
                                    )
                                )
                            }
                        }
                    }
                }

                else -> DirectUtils.directToLinkPage(
                    context,
                    contentCardEntity.link,
                    viewModel.entrance ?: "",
                    path,
                    ExposureEvent.createEvent(
                        null,
                        listOf(
                            ExposureSource("游戏详情", viewModel.game?.id ?: ""),
                            ExposureSource("内容卡片", contentCardEntity.id)
                        )
                    ),
                    "游戏详情页-内容卡片"
                )
            }
        }
    }
}