package com.gh.gamecenter.gamecollection.publish

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.widget.TextView
import androidx.core.widget.doOnTextChanged
import com.gh.common.util.CheckLoginUtils
import com.gh.common.util.ErrorHelper
import com.gh.common.util.NewLogUtils
import com.gh.gamecenter.CropImageActivity
import com.gh.gamecenter.R
import com.gh.gamecenter.WebActivity
import com.gh.gamecenter.common.base.activity.ToolBarActivity
import com.gh.gamecenter.common.base.fragment.WaitingDialogFragment
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.utils.PatternUtils
import com.gh.gamecenter.databinding.ActivityGameCollectionEditBinding
import com.gh.gamecenter.databinding.ItemGameCollectionFlexTagBinding
import com.gh.gamecenter.entity.*
import com.gh.gamecenter.common.eventbus.EBReuse
import com.gh.gamecenter.gamecollection.choose.ChooseGamesActivity
import com.gh.gamecenter.gamecollection.choose.ChooseGamesViewModel
import com.gh.gamecenter.gamecollection.tag.GameCollectionTagSelectActivity
import com.gh.gamecenter.gamecollection.tag.GameCollectionTagSelectFragment
import com.gh.gamecenter.common.mvvm.Status
import com.zhihu.matisse.Matisse
import com.zhihu.matisse.internal.utils.PathUtils
import org.greenrobot.eventbus.EventBus
import org.json.JSONObject

class GameCollectionEditActivity : ToolBarActivity() {

    private lateinit var mMenuPost: MenuItem
    private lateinit var mBinding: ActivityGameCollectionEditBinding
    private lateinit var mViewModel: GameCollectionEditViewModel
    private lateinit var mChooseGamesViewModel: ChooseGamesViewModel
    private var mProcessingDialog: WaitingDialogFragment? = null
    private var mPatchCommitCount = 0
    private var mActivityId = ""
    private var mActivityName = ""
    private var mGameEntity: GameEntity? = null

    override fun getLayoutId(): Int = R.layout.activity_game_collection_edit

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        updateStatusBarColor(R.color.background_white, R.color.background_white)
        mBinding = ActivityGameCollectionEditBinding.bind(mContentView)
        mViewModel = viewModelProvider()
        mChooseGamesViewModel = viewModelProvider(ChooseGamesViewModel.Factory())
        setToolbarMenu(R.menu.menu_game_collection_edit)
        mMenuPost = getMenuItem(R.id.menu_game_collection_post)
        setNavigationTitle("创建游戏单")
        mViewModel.gameCollectionPatch = intent.getParcelableExtra(GamesCollectionEntity::class.java.name)
        val path = intent.getStringExtra(EntranceConsts.KEY_PATH) ?: ""
        if (path.isNotEmpty()) {
            NewLogUtils.logEnterGameCollectionEdit(path)
        }
        mActivityId = intent.getStringExtra(EntranceConsts.KEY_ACTIVITY_ID) ?: ""
        mActivityName = intent.getStringExtra(EntranceConsts.KEY_ACTIVITY_NAME) ?: ""
        if (mActivityId.isNotEmpty() && mActivityName.isNotEmpty()) {
            mViewModel.selectActivityTag = ActivityLabelEntity(id = mActivityId, name = mActivityName)
            mBinding.activityTipTv.text = mActivityName
        }
        val gameId = intent.getStringExtra(EntranceConsts.KEY_GAMEID) ?: ""
        if (gameId.isNotEmpty()) {
            mViewModel.getGameDigest(gameId) {
                if (it != null) {
                    var isDuplicate = false
                    val gamesList = ArrayList<GameEntity>()
                    val simpleGames = mViewModel.gameCollectionPatch?.games?.map { game -> game.toGameEntity() }
                    if (!simpleGames.isNullOrEmpty()) {
                        simpleGames.forEach { game ->
                            if (game.id == gameId) isDuplicate = true
                        }
                        gamesList.addAll(simpleGames)
                    }
                    mGameEntity = it
                    mChooseGamesViewModel.chooseGamesLiveData.postValue(gamesList.apply { if (!isDuplicate) add(it) })
                }
            }
        }

        initData()
        observeData()
        initListener()
    }

    private fun initListener() {
        mBinding.gameCollectionTitleEt.run {
            doOnTextChanged { text, start, _, _ ->
                if (text?.contains("\n") == true) {
                    setText(text.toString().replace("\n", ""))
                    setSelection(start)
                    return@doOnTextChanged
                }
                if (PatternUtils.isHasSpace(text.toString())) {
                    setText(PatternUtils.replaceSpace(text.toString()))
                    setSelection(start)
                    return@doOnTextChanged
                }
            }
        }
        mBinding.gameCollectionIntroduceEt.run {
            doOnTextChanged { text, start, _, _ ->
                if (PatternUtils.isHasWrap(text.toString())) {
                    setText(PatternUtils.replaceWrap(text.toString()))
                    setSelection(start)
                    return@doOnTextChanged
                }
                if (PatternUtils.isHasSpace(text.toString())) {
                    setText(PatternUtils.replaceSpace(text.toString()))
                    setSelection(start)
                    return@doOnTextChanged
                }
            }
        }
        mBinding.uploadPictureBtn.setOnClickListener {
//            PermissionHelper.checkStoragePermissionBeforeAction(
//                this,
//                object : EmptyCallback {
//                    override fun onCallback() {
//                        startActivityForResult(
//                            LocalMediaActivity.getIntent(
//                                this@GameCollectionEditActivity,
//                                LocalMediaActivity.ChooseType.IMAGE,
//                                1,
//                                "创建游戏单"
//                            ), REQUEST_CODE_IMAGE
//                        )
//                    }
//                })
            ChooseGameCollectionCoverTypeDialog.show(this, this::class.java.name)
        }

        mBinding.changePosterBtn.setOnClickListener { mBinding.uploadPictureBtn.performClick() }

        mBinding.deleteBtn.setOnClickListener {
            mViewModel.imageUrl = ""
            mViewModel.imagePath = ""
            mBinding.uploadPictureTv.text = "点击上传图片"
            initPosterUI()
        }

        mBinding.gameCollectionIntroduceEt.doOnTextChanged { text, _, _, _ ->
            mBinding.introduceSizeTv.text = "${text?.toString()?.lengthOfEmojiHalf() ?: 0}/200"
        }

        mBinding.chooseLabelContainer.setOnClickListener {
            startActivityForResult(
                GameCollectionTagSelectActivity.getIntent(this, 3, mViewModel.tags),
                REQUEST_CHOOSE_TAG
            )
        }

        mBinding.chooseGameContainer.setOnClickListener {
            startActivity(ChooseGamesActivity.getIntent(this))
        }
        mBinding.chooseActivityContainer.setOnClickListener {
            if (mViewModel.gameCollectionPatch?.status != "draft" && mViewModel.gameCollectionPatch?.isLocalDraft == false) return@setOnClickListener
            ChooseGameCollectionActivityDialog.show(this, mViewModel.selectActivityTag?.id, this::class.java.name)
        }
        mBinding.normsLinkTv.setOnClickListener {
            startActivity(WebActivity.getWebIntent(this, "游戏单管理规范", Constants.GAME_COLLECTION_RULE))
        }
    }

    private fun initData(isFirst: Boolean = true) {
        mBinding.gameCollectionTitleEt.filters = arrayOf(TextHelper.getFilterOfEmojiHalf(20, "最多输入20个字"))
        mBinding.gameCollectionIntroduceEt.filters = arrayOf(TextHelper.getFilterOfEmojiHalf(200, "最多输入200个字"))
        initTagsUI(mViewModel.tags)

        mViewModel.gameCollectionPatch?.run {
            if (!activityTags.isNullOrEmpty() && mActivityId.isEmpty() && mActivityName.isEmpty()) {
                mViewModel.selectActivityTag = activityTags!![0]
                mBinding.activityTipTv.text = activityTags!![0].name
            }
            mViewModel.imageUrl = cover
            if (status != "draft" && !isLocalDraft) {
                setNavigationTitle("编辑游戏单")
            }
            initPosterUI()
            mBinding.gameCollectionTitleEt.setText(title)
            mBinding.gameCollectionTitleEt.setSelection(title.length)
            mBinding.gameCollectionIntroduceEt.setText(intro)
            mBinding.gameCollectionIntroduceEt.setSelection(intro.length)
            mBinding.selfOnlyCb.isChecked = display == "self_only"
            if (isFirst) {
                mViewModel.getGameCollectionDetail(id)
            }
        } ?: mViewModel.getDraft()
    }

    private fun observeData() {
        mChooseGamesViewModel.chooseGamesLiveData.observe(this) {
            mBinding.gamesTv.text = if (it.isEmpty()) "选择游戏" else "已选 ${it.size} 款游戏"
            mBinding.gamesTipTv.goneIf(it.isNotEmpty())
        }
        mViewModel.processDialog.observe(this) {
            if (it.isShow) {
                if (mProcessingDialog?.dialog?.isShowing == true) {
                    mProcessingDialog?.uploadWaitingHint(it.msg)
                } else {
                    mProcessingDialog = WaitingDialogFragment.newInstance(it.msg, false)
                    mProcessingDialog?.show(supportFragmentManager, null)
                }
            } else {
                mProcessingDialog?.dismiss()
            }
        }
        mViewModel.uploadImageSuccessLiveData.observe(this) {
            if (it.isNotEmpty()) {
                initPosterUI()
            }
            mBinding.uploadPictureTv.text = "点击上传图片"
        }
        mViewModel.postLiveData.observe(this) {
            if (it.status == Status.SUCCESS) {
                toast("提交成功")
                EventBus.getDefault().post(EBReuse("createGameCollectionSuccess"))
                it.data?.run {
                    if (mActivityName.isNotEmpty()) {
                        val games = mChooseGamesViewModel.chooseGamesLiveData.value ?: arrayListOf()
                        NewLogUtils.logCreateGameCollectionSuccess(
                            games.map { gameEntity -> gameEntity.id }.toList(),
                            mBinding.gameCollectionTitleEt.text.toString().trim(),
                            this,
                            mActivityName
                        )
                    }
                }
                finish()
            } else {
                val errorMsg = it.exception?.response()?.errorBody()?.string() ?: ""
                val errorCode = JSONObject(errorMsg).getInt("code")
                if (errorCode == 400401) {
                    CheckLoginUtils.checkLogin(this, mEntrance) {}
                    return@observe
                }
                ErrorHelper.handleError(this, errorMsg, false, {
                    if (::mMenuPost.isInitialized) {
                        onMenuItemClick(mMenuPost)
                    }
                }, "发布游戏单")
            }
        }
        mViewModel.detailLiveData.observe(this) {
            mViewModel.gameCollectionPatch?.apply {
                games = it.games
                tags = it.tags
                title = it.title
                intro = it.intro
                cover = it.cover
                display = it.display
            }
            mViewModel.gameCollectionPatch?.run {
                initData(false)
                mViewModel.tags = tags ?: arrayListOf()
                initTagsUI(mViewModel.tags)
                val simpleGames = games?.map { game -> game.toGameEntity() }?.toList()
                mChooseGamesViewModel.chooseGamesLiveData.postValue(ArrayList(simpleGames))
            }
        }
        mViewModel.draftLiveData.observe(this) {
            mViewModel.gameCollectionPatch = it.convertGameCollectionEntity()
            mViewModel.gameCollectionPatch?.run {
                isLocalDraft = true
                initData(false)
                mViewModel.tags = tags ?: arrayListOf()
                initTagsUI(mViewModel.tags)
                val simpleGames = games?.map { game -> game.toGameEntity() }
                var isDuplicate = false
                if (!simpleGames.isNullOrEmpty()) {
                    simpleGames.forEach { game ->
                        if (mGameEntity != null && game.id == mGameEntity?.id) isDuplicate = true
                    }
                }
                mChooseGamesViewModel.chooseGamesLiveData.postValue(ArrayList(simpleGames).apply {
                    if (mGameEntity != null && !isDuplicate) add(mGameEntity)
                })
            }
            if (!it.activityTags.isNullOrEmpty() && mActivityId.isEmpty() && mActivityName.isEmpty()) {
                mViewModel.selectActivityTag = it.activityTags!![0]
                mBinding.activityTipTv.text = it.activityTags!![0].name
            }
        }
    }

    override fun onMenuItemClick(item: MenuItem?): Boolean {
        item?.run {
            if (itemId == R.id.menu_game_collection_post) {
                debounceActionWithInterval(R.id.menu_game_collection_post, 3000L) {
                    verifyData()
                }
            }
        }
        return super.onMenuItemClick(item)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (data == null || resultCode != Activity.RESULT_OK) return
        when (requestCode) {
            REQUEST_CODE_IMAGE_CROP -> {
                val imagePath = data.getStringExtra(CropImageActivity.RESULT_CLIP_PATH) ?: ""
                mViewModel.imageUrl = ""
                mViewModel.imagePath = imagePath
                if (imagePath.isEmpty()) {
                    mBinding.uploadPictureTv.text = "点击上传图片"
                } else {
                    mBinding.uploadPictureTv.text = "图片上传中..."
                    mViewModel.uploadPoster()
                }
                initPosterUI()
            }
            REQUEST_CHOOSE_TAG -> {
                val tags = data.getParcelableArrayListExtra<TagInfoEntity>(GameCollectionTagSelectFragment.SELECTED_TAG)
                    ?: arrayListOf()
                mViewModel.tags = tags
                initTagsUI(tags)
            }
        }
    }

    fun onActivityDialogResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (resultCode == Activity.RESULT_OK && data != null) {
            if (requestCode == REQUEST_CODE_IMAGE) {
                val selectedPaths = Matisse.obtainResult(data)
                if (!selectedPaths.isNullOrEmpty()) {
                    val path = PathUtils.getPath(this, selectedPaths[0])
                    val intent =
                        CropImageActivity.getIntent(
                            this,
                            path,
                            142 / 328F,
                            false,
                            R.layout.layout_game_collection_crop_image_assist,
                            mEntrance
                        )
                    startActivityForResult(intent, REQUEST_CODE_IMAGE_CROP)
                }
            } else if (requestCode == ChooseGameCollectionDefaultCoverDialog.REQUEST_CODE_DEFAULT_IMAGE) {
                val entity = data.getParcelableExtra<GameCollectionCoverEntity>(EntranceConsts.KEY_DATA)
                if (entity != null) {
                    mViewModel.imageUrl = entity.url
                    mViewModel.uploadImageSuccessLiveData.postValue(entity.url)
                }
            } else if (requestCode == REQUEST_CHOOSE_ACTIVITY) {
                val entity = data.getParcelableExtra<ActivityLabelEntity>(EntranceConsts.KEY_DATA)
                if (entity != null) {
                    mViewModel.selectActivityTag = entity
                    mBinding.activityTipTv.text = entity.name
                } else {
                    mViewModel.selectActivityTag = null
                    mBinding.activityTipTv.text = ""
                }
            }
        }
    }

    private fun initPosterUI() {
        mBinding.placeholderView.goneIf(mViewModel.imageUrl.isNotEmpty())
        mBinding.uploadPictureBtn.goneIf(mViewModel.imageUrl.isNotEmpty())
        mBinding.posterView.goneIf(mViewModel.imageUrl.isEmpty())
        mBinding.changePosterBtn.goneIf(mViewModel.imageUrl.isEmpty())
        mBinding.deleteBtn.goneIf(mViewModel.imageUrl.isEmpty())
        if (mViewModel.imageUrl.isNotEmpty()) {
            ImageUtils.display(mBinding.posterView, mViewModel.imageUrl)
        }
    }

    private fun initTagsUI(tags: ArrayList<TagInfoEntity>) {
        mBinding.gameCollectionTagsContainer.removeAllViews()
        mBinding.labelTipTv.goneIf(tags.isNotEmpty())
        if (tags.isEmpty()) {
            val tagBinding = ItemGameCollectionFlexTagBinding.inflate(LayoutInflater.from(this), null, false)
            tagBinding.tagNameTv.run {
                text = "选择标签"
                setTextColor(R.color.text_title.toColor(this@GameCollectionEditActivity))
                textSize = 14f
            }
            tagBinding.divider.visibility = View.GONE
            mBinding.gameCollectionTagsContainer.addView(tagBinding.root)
        } else {
            tags.forEachIndexed { index, tag ->
                val tagBinding = ItemGameCollectionFlexTagBinding.inflate(LayoutInflater.from(this), null, false)
                tagBinding.tagNameTv.run {
                    text = tag.name
                    setTextColor(R.color.text_title.toColor(this@GameCollectionEditActivity))
                    textSize = 14f
                }
                tagBinding.divider.run {
                    alpha = 0.2f
                    setBackgroundColor(R.color.text_title.toColor(this@GameCollectionEditActivity))
                    goneIf(index == tags.size - 1)
                    setPadding(8f.dip2px(), 0, 8f.dip2px(), 0)
                }
                mBinding.gameCollectionTagsContainer.addView(tagBinding.root)
            }
        }
    }

    override fun handleBackPressed(): Boolean {
        val patch = mViewModel.gameCollectionPatch
        if (patch != null && patch.status != "draft" && !patch.isLocalDraft) {
            DialogHelper.showDialog(this, "温馨提示", "退出将不会保留本次游戏单编辑的内容，是否确定退出", "确定", "取消", {
                finish()
            }, extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true))
            return true
        } else if (patch == null || patch.isLocalDraft) {
            val games = mChooseGamesViewModel.chooseGamesLiveData.value ?: arrayListOf()
            val title = mBinding.gameCollectionTitleEt.text.toString()
            val introduce = mBinding.gameCollectionIntroduceEt.text.toString()
            if (mViewModel.imageUrl.isNotEmpty()
                || mViewModel.tags.isNotEmpty()
                || games.isNotEmpty()
                || title.isNotEmpty()
                || introduce.isNotEmpty()
                || mViewModel.selectActivityTag != null
            ) {
                val entity = GameCollectionDraft()
                entity.tags = mViewModel.tags
                if (mViewModel.selectActivityTag != null) entity.activityTags =
                    arrayListOf(mViewModel.selectActivityTag!!)
                entity.title = title
                entity.intro = introduce
                entity.cover = mViewModel.imageUrl
                entity.display = if (mBinding.selfOnlyCb.isChecked) "self_only" else ""
                entity.games = arrayListOf()
                entity.games?.addAll(games.map { it.toSimpleGame() }.toList())
                mViewModel.addDraft(entity)
            }
        }
        return super.handleBackPressed()
    }

    private fun verifyData() {
        if (mViewModel.imageUrl.isEmpty()) {
            toast("请上传游戏单的封面")
            return
        }
        if (mViewModel.tags.isEmpty()) {
            toast("请选择游戏单的标签")
            return
        }
        val games = mChooseGamesViewModel.chooseGamesLiveData.value ?: arrayListOf()

        val title = mBinding.gameCollectionTitleEt.text.toString().trim()
        if (title.isEmpty()) {
            toast("请填写游戏单的标题")
            return
        }
        val introduce = mBinding.gameCollectionIntroduceEt.text.toString().trim()
        if (introduce.lengthOfEmojiHalf() < 10) {
            toast("介绍至少10个字")
            return
        }

        val isSelfOnly = mBinding.selfOnlyCb.isChecked
        val requestMap = hashMapOf(
            "id" to (mViewModel.gameCollectionPatch?.id ?: ""),
            "title" to title,
            "intro" to introduce,
            "tag_ids" to mViewModel.tags.map { it.id }.toList(),
            "cover" to mViewModel.imageUrl,
            "display" to if (isSelfOnly) "self_only" else "",
            "games" to games.map {
                hashMapOf<String, Any>(
                    "_id" to it.id,
                    "recommend_star" to it.recommendStar,
                    "recommend_text" to it.recommendText,
                )
            }.toList()
        )
        if (mViewModel.selectActivityTag != null) {
            requestMap["activity_tag_ids"] = listOf(mViewModel.selectActivityTag?.id)
        }

        val patch = mViewModel.gameCollectionPatch
        if (patch != null
            && !patch.isLocalDraft
            && !mBinding.selfOnlyCb.isChecked
            && games.size < 8
        ) {
            if (mPatchCommitCount < 2) {
                toast("游戏单收录的游戏不能少于8款")
                mPatchCommitCount++
            } else {
                toast("没想好收录的游戏，开启仅自己可见试试")
                mPatchCommitCount++
            }
            return
        }

        if (isSelfOnly) {
            DialogHelper.showDialog(this, "温馨提示", "游戏单开启“仅自己可见”后，将不会对其他用户展示，是否继续提交", "确定", "取消", {
                mViewModel.uploadContent(this, requestMap)
            }, extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true))
        } else {
            if (games.size < 8) {
                DialogHelper.showDialog(
                    this,
                    "温馨提示",
                    "游戏单需要收录至少8个游戏，才可以投稿至游戏单广场，是否在“我的光环-我的游戏单”继续保存为草稿",
                    "继续保存",
                    "添加游戏",
                    {
                        mViewModel.uploadContent(this, requestMap)
                    },
                    {
                        startActivity(ChooseGamesActivity.getIntent(this))
                    },
                    extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true)
                )
            } else {
                DialogHelper.showDialog(this, "温馨提示", "游戏单会在1-2个工作日内审核完成，您可以在“我的光环-我的游戏单”查看进度", "继续提交", "取消", {
                    mViewModel.uploadContent(this, requestMap)
                }, extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true))
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mChooseGamesViewModel.chooseGamesLiveData.postValue(arrayListOf())
    }

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        updateStatusBarColor(R.color.background_white, R.color.background_white)
        mMenuPost.actionView?.findViewById<TextView>(R.id.postTv)?.background =
            R.drawable.textview_concern_red_up_round.toDrawable(this)
        if (::mBinding.isInitialized) {
            mBinding.run {
                root.setBackgroundColor(R.color.background_white.toColor(this@GameCollectionEditActivity))
                labelDivider.setBackgroundColor(R.color.divider.toColor(this@GameCollectionEditActivity))
                gameDivider.setBackgroundColor(R.color.divider.toColor(this@GameCollectionEditActivity))
                activityDivider.setBackgroundColor(R.color.divider.toColor(this@GameCollectionEditActivity))
                titleDivider.setBackgroundColor(R.color.divider.toColor(this@GameCollectionEditActivity))
                introduceDivider.setBackgroundColor(R.color.divider.toColor(this@GameCollectionEditActivity))
                placeholderView.background = R.drawable.bg_shape_f5_radius_8.toDrawable(this@GameCollectionEditActivity)
                selfOnlyCb.background =
                    R.drawable.border_round_stroke_0dot5_eee_999.toDrawable(this@GameCollectionEditActivity)
                uploadPictureTv.setTextColor(R.color.text_body.toColor(this@GameCollectionEditActivity))
                labelTipTv.setTextColor(R.color.text_body.toColor(this@GameCollectionEditActivity))
                gamesTv.setTextColor(R.color.text_title.toColor(this@GameCollectionEditActivity))
                gamesTipTv.setTextColor(R.color.text_body.toColor(this@GameCollectionEditActivity))
                activityTv.setTextColor(R.color.text_title.toColor(this@GameCollectionEditActivity))
                gameCollectionTitleEt.setTextColor(R.color.text_title.toColor(this@GameCollectionEditActivity))
                gameCollectionIntroduceEt.setTextColor(R.color.text_title.toColor(this@GameCollectionEditActivity))
                introduceSizeTv.setTextColor(R.color.text_body.toColor(this@GameCollectionEditActivity))
                normsLinkTv.setTextColor(R.color.theme_font.toColor(this@GameCollectionEditActivity))
                selfOnlyCb.setTextColor(R.color.text_subtitleDesc.toColor(this@GameCollectionEditActivity))
                labelTipTv.setHintTextColor(R.color.text_subtitleDesc.toColor(this@GameCollectionEditActivity))
                gamesTipTv.setHintTextColor(R.color.text_subtitleDesc.toColor(this@GameCollectionEditActivity))
                activityTipTv.setHintTextColor(R.color.text_subtitleDesc.toColor(this@GameCollectionEditActivity))
                gameCollectionTitleEt.setHintTextColor(R.color.text_body.toColor(this@GameCollectionEditActivity))
                gameCollectionIntroduceEt.setHintTextColor(R.color.text_body.toColor(this@GameCollectionEditActivity))
                for (i in 0 until mBinding.gameCollectionTagsContainer.childCount) {
                    mBinding.gameCollectionTagsContainer.getChildAt(i)?.findViewById<TextView>(R.id.tagNameTv)
                        ?.setTextColor(R.color.text_title.toColor(this@GameCollectionEditActivity))
                    mBinding.gameCollectionTagsContainer.getChildAt(i)?.findViewById<View>(R.id.divider)
                        ?.setBackgroundColor(R.color.text_title.toColor(this@GameCollectionEditActivity))
                }
            }
        }
    }

    companion object {

        const val REQUEST_CODE_IMAGE = 100
        const val REQUEST_CODE_IMAGE_CROP = 101
        const val REQUEST_CHOOSE_GAMES = 102
        const val REQUEST_CHOOSE_TAG = 103
        const val REQUEST_CHOOSE_ACTIVITY = 105

        @JvmStatic
        fun getIntent(context: Context, entrance: String = "", path: String = ""): Intent {
            val intent = Intent(context, GameCollectionEditActivity::class.java)
            intent.putExtra(EntranceConsts.KEY_ENTRANCE, mergeEntranceAndPath(entrance, path))
            intent.putExtra(EntranceConsts.KEY_PATH, path)
            return intent
        }

        @JvmStatic
        fun getIntent(
            context: Context,
            entity: GamesCollectionEntity,
            entrance: String = "",
            path: String = ""
        ): Intent {
            val intent = Intent(context, GameCollectionEditActivity::class.java)
            intent.putExtra(GamesCollectionEntity::class.java.name, entity)
            intent.putExtra(EntranceConsts.KEY_ENTRANCE, mergeEntranceAndPath(entrance, path))
            intent.putExtra(EntranceConsts.KEY_PATH, path)
            return intent
        }

        @JvmStatic
        fun getIntent(
            context: Context,
            activityId: String = "",
            activityName: String = "",
            gameId: String = "",
            entrance: String = "",
            path: String = ""
        ): Intent {
            val intent = Intent(context, GameCollectionEditActivity::class.java)
            intent.putExtra(EntranceConsts.KEY_ACTIVITY_ID, activityId)
            intent.putExtra(EntranceConsts.KEY_ACTIVITY_NAME, activityName)
            intent.putExtra(EntranceConsts.KEY_GAMEID, gameId)
            intent.putExtra(EntranceConsts.KEY_ENTRANCE, mergeEntranceAndPath(entrance, path))
            intent.putExtra(EntranceConsts.KEY_PATH, path)
            return intent
        }
    }
}