package com.renrenliao.im.viewmodel

import com.renrenliao.im.base.BaseViewModel
import com.renrenliao.im.http.checkSuccess
import com.renrenliao.im.im.IMClientManager
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.DataCacheUtils
import com.renrenliao.im.utils.RouteUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import net.openmob.mobileimsdk.android.core.LocalDataSender

/**
 **@ClassName SettingViewModel
 **@Description
 **@Author gan
 **@Date 2022/5/28 14:41
 **/
class SettingViewModel(
    private val remoteRepo: RemoteDataSource,
    private val localDataSource: LocalDataSource
) : BaseViewModel() {

    //val userInfo = LocalDataSource.readOnlyUserFlow//localDataSource.CreadOnlyUserFlow


    //    fun change(){
//        val userInfo = DataCacheUtils.getUserInfo()
//        userInfo?.nickname = "change"
//        viewModelScope.launch(Dispatchers.IO) {
//          //  localDataSource.userFlow.emit(userInfo)
//            localDataSource.updateUserInfo(userInfo!!)
//        }
//    }


    //退出登陆成功后 再退出IM  在清除用户数据   跳转到登陆
    fun logout() {
        launchUI({
            val map = HashMap<String, String>()
            map["accessToken"] = DataCacheUtils.getToken()
            map["modleType"] = "android"
            map["userUid"] = DataCacheUtils.getUid()
            map["umDeviceToken"] = DataCacheUtils.getDeviceToken()

            val result = withContext(Dispatchers.IO) {
                remoteRepo.logout(map)
            }
            result.checkSuccess {
                //退出IM
                val code = LocalDataSender.getInstance().sendLogout()
                if (code == 0){
                    IMClientManager.getInstance(ClarityPotion.healingSalve).release()
                }
                //清除用户数据
                DataCacheUtils.isLogin = false
                DataCacheUtils.clearUserInfo()
                //跳转到登陆
                RouteUtils.exitAndLogin()
            }
        })
    }

}