package com.za.ui.main

import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.ToastUtils
import com.za.base.BaseVm
import com.za.base.view.LoadingManager
import com.za.bean.LoginWithTaskBean
import com.za.bean.LoginWithTaskRequest
import com.za.bean.db.order.OrderInfo
import com.za.common.GlobalData
import com.za.net.BaseObserver
import com.za.net.CommonMethod
import com.za.net.RetrofitHelper
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.schedulers.Schedulers
import kotlinx.coroutines.flow.MutableStateFlow

class ServicingMainVm : BaseVm<ServicingMainVm.Action, ServicingMainVm.UiState>() {

	private val _uiState = MutableStateFlow(UiState())
	val uiState get() = _uiState
	override fun updateState(uiState : UiState) {
		_uiState.value = uiState
	}

	override fun dispatch(action : Action) {
		when (action) {
			is Action.Init -> init(action.jobCode,
				action.phone,
				action.taskCode,
				action.vehicleId,
				action.deviceId,
				action.rescueVehicle)
		}
	}

	private fun init(jobCode : String? = null,
		phone : String? = null,
		taskCode : String? = null,
		vehicleId : String? = null,
		deviceId : String? = null,
		rescueVehicle : String? = null) {
		LoadingManager.showLoading()

		login(jobCode, phone, taskCode, vehicleId, deviceId, rescueVehicle, success = {
			CommonMethod.queryOrderList(context = ActivityUtils.getTopActivity(),
				success = { orderInfo : OrderInfo?, orderInfos : List<OrderInfo>? ->
					LoadingManager.hideLoading()
					if (orderInfo == null) {
						ToastUtils.showShort("未查询到订单")
						GlobalData.clearAllOrderCache()
						updateState(uiState.value.copy(state = 3))
						return@queryOrderList
					}
					GlobalData.currentOrder = orderInfo
					updateState(uiState.value.copy(state = 1))
				},
				failed = {
					updateState(uiState.value.copy(state = 2))
					LoadingManager.hideLoading()
					ToastUtils.showShort(it)
				})
		}, failure = {
			LoadingManager.hideLoading()
			updateState(uiState.value.copy(state = 2))
			ToastUtils.showShort(it)
		})
	}

	private fun login(jobCode : String? = null,
		phone : String? = null,
		taskCode : String? = null,
		vehicleId : String? = null,
		deviceId : String? = null,
		rescueVehicle : String? = null,
		success : () -> Unit,
		failure : (String) -> Unit) {
		val loginWithTaskRequest =
			LoginWithTaskRequest(jobCode, phone, taskCode, rescueVehicle, deviceId, vehicleId)
		RetrofitHelper.getDefaultService().loginWithTask(loginWithTaskRequest)
			.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
			.subscribe(object : BaseObserver<LoginWithTaskBean>() {
				override fun doSuccess(it : LoginWithTaskBean?) {
					if (it == null) {
						ToastUtils.showLong("登录失败")
						failure("登录失败")
						return
					}
					GlobalData.token = it.token
					CommonMethod.getGenerateInfo(vehicleId = it.vehicleId,
						userId = it.userId,
						success = { success() },
						failed = { failure(it ?: "") })
				}

				override fun doFailure(code : Int, msg : String?) {
					failure(msg ?: "")
				}
			})
	}

	sealed class Action {
		data class Init(val jobCode : String? = null,
			val phone : String? = null,
			val taskCode : String? = null,
			val vehicleId : String? = null,
			val deviceId : String? = null,
			val rescueVehicle : String? = null) : Action()
	}

	data class UiState(
		val state : Int? = null, //1 成功  2 失败  3:订单为空
	)
}