package com.swago.user.vm

import android.app.Application
import android.content.Intent
import android.widget.Toast
import androidx.lifecycle.MutableLiveData
import com.alibaba.android.arouter.launcher.ARouter
import com.swago.baseswago.constant.ARouteConstant
import com.swago.baseswago.inter.ApiManager
import com.swago.baseswago.model.ConfigModel
import com.swago.baseswago.model.mine.TaskModel
import com.swago.baseswago.util.AppContext
import com.swago.baseswago.util.BaseViewModel
import com.swago.baseswago.util.SpUtil
import com.swago.baseswago.util.SwagoLoading
import com.swago.baseswago.util.UserInfo
import com.swago.user.R
import com.tencent.qcloud.tim.uikit.TUIKit
import com.tencent.qcloud.tim.uikit.base.IUIKitCallBack

/**
 *@date 2021/11/28 13:03
 *description:
 */
class TaskVm (application: Application) : BaseViewModel(application) {

    val taskListLiveData by lazy {
        MutableLiveData<List<TaskModel>?>()
    }

    val receiveLiveData by lazy {
        MutableLiveData<Int>()
    }

    fun getTaskList(type:Int){
        requestData2 {
            requestData {
                val data = ApiManager.userApi.getTaskList(type)
                taskListLiveData.value  = data
            }
            requestError {
                taskListLiveData.value = null
            }
        }
    }


    fun receiveReward(id:String,position:Int){
        requestData {
            ApiManager.userApi.receiveTaskReward(id)
            receiveLiveData.value = position
        }
    }


    fun changePwd(oldPwd:String,newPwd:String,confirmNewPwd:String){
        requestData2 {
            requestData {
                if(oldPwd.isEmpty()){
                    ApiManager.userApi.firstChangePwd(newPwd,confirmNewPwd)
                }else{
                    ApiManager.userApi.changePwd(oldPwd,newPwd,confirmNewPwd)
                }
                ApiManager.userApi.logout()
                UserInfo.clearUserInfo()
                SpUtil.clearSp()
                TUIKit.logout(object : IUIKitCallBack {
                    override fun onSuccess(data: Any?) {}
                    override fun onError(module: String?, errCode: Int, errMsg: String?) {}
                })
                TUIKit.unInit()
                ARouter.getInstance().build(ARouteConstant.Login.login)
                    .withFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
                    .navigation()
                SwagoLoading.cancelLoadingDialog()
                Toast.makeText(AppContext.getContext(), AppContext.getContext().resources.getString(R.string.pwd_change_success), Toast.LENGTH_SHORT).show()
            }
            requestError{
                SwagoLoading.cancelLoadingDialog()
            }
        }
    }
}