package com.gh.gamecenter.home.custom.viewholder

import android.view.View
import androidx.annotation.CallSuper
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.exposure.IExposable
import com.gh.common.util.AdHelper
import com.gh.common.util.NewFlatLogUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.common.exposure.ExposureSource
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.utils.MtaHelper
import com.gh.gamecenter.databinding.LayoutTitleCustomBinding
import com.gh.gamecenter.eventbus.EBDownloadStatus
import com.gh.gamecenter.eventbus.EBPackage
import com.gh.gamecenter.feature.entity.CustomPageTrackData
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.feature.entity.PageLocation
import com.gh.gamecenter.feature.exposure.ExposureConstants
import com.gh.gamecenter.feature.exposure.ExposureEvent
import com.gh.gamecenter.home.PageConfigure
import com.gh.gamecenter.home.custom.CustomPageViewModel
import com.gh.gamecenter.home.custom.IGameChangedNotifier
import com.gh.gamecenter.home.custom.OnViewHolderAttachListener
import com.gh.gamecenter.home.custom.createExposureEvent
import com.gh.gamecenter.home.custom.eventlistener.CustomPageItemChildEventHelper
import com.gh.gamecenter.home.custom.eventlistener.GameSubjectCollectionEventHelper
import com.gh.gamecenter.home.custom.eventlistener.SubjectEventHelper
import com.gh.gamecenter.home.custom.model.CustomPageItem
import com.gh.gamecenter.home.custom.model.CustomSplitSubjectItem
import com.gh.gamecenter.home.custom.model.CustomSubjectCollectionItem
import com.gh.gamecenter.home.custom.model.CustomSubjectItem
import com.lightgame.download.DownloadEntity

abstract class BaseCustomViewHolder(
    val viewModel: CustomPageViewModel,
    itemView: View
) : RecyclerView.ViewHolder(itemView), IGameChangedNotifier, IExposable, OnViewHolderAttachListener {

    protected val pageConfigure: PageConfigure
        get() = viewModel.pageConfigure

    protected val pageLocation: PageLocation
        get() = viewModel.pageLocation

    fun createTrackData(item: CustomPageItem) =
        CustomPageTrackData(
            viewModel.pageLocation,
            item.componentName,
            item.componentStyle,
            item.link.text ?: "",
            item.link.link ?: ""
        )

    protected var darkMode = DarkModeUtils.isDarkModeOn(itemView.context)

    open val gameChangedNotifier: IGameChangedNotifier?
        get() = null

    open val onlyNotifyItemChanged: Boolean
        get() = false

    abstract val childEventHelper: CustomPageItemChildEventHelper

    protected lateinit var _item: CustomPageItem

    protected var isDarkModeChanged = false

    @CallSuper
    open fun bindView(item: CustomPageItem) {
        _item = item
        childEventHelper.onBind(item)
        val currentDarkMode = DarkModeUtils.isDarkModeOn(itemView.context)
        isDarkModeChanged = darkMode != currentDarkMode
        darkMode = currentDarkMode
    }

    override fun notifyDownload(download: DownloadEntity) {
        gameChangedNotifier?.notifyDownload(download)
    }

    override fun notifyDownloadDeleted(status: EBDownloadStatus) {
        gameChangedNotifier?.notifyDownloadDeleted(status)

    }

    override fun notifyInstalled(busFour: EBPackage) {
        gameChangedNotifier?.notifyInstalled(busFour)
    }

    fun setSplitSubjectTitle(
        titleBinding: LayoutTitleCustomBinding,
        item: CustomSplitSubjectItem,
        eventHelper: SubjectEventHelper,
        titleType: String = TITLE_TYPE_REGULAR
    ) {
        if (item.isFirstLine) {
            titleBinding.root.goneIf(false)
            setSubjectTitle(
                titleBinding,
                CustomSubjectItem(item.link, item.data, item.position, item.componentPosition),
                eventHelper,
                titleType
            )
        } else {
            titleBinding.root.goneIf(true)
        }
    }

    fun fillExposureAndReportAd(gameEntity: GameEntity, sequence: Int, item: CustomPageItem) {
        if (item is CustomSplitSubjectItem || item is CustomSplitSubjectItem) {
            gameEntity.isAdData = item.data.adIconActive
        }

        val exposureSource = ArrayList<ExposureSource>().apply {
            addAll(pageConfigure.exposureSourceList)
            if (item is CustomSplitSubjectItem || item is CustomSplitSubjectItem) {
                addAll(item.exposureSource)
            }
        }

        gameEntity.exposureEvent = createExposureEvent(
            game = gameEntity,
            source = exposureSource,
            base = arrayListOf(),
            childPosition = sequence,
            position = item.componentPosition,
            customPageTrackData = createTrackData(item)
        )

        if (gameEntity.adGroupId.isNotEmpty() && !gameEntity.isAdRequestReported) {
            AdHelper.reportAdRequest(gameEntity)
            gameEntity.isAdRequestReported = true
        }
    }

    private val _title = TitleData()

    // 专题标题
    fun setSubjectTitle(
        titleBinding: LayoutTitleCustomBinding,
        item: CustomSubjectItem,
        eventHelper: SubjectEventHelper,
        titleType: String = TITLE_TYPE_REGULAR
    ) {
        if (isDarkModeChanged) {
            setTitleStyle(titleBinding)
        }

        val subject = item.data
        if (subject.showName) {
            titleBinding.clContainerTitle.goneIf(false)
            with(titleBinding) {
                if (_title.name != subject.name) {
                    _title.name = subject.name
                    tvTitle.text = subject.name ?: ""
                }
                val home = subject.home ?: ""
                val homeText = subject.homeText ?: ""
                if (_title.rightHome != home || _title.rightText != homeText) {
                    _title.rightHome = home
                    _title.rightText = homeText

                    fun getHomeText(defaultResId: Int): String =
                        if (subject.homeText.isNullOrBlank()) {
                            defaultResId.toResString()
                        } else {
                            subject.homeText
                        }
                    tvRight.text = when (subject.home) {
                        HOME_CHANGE -> R.string.custom_home_text_change.toResString()
                        HOME_MORE -> getHomeText(R.string.custom_home_text_more)
                        HOME_ALL -> getHomeText(R.string.custom_home_text_all)
                        HOME_HIDE -> ""
                        else -> R.string.custom_home_text_all.toResString()
                    }
                    val arrowRes =
                        if (subject.home == HOME_HIDE || subject.home == HOME_CHANGE) {
                            0
                        } else {
                            R.drawable.ic_home_head_arrow
                        }
                    tvRight.setCompoundDrawablesWithIntrinsicBounds(0, 0, arrowRes, 0)
                }

                setTitlePadding(titleType, clContainerTitle)

                tvRight.setOnClickListener {
                    when (subject.home) {
                        HOME_CHANGE -> {
                            // 点击换一批
                            eventHelper.onChangeABatch(subject)
                        }

                        HOME_MORE -> {
                            // 点击更多
                            subject.moreLink?.let { link ->
                                eventHelper.onMoreClick(link)
                            }
                        }

                        else -> {
                            MtaHelper.onEvent("游戏专题", "全部", subject.name)
                            eventHelper.onAllClick(subject)
                        }
                    }
                }
            }
            titleBinding.lavRefresh.goneIf(true)
            titleBinding.gUser.goneIf(true)
        } else {
            titleBinding.clContainerTitle.goneIf(true)
        }
    }

    // 游戏单
    fun setSubjectCollectionTitle(
        item: CustomSubjectCollectionItem,
        titleBinding: LayoutTitleCustomBinding,
        eventHelper: GameSubjectCollectionEventHelper,
        showUser: Boolean = false,
        titleType: String = TITLE_TYPE_REGULAR,
        visibleCallback: (Boolean) -> Unit = {}
    ) {
        with(titleBinding) {

            if (item.data.styleSetting.hideName) {
                titleBinding.clContainerTitle.goneIf(true)
                visibleCallback(false)
            } else {
                val isRefreshStyle = item.data.style.contains("refresh")

                titleBinding.clContainerTitle.goneIf(false)
                visibleCallback(true)
                val subject = item.showSubject ?: return
                checkAndSetDarkMode(this)
                val title = if (isRefreshStyle) subject.title else item.data.name
                if (_title.name != title) {
                    _title.name = title
                    tvTitle.text = title
                }

                if (showUser && subject.user.isValid) {
                    gUser.goneIf(false)
                    if (_title.icon != subject.user.icon) {
                        _title.icon = subject.user.icon
                        ImageUtils.display(ivUser, subject.user.icon)
                    }

                    if (_title.userName != subject.user.name) {
                        _title.userName = subject.user.name
                        tvUserName.text = subject.user.name
                    }

                    gUser.setOnClickListener {
                        eventHelper.onUserClick(subject.user.id)
                    }
                } else {
                    gUser.goneIf(true)
                }

                setTitlePadding(titleType, clContainerTitle)

                if (_title.rightText != item.data.styleSetting.rightTop) {
                    _title.rightText = item.data.styleSetting.rightTop
                    val rightTopText = when (item.data.styleSetting.rightTop) {
                        RIGHT_TOP_ALL -> R.string.custom_home_text_all.toResString()
                        HOME_GAME_LIST_SQUARE -> R.string.custom_home_text_game_list_square.toResString()
                        RIGHT_TOP_LINK -> R.string.custom_home_text_more.toResString()
                        else -> ""
                    }
                    tvRight.visibleIf(rightTopText.isNotBlank())
                    if (rightTopText.isNotBlank()) {
                        tvRight.text = rightTopText
                    }
                }


                val styleSetting = item.data.styleSetting
                tvRight.setOnClickListener {
                    if (item.isSubjectCollection) {
                        // 专题合集
                        // 更多
                        if (styleSetting.rightTop == RIGHT_TOP_LINK) {
                            eventHelper.onMoreClick(styleSetting.rightTopLink)
                        } else {
                            // 全部
                            eventHelper.onAllClick()
                        }
                    } else {
                        // 游戏单合集
                        when (styleSetting.rightTop) {
                            RIGHT_TOP_LINK -> {  // 更多
                                eventHelper.onMoreClick(styleSetting.rightTopLink)

                            }

                            RIGHT_TOP_ALL -> {   // 全部
                                eventHelper.onAllClick()
                            }

                            HOME_GAME_LIST_SQUARE -> {   // 游戏单广场
                                NewFlatLogUtils.logGameListCollectionClick(
                                    "版块内容列表",
                                    "",
                                    "",
                                    item.data.name,
                                    item.data.id,
                                    "游戏单广场"
                                )
                                eventHelper.navigateGameListSquare()
                            }
                        }
                    }
                }

                lavRefresh.goneIf(!isRefreshStyle)
                if (isRefreshStyle) {
                    lavRefresh.setAnimation(
                        if (DarkModeUtils.isDarkModeOn(itemView.context)) {
                            "lottie/icon_title_change_dark.json"
                        } else {
                            "lottie/icon_title_change_light.json"
                        }
                    )
                }

                lavRefresh.setOnClickListener {
                    if (!lavRefresh.isAnimating) {
                        lavRefresh.playAnimation()
                        eventHelper.onRotateRefresh()
                        NewFlatLogUtils.logGameListCollectionClick(
                            pageConfigure.entrance,
                            "",
                            "",
                            item.data.name,
                            item.data.id,
                            "刷新"
                        )
                    }
                }
            }
        }
    }

    private fun checkAndSetDarkMode(titleBinding: LayoutTitleCustomBinding) {
        if (isDarkModeChanged) {
            titleBinding.run {
                tvTitle.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(root.context))
                tvUserName.setTextColor(com.gh.gamecenter.common.R.color.text_tertiary.toColor(root.context))
                lavRefresh.cancelAnimation()
                lavRefresh.setAnimation(if (DarkModeUtils.isDarkModeOn(root.context)) "lottie/icon_title_change_dark.json" else "lottie/icon_title_change_light.json")
                lavRefresh.progress = 0F
            }
        }
    }

    private fun setTitlePadding(titleType: String, titleView: View) {
        if (_title.titleType != titleType) {
            _title.titleType = titleType
            val paddingBottom = if (titleType == TITLE_TYPE_SMALL) {
                8f.dip2px()
            } else {
                16f.dip2px()
            }
            titleView.setPadding(titleView.paddingLeft, titleView.paddingTop, titleView.paddingRight, paddingBottom)
        }
    }

    protected fun setTitleStyle(titleBinding: LayoutTitleCustomBinding) {
        with(titleBinding) {
            tvTitle.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(itemView.context))
        }
    }

    override fun getEventByPosition(pos: Int): ExposureEvent? {
        return null
    }

    override fun getEventListByPosition(pos: Int): List<ExposureEvent>? {
        return listOf()
    }

    companion object {

        private const val HOME_CHANGE = "change"
        private const val HOME_MORE = "more"
        private const val HOME_GAME_LIST_SQUARE = "game_list_square"
        private const val HOME_HIDE = "hide"
        private const val HOME_ALL = "all"

        private const val RIGHT_TOP_ALL = "all"
        private const val RIGHT_TOP_LINK = "link"

        const val TITLE_TYPE_REGULAR = "title_type_regular"
        const val TITLE_TYPE_SMALL = "title_type_small"
    }

    data class TitleData(
        var name: String? = null,
        var rightHome: String? = null,
        var rightText: String? = null,
        var isRefresh: Boolean = false,
        var icon: String? = null,
        var userName: String? = null,
        var titleType: String? = null,
    )
}