package com.za.ui.servicing.order_confirm.real_order_confirm


import com.alibaba.fastjson.JSONObject
import com.blankj.utilcode.util.ToastUtils
import com.za.base.Const
import com.za.base.IServicingVm
import com.za.base.view.LoadingManager
import com.za.bean.db.order.OrderInfo
import com.za.bean.db.order.PhotoTemplateInfo
import com.za.bean.request.UpdateOrderConfirmTaskRequest
import com.za.bean.request.UpdateTaskBean
import com.za.common.GlobalData
import com.za.common.log.LogUtil
import com.za.ext.getTaskNode
import com.za.ext.toJson
import com.za.net.BaseObserver
import com.za.net.RetrofitHelper
import com.za.room.RoomHelper
import com.za.service.location.ZdLocationManager
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.schedulers.Schedulers
import kotlinx.coroutines.flow.MutableStateFlow

class OrderConfirmVm : IServicingVm<OrderConfirmVm.Action, OrderConfirmVm.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.Submit -> submit()
			is Action.UpdateState -> updateState(action.uiState)
			is Action.UpdatePhotoTemplate -> updateTemplate()
			is Action.UpdateAbKm -> updateState(uiState.value.copy(abKm = action.abKm))
			is Action.UpdateAbRoadFee -> updateState(uiState.value.copy(abRoadFee = action.abRoadFee))
			is Action.UpdateBasementFee -> updateState(uiState.value.copy(basementFee = action.basementFee))
			is Action.UpdateBcKm -> updateState(uiState.value.copy(bcKm = action.bcKm))
			is Action.UpdateBcRoadFee -> updateState(uiState.value.copy(bcRoadFee = action.bcRoadFee))
			is Action.UpdateDilemmaFee -> updateState(uiState.value.copy(dilemmaFee = action.dilemmaFee))
			is Action.UpdateOverKm -> updateState(uiState.value.copy(overKm = action.overKm))
			is Action.UpdateUnitKmPrice -> updateState(uiState.value.copy(unitKmPrice = action.unitKmPrice))
			is Action.UpdateStartPrice -> updateState(uiState.value.copy(startPrice = action.startPrice))
		}
	}

	private fun updateTemplate() {
		getCurrentPhotoTemplate(success = { handlerPhoto(it) })
	}

	private fun submit() {

		if (! getCurrentOrderOfflineTask().isNullOrEmpty()) {
			showTipDialog("请等待离线任务提交完成!!")
			return
		}

		val photoTemplateList = RoomHelper.db?.photoTemplateDao()
			?.getOrderPhotoTemplateFromTaskNode(uiState.value.orderInfo?.getTaskNode() ?: 0,
				uiState.value.orderInfo?.userOrderId ?: 0)

		if ((uiState.value.abRoadFee
				?: 0) > 0 && uiState.value.aBAndBCPhotos?.find { it.numbering == "P.1" }?.photoUploadPath.isNullOrBlank()
		) {
			ToastUtils.showShort("请在出发段路桥费下方，拍摄发车段路桥费照片")
			return
		}
		if ((uiState.value.bcRoadFee
				?: 0) > 0 && uiState.value.aBAndBCPhotos?.find { it.numbering == "P.2" }?.photoUploadPath.isNullOrBlank()
		) {
			ToastUtils.showShort("请在背车段路桥费下方，拍摄背车段路桥费照片")
			return
		}

		uiState.value.photoTemplateList?.forEach {
			if (it.doHaveFilm == 1 && it.photoUploadPath.isNullOrBlank()) {
				ToastUtils.showShort("请拍摄${it.imageTitle}照片")
				return
			}
		}

		if (GlobalData.driverInfoBean?.supplierType != Const.CHILD_COMPANY) {

			// AB段不为0  BC段拖车流程不为0
			if (uiState.value.abKm == null || uiState.value.abKm == 0) {
				ToastUtils.showShort("出发地-事发地距离不可为0")
				return
			}
			if (uiState.value.orderInfo?.flowType == Const.TUO_CHE && (uiState.value.bcKm == null || uiState.value.bcKm == 0)) {
				ToastUtils.showShort("事发地-目的地距离不可为0")
				return
			}
		}


		val tempPhotoList = arrayListOf<String?>()
		photoTemplateList?.forEach { item ->
			if (item.photoType == 2 || item.photoUploadPath.isNullOrBlank()) {
				tempPhotoList.add(null)
			} else {
				val jsonObject = JSONObject()
				jsonObject["realTakePhotoTime"] = item.realTakePhotoTime ?: ""
				jsonObject["photoSource"] = item.photoSource
				jsonObject["path"] = item.photoUploadPath
				jsonObject["time"] = item.time
				jsonObject["sort"] = item.sort
				jsonObject["lat"] = item.lat
				jsonObject["lng"] = item.lng
				jsonObject["address"] = item.address
				tempPhotoList.add(jsonObject.toJSONString())
			}
		}

		LoadingManager.showLoading()
		ZdLocationManager.getSingleLocation(success = { it ->
			LoadingManager.hideLoading()
			val orderConfirmTaskRequest = UpdateOrderConfirmTaskRequest(type = "SETTLEMENT",
				taskId = GlobalData.currentOrder?.taskId,
				userId = GlobalData.driverInfoBean?.userId,
				vehicleId = GlobalData.driverInfoBean?.vehicleId,
				currentState = uiState.value.orderInfo?.taskState,
				operateTime = System.currentTimeMillis().toString(),
				supplierType = GlobalData.driverInfoBean?.supplierType,
				settleType = GlobalData.currentOrder?.settleType,
				carryMileage = uiState.value.bcKm,
				startMileage = uiState.value.abKm,
				startRoadFee = uiState.value.abRoadFee,
				carryRoadFee = uiState.value.bcRoadFee,
				dilemmaFee = uiState.value.dilemmaFee,
				basementFee = uiState.value.basementFee,
				basePrice = if (GlobalData.driverInfoBean?.supplierType == Const.CHILD_COMPANY) {
					computerBaseFee()
				} else null,
				assistFee = if (GlobalData.driverInfoBean?.supplierType == Const.CHILD_COMPANY) {
					computerAssistantsFee()
				} else null,
				totalFee = computerTotalFee(),
				offlineMode = 0,
				lat = it.latitude,
				lng = it.longitude,
				templatePhotoInfoList = tempPhotoList.toList())
			LoadingManager.showLoading()
			RetrofitHelper.getDefaultService().submitOrderConfirmTask(orderConfirmTaskRequest)
				.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
				.subscribe(object : BaseObserver<UpdateTaskBean>() {
					override fun doSuccess(it : UpdateTaskBean?) {
						LoadingManager.hideLoading()
						updateOrder(getCurrentOrder()?.copy(taskState = it?.nextState))
						updateState(uiState.value.copy(goNextPage = it,
							orderInfo = getCurrentOrder()))
					}

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

		}, failed = {
			LoadingManager.hideLoading()
			ToastUtils.showShort(it)
		})
	}

	private fun computerBaseFee() : Double {
		return (uiState.value.startPrice ?: 0) + (uiState.value.unitKmPrice
			?: 0) * (uiState.value.overKm ?: 0).toDouble()
	}

	private fun computerAssistantsFee() : Double {
		return (uiState.value.abRoadFee ?: 0) + (uiState.value.bcRoadFee
			?: 0) + (uiState.value.dilemmaFee ?: 0) + (uiState.value.basementFee ?: 0).toDouble()
	}

	private fun computerTotalFee() : Double {
		return computerBaseFee() + computerAssistantsFee()
	}

	private fun init() {
		LoadingManager.hideLoading()
		updateState(uiState.value.copy(orderInfo = getCurrentOrder()))
		getCurrentPhotoTemplate(success = {
			handlerPhoto(it)
		})
	}

	private fun handlerPhoto(photoTemplateList : List<PhotoTemplateInfo>?) {
		LogUtil.print("handlerPhoto", photoTemplateList?.toJson() ?: "")
		val abPhoto = photoTemplateList?.filter {
			it.numbering == "P.1" || it.numbering == "P.2"
		}
		val otherPhoto = photoTemplateList?.filter {
			it.numbering != "P.1" && it.numbering != "P.2"
		}
		updateState(uiState.value.copy(photoTemplateList = otherPhoto, aBAndBCPhotos = abPhoto))
	}

	sealed class Action {
		data object Init : Action()
		data object Submit : Action()
		data class UpdateState(val uiState : UiState) : Action()
		data class UpdatePhotoTemplate(val photoTemplateInfo : PhotoTemplateInfo) : Action()
		data class UpdateStartPrice(val startPrice : Int) : Action()
		data class UpdateUnitKmPrice(val unitKmPrice : Int) : Action()
		data class UpdateOverKm(val overKm : Int) : Action()
		data class UpdateAbKm(val abKm : Int) : Action()
		data class UpdateBcKm(val bcKm : Int) : Action()
		data class UpdateAbRoadFee(val abRoadFee : Int) : Action()
		data class UpdateBcRoadFee(val bcRoadFee : Int) : Action()
		data class UpdateDilemmaFee(val dilemmaFee : Int) : Action()
		data class UpdateBasementFee(val basementFee : Int) : Action()
	}

	data class UiState(
		val orderInfo : OrderInfo? = null,
		val goNextPage : UpdateTaskBean? = null,
		val isGoNextPageDialog : Boolean? = null,
		val aBAndBCPhotos : List<PhotoTemplateInfo>? = null,
		val photoTemplateList : List<PhotoTemplateInfo>? = null,
		val startPrice : Int? = null, //起步价
		val unitKmPrice : Int? = null, //每公里价格
		val overKm : Int? = null, //超出公里数
		val abKm : Int? = null, //ab段里程
		val bcKm : Int? = null, //bc段里程
		val abRoadFee : Int? = null, //ab段路桥费
		val bcRoadFee : Int? = null, //bc段路桥费
		val dilemmaFee : Int? = null, //困境费
		val basementFee : Int? = null, //地库费
	)
}
