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

import android.annotation.SuppressLint
import android.app.Activity
import android.text.TextUtils
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.UMEventUtils
import com.ydl.ydlcommon.utils.YDLCacheUtils
import com.ydl.ydlcommon.utils.actionutil.ActionCountUtils
import com.ydl.ydlcommon.utils.log.LogHelper
import com.yidianling.common.tools.ToastUtil
import com.yidianling.router.user.UserResponse
import com.yidianling.user.LoginUtils
import com.yidianling.user.UserHelper
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.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.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) {//第一次登录：是注册
                            mView.baiduActionBury(it.data.uid, UserBIConstants.POSITION_ALIYUN_REGISTER_CLICK)
                        } else {
                            ActionCountUtils.count(UserBIConstants.ACTION_TYPE_DIRECT_LOGIN)

                        }
                        mView.autoLoginSuccess()
                    } else {
//                        ToastUtil.toastShort(it.msg)
                        mView.aliAuthFailed()
                    }
                }, {
                    //走验证码、密码登录
                    mView.aliAuthFailed()
                })
    }


    /**
     * 保存登录信息
     */
    private fun saveUserData(userResponse: UserResponse) {
        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()
                    } else {
                        mView.getAuthToken(it.data.vendorConfigDTOs)
                    }
                }, {
                    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(UserHelper.getUserInfo()!!.uid, UserBIConstants.PART_ID_LOGIN_MAIN,
                UserBIConstants.POSITION_LOGIN_CLICK, "友盟三方登录url无法获取",
                "友盟三方登录api无法获取", 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
                    }
                    LoginUtils.onLogin(it.data)
                    mView.thirdLoginSuccess(it.data.userInfo!!)
                    LogHelper.getInstance().writeLogSync(media.getName() + "登录成功")
                    if (media == SHARE_MEDIA.QQ) {
                        if (it.data.firstLogin == 1) {//第一次登录：是注册
                            mView.baiduActionBury(it.data.uid,UserBIConstants.POSITION_QQ_REGISTER_CLICK)
                        } else {
                            ActionCountUtils.count(UserHelper.getUserInfo()!!.uid, UserBIConstants.PART_ID_LOGIN_MAIN,
                                    UserBIConstants.POSITION_LOGIN_SUCCESS_CLICK, "友盟三方登录url无法获取",
                                    "友盟三方登录api无法获取", sign1)
                        }
                    } else {
                        if (it.data.firstLogin == 1) {//第一次登录：是注册
                            mView.baiduActionBury(it.data.uid,UserBIConstants.POSITION_WX_REGISTER_CLICK)
                        } else {
                            ActionCountUtils.count(UserHelper.getUserInfo()!!.uid, UserBIConstants.PART_ID_LOGIN_MAIN,
                                    UserBIConstants.POSITION_LOGIN_SUCCESS_CLICK, "友盟三方登录url无法获取",
                                    "友盟三方登录api无法获取", sign1)
                        }
                    }
                }, {
                    mView.dismissProgressView()
                    YdlCommonOut.showToast(it.message!!)
                })
    }

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