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

import android.annotation.SuppressLint
import android.text.TextUtils
import com.ydl.audioim.api.IAudioImService
import com.ydl.ydlcommon.app.Apm
import com.ydl.ydlcommon.modular.findRouteService
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.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.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.POSITION_LOGIN_CLICK,
            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.countUid(
                            UserBIConstants.POSITION_LOGIN_SUCCESS_CLICK,
                            it.data.uid!!,
                            UserBIConstants.ACTION_TYPE_RESET_PWD
                        )
                        if (it.data.firstLogin == 1) {//第一次登录：是注册
                            StatusUtils.isFirstLogin = true
                            // 重设密码登录已经不可能是首次登录，所以不进行百度埋点
                            //view.baiduActionBury()
                        } else {
                        }
                        mView.closeActivity()
                    }
                }
            }, {
                YdlCommonOut.showToast(it.message!!)
            })
    }


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

        var param = PhoneLoginPwdParam(StringUtils.md5(inputPassword), phoneCountryCode, phone)
        findRouteService(IAudioImService::class.java).reportCallEvent("login", "userLogin", "用户登录", null)
        mModel.userLoginByPassword(param)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .doOnSubscribe { mView.showLoading(true) }
            .doAfterTerminate { mView.showLoading(false) }
            .subscribe({
                if (it?.data == null) {
                    AliYunRichLogsHelper.getInstance()
                        .sendRichLog(AliYunLogConfig.LOGIN, "手机号密码 登录失败 msg: ${it.msg}")
                    ToastUtil.toastShort(it.msg)
                    Apm.reportEvent("login_android", "password_error", "密码登录失败,$phoneCountryCode-$phone")
                    mView.startAnim()
                    findRouteService(IAudioImService::class.java).reportCallEvent("login", "userLoginFail", "用户登录失败", null)
                } else {
                    if (it.data.userInfo?.user_type == 2) {
                        mView.showNormalDialog()
                        Apm.reportEvent("login_android", "isexpert", "登录—专家帐号,$phoneCountryCode-$phone")
                    } else {
                        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_PWD_LOGIN
                            )
                        }
                        mView.closeActivity()
                    }
                    findRouteService(IAudioImService::class.java).reportCallEvent("login", "userLoginSuccess", "用户登录成功", null)
                    AliYunRichLogsHelper.getInstance().sendRichLog(AliYunLogConfig.LOGIN, "手机号密码 登录成功")

                }
            }, {
                YdlCommonOut.showToast(it.message!!)
                Apm.reportEvent("login_android", "password_error", "密码登录失败${it.message}")
                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)
    }
}
