package com.rdiot.yx485.login.viewModel

import android.text.TextUtils
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.google.gson.Gson
import com.king.zxing.util.LogUtils
import com.rdiot.yx485.base.BaseViewModel
import com.rdiot.yx485.http.Url
import com.rdiot.yx485.http.Url.BACKGROUNDS
import com.rdiot.yx485.http.entity.BaseReplyBean
import com.rdiot.yx485.login.CodeRequestBean
import com.rdiot.yx485.login.LoginAccountBean
import com.rdiot.yx485.login.LoginReplyBean
import com.rdiot.yx485.login.SetPwd
import com.rdiot.yx485.login.model.LoginSmsBean
import com.rdiot.yx485.login.model.SplashResultBean
import com.rdiot.yx485.login.model.SplashResultBean.SplashBean.SplashPicture
import com.rdiot.yx485.util.LocalCache
import com.zcolin.frame.http.ZHttp
import com.zcolin.frame.http.response.ZResponse
import com.zcolin.frame.util.MD5Util
import com.zcolin.frame.util.SpUtil
import okhttp3.Response

class LoginViewModel : BaseViewModel() {
    private var mSplashPicture = MutableLiveData<SplashPicture>()
    val splashPicture: LiveData<SplashPicture>
        get() = mSplashPicture

    val loginType = MutableLiveData<String>("验证码登录")

    fun loadSplashPicture() {
        LogUtils.d("loadSplashPicture")
        var map = HashMap<String, String>()
        map["q"] = "list"
        map["type"] = "1"
        ZHttp.get<SplashResultBean?>(BACKGROUNDS, map, object : ZResponse<SplashResultBean?>() {
            override fun onSuccess(
                response: Response?,
                resObj: SplashResultBean?
            ) {
                LogUtils.d(resObj.toString())
                resObj?.let {
                    if (!it.isSuccess || it.data == null) {
                        mErrorMessage.value = it.message
                        return
                    }

                    if (it.data.list == null || it.data.list.isEmpty()) {
                        mErrorMessage.value = "启动图片为空"
                        return
                    }

                    mSplashPicture.value = it.data.list[0]
                }
            }

            override fun onError(code: Int, error: String?) {
                super.onError(code, error)
                mErrorMessage.value = error
            }
        })
    }

    private var mSendState = MutableLiveData<Boolean>()
    val sendState: LiveData<Boolean>
        get() = mSendState
    private var mPhone = ""

    fun sendSmsCode(phone: String) {
        if (TextUtils.isEmpty(phone)) {
            //提示输入手机号
            mErrorMessage.value = "请输入手机号"
            return
        }
        if (!phone.matches("^1[3-9]\\d{9}$".toRegex())) {
            //提示输入手机号
            mErrorMessage.value = "请输入正确的手机号"
            return
        }
        val codeRequestBean = CodeRequestBean()
        codeRequestBean.tel = phone
        codeRequestBean.bzty = 1
        ZHttp.postJson<BaseReplyBean?>(
            Url.LOGINCODE,
            codeRequestBean,
            object : ZResponse<BaseReplyBean?>() {
                override fun onSuccess(response: Response?, resObj: BaseReplyBean?) {
                    resObj?.let {
                        mSendState.value = it.isSuccess
                        if (it.isSuccess) {
                            mPhone = phone
                        } else {
                            mErrorMessage.value = it.message
                        }
                    }
                }

                override fun onError(code: Int, error: String?) {
                    super.onError(code, error)
                    mErrorMessage.value = error
                }
            },
        )
    }

    private var mLoginState = MutableLiveData<Boolean>()
    val loginState: LiveData<Boolean>
        get() = mLoginState

    fun loginWithSms(phone: String, code: String) {
        if (TextUtils.isEmpty(phone) || TextUtils.isEmpty(code)) {
            //提示输入手机号
            mErrorMessage.value = "请输入手机号和验证码"
            return
        }
        val loginSmsBean = LoginSmsBean()
        loginSmsBean.code = code
        loginSmsBean.phone = phone
        ZHttp.postJson<LoginReplyBean?>(
            Url.LOGINSMS,
            loginSmsBean,
            object : ZResponse<LoginReplyBean?>() {
                override fun onSuccess(response: Response?, bean: LoginReplyBean?) {
                    bean?.let {
                        mLoginState.value = it.isSuccess
                        if (!it.isSuccess) {
                            mErrorMessage.value = it.message
                            return
                        }

                        LocalCache.saveLoginInfo(it.data)
                        LocalCache.saveLoginAccount(phone, "")
                        SpUtil.putString("access_token", it.data.access_token)
                        SpUtil.putString("token_type", it.data.token_type)
                        SpUtil.putBoolean("app_first_login", it.data.app_first_login)
                        SpUtil.putInt("expires_at", it.data.expires_at)
                    }
                }

                override fun onError(code: Int, error: String?) {
                    super.onError(code, error)
                    mErrorMessage.value = "登录失败"
                }
            })
    }

    fun loginWithPwd(phone: String, pwd: String) {
        if (phone.isEmpty() || pwd.isEmpty()) {
            mErrorMessage.value = "手机号和密码不能为空"
            return
        }

        //登录
        val loginBean = LoginAccountBean()
        loginBean.phone = phone
        loginBean.password = MD5Util.getMD5Str(pwd)
        ZHttp.postJson<LoginReplyBean?>(
            Url.LOGIN,
            loginBean,
            object : ZResponse<LoginReplyBean?>() {
                override fun onSuccess(response: Response?, bean: LoginReplyBean?) {
                    bean?.let {
                        mLoginState.value = it.isSuccess
                        if (!it.isSuccess) {
                            mErrorMessage.value = it.message
                            return
                        }

                        LocalCache.saveLoginInfo(it.data)
                        LocalCache.saveLoginAccount(phone, pwd)
                        SpUtil.putString("access_token", it.data.access_token)
                        SpUtil.putString("token_type", it.data.token_type)
                        SpUtil.putBoolean("app_first_login", it.data.app_first_login)
                        SpUtil.putInt("expires_at", it.data.expires_at)
                    }
                }

                override fun onError(code: Int, error: String?) {
                    super.onError(code, error)
                    mErrorMessage.value = "登录失败，请检查账号密码是否正确"
                }
            })
    }

    private var mSetPwdState = MutableLiveData<Boolean>()
    val setPwdState: LiveData<Boolean>
        get() = mSetPwdState

    fun setPassword(phone: String, code: String, pwd: String, isFirst: Boolean) {
        if (pwd.isEmpty()) {
            mErrorMessage.value = "请输入密码"
            return
        }

        if (!isFirst && (phone.isEmpty() || code.isEmpty())) {
            mErrorMessage.value = "请输入手机号和验证码"
            return
        }

        val setPwd = SetPwd().apply {
            this.phone = phone
            this.code = code
            this.new_password = MD5Util.getMD5Str(pwd)
        }
        if (isFirst) setPwd.password = MD5Util.getMD5Str(pwd)
        val url = if (isFirst) Url.SETPASSWORD else Url.UPDATEPASSWORD
        ZHttp.putWithHeader(
            url,
            getHeaders(),
            Gson().toJson(setPwd),
            object : ZResponse<BaseReplyBean>() {
                override fun onSuccess(response: Response, resObj: BaseReplyBean) {
                    mSetPwdState.value = resObj.isSuccess
                    if (!resObj.isSuccess) {
                        mErrorMessage.value = resObj.message
                    }
                }

                override fun onError(code: Int, error: String) {
                    super.onError(code, error)
                    mErrorMessage.value = error
                }
            })
    }

    fun sendSmsCodeForPwd(phone: String) {
        if (phone.isEmpty()) {
            mErrorMessage.value = "请输入手机号"
            return
        }
        if (!phone.matches("^1[3-9]\\d{9}$".toRegex())) {
            mErrorMessage.value = "请输入正确的手机号"
            return
        }

        val codeRequestBean = CodeRequestBean().apply {
            this.tel = phone
            this.bzty = 2
        }

        ZHttp.postJson(Url.LOGINCODE, codeRequestBean, object : ZResponse<BaseReplyBean>() {
            override fun onSuccess(response: Response, resObj: BaseReplyBean) {
                mSendState.value = resObj.isSuccess
                if (!resObj.isSuccess) {
                    mErrorMessage.value = resObj.message
                }
            }

            override fun onError(code: Int, error: String) {
                super.onError(code, error)
                mErrorMessage.value = error
            }
        })
    }

    override fun onCleared() {
        super.onCleared()
    }
}