package com.yidianling.user.ui.login.presenter

import android.annotation.SuppressLint
import android.text.TextUtils
import com.ydl.ydlcommon.mvp.base.BasePresenter
import com.ydl.ydlcommon.router.YdlCommonOut
import com.ydl.ydlcommon.utils.YDLCacheUtils
import com.ydl.ydlcommon.utils.log.AliYunLogConfig
import com.ydl.ydlcommon.utils.log.AliYunRichLogsHelper
import com.ydl.ydlcommon.utils.log.LogHelper
import com.yidianling.common.tools.LogUtil
import com.yidianling.common.tools.ToastUtil
import com.yidianling.user.LoginUtils
import com.yidianling.user.StatusUtils
import com.yidianling.user.api.bean.UserResponseBean
import com.yidianling.user.constants.UserBIConstants
import com.yidianling.user.http.request.CheckAliAuthParam
import com.yidianling.user.http.request.PhoneLoginAutoParam
import com.yidianling.user.ui.login.contract.ILoginContract
import com.yidianling.user.ui.login.model.LoginModelImpl
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.math.BigDecimal

/**
 * @author jiucheng
 * @描述:
 * @Copyright Copyright (c) 2018
 * @Company 壹点灵
 * @date 2018/11/29
 */
class LoginPresenterImpl(view: ILoginContract.View) :
    BasePresenter<ILoginContract.View, ILoginContract.Model>(), ILoginContract.Presenter {

    /**
     * 保存登录信息
     */
    private fun saveUserData(userResponse: UserResponseBean) {
        if (!TextUtils.isEmpty(userResponse.userInfo!!.phone)) {
            YDLCacheUtils.saveUserPhone(userResponse.userInfo!!.phone)
            YDLCacheUtils.saveCountryPhoneCode(userResponse.userInfo!!.country_code)
        }
        if (userResponse.uid!!.contains(".")) {
            val bd = BigDecimal(userResponse.uid)
            var uid = bd.toPlainString()
            if (uid.endsWith(".0")) {
                uid = uid.replace(".0", "")
            }
            userResponse.userInfo!!.uid = uid
            userResponse.uid = uid
        }
        LoginUtils.saveData(userResponse)
        LogHelper.getInstance().writeLogSync("登录成功")
        LoginUtils.onLogin(userResponse)
    }

    /**
     * 通过一键认证服务登陆
     */
    @SuppressLint("CheckResult")
    override fun autoLogin(bean: PhoneLoginAutoParam) {
        mModel.autoLogin(bean)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .doOnSubscribe { mView.showLoading(true) }
            .doAfterTerminate { mView.showLoading(false) }
            .subscribe({
                if (it.code == 200) {
                    //绑定手机号
                    saveUserData(it.data)
                    if (it.data.firstLogin == 1) {//第一次登录：是注册
                        StatusUtils.isFirstLogin = true
                    }
                    mView.autoLoginSuccess()
                    AliYunRichLogsHelper.getInstance()
                        .sendRichLog(AliYunLogConfig.LOGIN, "通过一键认证服务登录成功")
                } else {
//                        ToastUtil.toastShort(it.msg)
                    mView.aliAuthFailed()
                    AliYunRichLogsHelper.getInstance()
                        .sendRichLog(AliYunLogConfig.LOGIN, "通过一键认证服务登陆 失败 msg: ${it.msg}")

                }
            }, {
                //走验证码、密码登录
                mView.aliAuthFailed()

                AliYunRichLogsHelper.getInstance()
                    .sendRichLog(AliYunLogConfig.LOGIN, "通过一键认证服务登陆 Error msg: ${it.message}")
            })
    }

    /**
     * 服务端校验阿里一键认证
     */
    @SuppressLint("CheckResult")
    override fun checkAliAuth(param: CheckAliAuthParam) {
        mModel.checkAliAuth(param)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                if (it?.data == null) {
                    mView.aliAuthFailed()
                }
            }, {
                mView.aliAuthFailed()
            })
    }

    /**
     * 校验手机号：是否是用户版号码、是否有设置密码、是否被绑定
     *@param isBind 是否是第三方登录成功后的绑定操作
     */
    @SuppressLint("CheckResult")
    override fun checkPhoneStatus(
        phone: String,
        countryCode: String,
        isBind: Boolean,
        gatewayUrl: String
    ) {
        mView.showLoading(true)
        mModel.checkPhoneStatus(phone, countryCode, gatewayUrl)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                if (it?.data == null || it?.code != 200) {
                    LogUtil.e("checkPhoneStatus 非200  data null")

                    ToastUtil.toastShort(it.msg)
                    mView.showLoading(false)
                    return@subscribe
                }
                //登录逻辑
                if (it.data.isDoctor == 1) {//是专家账号
                    LogUtil.e("checkPhoneStatus 是专家账号")

                    mView.showLoading(false)
                    mView.showNormalDialog()
                } else {
                    LogUtil.e("present checkPhoneStatusSuccess（）")

                    mView.checkPhoneStatusSuccess(it.data, phone)
                }
            }, {
                LogUtil.e("checkPhoneStatus error  phone:$phone  countryCode:$countryCode ")
                it.printStackTrace()

                mView.showLoading(false)
                if (null != it && !TextUtils.isEmpty(it.message)) {
                    YdlCommonOut.showToast(it.message!!)
                }
            })
    }


    override fun createModel(): ILoginContract.Model {
        return LoginModelImpl()
    }
}