package com.renrenliao.im.viewmodel

import androidx.lifecycle.MutableLiveData
import com.renrenliao.im.base.BaseViewModel
import com.renrenliao.im.bean.LineEntity
import com.renrenliao.im.http.checkError
import com.renrenliao.im.http.checkSuccess
import com.renrenliao.im.model.repository.LocalDataSource
import com.renrenliao.im.model.repository.RemoteDataSource
import com.renrenliao.im.provider.ClarityPotion
import com.renrenliao.im.utils.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import net.openmob.mobileimsdk.android.ClientCoreSDK

/**
 **@ClassName LoginViewModel
 **@Description
 **@Author ganzhe
 **@Date 2022/5/23 10:57
 **/
class LoginViewModel(private val remoteRepo: RemoteDataSource,private val localDataSource: LocalDataSource):BaseViewModel() {

    val loginLiveData = MutableLiveData<Boolean>()
    val lineLiveData = MutableLiveData<LineEntity>()

    fun login(map: Map<String,String>){

        launchUI({

            val result = withContext(Dispatchers.IO){
                remoteRepo.login(map)
            }
           // LogUtils.error(result)
            result.checkSuccess {
                LogUtils.error(it)
                //初始化IM 防止从设置中退出后 im释放了
                ClientCoreSDK.getInstance().init(ClarityPotion.healingSalve)
//
                //保存用户信息
                val userInfo = it.authed_info//GsonUtils.convertEntity(Des3Util.decode(it),AuthInfo::class.java).authed_info
                DataCacheUtils.isLogin = true
                DataCacheUtils.setToken(userInfo.token.toString())
                DataCacheUtils.setUid(userInfo.userUid)
                localDataSource.updateUserInfo(userInfo)
                loginLiveData.value = true

            }
            result.checkError {
                LogUtils.error(it)
            }


        }, isShowDiaLoading = true)

    }

    fun getRouter(){
        launchUI({
            val lines = withContext(Dispatchers.IO){
                remoteRepo.getLines()
            }
            //LogUtils.error(lines)
            lineLiveData.value = lines

        }, isShowDiaLoading = true)
    }

}