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

import android.annotation.SuppressLint
import android.text.TextUtils
import com.ydl.ydlcommon.modular.ModularServiceManager
import com.ydl.ydlcommon.mvp.base.BasePresenter
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.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.BindPhoneJavaParam
import com.yidianling.user.http.request.PhoneLoginCodeParam
import com.yidianling.user.ui.login.contract.IVerificationCodeContract
import com.yidianling.user.ui.login.model.VerificationCodeModelImpl
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.math.BigDecimal

/**
 * @author jiucheng
 * @描述:
 * @Copyright Copyright (c) 2018
 * @Company 壹点灵
 * @date 2018/12/3
 */
class VerificationCodePresenterImpl(view: IVerificationCodeContract.View) : BasePresenter<IVerificationCodeContract.View, IVerificationCodeContract.Model>(), IVerificationCodeContract.Presenter {

    override fun createModel(): IVerificationCodeContract.Model {
        return VerificationCodeModelImpl()
    }

    //发送登录验证码
    @SuppressLint("CheckResult")
    override fun sendLoginCode(phone: String, phoneCountryCode: String) {
        mModel.sendLoginMsgCode(phone, phoneCountryCode)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe { mView.showLoading(true) }
                .doAfterTerminate { mView.showLoading(false) }
                .subscribe({
                    if (it.code == 200) {
                        YDLCacheUtils.saveCodeTime(phone, System.currentTimeMillis().toString())
                        mView.startCountdown(60)
                    } else {
                        mView.startAnim()
                        ToastUtil.toastShort(it.msg)
                    }
                }, {
                    mView.startAnim()
                    ToastUtil.toastShort(it.message)
                })
    }

    /**
     * 重置密码的验证码
     */
    @SuppressLint("CheckResult")
    override fun sendResetCode(phone: String, countryCode: String) {
        mModel.sendResetCode(phone, countryCode)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe { mView.showLoading(true) }
                .doAfterTerminate { mView.showLoading(false) }
                .subscribe({
                    if (it.data!=null){
                        if (it.code == 200) {
                            YDLCacheUtils.saveResetCodeTime(phone, System.currentTimeMillis().toString())
//                        ToastUtil.toastShort("验证码已发送")
                            mView.startCountdown(60)
                        } else {
                            mView.startAnim()
                        }
                    }else{
                        ToastUtil.toastShort(it.msg)//服务端返回{验证码错误&异常}信息
//                        mView.startAnim()
                        mView.verificationErrorCode()
                    }

                }, {
                    mView.startAnim()
                    ToastUtil.toastShort(it.message)
                })
    }

    /**
     * 绑定手机号
     */
    @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.data != null) {
                        if (it.code == 200) {
                            //绑定手机号成功后清空本地保存时间
                            YDLCacheUtils.saveCodeTime(param.phoneNumber, "")

                            ToastUtil.toastShort("手机号绑定成功")
                            mView.bindSuccess()
                        } else {
//                            mView.startAnim()
                            ToastUtil.toastShort(it.msg)
                            mView.verificationErrorCode()
                        }
                    } else {
                        ToastUtil.toastShort(it.msg)//服务端返回{验证码错误&异常}信息
//                        mView.startAnim()
                        mView.verificationErrorCode()
                    }
                }, {
//                    mView.startAnim()
                    mView.verificationErrorCode()
                    ToastUtil.toastShort(it.message)
                })

    }

    /**
     * 检查重置密码的验证码(重置密码就是忘记密码)
     */
    @SuppressLint("CheckResult")
    override fun checkResetCode(phone: String, countryCode: String, msgCode: String) {
        mModel.checkResetCode(phone, countryCode, msgCode)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe { mView.showLoading(true) }
                .doAfterTerminate { mView.showLoading(false) }
                .subscribe({
                    if (it.data!=null){
                        if (it.code == 200) {
                            //检查重置密码的验证码后清空本地保存时间
                            YDLCacheUtils.saveResetCodeTime(phone, "")

                            mView.checkResetCodeSuccess(msgCode)
                        } else {
                            mView.startAnim()
                            ToastUtil.toastShort(it.msg)//服务端返回{验证码错误&异常}信息
//                        mView.startAnim()
                            mView.verificationErrorCode()
                        }
                    }else{
                        ToastUtil.toastShort(it.msg)//服务端返回{验证码错误&异常}信息
//                        mView.startAnim()
                        mView.verificationErrorCode()
                    }

                }, {
                    mView.startAnim()
                    ToastUtil.toastShort(it.message)
                })
    }

    /**
     * 验证码验证码登录
     */
    @SuppressLint("CheckResult")
    override fun loginByMsgCode(phone: String, phoneCountryCode: String, msgCode: String) {
        ActionCountUtils.count(UserBIConstants.POSITION_LOGIN_CLICK,UserBIConstants.ACTION_TYPE_CODE_LOGIN)
        var param = PhoneLoginCodeParam(msgCode, phoneCountryCode, phone)
        mModel.loginByMsgCode(param)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe { mView.showLoading(true) }
                .doAfterTerminate { mView.showLoading(false) }
                .subscribe({
                    if (it.data != null) {
                        //登录成功后toast提示
                        ToastUtil.toastShort("登录成功")
                        //验证码登录成功后清空本地保存时间
                        YDLCacheUtils.saveCodeTime(phone, "")

                        saveUserData(it.data)
                        
                        if (it.data.firstLogin == 1) {//第一次登录：是注册
                            StatusUtils.isFirstLogin = true
                            mView.baiduActionBury()
                        } else {
                            ActionCountUtils.countUid(UserBIConstants.POSITION_LOGIN_SUCCESS_CLICK,it.data.uid!!,UserBIConstants.ACTION_TYPE_CODE_LOGIN)
                        }
                        mView.closeActivity()
                    } else {
                        ToastUtil.toastShort(it.msg)//服务端返回{验证码错误&异常}信息
//                        mView.startAnim()
                        mView.verificationErrorCode()
                    }
                }, {
                    mView.startAnim()
                    ToastUtil.toastShort(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)
    }
}