package com.bc_chat.account.presenter

import com.alibaba.android.arouter.launcher.ARouter
import com.bc_chat.account.contract.LoginContract
import com.bc_chat.account.task.LoginTask
import com.bc_chat.bc_base.ImService.ImRongService
import com.bc_chat.bc_base.entity.dao.GroupMemberDao
import com.bc_chat.bc_base.presenter.WebPresenter
import com.bc_chat.bc_base.utils.AppConfig
import com.bc_chat.bc_base.utils.Const
import com.google.gson.JsonObject
import com.zhaohaoting.framework.requset.NetWorkCallBack
import com.zhaohaoting.framework.utils.Preferences
import com.zhaohaoting.framework.utils.ToastUtils
import com.zhaohaoting.framework.utils.observer.Observer
import java.lang.Exception

/**
 * author：Created by zhaohaoting on 2019/3/5
 * email：526309416@qq.com
 * desc：登录
 */
class LoginPresenter constructor(view: LoginContract.View) : WebPresenter<LoginContract.View>(view), LoginContract.Presenter {
    override fun login(phone: String?, password: String?) {
        taskHelper.execute<Any>(LoginTask(phone, password), object : NetWorkCallBack<JsonObject>() {

            override fun onPreExecute(task: Any?) {
                view.showLoading(task)
            }

            override fun onPostExecuteSuccess(task: Any?, data: JsonObject?) {
                val uid = data?.get("uid")?.asString
                val token = data?.get("token")?.asString
                loginIM(uid, token)
//                val saveUser = AppConfig.instance.getUser()
//                saveUser.userId = uid!!
//                saveUser.accessToken = token
//                GroupMemberDao.instance.saveUserInfo(saveUser)
//                view.loginSuccess(uid)
            }

            override fun onPostExecuteFailure(task: Any?, exception: Exception?) {
                super.onPostExecuteFailure(task, exception)
                view.loginFailure(exception)
                view.dismissLoading(task)
            }
        })
    }

    /**
     * 登录融云
     */
    private fun loginIM(uid: String?, token: String?) {
        ARouter.getInstance().navigation(ImRongService::class.java).loginIM(uid, token, Observer { key, var1 ->
            if (key.equals(Const.ObserverKey.USER_LOGIN)) {
                if (var1) {
                    view.loginSuccess(uid)
                } else {
                    ToastUtils.show("无法连接聊天服务器")
                    view.loginFailure(Exception("无法连接聊天服务器"))
                }
            }
        })
    }
}
