package com.gh.gamecenter.login.utils

import android.app.Activity
import android.content.Intent
import com.alibaba.android.arouter.launcher.ARouter
import com.gh.gamecenter.common.constant.RouteConsts
import com.gh.gamecenter.common.utils.tryWithDefaultCatch
import com.gh.gamecenter.core.provider.IConfigProvider
import com.lightgame.utils.RuntimeUtils
import com.gh.gamecenter.login.HaloApp
import com.gh.gamecenter.login.R
import com.gh.gamecenter.login.user.LoginTag
import com.lightgame.utils.Utils
import com.sina.weibo.sdk.auth.AuthInfo
import com.sina.weibo.sdk.auth.Oauth2AccessToken
import com.sina.weibo.sdk.auth.WbAuthListener
import com.sina.weibo.sdk.openapi.IWBAPI
import com.sina.weibo.sdk.openapi.WBAPIFactory
import com.tencent.mm.opensdk.modelmsg.SendAuth
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import com.tencent.tauth.IUiListener
import com.tencent.tauth.Tencent
import com.tencent.tauth.UiError
import org.json.JSONException
import org.json.JSONObject

/**
 * 第三方登录辅助类
 */
object LoginHelper {

    const val WEIBO_SCOPE = (
            "email,direct_messages_read,direct_messages_write,"
                    + "friendships_groups_read,friendships_groups_write,statuses_to_me_read,"
                    + "follow_app_official_microblog," + "invitation_write") // weiboCode

    private var mTencent: Tencent // QQ
    private var mIWXAPI: IWXAPI // 微信
    private lateinit var mWBAPI: IWBAPI // 微博

    private var mQqLoginListener: IUiListener

    private var mAccessToken: Oauth2AccessToken? = null // weibo
    private var mLoginCallback: LoginCallback? = null

    init {
        val context = HaloApp.getInstance().applicationContext
        val config = ARouter.getInstance().build(RouteConsts.provider.config).navigation() as? IConfigProvider
        Tencent.setIsPermissionGranted(true)

        mTencent = Tencent.createInstance(config?.getTencentAppId(), context) //初始化QQ分享
        mIWXAPI = WXAPIFactory.createWXAPI(context, config?.getWechatAppId(), true) //初始化微信分享

        mQqLoginListener = object : IUiListener {
            override fun onComplete(o: Any?) {
                Utils.log("QQ 登录成功")
                if (o is JSONObject) {
                    val s = o.toString()
                    Utils.log("QQLoginComplete::$s")
                    try {
                        mTencent.openId = o.getString("openid")
                        mTencent.setAccessToken(
                            o.getString("access_token"),
                            o.getString("expires_in")
                        )

                        val content = JSONObject()
                        content.put("openid", o.getString("openid"))
                        content.put(
                            "access_token_expire",
                            Utils.getTime(context) + o.getLong("expires_in")
                        )
                        content.put("access_token", o.getString("access_token"))

                        mLoginCallback?.onLoginSuccess(LoginTag.qq, content) // 回调QQ登录成功
                    } catch (e: JSONException) {
                        val errorString = "QQ登录数据回调异常：：$e"

                        mLoginCallback?.onLoginFailure(LoginTag.qq, errorString) // 回调QQ登录失败

                        Utils.log(errorString)
                        e.printStackTrace()
                    }
                }
            }

            override fun onCancel() {
                mLoginCallback?.onLoginFailure(LoginTag.qq, "登录取消")
                Utils.log("QQ 登录取消")
            }

            override fun onWarning(p0: Int) {

            }

            override fun onError(p0: UiError?) {
                mLoginCallback?.onLoginFailure(LoginTag.qq, "登录失败")
                Utils.log("QQ 登录失败")
            }
        }


//        DouYinOpenApiFactory.init(DouYinOpenConfig(Config.DOUYIN_CLIENTKEY))

        Utils.log("LoginHelper initialization")
    }

    @JvmStatic
    fun onQQLoginCallback(requestCode: Int, resultCode: Int, data: Intent?) {
        Tencent.onActivityResultData(requestCode, resultCode, data, mQqLoginListener);
    }

    @JvmStatic
    fun onWechatLoginSuccess(content: JSONObject) {
        mLoginCallback?.onLoginSuccess(LoginTag.wechat, content)
    }

    @JvmStatic
    fun onWechatLoginFailure(error: String) {
        mLoginCallback?.onLoginFailure(LoginTag.wechat, error)
    }

    @JvmStatic
    fun onDouYinLoginSuccess(content: JSONObject) {
        mLoginCallback?.onLoginSuccess(LoginTag.douyin, content)
    }

    @JvmStatic
    fun onDouYinLoginFailure(error: String) {
        mLoginCallback?.onLoginFailure(LoginTag.douyin, error)
    }

    @JvmStatic
    fun onWeiboLoginCallback(activity: Activity, requestCode: Int, resultCode: Int, data: Intent?) {
        mWBAPI.authorizeCallback(activity, requestCode, resultCode, data)
    }

    // QQ登录
    @JvmStatic
    fun loginWithQQ(loginCallback: LoginCallback, activity: Activity) {
        mLoginCallback = loginCallback
        if (!mTencent.isSessionValid) {
            Utils.log("QQLogin")
            mTencent.login(activity, "all", mQqLoginListener)
        }
    }

    @JvmStatic
    fun logoutWithQQ() {
        if (mTencent.isSessionValid) {
            mTencent.logout(HaloApp.getInstance().applicationContext)
        }
    }

    // 微信登录
    @JvmStatic
    fun loginWithWechat(loginCallback: LoginCallback) {
        mLoginCallback = loginCallback
        val config = ARouter.getInstance().build(RouteConsts.provider.config).navigation() as? IConfigProvider
        val register = mIWXAPI.registerApp(config?.getWechatAppId())

        val req = SendAuth.Req()
        req.scope = "snsapi_userinfo"
        req.state = HaloApp.getInstance().getString(R.string.app_name)
        val b = mIWXAPI.sendReq(req)
        Utils.log("微信注册状态：：$register\n 发送状态：：$b")
        if (!register || !b) {
            loginCallback.onLoginFailure(LoginTag.wechat, "请检查是否安装微信客户端")
            Utils.toast(HaloApp.getInstance(), "请检查是否安装微信客户端")
        }
    }

    // 微博登录
    @JvmStatic
    fun loginWithWeibo(loginCallback: LoginCallback, context: Activity) {
        mWBAPI = WBAPIFactory.createWBAPI(context) //初始化微博分享
        mLoginCallback = loginCallback
        val config = ARouter.getInstance().build(RouteConsts.provider.config).navigation() as? IConfigProvider
        mWBAPI.registerApp(
            context,
            AuthInfo(context, config?.getWeiboAppKey(), "http://www.sina.com", WEIBO_SCOPE)
        )
        mWBAPI.authorizeClient(context, object : WbAuthListener {
            override fun onComplete(token: Oauth2AccessToken?) {
                token?.let {
                    RuntimeUtils.getInstance().runOnUiThread {
                        mAccessToken = token
                        if (mAccessToken?.isSessionValid == true) {
                            // 保存 Token 到 SharedPreferences
                            AccessTokenKeeper.writeAccessToken(context, mAccessToken)
                            Utils.toast(context, "授权成功")
                        }
                    }

                    val content = JSONObject()
                    tryWithDefaultCatch {
                        content.put("uid", token.uid)
                        content.put("userName", token.screenName)
                        content.put("access_token", token.accessToken)
                        content.put(
                            "access_token_expire",
                            Utils.getTime(context) + token.expiresTime
                        )
                        content.put("refresh_token", token.refreshToken)
                        // content.put("refresh_token_expire",  Utils.getTime(mContext) + 86400 * 30); //  refresh_token 有效期30天
                        mLoginCallback?.onLoginSuccess(LoginTag.weibo, content)// 微博 登录回调
                    }
                }
            }

            override fun onError(error: com.sina.weibo.sdk.common.UiError?) {
                mLoginCallback?.onLoginFailure(LoginTag.weibo, "微博登录需要客户端支持，请先安装微博")
            }

            override fun onCancel() {
                mLoginCallback?.onLoginFailure(LoginTag.weibo, "取消授权")
            }
        })

        // 第一次启动本应用，AccessToken 不可用
        mAccessToken = AccessTokenKeeper.readAccessToken(context)
    }

    // 抖音登录
    @JvmStatic
    fun loginWithDouYin(loginCallback: LoginCallback, context: Activity) {
//        mLoginCallback = WeakReference(loginCallback)
//        val douYinOpenApi = DouYinOpenApiFactory.create(context)
//
//        val request = Authorization.Request()
//        request.scope = "user_info"                             // 用户授权时必选权限
//        //request.state = "ww";                                 // 用于保持请求和回调的状态，授权请求后原样带回给第三方。
//        //request.callerLocalEntry = "com.xxx.xxx...activity";
//        douYinOpenApi.authorize(request)
    }

    /**
     * 移除登录 callback 引用，避免内存泄漏
     */
    @JvmStatic
    fun unregisterCallback() {
        mLoginCallback = null
    }

    interface LoginCallback {
        fun onLoginSuccess(loginType: LoginTag, jsonContent: JSONObject)

        fun onLoginFailure(loginType: LoginTag, error: String)
    }

}
