package com.zxhl.cms.utils

import android.app.Activity
import android.content.Intent
import android.os.Handler
import android.util.Log
import com.facebook.*
import com.facebook.login.LoginManager
import com.facebook.login.LoginResult
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-26 11:04 GMT+8
 * @detail :
 */
class FaceBookLoginUtil {

    private val TAG = "FaceBookLoginUtil"

    private var mActivity: Activity;
    private var mLoginCallBack: LoginCallBack? = null;
    private var callbackManager: CallbackManager? = null;

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

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

    fun init() {
        callbackManager = CallbackManager.Factory.create()
        LoginManager.getInstance().registerCallback(callbackManager,
            object : FacebookCallback<LoginResult> {
                override fun onSuccess(loginResult: LoginResult) {
                    //延时500毫秒获取信息，不然获取不到
                    val handler = Handler()
                    handler.postDelayed(
                        {
                            val accessToken = loginResult.accessToken
                            val profile = Profile.getCurrentProfile()
                            if (profile != null) {
                                bindFaceBookLogin(
                                    accessToken.userId,
                                    profile.name,
                                    profile.getProfilePictureUri(
                                        200,
                                        200
                                    ).toString()
                                )
                            } else {
                                mLoginCallBack?.onLoginError("Success_未获取到登录信息")
                            }
                        }, 1000
                    )
                }

                override fun onCancel() {
                    mLoginCallBack?.onLoginError("FaceBookLoginCancel")
                }

                override fun onError(exception: FacebookException) {
                    mLoginCallBack?.onLoginError("FaceBookLogin error:" + exception.message)
                }
            })
    }

    /**
     * faceBook登录
     */
    fun faceBookLogin(callBack: LoginCallBack) {
        mLoginCallBack = callBack;
        val accessToken = AccessToken.getCurrentAccessToken()
        val profile = Profile.getCurrentProfile()
        if (accessToken != null && !accessToken.isExpired && profile != null) {
            bindFaceBookLogin(
                accessToken.userId,
                profile.name,
                profile.getProfilePictureUri(200, 200).toString()
            )
        } else {
            LoginManager.getInstance()
                .logInWithReadPermissions(mActivity, listOf("public_profile"));
        }
    }

    /**
     * Activity 重写
     * */
    fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        callbackManager?.onActivityResult(requestCode, resultCode, data)
    }

    /**
     * faceBook 绑定后端服务器
     * */
    private fun bindFaceBookLogin(userId: String?, userName: String?, picture: String?) {
        ApiClient.homeApi.authFaceBookLogin(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() {

    }

    /**
     * 断开链接
     */
    fun revokeAccess() {

    }


}