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.StringUtils

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.constants.UserBIConstants
import com.yidianling.user.http.request.PhoneLoginPwdParam
import com.yidianling.user.http.request.PhoneResetPwdParam
import com.yidianling.user.ui.login.contract.IInputPassWordContract
import com.yidianling.user.ui.login.model.InputPassWordModelImpl
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.math.BigDecimal

/**
 * @author jiucheng
 * @描述:密码输入页面presenter
 * @Copyright Copyright (c) 2018
 * @Company 壹点灵
 * @date 2018/12/2
 */
class InputPassWordPresenterImpl : BasePresenter<IInputPassWordContract.View, IInputPassWordContract.Model>(), IInputPassWordContract.Presenter {

    override fun createModel(): IInputPassWordContract.Model {
        return InputPassWordModelImpl()
    }

    /**
     * 重新设置密码
     */
    override fun resetPwd(newPassword: String, phone: String, msgCode: String, phoneCountryCode: String) {

        ActionCountUtils.count(UserBIConstants.ACTION_TYPE_RESET_PWD)

        var param = PhoneResetPwdParam(StringUtils.md5(newPassword), phoneCountryCode, msgCode, phone)
        mModel.resetPwd(param)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe { mView.showLoading(true) }
                .doAfterTerminate { mView.showLoading(false) }
                .subscribe({
                    if (it?.data == null) {
                        ToastUtil.toastShort(it.msg)
                    } else {
                        if (it.data.userInfo?.user_type == 2) {
                            mView.showNormalDialog()
                        } else {
                            ToastUtil.toastShort("修改密码成功")
                            saveUserData(it.data)
                            ActionCountUtils.count(UserBIConstants.ACTION_TYPE_RESET_PWD)
                            if (it.data.firstLogin == 1) {//第一次登录：是注册
                                // 重设密码登录已经不可能是首次登录，所以不进行百度埋点
                                //view.baiduActionBury()
                            } else {
                            }
                            mView.closeActivity()
                        }
                    }
                }, {
                    YdlCommonOut.showToast(it.message!!)
                })
    }


    /**
     * 手机号密码登录
     */
    @SuppressLint("CheckResult")
    override fun userLoginByPassword(inputPassword: String, phone: String, phoneCountryCode: String) {

        ActionCountUtils.count(UserBIConstants.ACTION_TYPE_PWD_LOGIN)


        var param = PhoneLoginPwdParam(StringUtils.md5(inputPassword), phoneCountryCode, phone)
        mModel.userLoginByPassword(param)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe { mView.showLoading(true) }
                .doAfterTerminate { mView.showLoading(false) }
                .subscribe({
                    if (it?.data == null) {
                        ToastUtil.toastShort(it.msg)
                        mView.startAnim()
                    } else {
                        if (it.data.userInfo?.user_type == 2) {
                            mView.showNormalDialog()
                        } else {
                            saveUserData(it.data)
                            if (it.data.firstLogin == 1) {//第一次登录：是注册
                                mView.baiduActionBury()
                            } else {
                                ActionCountUtils.countUid(UserBIConstants.ACTION_TYPE_PWD_LOGIN,it.data.uid!!)
                            }
                            mView.closeActivity()
                        }
                    }
                }, {
                    YdlCommonOut.showToast(it.message!!)
                })
    }

    /**
     * 保存登录信息
     */
    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)
    }
}
