package com.gh.gamecenter.gamedetail.rating.edit

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.Message
import android.view.Gravity
import android.view.MenuItem
import android.view.View
import android.webkit.*
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.gh.common.DefaultJsApi
import com.gh.common.util.*
import com.gh.common.util.DialogUtils
import com.gh.common.util.NewLogUtils
import com.gh.gamecenter.BuildConfig
import com.gh.gamecenter.R
import com.gh.gamecenter.ShellActivity
import com.gh.gamecenter.WebActivity
import com.gh.gamecenter.adapter.viewholder.UnAvaliableWebviewViewHolder
import com.gh.gamecenter.common.base.activity.ToolBarActivity
import com.gh.gamecenter.common.base.fragment.WaitingDialogFragment
import com.gh.gamecenter.common.callback.CancelListener
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.entity.NotificationUgc
import com.gh.gamecenter.common.mvvm.Status
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.common.view.dsbridge.DWebView
import com.gh.gamecenter.common.view.dsbridge.OnReturnValue
import com.gh.gamecenter.core.AppExecutor
import com.gh.gamecenter.core.utils.*
import com.gh.gamecenter.databinding.ActivityRatingEditBinding
import com.gh.gamecenter.databinding.FragmentWebWarningBinding
import com.gh.gamecenter.entity.*
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.suggest.SuggestType
import com.halo.assistant.HaloApp
import com.lightgame.utils.Utils
import com.walkud.rom.checker.RomIdentifier
import okhttp3.MediaType
import okhttp3.RequestBody
import org.json.JSONObject
import retrofit2.HttpException

class RatingEditActivity : ToolBarActivity(), KeyboardHeightObserver {

    private var mPostDialog: WaitingDialogFragment? = null
    private var mInstallPackageName: String? = null

    private lateinit var mBinding: ActivityRatingEditBinding
    private var mGame: GameEntity? = null
    private lateinit var mRatingScoreTip: Array<String>

    private var mFromAmway = false
    private var mIsSkipSuccessPage = false
    private var mComment: RatingComment? = null
    private var mDraft: RatingDraftEntity? = null

    private lateinit var mViewModel: RatingEditViewModel
    private var mPlaceholder: String = ""
    private var mLoadFinish = false
    private var mLoadError = false
    private var mKeyboardHeightProvider: KeyboardHeightProvider? = null
    private var mIsKeyBoardShow = false
    private var mIsWebViewInstalled = true // 当前设备是否存在可用的 WebView
    private var mAutoSaveDraftsCount = 0

    override fun getLayoutId(): Int {
        return if (mIsWebViewInstalled) R.layout.activity_rating_edit else R.layout.fragment_web_warning
    }

    override fun handleMessage(msg: Message) {
        super.handleMessage(msg)
        if (msg.what == SAVE_DRAFTS_MESSAGE_WHAT) {
            mBinding.mWebView.callHandler("getComment", OnReturnValue<String> { content ->
                if (isNeedSaveDraft(content)) {
                    mViewModel.saveRatingDraft(SaveDraftType.AUTO, getCurrentDraft(content))
                }
            })
            mBaseHandler.sendEmptyMessageDelayed(SAVE_DRAFTS_MESSAGE_WHAT, SAVE_DRAFTS_INTERVAL_TIME)
        }
    }

    /**
     * 根据当前编辑内容与当前评论内容/草稿内容进行比较是否相同来返回是否需要保存草稿
     * @param draftContent 当前编辑内容
     * @param isForceWithHasDraft true代表只要当前存在草稿就保存，false代表需要当前编辑内容与草稿内容进行比较，默认为false
     */
    private fun isNeedSaveDraft(draftContent: String?, isForceWithHasDraft: Boolean = false): Boolean {
        return when {
            draftContent.isNullOrBlank() -> false
            else -> {
                when (mDraft) {
                    null -> mComment?.run { content != draftContent } ?: true
                    else -> isForceWithHasDraft || mDraft!!.content != draftContent
                }
            }
        }
    }

    private fun getCurrentDraft(content: String) = RatingDraftEntity(
        star = mBinding.ratingScore.rating.toInt(),
        showDevice = mBinding.deviceBox.isChecked,
        content = content
    )

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (IM_REQUEST_CODE == requestCode) {
            finish()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        mIsWebViewInstalled = PackageUtils.checkWebViewIsAvailable(this)
        super.onCreate(savedInstanceState)
        if (!mIsWebViewInstalled) {
            val holder = UnAvaliableWebviewViewHolder(FragmentWebWarningBinding.bind(mContentView))
            holder.binding.toolbar.root.visibility = View.VISIBLE
            holder.bindView()
            return
        }
        setToolbarMenu(R.menu.menu_game_comment)
        mGame = intent.getParcelableExtra(GameEntity.TAG) ?: GameEntity(id = "")
        mFromAmway = intent.getBooleanExtra(EntranceConsts.KEY_AMWAY, false)
        mIsSkipSuccessPage = intent.getBooleanExtra(EntranceConsts.KEY_SKIP_SUCCESS_PAGE, false)
        mComment = intent.getParcelableExtra(RatingComment::class.java.simpleName)
        mInstallPackageName = intent.getStringExtra(EntranceConsts.KEY_PACKAGENAME)

        mRatingScoreTip = resources.getStringArray(R.array.rating_score_tip)
        mPlaceholder = "您觉得《${mGame?.name}》怎么样？真实、客观、丰富、大于100字的评论内容，更容易获得点赞并推荐到安利墙哦~"
        val factory = RatingEditViewModel.Factory(HaloApp.getInstance().application, mGame?.id ?: "")
        mViewModel = ViewModelProviders.of(this, factory).get(RatingEditViewModel::class.java)
        mViewModel.getRatingDraft()

        mBinding = ActivityRatingEditBinding.bind(mContentView)
        mKeyboardHeightProvider = KeyboardHeightProvider(this)
        mBinding.root.post { mKeyboardHeightProvider?.start() }

        initWebView()
        initObserver()
        mViewModel.getDeviceName()
        mViewModel.getGuideTags()
        mBaseHandler.sendEmptyMessageDelayed(SAVE_DRAFTS_MESSAGE_WHAT, SAVE_DRAFTS_INTERVAL_TIME)
    }

    private fun initView() {
        mGame?.let {
            mBinding.givThumb.displayGameIcon(it)
        }
        mBinding.commentRules.setOnClickListener {
            startActivity(
                WebActivity.getWebIntent(
                    this,
                    getString(R.string.comment_rules_title),
                    getString(R.string.comment_rules_url)
                )
            )
        }

        val navigationTitle: String
        if (mComment == null) {
            navigationTitle = "评论"
            var ratingStartCount = intent.getFloatExtra(EntranceConsts.KEY_RATING_STAR_COUNT, 0.0F)
            if (mDraft != null) {
                mBinding.deviceBox.isChecked = mDraft!!.showDevice
                if (ratingStartCount == 0.0F) {
                    ratingStartCount = mDraft!!.star.toFloat()
                }
            }
            mBinding.ratingEditName.text =
                if (ratingStartCount.toInt() > 0) mRatingScoreTip[ratingStartCount.toInt() - 1] else ""
            mBinding.ratingScore.rating = ratingStartCount
        } else {
            navigationTitle = "修改评论"
            var ratingStartCount = mComment!!.star.toFloat()
            var isChecked = mComment!!.getDevice().isNotEmpty()
            if (mDraft != null) {
                ratingStartCount = mDraft!!.star.toFloat()
                isChecked = mDraft!!.showDevice
            }
            mBinding.ratingEditName.text =
                if (ratingStartCount.toInt() > 0) mRatingScoreTip[ratingStartCount.toInt() - 1] else ""
            mBinding.ratingScore.rating = ratingStartCount
            mBinding.deviceBox.isChecked = isChecked
        }
        setNavigationTitle(navigationTitle)

        mBinding.ratingScore.setOnRatingChangeListener { _, rating ->
            if (rating == 5F) {
                mBinding.lottieAnimationView.setAnimation("lottie/score_fireworks.json")
                mBinding.lottieAnimationView.playAnimation()
            }
            if (rating > 0) {
                mBinding.ratingEditName.text = mRatingScoreTip[rating.toInt() - 1]
            } else {
                mBinding.ratingEditName.text = ""
            }
        }

        mBinding.noConnection.root.setOnClickListener {
            mViewModel.getDeviceName()
            mViewModel.getGuideTags()
            mBinding.mWebView.reload()
        }

        updateRegulationViewStatus()
    }

    @SuppressLint("SetJavaScriptEnabled")
    private fun initWebView() {
        val settings = mBinding.mWebView.settings
        settings.javaScriptEnabled = true
        mBinding.mWebView.enableForceDark(DarkModeUtils.isDarkModeOn(this))
        mBinding.mWebView.setTransparentBackground()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
        }
        // 避免提示网页有害信息不能访问
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            tryWithDefaultCatch {
                settings.safeBrowsingEnabled = false
            }
        }
        DWebView.setWebContentsDebuggingEnabled(PackageFlavorHelper.IS_TEST_FLAVOR)

        // 适配大于屏幕宽度的页面
        settings.useWideViewPort = true
        settings.loadWithOverviewMode = true
        settings.domStorageEnabled = true

        // 自适应屏幕
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            settings.layoutAlgorithm = WebSettings.LayoutAlgorithm.TEXT_AUTOSIZING
        }
        mBinding.mWebView.webViewClient = object : WebViewClient() {
            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
                val insertContent = when {
                    mDraft != null -> mDraft!!.content
                    mComment != null -> mComment!!.content
                    else -> ""
                }
                mBinding.mWebView.callHandler("setComment", arrayOf(insertContent), OnReturnValue<Any> {})
                if (mViewModel.guideTags.value != null) {
                    mBinding.mWebView.callHandler("setPlaceholder", arrayOf(mPlaceholder), OnReturnValue<Any> {})
                    mBinding.mWebView.callHandler(
                        "setGuideTags",
                        arrayOf(mViewModel.guideTags.value),
                        OnReturnValue<Any> {})
                }
                if (mLoadError) {
                    mBinding.mWebView.visibility = View.GONE
                    mBinding.noConnection.root.visibility = View.VISIBLE
                    mLoadError = false
                } else {
                    mBinding.mWebView.visibility = View.VISIBLE
                    mBinding.noConnection.root.visibility = View.GONE
                }
                mLoadFinish = true
            }

            override fun onReceivedError(view: WebView?, request: WebResourceRequest?, error: WebResourceError?) {
                super.onReceivedError(view, request, error)
                mLoadFinish = false
                mLoadError = true
            }
        }
        mBinding.mWebView.addJavascriptObject(DefaultJsApi(this), null)
        val url = if ("internal" == BuildConfig.FLAVOR) {
            "https://resource.ghzs.com/page/comment_tag_editor_dev/index.html?timestamp=${System.currentTimeMillis()}"
        } else {
            "https://resource.ghzs.com/page/comment_tag_editor/index.html?timestamp=${System.currentTimeMillis()}"
        }
        mBinding.mWebView.loadUrl(url)
    }

    private fun initObserver() {
        mViewModel.deviceName.observe(this, Observer {
            mBinding.deviceName.text = it
        })

        mViewModel.guideTags.observe(this, Observer {
            if (mLoadFinish) {
                mBinding.mWebView.callHandler("setPlaceholder", arrayOf(mPlaceholder), OnReturnValue<Any> {})
                mBinding.mWebView.callHandler("setGuideTags", arrayOf(it), OnReturnValue<Any> {})
            }
        })

        mViewModel.processDialog.observe(this, Observer {
            if (it.isShow) {
                if (mPostDialog?.dialog?.isShowing == true) {
                    mPostDialog?.uploadWaitingHint(it.msg)
                } else {
                    mPostDialog = WaitingDialogFragment.newInstance(it.msg)
                    mPostDialog?.show(supportFragmentManager, null)
                }
            } else {
                mPostDialog?.dismiss()
            }
        })

        mViewModel.ratingDraftLiveData.observe(this) {
            mDraft = it
            initView()
        }

        mViewModel.postRatingDrafts.observeNonNull(this) {
            when (it.first) {
                SaveDraftType.AUTO -> {
                    if (mAutoSaveDraftsCount % SAVE_DRAFTS_TOAST_COUNT == 0) {
                        toast("内容已保存至草稿箱")
                    }
                    mAutoSaveDraftsCount++
                    mDraft = it.second
                }

                SaveDraftType.EXIT -> {
                    // Do nothing
                }
            }
        }

        mViewModel.postLiveData.observe(this, Observer {
            if (it.status == Status.SUCCESS) {
                MtaHelper.onEvent("发表评论", "提交", mGame?.name)
                setResult(Activity.RESULT_OK)
                toast("提交成功")

                if (mFromAmway) {
                    if (mIsSkipSuccessPage) {
                        startActivity(ShellActivity.getIntent(this, ShellActivity.Type.AMWAY_SUCCESS, mGame))
                    }
                    finish()
                    return@Observer
                }

                if (mComment != null) { // patch
                    if (!mComment!!.active) { // 评论被隐藏后修改要变成审核状态
                        mComment!!.audit = true
                    }
                    mBinding.mWebView.callHandler("getComment", OnReturnValue<String> { content ->
                        if (mComment!!.content != content) {
                            mComment!!.content = content
                            mComment!!.isEditContent = true
                        } else if (mComment!!.isEditContent == null) {
                            mComment!!.isEditContent = false
                        }

                        mComment!!.time = System.currentTimeMillis() / 1000
                        mComment!!.star = mBinding.ratingScore.rating.toInt()
                        if (!mBinding.deviceBox.isChecked) {
                            mComment!!.setDevice("")
                        } else {
                            mComment!!.setDevice(mBinding.deviceName.text.toString())
                        }
                        if (!SyncDataBetweenPageHelper.setResultAndFinish(this@RatingEditActivity, mComment)) {
                            Utils.log("RatingEditActivity没有触发页面数据同步")
                            finish()
                        }
                    })

                } else {
                    finish()
                }
                AppExecutor.uiExecutor.executeWithDelay(Runnable {
                    if (mFromAmway) {
                        NotificationHelper.showNotificationHintDialog(NotificationUgc.RATING)
                    }
                }, 1000)
            } else if (it.status == Status.ERROR) {
                var errorString: String? = null
                try {
                    if (it.exception is HttpException) {
                        errorString = it.exception!!.response()?.errorBody()?.string()
                    }
                } catch (e1: Exception) {
                    e1.printStackTrace()
                }

                val errorEntity = errorString?.toObject<ErrorEntity>()

                when (errorEntity?.code) {
                    403079 -> {
                        MtaHelper.onEvent("游戏评论跳转", "出现弹窗", mGame?.name ?: "")
                        MtaHelper.onEvent("游戏评论跳转", "联系客服弹窗", "出现弹窗")
                        DialogUtils.showTrackableDialog(
                            this@RatingEditActivity, true, "提示",
                            "检测到您评论的内容中含有反映游戏问题相关内容，可选择点击下方联系客服按钮，将问题反馈给客服，以便更优解决！",
                            "联系客服", "继续提交",
                            {
                                DirectUtils.directToWebView(
                                    this@RatingEditActivity,
                                    Constants.TENCENT_QIDIAN_ADDRESS,
                                    mEntrance
                                )
                                MtaHelper.onEvent("游戏评论跳转", "联系客服弹窗", "点击联系客服")
                            }, object : CancelListener {
                                override fun onCancel() {
                                    postGameComment(again = true)
                                    MtaHelper.onEvent("游戏评论跳转", "联系客服弹窗", "点击继续提交")
                                }
                            }, TrackableEntity(event = "游戏评论跳转", key = "联系客服弹窗")
                        )
                    }
                    403080 -> {
                        MtaHelper.onEvent("游戏评论跳转", "出现弹窗", mGame?.name ?: "")
                        MtaHelper.onEvent("游戏评论跳转", "意见反馈弹窗", "出现弹窗")
                        DialogUtils.showTrackableDialog(
                            this@RatingEditActivity, "提示",
                            "检测到您评论的内容中含有反映游戏问题相关内容，可选择点击下方问题反馈按钮，将问题反馈给后台客服，以便更优解决！",
                            "问题反馈", "继续提交",
                            {
                                MtaHelper.onEvent("游戏评论跳转", "意见反馈弹窗", "点击问题反馈")
                                mBinding.mWebView.callHandler("getComment", OnReturnValue<String> { content ->
                                    DirectUtils.directToSuggestion(
                                        context = this@RatingEditActivity,
                                        type = SuggestType.gameQuestion,
                                        content = content.replace(LABEL_REPLACE_REGEX.toRegex(), ""),
                                        fromRatingKey = true,
                                        game = SimpleGameEntity(mGame?.id ?: "", mGame?.name ?: "")
                                    )
                                    finish()
                                })
                            }, object : CancelListener {
                                override fun onCancel() {
                                    MtaHelper.onEvent("游戏评论跳转", "意见反馈弹窗", "点击继续提交")
                                    postGameComment(again = true)
                                }
                            }, TrackableEntity(event = "游戏评论跳转", key = "意见反馈弹窗")
                        )
                    }
                    400401 -> {
                        CheckLoginUtils.checkLogin(this, mEntrance) {}
                    }
                    else -> {
                        ErrorHelper.handleError(this@RatingEditActivity, errorString, false, {
                            postGameComment(again = false)
                        }, "游戏评论及回复")
                    }
                }
            }
        })

    }

    override fun onMenuItemClick(item: MenuItem?): Boolean {
        if (item?.itemId == R.id.menu_game_comment) {
            debounceActionWithInterval(R.id.menu_game_comment, 1000L) {
                postGameComment(again = false)
            }
        }
        return super.onMenuItemClick(item)
    }

    @SuppressLint("CheckResult")
    private fun postGameComment(again: Boolean) {
        mBinding.mWebView.callHandler("getComment", OnReturnValue<String> { content ->
            val rating = mBinding.ratingScore.rating
            if (rating == 0F) {
                ToastUtils.showToast("请先给游戏打分", if (mIsKeyBoardShow) Gravity.CENTER else -1)
                return@OnReturnValue
            }
            if (content.isEmpty()) {
                ToastUtils.showToast("评论内容不能为空喔~", if (mIsKeyBoardShow) Gravity.CENTER else -1)
                return@OnReturnValue
            }

            if (content.length > 10000) {
                ToastUtils.showToast("评论最多10000个字", if (mIsKeyBoardShow) Gravity.CENTER else -1)
                return@OnReturnValue
            }

            logRatingClickEvent(content, true)

            val gameVersion = if (mInstallPackageName.isNullOrEmpty()) {
                val apk = mGame?.getApk()
                if (!apk.isNullOrEmpty()) apk[0].version else ""
            } else {
                PackageUtils.getVersionNameByPackageName(mInstallPackageName)
            }
            val jsonObject = JSONObject()
            jsonObject.put("star", rating)
            jsonObject.put("content", content)
            jsonObject.put("show_device", mBinding.deviceBox.isChecked)
            jsonObject.put("device", DeviceUtils.getLoginDevice(this))
            jsonObject.put("gh_version", PackageUtils.getGhVersionName())
            jsonObject.put("game_version", gameVersion)
            jsonObject.put("source", if (mFromAmway) "anliwall" else "game_detail")
            jsonObject.put("plugin_version", PackageUtils.getMetaData(this, mInstallPackageName, "gh_version"))
            jsonObject.put("rom", RomIdentifier.getRom().name + " " + RomIdentifier.getRom().versionName)
            jsonObject.put("again", again)

            val body = RequestBody.create(MediaType.parse("application/json"), jsonObject.toString())

            CheckLoginUtils.checkLogin(this, mEntrance) {
                mViewModel.postGameComment(mComment?.id ?: "", body)
            }
        })
    }

    override fun onResume() {
        super.onResume()
        updateRegulationViewStatus()
        mKeyboardHeightProvider?.setKeyboardHeightObserver(this)
    }

    override fun onPause() {
        super.onPause()
        mKeyboardHeightProvider?.setKeyboardHeightObserver(null)
    }

    override fun onDestroy() {
        super.onDestroy()
        mKeyboardHeightProvider?.close()
    }

    override fun onKeyboardHeightChanged(height: Int, orientation: Int) {
        mIsKeyBoardShow = height > 0
    }

    override fun handleBackPressed(): Boolean {
        if (!mIsWebViewInstalled) return false
        mBinding.mWebView.callHandler("getComment", OnReturnValue<String> { content ->
            logRatingClickEvent(content, false)

            if (isNeedSaveDraft(content, true)) {
                DialogHelper.showDialog(
                    this,
                    "提示",
                    "是否保存评价内容用于下次编辑？",
                    "保存并退出",
                    "不保存",
                    {
                        if (isNeedSaveDraft(content)) {
                            mViewModel.saveRatingDraft(SaveDraftType.EXIT, getCurrentDraft(content))
                        }
                        finish()
                    },
                    {
                        mViewModel.deleteRatingDraft()
                        finish()
                    },
                    extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true)
                )
            } else finish()
        })
        if (!mLoadError) return true
        return false
    }

    private fun updateRegulationViewStatus() {
        if (::mBinding.isInitialized) {
            mBinding.regulationHintContainer.goneIf(!UserManager.getInstance().userShouldTakeRegulationTest())
            mBinding.regulationHintContainer.setOnClickListener {
                NewLogUtils.logCommentTabOrCommentDetailClick(
                    "click_game_comment_etiquette_test",
                    mGame?.id ?: "",
                    mGame?.type ?: ""
                )
                DirectUtils.directToRegulationTestPage(this)
            }
        }
    }

    private fun logRatingClickEvent(content: String, isPost: Boolean) {
        var commentTags = ""
        val splitList = content.split("<tag>")
        if (splitList.size > 1) {
            commentTags = splitList.takeLast(splitList.size - 1).joinToString("-") { it.split("</tag>")[0] }
        }
        NewLogUtils.logRatingEditClick(
            if (isPost) "click_game_comment_submit" else "click_game_comment_return",
            mGame?.id ?: "",
            mGame?.gameType ?: "",
            mBinding.deviceBox.isChecked,
            mBinding.ratingScore.rating,
            commentTags,
            content.length
        )
    }

    override fun isAutoResetViewBackgroundEnabled(): Boolean = true

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        updateStatusBarColor(R.color.background_white, R.color.background_white)
        mBinding.mWebView.enableForceDark(DarkModeUtils.isDarkModeOn(this))
    }

    companion object {
        const val SAVE_DRAFTS_MESSAGE_WHAT = 1
        const val SAVE_DRAFTS_INTERVAL_TIME = 15000L
        const val SAVE_DRAFTS_TOAST_COUNT = 4
        const val LABEL_REPLACE_REGEX = "<tag[^>]*?>[\\s\\S]*?<\\/tag>"
        const val LABEL_PREFIX = "<tag>"
        const val LABEL_REGEX = "<tag>(\\S+)</tag>([\\S\\s\n]+)"

        const val RATING_CONTENT_LIMIT = 5000
        const val IM_REQUEST_CODE = 345

        fun getIntent(
            context: Context,
            game: GameEntity,
            starCount: Float,
            installPackageName: String?,
            fromAmway: Boolean = false,
            isSkipSuccessPage: Boolean = true
        ): Intent {
            val intent = Intent(context, RatingEditActivity::class.java)
            intent.putExtra(GameEntity.TAG, game)
            intent.putExtra(EntranceConsts.KEY_RATING_STAR_COUNT, starCount)
            intent.putExtra(EntranceConsts.KEY_AMWAY, fromAmway)
            intent.putExtra(EntranceConsts.KEY_SKIP_SUCCESS_PAGE, isSkipSuccessPage)
            intent.putExtra(EntranceConsts.KEY_PACKAGENAME, installPackageName)
            return intent
        }

        fun getPatchIntent(context: Context, game: GameEntity, comment: RatingComment): Intent {
            val intent = Intent(context, RatingEditActivity::class.java)
            intent.putExtra(GameEntity.TAG, game)
            intent.putExtra(RatingComment::class.java.simpleName, comment)
            return intent
        }
    }

    enum class SaveDraftType {
        EXIT, // 退出时保存
        AUTO, // 自动保存
    }
}