package com.yidianling.user

import com.tencent.bugly.crashreport.CrashReport
import com.ydl.ydlcommon.data.http.RxUtils
import com.ydl.ydlcommon.utils.BuryPointUtils
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.http.UserHttpImpl
import com.yidianling.user.http.request.Logout
import com.yidianling.user.route.UserIn
import de.greenrobot.event.EventBus
import io.reactivex.android.schedulers.AndroidSchedulers


/**
 * author : Zhangwenchao
 * e-mail : zhangwch@yidianling.com
 * time   : 2018/05/09
 */
object LoginUtils {

    @JvmStatic
    fun saveData(userInfo: UserResponseBean?) {
        UserHelper.setUserinfo(userInfo)
    }

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

        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?) {
                UserIn.imSetAccount(userInfo?.uid ?: "")
            }

            override fun onFailed(i: Int) {
                LogUtil.e("IM登录失败：$i")
            }

            override fun onException(throwable: Throwable?) {
                LogUtil.e("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() {
        UserIn.imLogout()
        UserIn.closePlayer()
        UserIn.clearImData()
        UserHelper.setUserinfo(null)
    }


}