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

import android.annotation.SuppressLint
import android.app.Activity
import android.text.TextUtils
import com.fm.openinstall.OpenInstall
import com.umeng.socialize.bean.SHARE_MEDIA
import com.ydl.ydlcommon.mvp.base.BasePresenter
import com.ydl.ydlcommon.router.YdlCommonOut
import com.ydl.ydlcommon.utils.YDLCacheUtils
import com.ydl.ydlcommon.utils.actionutil.ActionCountUtils
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.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.UserHttpImpl
import com.yidianling.user.http.request.BindPhoneJavaParam
import com.yidianling.user.http.request.CheckAliAuthParam
import com.yidianling.user.http.request.PhoneLoginAutoParam
import com.yidianling.user.ui.login.OneKeyLoginHelp
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 {
    @SuppressLint("CheckResult")
    override fun bindPhone(param: BindPhoneJavaParam) {
        mModel.bindPhone(param)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .doOnSubscribe { mView.showLoading(true) }
            .doAfterTerminate { mView.showLoading(false) }
            .subscribe({
                if (it.code == 200) {
                    ToastUtil.toastShort("手机号绑定成功")
                    mView.bindSuccess()
                } else {
                    ToastUtil.toastShort(it.msg)
                }
            }, {
                ToastUtil.toastShort(it.message)
            })

    }

    /**
     * 通过一键认证服务登陆
     */
    @SuppressLint("CheckResult")
    override fun autoLogin(bean: PhoneLoginAutoParam) {

        ActionCountUtils.count(
            UserBIConstants.POSITION_LOGIN_CLICK,
            UserBIConstants.ACTION_TYPE_DIRECT_LOGIN
        )

        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.baiduActionBury(
                            it.data.uid,
                            UserBIConstants.POSITION_ALIYUN_REGISTER_CLICK
                        )
                    } else {
                        ActionCountUtils.countUid(
                            UserBIConstants.POSITION_LOGIN_SUCCESS_CLICK,
                            it.data.uid!!,
                            UserBIConstants.ACTION_TYPE_DIRECT_LOGIN
                        )
                    }
                    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}")
            })
    }


    /**
     * 保存登录信息
     */
    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 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) {
        mView.showLoading(true)
        mModel.checkPhoneStatus(phone, countryCode)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                if (it?.data == null || it?.code != 200) {
                    ToastUtil.toastShort(it.msg)
                    mView.showLoading(false)
                    return@subscribe
                }
                if (isBind) {//第三方登录成功后的绑定逻辑
                    if (it.data.isRegistered == 1) {
                        mView.showLoading(false)
                        mView.showHasBindedDialog()
                    } else {
                        mView.checkPhoneStatusSuccess(it.data, phone)
                    }
                } else {//登录逻辑
                    if (it.data.isDoctor == 1) {//是专家账号
                        mView.showLoading(false)
                        mView.showNormalDialog()
                    } else {
                        mView.checkPhoneStatusSuccess(it.data, phone)
                    }
                }
            }, {
                mView.showLoading(false)
                if (null != it && !TextUtils.isEmpty(it.message)) {
                    YdlCommonOut.showToast(it.message!!)
                }
            })
    }

    /**
     * 三方登录
     */
    @SuppressLint("CheckResult")
    override fun loginByThird(activity: Activity, media: SHARE_MEDIA) {

        val sign1 =
            if (media == SHARE_MEDIA.QQ) UserBIConstants.ACTION_TYPE_QQ_THIRD_LOGIN else UserBIConstants.ACTION_TYPE_WX_THIRD_LOGIN
        ActionCountUtils.count(UserBIConstants.POSITION_LOGIN_CLICK, sign1)

        UserHttpImpl.getInstance()
            .umLogin(activity, media)
            .doOnSubscribe { mView.showProgressView() }
            .doAfterTerminate {
                mView.dismissProgressView()
            }
            .observeOn(Schedulers.io())
            .flatMap { thirdLoginParam ->
                UserHttpImpl.getInstance().thirdPartJavaLogin(thirdLoginParam)
            }
            .doOnNext { LoginUtils.saveData(it.data) }
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                mView.dismissProgressView()
                if (it?.data == null) {
                    ToastUtil.toastShort(it.msg)
                    return@subscribe
                }
                if (it.data.firstLogin == 1) {//第一次登录：是注册
                    StatusUtils.isFirstLogin = true
                    if (media == SHARE_MEDIA.QQ) {
                        mView.baiduActionBury(
                            it.data.uid,
                            UserBIConstants.POSITION_QQ_REGISTER_CLICK
                        )
                        ActionCountUtils.baiduCount(
                            it.data.uid,
                            UserBIConstants.APP_REGISTER_PAGE,
                            UserBIConstants.POSITION_QQ_REGISTER_CLICK,
                            "",
                            "",
                            25,
                            OneKeyLoginHelp.openInstallKey
                        )
                    } else {
                        mView.baiduActionBury(
                            it.data.uid,
                            UserBIConstants.POSITION_WX_REGISTER_CLICK
                        )
                        ActionCountUtils.baiduCount(
                            it.data.uid,
                            UserBIConstants.APP_REGISTER_PAGE,
                            UserBIConstants.POSITION_WX_REGISTER_CLICK,
                            "",
                            "",
                            25,
                            OneKeyLoginHelp.openInstallKey
                        )
                    }
                    // 用户注册成功后调用
                    OpenInstall.reportRegister()
                } else {
                    ActionCountUtils.countUid(
                        UserBIConstants.POSITION_LOGIN_SUCCESS_CLICK,
                        it.data.uid!!,
                        sign1
                    )
                }

                LoginUtils.onLogin(it.data)
                mView.thirdLoginSuccess(
                    it.data.userInfo!!,
                    if (media == SHARE_MEDIA.QQ) "qq" else "weixin"
                )
                LogHelper.getInstance().writeLogSync(media.getName() + "登录成功")
                AliYunRichLogsHelper.getInstance()
                    .sendRichLog(AliYunLogConfig.LOGIN, media.getName() + "登录成功")

            }, {
                mView.dismissProgressView()
                YdlCommonOut.showToast(it.message!!)
                AliYunRichLogsHelper.getInstance()
                    .sendRichLog(AliYunLogConfig.LOGIN, media.getName() + "登录失败")

            })
    }

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