package com.casic.smarttube.vm import androidx.lifecycle.MutableLiveData import com.casic.smarttube.base.BaseApplication import com.casic.smarttube.extensions.separateResponseCode import com.casic.smarttube.extensions.toErrorMessage import com.casic.smarttube.model.AreaModel import com.casic.smarttube.model.DistrictModel import com.casic.smarttube.model.PublicKeyModel import com.casic.smarttube.model.StreetModel import com.casic.smarttube.utils.retrofit.RetrofitServiceManager import com.google.gson.Gson import com.google.gson.reflect.TypeToken import com.pengxh.kt.lite.extensions.launch import com.pengxh.kt.lite.extensions.show import com.pengxh.kt.lite.vm.BaseViewModel class AuthenticateViewModel : BaseViewModel() { private val gson = Gson() val keyModel = MutableLiveData<PublicKeyModel>() val areaModel = MutableLiveData<AreaModel>() val districtModel = MutableLiveData<DistrictModel>() val streetModel = MutableLiveData<StreetModel>() fun obtainPublicKey() = launch({ val response = RetrofitServiceManager.authenticate() val responseCode = response.separateResponseCode() if (responseCode == 200) { keyModel.value = gson.fromJson<PublicKeyModel>( response, object : TypeToken<PublicKeyModel>() {}.type ) } else { response.toErrorMessage().show(BaseApplication.obtainInstance()) } }, { it.printStackTrace() }) /** * 根据部门获取区ID */ fun obtainAreaByDept(deptId: String) = launch({ val response = RetrofitServiceManager.obtainAreaByDept(deptId) val responseCode = response.separateResponseCode() if (responseCode == 200) { areaModel.value = gson.fromJson<AreaModel>( response, object : TypeToken<AreaModel>() {}.type ) } else { response.toErrorMessage().show(BaseApplication.obtainInstance()) } }, { it.printStackTrace() }) /** * 区/县等 */ fun obtainDistrict(pid: String) = launch({ val response = RetrofitServiceManager.obtainDistrict(pid) val responseCode = response.separateResponseCode() if (responseCode == 200) { districtModel.value = gson.fromJson<DistrictModel>( response, object : TypeToken<DistrictModel>() {}.type ) } else { response.toErrorMessage().show(BaseApplication.obtainInstance()) } }, { it.printStackTrace() }) /** * 街道 */ fun obtainStreet(areaId: String) = launch({ val response = RetrofitServiceManager.obtainStreet(areaId) val responseCode = response.separateResponseCode() if (responseCode == 200) { streetModel.value = gson.fromJson<StreetModel>( response, object : TypeToken<StreetModel>() {}.type ) } else { response.toErrorMessage().show(BaseApplication.obtainInstance()) } }, { it.printStackTrace() }) }