package com.yidianling.user

import com.ydl.webview.RefreshWebEvent
import com.ydl.ydlcommon.data.http.RxUtils
import com.ydl.ydlcommon.data.http.ThrowableConsumer
import com.ydl.ydlcommon.mvp.base.BasePresenter
import com.ydl.ydlcommon.utils.log.LogHelper
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.http.request.LoginParam
import com.yidianling.user.route.UserIn
import de.greenrobot.event.EventBus
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Consumer

/**
 * author : Zhangwenchao
 * e-mail : zhangwch@yidianling.com
 * time   : 2018/02/02
 */
class LoginPresenter(view: LoginContract.View): BasePresenter<LoginContract.View, LoginContract.Model>(), LoginContract.Presenter {

    override fun createModel(): LoginContract.Model {
        return LoginModel()
    }

    override fun login(param: LoginParam) {
        val d = mModel.login(param).compose(RxUtils.resultData())
                .doOnNext {
                    //存储登录缓存
                    LoginHelper.login(it)
                }
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe { mView.startLogin() }
                .doAfterTerminate {
                    mView.onLoginStop()
                }
                .subscribe(Consumer {
                    LogHelper.getInstance().writeLogSync("登录成功")
                    EventBus.getDefault().post(RefreshWebEvent())
                    mView.loginSuccess(it)
                    val info = IMLoginInfo(it.uid.toString(), it.hxpwd!!)
                    val callback = object : IMRequestCallback<IMLoginInfo> {
                        override fun onSuccess(t: IMLoginInfo?) {
                            setHXInfo(it)
                        }

                        override fun onFailed(i: Int) {
                            mView.loginFail("账号登录异常")
                        }

                        override fun onException(throwable: Throwable?) {
                            mView.loginFail("未知错误02")
                        }
                    }
                    UserIn.imSetAccount(info.account)
                    UserIn.imLogin(info, callback)
                }, object : ThrowableConsumer() {
                    override fun accept(msg: String) {
                        LogHelper.getInstance().writeLogSync("登录失败：$msg")
                        mView.loginFail(msg)
                    }
                })
    }

    private fun setHXInfo(userInfo: UserResponseBean?) {
        try {
            if (userInfo != null) {
                UserIn.imSetAccount(userInfo.uid.toString())
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}