package com.develop.auth.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.scopeNetLife
import com.develop.base.mvvm.BaseViewModel
import com.develop.base.util.MMkvUtils
import com.develop.common.data_repo.FoodDataProvider
import com.develop.common.data_repo.db.AuthModel
import com.develop.common.data_repo.db.entity.UserInfo
import com.develop.common.data_repo.net.Api
import com.develop.common.data_repo.net.model.request.*
import com.develop.common.data_repo.net.model.response.LoginResult
import com.develop.common.data_repo.net.model.response.PerfectInfoResult
import com.develop.common.data_repo.net.model.response.RegisterResult
import com.develop.common.data_repo.net.model.response.VerifyCodeResult
import com.develop.common.tag.API_TOKEN
import com.develop.common.tag.CURRENT_USER_ID
import com.develop.common.tag.CURRENT_USER_ID_TAG
import com.develop.common.tag.LOGIN_TAG
import com.drake.net.Post
import com.develop.base.util.UnPeekLiveData

class MemberViewModel : BaseViewModel() {
    private var mVerifyCodeKey = ""
    val chooseAvatar = MutableLiveData<Int>()
    var enterFromHome: Boolean = false

    var registerLiveData = MutableLiveData<AuthModel>()
    var loginLiveData = MutableLiveData<AuthModel>()
    var sendEmailLiveData = MutableLiveData<AuthModel>()
    var resetPasswordLiveData = MutableLiveData<AuthModel>()
    var perfectInfoLiveData = MutableLiveData<AuthModel>()

    val userInfoLiveData = MutableLiveData<UserInfo>()

    var fragmentChangeLiveData = MutableLiveData<FragmentTag>()


    fun register(email: String, password: String) = scopeNetLife {
        Post<RegisterResult>(Api.REGISTER) {
            body = RegisterBody.genRegisterBody(email, password)
        }.await().apply {
            login(email, password, true)
        }
    }.catch {
        if (it.message == "账号已存在") {
            registerLiveData.postValue(AuthModel(false, "The email has been already registered."))
        } else {
            registerLiveData.postValue(AuthModel(false, it.message))
        }
    }

    fun login(email: String, password: String, isFromRegister: Boolean = false) = scopeNetLife {
        Post<LoginResult>(Api.LOGIN) {
            body = LoginBody.genLoginBody(email, password)
        }.await().apply {
            MMkvUtils.save(API_TOKEN, token)
            MMkvUtils.save(LOGIN_TAG, true)
            MMkvUtils.save(CURRENT_USER_ID_TAG, user.id.toLong())
            user.apply {
                val userInfo = UserInfo(
                    id.toLong(), nickname, portrait, gender, age
                )
                FoodDataProvider.getUserDatabase().userInfoDao().updateUserInfo(userInfo)
                if (isFromRegister) {
                    registerLiveData.postValue(AuthModel(true))
                } else {
                    loginLiveData.postValue(AuthModel(true))
                }
                userInfoLiveData.postValue(userInfo)
            }
        }
    }.catch {
        if (isFromRegister) {
            registerLiveData.postValue(AuthModel(false, it.message))
        } else {
            loginLiveData.postValue(AuthModel(false, it.message))
        }
    }

    fun sendEmail(email: String) = scopeNetLife {
        Post<VerifyCodeResult>(Api.SEND_VERIFY_CODE) {
            body = SendVerifyCodeBody.genSendVerifyCodeBody(email)
        }.await().apply {
            mVerifyCodeKey = verifyCodeKey
            sendEmailLiveData.postValue(AuthModel(true, "Email send"))
        }
    }.catch {
        sendEmailLiveData.postValue(AuthModel(false))
    }

    fun resetPassword(
        email: String,
        captcha: String,
        password: String
    ) = scopeNetLife {
        Post<Any>(Api.UPDATE_PWD) {
            body = UpdatePasswordBody.genUpdatePasswordBody(
                email,
                password,
                mVerifyCodeKey,
                captcha
            )
        }.await().apply {
            resetPasswordLiveData.postValue(AuthModel(true, "Reset password success!"))
        }
    }.catch {
        resetPasswordLiveData.postValue(AuthModel(false, it.message))
    }


    fun perfectInfo(nickName: String, sex: String, portrait: String, age: String) = scopeNetLife {
        Post<PerfectInfoResult>(Api.PERFECT_INFO) {
            body = PerfectInfoBody.genPerfectInfoBody(nickName, sex, portrait, age)
        }.await().apply {
            perfectInfoLiveData.postValue(AuthModel(true, "Save success"))
            MMkvUtils.save(CURRENT_USER_ID_TAG, user.id.toLong())
            val userInfo = UserInfo(
                user.id.toLong(),
                user.nickname,
                user.portrait,
                user.gender,
                user.age
            )
            FoodDataProvider.getUserDatabase().userInfoDao().updateUserInfo(userInfo)
            userInfoLiveData.postValue(userInfo)
        }
    }.catch {
        perfectInfoLiveData.postValue(AuthModel(false, it.message))
    }

    fun queryUserInfo() {
        val result = FoodDataProvider
            .getUserDatabase()
            .userInfoDao()
            .queryUserInfoByUserId(CURRENT_USER_ID)
        userInfoLiveData.postValue(result)
    }
}

enum class FragmentTag {
    MEMBER_FORGER,
    MEMBER_LAUNCH,
    MEMBER_LOGIN,
    MEMBER_PROFILE,
    MEMBER_REGISTER
}