package com.zxhl.cms.utils

import android.app.Activity
import android.content.Intent
import android.util.Log
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.gms.common.api.ApiException
import com.google.android.gms.tasks.OnCompleteListener
import com.google.android.gms.tasks.Task
import com.zxhl.cms.common.Constant
import com.zxhl.cms.net.ApiClient
import com.zxhl.cms.net.RxSchedulers
import com.zxhl.cms.net.SettingPreference
import com.zxhl.cms.net.callback.BaseObserver
import com.zxhl.cms.net.model.other.WxBindEntity


/**
 * @author (wangXuewei)
 * @datetime 2022-03-25 14:04 GMT+8
 * @detail :
 */
class GoogleLoginUtil {

    private val TAG = "GoogleLoginUtil"
    private val RC_SIGN_IN = 9009
    private val googleClientId =
        "535211515800-fcblld827b8ojq7dccuohmeo199205ce.apps.googleusercontent.com"

    private var mActivity: Activity;
    private var mGoogleSignInClient: GoogleSignInClient? = null;
    private var mLoginCallBack: LoginCallBack? = null;

    constructor(mActivity: Activity) {
        this.mActivity = mActivity
    }

    interface LoginCallBack {
        fun onLoginSuccess()
        fun onLoginError(errorMsg: String)
    }

    fun init() {
        val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail()
            .requestIdToken(googleClientId)
            .requestId()
            .requestProfile()
            .build()
        mGoogleSignInClient = GoogleSignIn.getClient(mActivity, gso);
    }

    /**
     * google登录
     */
    fun googleLogin(callBack: LoginCallBack) {
        mLoginCallBack = callBack;
        val account = GoogleSignIn.getLastSignedInAccount(mActivity)
        if (account != null) {
            bindGoogle(account.id, account.displayName, account.photoUrl.toString())
        } else {
            mActivity.runOnUiThread {
                val signInIntent = mGoogleSignInClient?.signInIntent
                mActivity.startActivityForResult(signInIntent, RC_SIGN_IN)
            }
        }


    }

    /**
     * Activity 重写
     * */
    fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
// Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...);
        // Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...);
        if (requestCode === RC_SIGN_IN) {
            // The Task returned from this call is always completed, no need to attach
            // a listener.
            val task: Task<GoogleSignInAccount> = GoogleSignIn.getSignedInAccountFromIntent(data)
            handleSignInResult(task)
        }
    }

    private fun handleSignInResult(completedTask: Task<GoogleSignInAccount>) {
        try {
            // Signed in successfully, show authenticated UI.
            val account = completedTask.getResult(ApiException::class.java)
            if (account != null) {
                bindGoogle(account.id, account.displayName, account.photoUrl.toString())
            } else {
                mLoginCallBack?.onLoginError("code:-2 msg:account is null")
            }
        } catch (e: ApiException) {
            // The ApiException status code indicates the detailed failure reason.
            // Please refer to the GoogleSignInStatusCodes class reference for more information.
            mLoginCallBack?.onLoginError("code:${e.statusCode} msg:${e.message}")
        }
    }

    /**
     * 绑定后端服务器
     * */
    private fun bindGoogle(userId: String?, userName: String?, picture: String?) {
        ApiClient.homeApi.authGoogleLogin(userId, userName, picture)
            .compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<WxBindEntity>() {
                override fun onSuccess(result: WxBindEntity?) {
                    SettingPreference.saveToken(result?.token)
                    UserDataUtils.updateUserInfo(null)
                    Constant.Switch.isLogin = true
                    mLoginCallBack?.onLoginSuccess()
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                    //   callBack.loginSuccess(lottery)
                    mLoginCallBack?.onLoginError("net code:$code msg:$errorMsg")
                }
            })

    }

    /**
     * 退出登录
     */
    fun signOut() {
        mGoogleSignInClient?.signOut()
            ?.addOnCompleteListener(mActivity) {
                // ...
                //it.result
            }
    }

    /**
     * 断开链接
     */
    fun revokeAccess() {
        mGoogleSignInClient?.revokeAccess()
            ?.addOnCompleteListener(mActivity) {
                // ...
            }
    }


}