package com.gh.gamecenter

import android.content.Context
import android.content.ContextWrapper
import android.content.Intent
import android.os.Bundle
import android.view.View
import com.gh.base.DownloadToolbarActivity
import com.gh.common.exposure.ExposureManager
import com.gh.common.exposure.ExposureTraceUtils.appendTrace
import com.gh.gamecenter.common.base.GlobalActivityManager
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.constant.RouteConsts
import com.gh.gamecenter.common.utils.toArrayList
import com.gh.gamecenter.core.utils.DisplayUtils
import com.gh.gamecenter.entity.GamePlatform
import com.gh.gamecenter.feature.entity.CustomPageTrackData
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.feature.exposure.ExposureEvent
import com.gh.gamecenter.feature.exposure.ExposureEvent.Companion.createEvent
import com.gh.gamecenter.feature.exposure.ExposureType
import com.gh.gamecenter.gamedetail.GameDetailWrapperFragment
import com.gh.gamecenter.gamedetail.entity.GameDetailTabEntity
import com.therouter.TheRouter
import com.therouter.router.Autowired
import com.therouter.router.Route

@Route(
    path = RouteConsts.activity.gameDetailActivity,
    description = "游戏详情页"
)
class GameDetailActivity : DownloadToolbarActivity() {

    @JvmField
    @Autowired(name = EntranceConsts.KEY_GAME_ID, description = "游戏 id", required = true)
    var gameId: String? = null

    @JvmField
    @Autowired(name = EntranceConsts.KEY_GAME_ENTITY, description = "游戏摘要实体，如果你不懂这个是什么，那么不要用它，直接传入游戏 id 即可")
    var gameEntity: GameEntity? = null

    @JvmField
    @Autowired(name = EntranceConsts.KEY_ENTRANCE, description = "入口埋点字段（开发内部使用）")
    var entrance: String? = ""

    @JvmField
    @Autowired(name = EntranceConsts.KEY_DEFAULT_TAB, description = "默认选中 tab 的类型（目前可选的有五个类型 `详情`, `专区`，`云存档`，`评价`，`论坛`），首次进入匹配并切换至对应 tab")
    var defaultTab: String = ""

    @JvmField
    @Autowired(name = EntranceConsts.KEY_COMMENT_AS_DEFAULT_TAB, description = "跳转到评论 tab，首次进入直接跳转到评论 tab")
    var commentAsDefaultTab: Boolean = false

    @JvmField
    @Autowired(name = EntranceConsts.KEY_SCROLL_TO_LIBAO, description = "滚动到礼包区域，首次进入滚动到礼包区域")
    var scrollToLibao: Boolean = false

    @JvmField
    @Autowired(name = EntranceConsts.KEY_SCROLL_TO_SERVER, description = "滚动到开服表区域，首次进入滚动到开服表区域")
    var scrollToServer: Boolean = false

    @JvmField
    @Autowired(name = EntranceConsts.KEY_OPEN_VIDEO_STREAMING, description = "打开视频流，首次进入打开视频流")
    var openVideoStreaming: Boolean = false

    @JvmField
    @Autowired(name = EntranceConsts.KEY_OPEN_PLATFORM_WINDOW, description = "打开多版本窗口，首次进入打开多版本窗口")
    var openPlatformWindow: Boolean = false

    override fun onCreate(savedInstanceState: Bundle?) {
        TheRouter.inject(this)

        generateDataFromRoute()

        super.onCreate(savedInstanceState)
        DisplayUtils.setStatusBarColor(this, com.gh.gamecenter.common.R.color.transparent, !mIsDarkModeOn)
    }

    override fun provideNormalIntent(): Intent {
        return getTargetIntent(this, GameDetailActivity::class.java, GameDetailWrapperFragment::class.java)
    }

    override fun getLayoutId() = R.layout.activity_game_detail

    override fun showToolbarAtLeft() = true
    override fun showDownloadMenu() = true

    override fun getActivityNameInChinese() = "游戏详情"

    override fun getBusinessId(): Pair<String, String> {
        return if (!gameId.isNullOrEmpty()) {
            Pair(gameId ?: "", "")
        } else {
            super.getBusinessId()
        }
    }

    override fun attachBaseContext(newBase: Context) {
        super.attachBaseContext(object : ContextWrapper(newBase) {
            override fun getSystemService(name: String): Any? {
                // 解决 VideoView 中 AudioManager 造成的内存泄漏
                if (Context.AUDIO_SERVICE == name) {
                    return applicationContext.getSystemService(name)
                }
                return super.getSystemService(name)
            }
        })
    }

    override fun isAutoResetViewBackgroundEnabled(): Boolean = true

    override fun updateStaticViewBackground(view: View?) {
        updateStaticView(
            view,
            listOf(
                R.id.menu_download_iv,
                R.id.cardContainer,
                R.id.iv_reserve,
                R.id.iv_concern,
                R.id.tab_title
            )
        )
    }

    private fun generateDataFromRoute() {
        val bundle = intent.extras

        intent?.putExtra(NORMAL_FRAGMENT_NAME, GameDetailWrapperFragment::class.java.canonicalName)
        intent?.putExtra(NORMAL_FRAGMENT_BUNDLE, bundle)
    }

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        DisplayUtils.setStatusBarColor(this, com.gh.gamecenter.common.R.color.transparent, !mIsDarkModeOn)
    }

    companion object {

        @JvmStatic
        fun startGameDetailActivity(
            context: Context,
            gameEntity: GameEntity?,
            entrance: String,
            traceEvent: ExposureEvent?
        ) {
            startGameDetailActivity(context, gameEntity, entrance, "", traceEvent = traceEvent)
        }

        /**
         * @param gameEntity 游戏实体
         * @param defaultTab 默认定位到哪个tab
         * @param isSkipGameComment 是否跳转到评论tab
         * @param scrollToLibao 滚动到礼包区域
         * @param scrollToServer 滚动到开服表区域
         * @param traceEvent 曝光事件
         */
        @JvmStatic
        fun startGameDetailActivity(
            context: Context,
            gameEntity: GameEntity?,
            entrance: String,
            defaultTab: String = "",
            isSkipGameComment: Boolean = false,
            scrollToLibao: Boolean = false,
            scrollToServer: Boolean = false,
            traceEvent: ExposureEvent? = null
        ) {
            val bundle = Bundle()

            if (traceEvent != null) {
                val clickEvent = createEvent(gameEntity, traceEvent.source, appendTrace(traceEvent), ExposureType.CLICK)
                ExposureManager.log(clickEvent)
                bundle.putParcelable(EntranceConsts.KEY_TRACE_EVENT, clickEvent)
            }

            if (gameEntity != null && traceEvent != null && gameEntity.id != traceEvent.payload.gameId) {
                // 当游戏 ID 跟曝光 traceEvent 的游戏ID 不一样的时候更新 traceEvent 的游戏ID
                val (payload) = createEvent(
                    gameEntity,
                    traceEvent.source,
                    appendTrace(traceEvent),
                    ExposureType.EXPOSURE
                )
                traceEvent.payload = payload
            }

            if (defaultTab.isNotEmpty()) {
                bundle.putString(EntranceConsts.KEY_TARGET, defaultTab)
            }

            if (isSkipGameComment) {
                bundle.putBoolean(EntranceConsts.KEY_COMMENT_AS_DEFAULT_TAB, true)
            }

            if (scrollToLibao) {
                bundle.putString(EntranceConsts.KEY_TARGET, GameDetailTabEntity.TYPE_DETAIL)
                bundle.putBoolean(EntranceConsts.KEY_SCROLL_TO_LIBAO, true)
            }

            if (scrollToServer) {
                bundle.putString(EntranceConsts.KEY_TARGET, GameDetailTabEntity.TYPE_DETAIL)
                bundle.putBoolean(EntranceConsts.KEY_SCROLL_TO_SERVER, true)
            }

            bundle.putString(EntranceConsts.KEY_GAME_ID, gameEntity?.id)
            bundle.putString(EntranceConsts.KEY_ENTRANCE, entrance)
            bundle.putParcelable(EntranceConsts.KEY_GAME_ENTITY, gameEntity)

            TheRouter
                .build(RouteConsts.activity.gameDetailActivity)
                .fillParams {
                    it.putAll(bundle)
                }
                .navigation(context)
        }

        @JvmStatic
        fun startGameDetailActivity(
            context: Context,
            gameId: String,
            entrance: String?,
            traceEvent: ExposureEvent?
        ) {
            startGameDetailActivity(context, gameId, entrance, isSkipGameComment = false, traceEvent = traceEvent)
        }

        @JvmStatic
        fun startGameDetailActivity(
            context: Context,
            gameId: String,
            entrance: String?,
            isSkipGameComment: Boolean = false,
            scrollToLibao: Boolean = false,
            openVideoStreaming: Boolean = false,
            openPlatformWindow: Boolean = false,
            traceEvent: ExposureEvent? = null
        ) {
            startGameDetailActivity(
                context,
                gameId,
                entrance,
                isSkipGameComment,
                scrollToLibao,
                openVideoStreaming,
                openPlatformWindow,
                null,
                null,
                null,
                traceEvent
            )
        }

        /**
         * @param gameId 游戏Id
         * @param isSkipGameComment 是否跳转到评论tab
         * @param scrollToLibao 滚动到礼包区域
         * @param openVideoStreaming 是否打开视频流
         * @param openPlatformWindow 打开多版本下载弹窗
         * @param platformName 平台名称
         * @param packageName 包名
         * @param traceEvent 曝光事件
         */
        @JvmStatic
        fun startGameDetailActivity(
            context: Context,
            gameId: String,
            entrance: String?,
            isSkipGameComment: Boolean = false,
            scrollToLibao: Boolean = false,
            openVideoStreaming: Boolean = false,
            openPlatformWindow: Boolean = false,
            platformName: String? = null,
            packageName: String? = null,
            platforms: List<GamePlatform>? = null,
            traceEvent: ExposureEvent? = null,
            customPageTrackData: CustomPageTrackData? = null
        ) {
            val bundle = Bundle()

            if (traceEvent != null) {
                val clickEvent = createEvent(
                    GameEntity(
                        gameId,
                        traceEvent.payload.gameName
                    ),
                    traceEvent.source,
                    appendTrace(traceEvent),
                    ExposureType.CLICK
                )
                ExposureManager.log(clickEvent)
                bundle.putParcelable(EntranceConsts.KEY_TRACE_EVENT, clickEvent)
            }
            if (traceEvent != null && gameId != traceEvent.payload.gameId) {
                // 当游戏 ID 跟曝光 traceEvent 的游戏ID 不一样的时候更新 traceEvent 的游戏ID
                val (payload) = createEvent(
                    GameEntity(gameId),
                    traceEvent.source,
                    appendTrace(traceEvent),
                    ExposureType.EXPOSURE
                )
                traceEvent.payload = payload
            }
            if (isSkipGameComment) {
                bundle.putBoolean(EntranceConsts.KEY_COMMENT_AS_DEFAULT_TAB, true)
            }
            if (openVideoStreaming) {
                bundle.putBoolean(EntranceConsts.KEY_OPEN_VIDEO_STREAMING, true)
                bundle.putString(EntranceConsts.KEY_TARGET, GameDetailTabEntity.TYPE_DETAIL)
            }
            if (openPlatformWindow) {
                bundle.putBoolean(EntranceConsts.KEY_OPEN_PLATFORM_WINDOW, true)
                if (!platforms.isNullOrEmpty()) {
                    bundle.putParcelableArrayList(EntranceConsts.KEY_PLATFORMS, platforms.toArrayList())
                } else if (!platformName.isNullOrEmpty() || !packageName.isNullOrEmpty()) {
                    bundle.putParcelableArrayList(
                        EntranceConsts.KEY_PLATFORMS,
                        arrayListOf(GamePlatform(platformName, packageName))
                    )
                }
            }
            if (scrollToLibao) {
                bundle.putString(EntranceConsts.KEY_TARGET, GameDetailTabEntity.TYPE_DETAIL)
                bundle.putBoolean(EntranceConsts.KEY_SCROLL_TO_LIBAO, true)
            }
            bundle.putString(EntranceConsts.KEY_GAME_ID, gameId)
            bundle.putString(EntranceConsts.KEY_ENTRANCE, entrance)
            bundle.putParcelable(EntranceConsts.KEY_CUSTOM_PAGE_TRACK_DATA, customPageTrackData)
            bundle.putString(EntranceConsts.KEY_LAST_PAGE_ID, GlobalActivityManager.getLastPageEntity().pageId)
            bundle.putString(EntranceConsts.KEY_LAST_PAGE_NAME, GlobalActivityManager.getLastPageEntity().pageName)
            bundle.putString(
                EntranceConsts.KEY_LAST_PAGE_BUSINESS_ID,
                GlobalActivityManager.getLastPageEntity().pageBusinessId
            )

            TheRouter
                .build(RouteConsts.activity.gameDetailActivity)
                .fillParams {
                    it.putAll(bundle)
                }
                .navigation(context)
        }

    }
}