package com.za.ui.servicing.order_confirm.modify_money

import com.blankj.utilcode.util.ToastUtils
import com.za.base.BaseVm
import com.za.base.view.LoadingManager
import com.za.bean.PaymentInfoBean
import com.za.bean.request.PaymentInfoRequest
import com.za.bean.request.PaymentUpdateRequest
import com.za.net.BaseObserver
import com.za.net.RetrofitHelper
import com.za.ui.servicing.order_confirm.modify_money.ModifyMoneyViewModel.Action
import com.za.ui.servicing.order_confirm.modify_money.ModifyMoneyViewModel.UiState
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.schedulers.Schedulers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow

class ModifyMoneyViewModel : BaseVm<Action, UiState>() {
	private val _uiState = MutableStateFlow(UiState())
	val uiState get() = _uiState.asStateFlow()

	override fun updateState(uiState : UiState) {
		_uiState.value = uiState
	}

	override fun dispatch(action : Action) {
		when (action) {
			is Action.Init -> init(action.userOrderId, action.taskId)
			is Action.ChangeMileage -> changeMileage(action.mileage)
			is Action.ChangeAdjustAmount -> changeAdjustAmount(action.adjustAmount)
			is Action.Save -> save()
		}
	}


	private fun init(userOrderId : Int, taskId : Int) {
		LoadingManager.showLoading()
		val paymentInfoRequest = PaymentInfoRequest(userOrderId, taskId)
		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,
						userOrderId = userOrderId,
						taskId = taskId,
						unitPrice = it?.unitPrice,
						mileage = it?.mileage?.plus(uiState.value.paymentInfoBean?.limitedMileage
							?: 0),
						mileageText = "${it?.mileage?.plus(uiState.value.paymentInfoBean?.limitedMileage ?: 0)}",
						calculateAmount = it?.calculateAmount,
						adjustAmount = it?.adjustAmount?.toFloat(),
						adjustAmountText = "${it?.adjustAmount ?: ""}",
						amount = it?.amount,
						totalMoney = it?.amount))
				}

				override fun doFailure(code : Int, msg : String?) {
					LoadingManager.hideLoading()
				}
			})
	}

	private fun changeMileage(value : String?) {
		var mileage = value?.toFloatOrNull() ?: 0f
		val calculateAmount = if (mileage <= (uiState.value.paymentInfoBean?.limitedMileage ?: 0)) {
			0f
		} else {
			(mileage - (uiState.value.paymentInfoBean?.limitedMileage
				?: 0)).times(uiState.value.unitPrice ?: 0f)
		}

		updateState(uiState.value.copy(mileage = mileage,
			mileageText = value,
			calculateAmount = calculateAmount.toFloat(),
			totalMoney = calculateAmount.toFloat().plus(uiState.value.adjustAmount ?: 0f)))

	}

	private fun changeAdjustAmount(value : String?) {
		val adjustAmount = value?.toFloatOrNull() ?: 0f
		updateState(uiState.value.copy(adjustAmountText = value,
			adjustAmount = adjustAmount,
			totalMoney = uiState.value.calculateAmount?.plus(adjustAmount)))
	}


	private fun save() {
		if (uiState.value.adjustRemark.isEmpty()) {
			ToastUtils.showShort("请输入调整原因")
			return
		}


		if ((uiState.value.mileage ?: 0f) < (uiState.value.paymentInfoBean?.originalMileage
				?: 0f)
		) {
			ToastUtils.showShort("全程公里数不能小于${uiState.value.paymentInfoBean?.originalMileage}")
			return
		}


		if ((uiState.value.mileage?.minus(uiState.value.paymentInfoBean?.limitedMileage ?: 0)
				?: 0f) < (uiState.value.paymentInfoBean?.originalMileage ?: 0f)
		) {
			ToastUtils.showShort("全程公里数减去免拖公里数不能小于${uiState.value.paymentInfoBean?.originalMileage}")
			return
		}

		val paymentUpdateRequest = PaymentUpdateRequest(userOrderId = uiState.value.userOrderId,
			taskOrderId = uiState.value.taskId,
			payAmount = uiState.value.totalMoney,
			unitPrice = uiState.value.unitPrice,
			mileage = uiState.value.mileage?.minus(uiState.value.paymentInfoBean?.limitedMileage
				?: 0),
			orderPayDetailId = uiState.value.paymentInfoBean?.orderPayDetailId,
			calculateAmount = uiState.value.calculateAmount,
			adjustAmount = uiState.value.adjustAmount,
			updateRemark = uiState.value.adjustRemark,
			askPayment = uiState.value.paymentInfoBean?.askPayment)

		LoadingManager.showLoading()

		RetrofitHelper.getDefaultService().paymentAmountUpdate(paymentUpdateRequest)
			.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
			.subscribe(object : BaseObserver<String>() {
				override fun doSuccess(it : String?) {
					LoadingManager.hideLoading()
					ToastUtils.showShort("修改成功")
					updateState(uiState.value.copy(saveSuccess = true))
				}

				override fun doFailure(code : Int, msg : String?) {
					LoadingManager.hideLoading()
					ToastUtils.showShort(msg)
				}
			})

	}

	sealed class Action {
		data class Init(val userOrderId : Int, val taskId : Int) : Action()
		data class ChangeMileage(val mileage : String?) : Action()
		data class ChangeAdjustAmount(val adjustAmount : String?) : Action()
		data object Save : Action()
	}

	data class UiState(val userOrderId : Int = 0,
		val taskId : Int = 0,
		val paymentInfoBean : PaymentInfoBean? = null,
		val unitPrice : Float? = null, //超限单价
		val mileage : Float? = null, //公里数
		val calculateAmount : Float? = null, //计算金额
		val adjustAmount : Float? = null, //调整金额
		val amount : Float? = null,
		val adjustRemark : String = "", //调整原因
		val totalMoney : Float? = null,

		val mileageText : String? = null, //输入框文本展示
		val adjustAmountText : String? = null,
		val saveSuccess : Boolean? = null)
}
