package com.gh.common.dialog

import android.annotation.SuppressLint
import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.Paint
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.CheckBox
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.gh.gamecenter.common.avoidcallback.AvoidOnResultManager
import com.gh.gamecenter.common.avoidcallback.Callback
import com.gh.gamecenter.common.constant.Constants
import com.gh.common.util.*
import com.gh.gamecenter.R
import com.gh.gamecenter.ShellActivity
import com.gh.gamecenter.common.callback.ConfirmListener
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.utils.SensorsBridge
import com.gh.gamecenter.core.utils.GsonUtils
import com.gh.gamecenter.core.utils.SPUtils
import com.gh.gamecenter.feature.entity.AuthDialogEntity
import com.gh.gamecenter.feature.entity.AuthDialogLevel
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.login.user.UserManager
import com.google.gson.reflect.TypeToken
import com.halo.assistant.fragment.user.UserInfoEditFragment
import com.lightgame.utils.AppManager

class CertificationDialog(
    context: Context,
    private val authDialogEntity: AuthDialogEntity,
    val gameEntity: GameEntity,
    val listener: ConfirmListener
) :
    Dialog(context, R.style.GhAlertDialog) {

    private lateinit var view: View
    private lateinit var detailedDesTv: TextView
    private lateinit var noRemindAgainCb: CheckBox
    private lateinit var actionLeftTv: TextView
    private lateinit var actionRightTv: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        view = LayoutInflater.from(context).inflate(R.layout.dialog_sertification, null)
        setContentView(view)
        detailedDesTv = view.findViewById(R.id.detailedDesTv)
        noRemindAgainCb = view.findViewById(R.id.noRemindAgainCb)
        actionLeftTv = view.findViewById(R.id.actionLeftTv)
        actionRightTv = view.findViewById(R.id.actionRightTv)

        detailedDesTv.paint.flags = Paint.UNDERLINE_TEXT_FLAG
        detailedDesTv.paint.isAntiAlias = true

        detailedDesTv.setOnClickListener {
            DirectUtils.directToWebView(context, authDialogEntity.link)
        }

        when (authDialogEntity.level) {
            AuthDialogLevel.MUST_PASS.value -> {
                actionLeftTv.text = "暂不下载"
                actionRightTv.text = "去实名认证"
                noRemindAgainCb.visibility = View.GONE
                actionLeftTv.setOnClickListener {
                    SensorsBridge.trackEvent("VerificationPopupClick", "button_name", actionLeftTv.text.toString())
                    dismiss()
                }
                actionRightTv.setOnClickListener {
                    SensorsBridge.trackEvent("VerificationPopupClick", "button_name", actionRightTv.text.toString())
                    if (UserManager.getInstance().isLoggedIn) {
                        gotoAuthPage()
                    } else {
                        gotoLoginPage()
                    }
                }
            }
            AuthDialogLevel.ALWAYS_HINT.value -> {
                actionLeftTv.text = "去实名认证"
                actionRightTv.text = "继续下载"
                noRemindAgainCb.visibility = View.GONE
                actionLeftTv.setOnClickListener {
                    SensorsBridge.trackEvent("VerificationPopupClick", "button_name", actionLeftTv.text.toString())
                    if (UserManager.getInstance().isLoggedIn) {
                        gotoAuthPage()
                    } else {
                        gotoLoginPage()
                    }
                }
                actionRightTv.setOnClickListener {
                    SensorsBridge.trackEvent("VerificationPopupClick", "button_name", actionRightTv.text.toString())
                    listener.onConfirm()
                    dismiss()
                }
            }
            AuthDialogLevel.OPTIONAL_HINT.value -> {
                actionLeftTv.text = "去实名认证"
                actionRightTv.text = "继续下载"
                noRemindAgainCb.visibility = View.VISIBLE
                actionLeftTv.setOnClickListener {
                    SensorsBridge.trackEvent("VerificationPopupClick", "button_name", actionLeftTv.text.toString())
                    if (noRemindAgainCb.isChecked) {
                        SPUtils.setBoolean(gameEntity.id, true)
                    }
                    if (UserManager.getInstance().isLoggedIn) {
                        gotoAuthPage()
                    } else {
                        gotoLoginPage()
                    }
                }
                actionRightTv.setOnClickListener {
                    SensorsBridge.trackEvent("VerificationPopupClick", "button_name", actionRightTv.text.toString())
                    if (noRemindAgainCb.isChecked) {
                        SPUtils.getBoolean(gameEntity.id, true)
                    }
                    listener.onConfirm()
                    dismiss()
                }
            }
        }

        SensorsBridge.trackEvent(
            "VerificationDialogShow",
            "game_id",
            gameEntity.id,
            "game_name",
            gameEntity.name ?: "",
            "game_type",
            gameEntity.categoryChinese
        )
    }

    //跳转登录页面
    private fun gotoLoginPage() {
        val currentActivity = AppManager.getInstance().currentActivity() ?: return

        CheckLoginUtils.checkLogin(
            currentActivity as AppCompatActivity,
            null, true, "实名认证弹窗"
        ) {
            if (UserManager.getInstance().isAuth) {
                listener.onConfirm()
                dismiss()
            }
        }
    }

    //跳转实名认证页面
    private fun gotoAuthPage() {
        val currentActivity = AppManager.getInstance().currentActivity() ?: return

        AvoidOnResultManager.getInstance(currentActivity as AppCompatActivity)
            .startForResult(
                ShellActivity.getIntent(
                    context,
                    ShellActivity.Type.REAL_NAME_INFO,
                ).apply {
                    putExtra(EntranceConsts.KEY_GAME_ID, gameEntity.id)
                }, object : Callback {
                    override fun onActivityResult(resultCode: Int, data: Intent?) {
                        if (resultCode == Activity.RESULT_OK && data != null) {
                            val isAuthSuccess =
                                data.getBooleanExtra(UserInfoEditFragment.AUTH_SUCCESS, false)
                            if (isAuthSuccess) {
                                listener.onConfirm()
                                dismiss()
                            }
                        }
                    }
                })
    }


    companion object {
        @JvmStatic
        fun showCertificationDialog(context: Context, game: GameEntity, listener: ConfirmListener) {
            //1.先判断是否登录 是执行2 否执行3
            //2.判断是否实名认证 是终止 否执行3
            //3.判断是否需要弹出认证弹窗接口
            if (UserManager.getInstance().isLoggedIn) {
                if (UserManager.getInstance().isAuth) {//已实名认证
                    listener.onConfirm()
                } else {
                    authDialog(context, game, listener)
                }
            } else {
                authDialog(context, game, listener)
            }
        }

        @SuppressLint("CheckResult")
        private fun authDialog(context: Context, game: GameEntity, listener: ConfirmListener) {
            var authDialog: AuthDialogEntity? = null
            if (game.authDialog != null) {
                authDialog = game.authDialog
            }
            if (authDialog == null) {
                val datas = SPUtils.getString(Constants.SP_AUTH_DIALOG)
                val type = object : TypeToken<List<AuthDialogEntity>>() {}.type
                val authDialogs = GsonUtils.gson.fromJson<List<AuthDialogEntity>>(datas, type)
                if (!authDialogs.isNullOrEmpty()) {
                    authDialog = authDialogs.find { it.gameCategory == game.category }
                }
            }
            val isCloseAuthDialog = SPUtils.getBoolean(game.id, false)
            if (authDialog != null && (authDialog.level != AuthDialogLevel.OPTIONAL_HINT.value || !isCloseAuthDialog)) {
                val dialog = CertificationDialog(context, authDialog, game, listener)
                dialog.show()
            } else {
                listener.onConfirm()
            }
        }
    }
}