package com.gh.gamecenter.authorization

import android.content.Intent
import android.os.Build
import android.os.Bundle
import com.gh.common.util.CheckLoginUtils
import com.gh.common.util.DialogUtils
import com.gh.common.util.NewFlatLogUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.common.base.activity.ToolBarActivity
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.utils.ImageUtils
import com.gh.gamecenter.common.utils.updateStatusBarColor
import com.gh.gamecenter.common.utils.viewModelProvider
import com.gh.gamecenter.core.utils.DisplayUtils
import com.gh.gamecenter.databinding.ActivityAuthorizationBinding
import com.gh.gamecenter.login.user.UserManager
import com.gh.vspace.VHelper

/**
 * @author : liujiarui
 * date : 2023/4/3
 * description : 通用授权登陆界面
 * 1. 通过scheme跳转到该界面，传递参数，包括被授权app包名，跳转回的游戏包名(若没有则跳回被授权app)
 * 2. 检查参数，校验申请授权app 包名/签名信息/密钥 等是否合法，后续实现
 * 3. 检查是否已经登陆，如果已经登陆，直接初始化用户信息
 * 4. 如果未登陆，点击登陆按钮，跳转到登陆界面
 * 5. 登陆成功后，初始化用户信息
 * 6. 点击确认授权，跳转回被授权app
 * 7. 被授权app接收到授权成功的广播，进行相应的处理
 * 隐式意图示例：ghzhushou_authorization://authorize?packageName=com.lg.vspace&game_pkg=xxx.xxx.xxx
 * 注意：被授权的app需要创建一个(包名.AuthorizationReceiver)的广播接收者，用于接收授权成功的广播
 * 目前授权返回信息有：
 * 用户token[EntranceConsts.KEY_TOKEN]，
 * 用户昵称[EntranceConsts.KEY_USER_NAME]，
 * 用户头像[EntranceConsts.KEY_USER_AVATAR]，
 */
class AuthorizationActivity : ToolBarActivity() {

    private val mViewModel: AuthorizationViewModel by lazy {
        viewModelProvider()
    }

    private lateinit var mBinding: ActivityAuthorizationBinding

    //被授权app包名，用于获取icon和发送显示广播
    private var mRemotePkgName: String? = null

    //跳转回的游戏app,如果为空，跳转到被授权app
    private var mGamePkg: String? = null

    //授权内容
    private var mContent: String = ""

    /**
     * 畅玩助手当前运行的游戏ID
     */
    private var gameId: String = ""

    /**
     * 畅玩助手当前运行的游戏名称
     */
    private var gameName: String = ""

    //授权token
    private var mToken = ""

    override fun getLayoutId(): Int {
        return R.layout.activity_authorization
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        DisplayUtils.transparentStatusBar(this)
        setNavigationTitle("光环助手授权登陆")
        updateStatusBarColor(R.color.background_white, R.color.background_white)
        mBinding = ActivityAuthorizationBinding.bind(mContentView)
        checkParam()
        initView()
        mBinding.authorizeBtn.postDelayed({
            checkLogin {
                initUserInfo()
            }
        }, 500)
        NewFlatLogUtils.logLoginFromGHZSShow(
            gameId = gameId,
            gameName = gameName
        )
    }

    private fun initData() {
        if (mToken.isNotEmpty()) return
        val loadingDialog = DialogUtils.showWaitDialog(this, "请稍后...")
        mViewModel.getAccessToken(listOf(mContent), {
            mToken = it
            loadingDialog.dismiss()
        }, {
            toast("获取token失败")
            loadingDialog.dismiss()
        })
    }

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        updateStatusBarColor(R.color.background_white, R.color.background_white)
    }

    override fun onRestart() {
        super.onRestart()
        if (!CheckLoginUtils.isLogin()) {
            finish()
        } else {
            initUserInfo()
            initData()
        }
    }

    //检查参数,理论上来说需要 校验申请授权app 包名/签名信息/密钥 等是否合法，后续实现
    private fun checkParam() {
        val uri = intent.data
        if (uri == null) {
            finish()
            return
        }
        val host = uri.host
        if (host != "authorize") {
            finish()
            return
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
            mRemotePkgName = referrer?.host
        }
        mRemotePkgName = mRemotePkgName ?: uri.getQueryParameter(EntranceConsts.KEY_PACKAGENAME)
        mGamePkg = uri.getQueryParameter(EntranceConsts.KEY_GAME_PKG)
        mContent = uri.getQueryParameter(EntranceConsts.KEY_CONTENT) ?: ""
        gameId = uri.getQueryParameter(EntranceConsts.KEY_GAME_ID) ?: ""
        gameName = uri.getQueryParameter(EntranceConsts.KEY_GAME_NAME) ?: ""
        if (mRemotePkgName == null) {
            finish()
            return
        }
    }

    private fun initView() {
        //通过包名获取app图标和名称
        val pkgName = mRemotePkgName ?: return
        val icon = packageManager.getApplicationIcon(pkgName)
        val name = packageManager.getApplicationLabel(packageManager.getApplicationInfo(pkgName, 0))
        mBinding.authorizeAppIcon.setImageDrawable(icon)
        mBinding.authorizeAppName.text = name
        mBinding.authorizeBtn.setOnClickListener {
            NewFlatLogUtils.logLoginFromGHZSClick(
                gameId = gameId,
                gameName = gameName,
                buttonType = BUTTON_TYPE_CONFIRM
            )
            checkLogin {
                authorization()
            }
        }
    }

    private fun checkLogin(block: () -> Unit) {
        //判断光环是否登陆
        CheckLoginUtils.checkLogin(this, "光环助手授权登陆") {
            initData()
            block()
        }
    }

    private fun initUserInfo() {
        if (!CheckLoginUtils.isLogin()) return
        mBinding.nicknameTv.text = UserManager.getInstance().userInfoEntity?.name
        val icon = UserManager.getInstance().userInfoEntity?.icon
        if (icon != null) {
            ImageUtils.display(mBinding.avatarView, icon)
        }
    }

    private fun authorization() {
        val remotePkgName = mRemotePkgName
        if (remotePkgName == null) {
            finish()
            return
        }
        if (mToken.isEmpty()) {
            toast("授权失败")
            return
        }
        val token = mToken
        val userId = UserManager.getInstance().userInfoEntity?.userId
        val username = UserManager.getInstance().userInfoEntity?.name
        val userAvatar = UserManager.getInstance().userInfoEntity?.icon
        //授权成功，发送广播, 返回token
        val intent = Intent()
        intent.setClassName(remotePkgName, "$remotePkgName.AuthorizationReceiver")
        intent.setPackage(remotePkgName)
        intent.putExtra(EntranceConsts.KEY_TOKEN, token)
        intent.putExtra(EntranceConsts.KEY_USER_ID, userId)
        intent.putExtra(EntranceConsts.KEY_USER_NAME, username)
        intent.putExtra(EntranceConsts.KEY_USER_AVATAR, userAvatar)
        sendBroadcast(intent)
        backToLaunchApp()
        finish()
    }

    /**
     * 跳转回授权app
     */
    private fun backToLaunchApp(showLoading: Boolean = true) {
        val gamePkg = mGamePkg
        if (gamePkg != null) { // 跳转回游戏
            VHelper.launch(this, gamePkg, ignoreGApps = true, showLoading = showLoading)
            return
        }
        val remotePkgName = this.mRemotePkgName
        if (remotePkgName != null) {// 跳转回其他授权app
            startActivity(packageManager.getLaunchIntentForPackage(remotePkgName))
        }
    }

    override fun onBackPressed() {
        super.onBackPressed()

        backToLaunchApp(false)

        NewFlatLogUtils.logLoginFromGHZSClick(
            gameId = gameId,
            gameName = gameName,
            buttonType = BUTTON_TYPE_BACK
        )
    }

    companion object {
        private const val BUTTON_TYPE_CONFIRM = "确定"
        private const val BUTTON_TYPE_BACK = "返回"
    }

}