package com.za.ui.servicing.order_confirm

import com.za.base.IServicingVm
import com.za.base.view.LoadingManager
import com.za.bean.PaymentInfoBean
import com.za.bean.db.ele.EleWorkOrderBean
import com.za.bean.db.order.OrderInfo
import com.za.bean.request.PaymentInfoRequest
import com.za.bean.request.UpdateTaskBean
import com.za.common.log.LogUtil
import com.za.ext.toJson
import com.za.net.BaseObserver
import com.za.net.RetrofitHelper
import com.za.room.RoomHelper
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.schedulers.Schedulers
import kotlinx.coroutines.flow.MutableStateFlow

class OrderConfirmInitVm : IServicingVm<OrderConfirmInitVm.Action, OrderConfirmInitVm.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()
			is Action.UpdateState -> updateState(action.uiState)
		}
	}

	private fun init() {
		updateState(uiState.value.copy(orderInfo = getCurrentOrder()))
		queryPaymentInfo(uiState.value.orderInfo)
	}

	private fun queryPaymentInfo(orderInfo : OrderInfo?) {
		LoadingManager.showLoading()
		val paymentInfoRequest = PaymentInfoRequest(orderInfo?.userOrderId, orderInfo?.taskId)
		val eleWorkOrderBean =
			RoomHelper.db?.eleWorkOrderDao()?.getEleWorkOrder(taskId = orderInfo?.taskId ?: 0)
		RetrofitHelper.getDefaultService().paymentInfoQuery(paymentInfoRequest)
			.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
			.subscribe(object : BaseObserver<PaymentInfoBean>() {
				override fun doSuccess(it : PaymentInfoBean?) {
					LoadingManager.hideLoading()
					updateState(uiState.value.copy(paymentInfoBean = it,
						orderInfo = orderInfo,
						eleWorkOrderBean = eleWorkOrderBean))
					if (eleWorkOrderBean != null && eleWorkOrderBean.driverChoiceNoNeedReceiveMoney == true) {
						handlerOtherState(orderInfo, eleWorkOrderBean)
						return
					}
					if (it?.isPayment == true && it.tradeState != 2) {
						if (it.askPayment == true) {
							updateState(uiState.value.copy(showNoNeedPayDialog = true))
							return
						}
						updateState(uiState.value.copy(orderConfirmState = OrderConfirmState.PaymentInfo))
						return
					}

					handlerOtherState(orderInfo, eleWorkOrderBean)
				}

				override fun doFailure(code : Int, msg : String?) {
					LoadingManager.hideLoading()
					LogUtil.print("eleworkOrder", eleWorkOrderBean.toJson() ?: "")
					updateState(uiState.value.copy(orderInfo = orderInfo, eleWorkOrderBean = eleWorkOrderBean))
					handlerOtherState(orderInfo, eleWorkOrderBean)
					LogUtil.print("queryPaymentInfo", "failed=$msg request=${paymentInfoRequest.toJson()}")
				}
			})
	}

	private fun handlerOtherState(orderInfo : OrderInfo?, eleWorkOrderBean : EleWorkOrderBean?) {
		if (orderInfo?.electronOrderState == 0 || orderInfo?.electronOrderState == 1 || orderInfo?.electronOrderState == 2) {
			updateState(uiState.value.copy(orderConfirmState = OrderConfirmState.ConfirmEle))
			return
		}

		if (eleWorkOrderBean?.changeBattery == true) {
			updateState(uiState.value.copy(orderConfirmState = OrderConfirmState.ChangeBattery))
			return
		}
		if (eleWorkOrderBean?.hasCreatedEleWorkOrderPhoto == null || eleWorkOrderBean.hasCreatedEleWorkOrderPhoto != true) {
			updateState(uiState.value.copy(orderConfirmState = OrderConfirmState.ConfirmH5Success))
			return
		}
		updateState(uiState.value.copy(orderConfirmState = OrderConfirmState.OrderConfirm))
	}

	sealed class Action {
		data object Init : Action()
		data class UpdateState(val uiState : UiState) : Action()
	}

	data class UiState(
		val orderConfirmState : OrderConfirmState = OrderConfirmState.Init,
		val orderInfo : OrderInfo? = null,
		val eleWorkOrderBean : EleWorkOrderBean? = null,
		val goNextPage : UpdateTaskBean? = null,
		val isGoNextPageDialog : Boolean? = null,
		val paymentInfoBean : PaymentInfoBean? = null,
		val showNoNeedPayDialog : Boolean? = null,
	)

	sealed class OrderConfirmState {
		data object Init : OrderConfirmState()
		data object Failed : OrderConfirmState()
		data object PaymentInfo : OrderConfirmState()
		data object ConfirmEle : OrderConfirmState()
		data object ChangeBattery : OrderConfirmState()
		data object ConfirmH5Success : OrderConfirmState()
		data object OrderConfirm : OrderConfirmState()
	}
}