package com.grkj.iscs_mc.view.presenter

import android.content.Context
import com.grkj.iscs_mc.R
import com.grkj.iscs_mc.model.vo.card.CardInfoRespVO
import com.grkj.iscs_mc.model.vo.user.UserInfoRespVO
import com.grkj.iscs_mc.util.Executor
import com.grkj.iscs_mc.util.NetApi
import com.grkj.iscs_mc.util.SPUtils
import com.grkj.iscs_mc.util.ToastUtils
import com.grkj.iscs_mc.view.base.BasePresenter
import com.grkj.iscs_mc.view.iview.ILoginView

class LoginPresenter : BasePresenter<ILoginView>() {

    fun login(context: Context, account: String, pwd: String, callBack: (Boolean, CardInfoRespVO?, UserInfoRespVO?) -> Unit) {
        if (account.isEmpty()) {
            ToastUtils.tip(context.getString(R.string.please_input_account))
            return
        } else if (account.isEmpty()) {
            ToastUtils.tip(context.getString(R.string.please_input_password))
            return
        }
        NetApi.login(account, pwd) {
            if (it == true) {
                NetApi.getUserInfo { userInfo ->
                    NetApi.getCardInfoByLoginUser { itInfo ->
                        itInfo?.let { info ->
                            info.userName = userInfo?.user?.nickName
                            SPUtils.setLoginUser(mContext!!, info)
                        }
                        callBack.invoke(it, itInfo, userInfo)
                    }
                }
            } else {
                callBack.invoke(false, null, null)
            }
        }
    }

    fun cardLogin(card: String, callBack: (Boolean, CardInfoRespVO?, UserInfoRespVO?) -> Unit) {
        NetApi.cardLogin(card) {
            if (it == true) {
                NetApi.getUserInfo { userInfo ->
                    NetApi.getCardInfoByLoginUser { itInfo ->
                        Executor.runOnMain {
                            itInfo?.let { info ->
                                info.userName = userInfo?.user?.nickName
                                SPUtils.setLoginUser(mContext!!, info)
                            }
                            callBack.invoke(it, itInfo, userInfo)
                        }
                    }
                }
            } else {
                Executor.runOnMain {
                    callBack.invoke(false, null, null)
                }
            }
        }
    }
}