package com.sixin.module_p.ui.set

import androidx.lifecycle.MutableLiveData
import com.alibaba.android.arouter.launcher.ARouter
import com.lukouguoji.module_base.base.BaseViewModel
import com.lukouguoji.module_base.common.Constant
import com.lukouguoji.module_base.common.ConstantEvent
import com.lukouguoji.module_base.db.perference.SharedPreferenceUtil
import com.lukouguoji.module_base.http.net.NetApply
import com.lukouguoji.module_base.impl.FlowBus
import com.lukouguoji.module_base.ktx.launchCollect
import com.lukouguoji.module_base.ktx.noNull
import com.lukouguoji.module_base.ktx.showToast
import com.lukouguoji.module_base.ktx.toRequestBody
import com.lukouguoji.module_base.ktx.verifyNullOrEmpty
import com.lukouguoji.module_base.router.ARouterConstants
import com.lukouguoji.module_base.service.repository.LoginRepository

class PdaSetViewModel : BaseViewModel() {

    val account = SharedPreferenceUtil.getString(Constant.Share.userName).noNull()

    val password = MutableLiveData("")
    val oldPassword = MutableLiveData("")

    ///////////////////////////////////////////////////////////////////////////
    // 方法区
    ///////////////////////////////////////////////////////////////////////////

    /**
     * 确认 点击
     */
    fun onConfirmClick() {
        if ((password.value.verifyNullOrEmpty("请输入新密码")
                    || oldPassword.value.verifyNullOrEmpty("请输入原密码"))
        ) {
            return
        }
        showLoading()
        launchCollect({
            NetApply.api.modifyPassword(
                mapOf(
                    "id" to "",
                    "newPwd" to password.value,
                    "oldPwd" to oldPassword.value,
                ).toRequestBody()
            )
        }) {
            onSuccess = {
                if (it.verifySuccess()) {
                    showToast(it.msg.noNull("密码修改成功"))
                    LoginRepository.logout()
                    ARouter.getInstance().build(ARouterConstants.ACTIVITY_URL_LOGIN).navigation()
                    FlowBus.with<Any>(ConstantEvent.LOGOUT)
                        .tryEmit(true)
                } else {
                    showToast(it.msg.noNull("密码修改失败"))
                }
            }
            onComplete = {
                dismissLoading()
            }
        }
    }

    /**
     * 取消点击
     */
    fun onCancelClick() {
        password.value = ""
        oldPassword.value = ""
    }

    /**
     * 退出登录 点击
     */
    fun onLogoutClick() {
        LoginRepository.logout()
        ARouter.getInstance().build(ARouterConstants.ACTIVITY_URL_LOGIN).navigation()
        FlowBus.with<Any>(ConstantEvent.LOGOUT)
            .tryEmit(true)
    }

}