package com.lukouguoji.module_base.service.repository

import android.util.Log
import androidx.lifecycle.liveData
import com.alibaba.fastjson.JSON
import com.lukouguoji.module_base.common.Constant
import com.lukouguoji.module_base.db.perference.SharedPreferenceUtil
import com.lukouguoji.module_base.http.user.UserNetwork
import com.lukouguoji.module_base.ktx.loge
import kotlinx.coroutines.Dispatchers

object LoginRepository {

    fun login(username: String, password: String, roleTerm: String, userRole: String) =
        liveData(Dispatchers.IO) {
            try {
                val response = UserNetwork.login(username, password, roleTerm, userRole)

                if (response["status"] == "1") {
                    var auths = response["auths"]
                    var userName = response["username"]
                    var token = response["token"]

                    SharedPreferenceUtil.addString(Constant.Share.account, username)
                    SharedPreferenceUtil.addString(Constant.Share.userName, userName.toString())
                    SharedPreferenceUtil.addString(
                        Constant.Share.authList,
                        JSON.toJSONString(auths)
                    )
                    SharedPreferenceUtil.addString(Constant.Share.token, token.toString())
                    SharedPreferenceUtil.addString(Constant.Share.id, response["id"].toString())
                    SharedPreferenceUtil.addString(Constant.Share.roleId, userRole)

                    emit(1)
                } else {
                    emit(2)
                }
            } catch (e: Exception) {
                Log.e("LoginRepository", e.stackTraceToString())
                emit(3)
            }

        }

    fun logout() {
        SharedPreferenceUtil.remove(Constant.Share.userName)
        SharedPreferenceUtil.remove(Constant.Share.authList)
        SharedPreferenceUtil.remove(Constant.Share.token)
        SharedPreferenceUtil.remove(Constant.Share.id)
    }

}