package com.yidianling.user

import android.app.Activity
import android.content.Intent
import com.tencent.bugly.crashreport.CrashReport
import com.ydl.ydlcommon.data.http.RxUtils
import com.ydl.ydlcommon.utils.ActivityManager
import com.ydl.ydlcommon.utils.BuryPointUtils
import com.ydl.ydlcommon.utils.log.AliYunLogConfig
import com.ydl.ydlcommon.utils.log.AliYunRichLogsHelper
import com.yidianling.common.tools.LogUtil
import com.yidianling.im.api.bean.IMLoginInfo
import com.yidianling.im.api.bean.IMRequestCallback
import com.yidianling.user.api.bean.UserResponseBean
import com.yidianling.user.api.event.UserLoginEvent
import com.yidianling.user.api.event.UserLogoutEvent
import com.yidianling.user.api.listener.LoginCallBackListener
import com.yidianling.user.http.UserHttpImpl
import com.yidianling.user.http.request.Logout
import com.yidianling.user.route.UserIn
import com.yidianling.user.safePrivate.FingerPrintCheckActivity
import com.yidianling.user.safePrivate.FingerPrintUtil
import com.yidianling.user.safePrivate.HandUnlockCheckActivity
import com.yidianling.user.ui.collect.CollectSexAndBirthActivity
import com.yidianling.user.ui.login.InputPassWordActivity
import com.yidianling.user.ui.login.OneKeyLoginHelp
import com.yidianling.user.ui.login.RegisterAndLoginActivity
import com.yidianling.user.ui.login.VerificationCodeActivity
import de.greenrobot.event.EventBus
import io.reactivex.android.schedulers.AndroidSchedulers


/**
 * author : Zhangwenchao
 * e-mail : zhangwch@yidianling.com
 * time   : 2018/05/09
 */
object LoginUtils {
    var logingCallBackListener: LoginCallBackListener? = null
    fun setLoginCallBack(listener: LoginCallBackListener?) {
        logingCallBackListener = listener
    }
    @JvmStatic
    fun saveData(userInfo: UserResponseBean?) {
        UserHelper.setUserinfo(userInfo)
    }

    @JvmStatic
    fun onLogin(userInfo: UserResponseBean?) {
        //设置异常用户ID
        CrashReport.setUserId(userInfo?.uid)
        //登录IM聊天
        loginIm(userInfo)
        //设置极光注册id
        LoginHelper.setChannelId()

        val loginEvent = UserLoginEvent("login", userInfo?.uid!!)
        EventBus.getDefault().post(loginEvent)
        BuryPointUtils.bindUid(userInfo?.uid ?: "")
    }

    private fun loginIm(userInfo: UserResponseBean?) {
        val info = IMLoginInfo(userInfo?.uid ?: "", userInfo?.hxpwd ?: "")
        val callback = object : IMRequestCallback<IMLoginInfo> {
            override fun onSuccess(t: IMLoginInfo?) {
                LogUtil.e("IM登录成功：" + "info.account:" + info.account + "info.passWord" + info.passWord)
                UserIn.imSetAccount(userInfo?.uid ?: "")
               AliYunRichLogsHelper.getInstance().sendRichLog(AliYunLogConfig.LOGIN, "IM登录成功")
            }

            override fun onFailed(i: Int) {
                LogUtil.e("IM登录失败：$i" + "info.account:" + info.account + "info.passWord" + info.passWord)
               AliYunRichLogsHelper.getInstance().sendRichLog(AliYunLogConfig.LOGIN, "IM登录失败")

            }

            override fun onException(throwable: Throwable?) {
                LogUtil.e("IM登录onException：${throwable?.message}")
                AliYunRichLogsHelper.getInstance()
                    .sendRichLog(AliYunLogConfig.LOGIN, "IM登录onException：${throwable?.message}")

            }
        }

        UserIn.imSetAccount(info.account)
        UserIn.imLogin(info, callback)
    }


    @JvmStatic
    fun logout() {
        EventBus.getDefault().post(UserLogoutEvent())
        UserHttpImpl.getInstance().logout(Logout())
            .compose(RxUtils.resultData())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                logoutClearLocal()
            }, {
                logoutClearLocal()
            })
    }

    @JvmStatic
    fun logoutClearLocal() {
        logingCallBackListener=null
       AliYunRichLogsHelper.getInstance().sendRichLog(AliYunLogConfig.LOGIN, "退出登录")
        UserIn.imLogout()
        UserIn.closePlayer()
        UserIn.clearImData()
        UserHelper.setUserinfo(null)
    }

    @JvmStatic
    fun loginSuccessOperate(activity: Activity) {
        if (logingCallBackListener!=null){
            logingCallBackListener?.loginSuccess()
        }
        // 登录成功后，如果一键登录界面没有关闭，则关闭掉
        OneKeyLoginHelp.quitLoginPage()
        val size = ActivityManager.getActivitySize()
        if (size <= 2) {//当前stack只有两个页面，必然没有MainActivity
            ActivityManager.finishAll()
            if (StatusUtils.isFirstLogin && StatusUtils.isFirstStartApp) {
                activity.startActivity(Intent(activity, CollectSexAndBirthActivity::class.java))
            } else {
                UserIn.mainIntent(activity)
            }
        } else {//需要判断stack中是否有MainActivity
            //这里不能引用到MainActivity 想别的办法
            var flag = 0
            //判断stack中activity是否属于登录相关的三个页面
            for (activity in ActivityManager.getInstance().getActivitys()) {
                if (activity is RegisterAndLoginActivity
                    || activity is VerificationCodeActivity
                    || activity is InputPassWordActivity
                    || activity is FingerPrintCheckActivity
                    || activity is HandUnlockCheckActivity
                ) {
                    flag++
                }
            }
            //flag小于size：则stack中必然有其他的activity
            if (flag < size) {
                ActivityManager.getInstance().finishActivity(VerificationCodeActivity::class.java)
                ActivityManager.getInstance().finishActivity(InputPassWordActivity::class.java)
                ActivityManager.getInstance().finishActivity(RegisterAndLoginActivity::class.java)
                ActivityManager.getInstance().finishActivity(FingerPrintCheckActivity::class.java)
                ActivityManager.getInstance().finishActivity(HandUnlockCheckActivity::class.java)
                FingerPrintUtil.instance().setCurrentUnLockTime(System.currentTimeMillis())
            } else {
                ActivityManager.finishAll()
                if (StatusUtils.isFirstLogin && StatusUtils.isFirstStartApp) {
                    activity.startActivity(Intent(activity, CollectSexAndBirthActivity::class.java))
                } else {
                    UserIn.mainIntent(activity)
                }
            }
        }
    }
}