package com.za.ui.servicing.order_confirm

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.base.view.LoadingState
import com.za.bean.db.order.OrderInfo
import com.za.bean.request.ElectronOrderResponse
import com.za.bean.request.QueryEleOrderRequest
import com.za.bean.request.SaveEleOrderRequest
import com.za.bean.request.TaskFinishRequest
import com.za.bean.request.TaskFinishResponse
import com.za.common.log.LogUtil
import com.za.ext.toJson
import com.za.net.BaseObserver
import com.za.net.CommonMethod
import com.za.net.RetrofitHelper
import com.za.offline.OfflineUpdateTaskBean
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
import java.io.File

class ConfirmH5SuccessVm : IServicingVm<ConfirmH5SuccessVm.Action, ConfirmH5SuccessVm.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)
			is Action.TaskFinish -> taskFinish()
			is Action.ClearOfflineTask -> clearCurrentOrderOfflineTask()
			is Action.UpdateCurrentEleWorkOrder -> updateCurrentEleWorkOrder(action.type,
				action.path)
		}
	}

	private fun init() {
		updateState(uiState.value.copy(loadingState = LoadingState.Loading))
		updateState(uiState.value.copy(loadingState = LoadingState.LoadingSuccess,
			orderInfo = getCurrentOrder()))
	}

	private fun taskFinishOffline(taskFinishRequest : TaskFinishRequest) {
		val offlineUpdateTaskBean = OfflineUpdateTaskBean(
			taskCode = getCurrentOrder()?.taskCode,
			taskId = getCurrentOrder()?.taskId,
			userOrderId = getCurrentOrder()?.userOrderId,
			offlineMode = 1,
			offlineType = 8,
			offlineTitle = "任务完成",
			updateTaskLat = taskFinishRequest.lat,
			updateTaskLng = taskFinishRequest.lng,
			operateTime = "${System.currentTimeMillis()}",
		)
		insertOfflineTask(offlineUpdateTaskBean)

		val eleWorkOrderBean =
			RoomHelper.db?.eleWorkOrderDao()?.getEleWorkOrder(uiState.value.orderInfo?.taskId ?: 0)
		eleWorkOrderBean?.copy(hasCreatedEleWorkOrderPhoto = true)
			?.let { it1 -> updateCurrentEleWorkOrder(it1) }
		updateState(uiState.value.copy(goNextPage = true))
	}

	private fun queryEleWorkOrder(success : () -> Unit, failed : (String?) -> Unit) {
		LoadingManager.showLoading()
		val queryEleOrderRequest = QueryEleOrderRequest(taskOrderId = getCurrentOrder()?.taskId,
			userOrderId = getCurrentOrder()?.userOrderId,
			userOrderCode = getCurrentOrder()?.taskCode)
		RetrofitHelper.getDefaultService().queryElectronOrder(queryEleOrderRequest)
			.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
			.subscribe(object : BaseObserver<ElectronOrderResponse>() {
				override fun doSuccess(it : ElectronOrderResponse?) {
					LoadingManager.hideLoading()
					if (it == null) {
						failed("查询失败")
						LogUtil.print("queryEleWorkOrder", "查询失败")
						return
					}

					if (getCurrentOrder()?.flowType == Const.TUO_CHE) {
						if (it.customerSignPath.isNullOrEmpty()) {
							updateState(uiState.value.copy(showSignDialog = 1))
							return
						}
					}

					//接车人签字
					if (it.recipientSignPath.isNullOrEmpty()) {
						updateState(uiState.value.copy(showSignDialog = 2))
						return
					}
					if (it.waitstaffSignPath.isNullOrEmpty()) {
						updateState(uiState.value.copy(showSignDialog = 3))
						return
					}
					success()
				}

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

	private fun updateCurrentEleWorkOrder(type : Int, path : String) {
		CommonMethod.uploadImage(File(path), success = {
			var saveEleOrderRequest = SaveEleOrderRequest(taskOrderId = getCurrentOrder()?.taskId,
				userOrderId = getCurrentOrder()?.userOrderId,
				state = 3)
			when (type) {
				1 -> {
					saveEleOrderRequest = saveEleOrderRequest.copy(customerSignPath = it)
				}

				2 -> {
					saveEleOrderRequest = saveEleOrderRequest.copy(recipientSignPath = it)
				}

				3 -> {
					saveEleOrderRequest = saveEleOrderRequest.copy(waitstaffSignPath = it)
				}
			}
			doUpdateCurrentEleWorkOrder(type, saveEleOrderRequest)
		}, failed = {
			ToastUtils.showLong(it)
		})
	}

	private fun doUpdateCurrentEleWorkOrder(type : Int, saveEleOrderRequest : SaveEleOrderRequest) {
		RetrofitHelper.getDefaultService().saveElectronOrder(saveEleOrderRequest)
			.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
			.subscribe(object : BaseObserver<String>() {
				override fun doSuccess(it : String?) {
					val eleWorkOrderBean = getCurrentOrderEleWorkOrder() ?: return
					when (type) {
						1 -> {
							updateCurrentEleWorkOrder(eleWorkOrderBean.copy(serverCustomSignPath = saveEleOrderRequest.customerSignPath,
								orderWorkStatus = 3))
						}

						2 -> {
							updateCurrentEleWorkOrder(eleWorkOrderBean.copy(serverAcceptCarSignPath = saveEleOrderRequest.recipientSignPath,
								orderWorkStatus = 3))
						}

						3 -> {
							updateCurrentEleWorkOrder(eleWorkOrderBean.copy(
								serverServicePeopleSignPath = saveEleOrderRequest.waitstaffSignPath,
								orderWorkStatus = 3))
						}
					}
					LogUtil.print("doUpdateCurrentEleWorkOrder success",
						"saveEleOrderRequest==${saveEleOrderRequest.toJson()}")
				}

				override fun doFailure(code : Int, msg : String?) {
					ToastUtils.showLong(msg)
					LogUtil.print("doUpdateCurrentEleWorkOrder", "code==$code msg==$msg")
				}
			})
	}

	private fun taskFinish() {        //如果有离线任务，先提示用户离线任务信息
		if (! getCurrentOrderOfflineTask().isNullOrEmpty()) {
			updateState(uiState.value.copy(showOfflineTaskDialog = true))
			return
		}

		queryEleWorkOrder(success = {
			doTaskFinish()
		}, failed = {
			ToastUtils.showLong(it)
		})
	}

	private fun doTaskFinish() {
		LoadingManager.showLoading()
		ZdLocationManager.getSingleLocation(success = { it ->
			LoadingManager.hideLoading()
			val taskFinishRequest = TaskFinishRequest(uiState.value.orderInfo?.userOrderId,
				it.latitude,
				it.longitude,
				System.currentTimeMillis())
			LoadingManager.showLoading()
			RetrofitHelper.getDefaultService().taskFinish(taskFinishRequest)
				.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
				.subscribe(object : BaseObserver<TaskFinishResponse>() {
					override fun doSuccess(it : TaskFinishResponse?) {
						LoadingManager.hideLoading()
						val eleWorkOrderBean = RoomHelper.db?.eleWorkOrderDao()
							?.getEleWorkOrder(uiState.value.orderInfo?.taskId ?: 0)
						eleWorkOrderBean?.copy(hasCreatedEleWorkOrderPhoto = true)
							?.let { it1 -> updateCurrentEleWorkOrder(it1) }
						updateState(uiState.value.copy(goNextPage = true))
						LogUtil.print("任务完成，进入历史", "taskFinishRequest==$taskFinishRequest")
					}

					override fun doFailure(code : Int, msg : String?) {
						LoadingManager.hideLoading()
						if (msg?.contains("进入历史") == true) {
							RoomHelper.db?.eleWorkOrderDao()
								?.getEleWorkOrder(getCurrentOrder()?.taskId ?: 0)?.let {
									RoomHelper.db?.eleWorkOrderDao()
										?.update(it.copy(hasCreatedEleWorkOrderPhoto = true))
								}
							updateState(uiState.value.copy(goNextPage = true))
							return
						}
						updateState(uiState.value.copy(loadingState = LoadingState.LoadingFailed(msg)))
						LogUtil.print("任务失败", "code==$code msg==$msg")
					}
				})
		}, failed = {
			LoadingManager.hideLoading()
			ToastUtils.showLong(it)
			updateState(uiState.value.copy(loadingState = LoadingState.LoadingFailed(it)))
		})
	}

	sealed class Action {
		data object Init : Action()
		data class UpdateState(val uiState : UiState) : Action()
		data object TaskFinish : Action()
		data object ClearOfflineTask : Action()
		data class UpdateCurrentEleWorkOrder(val type : Int, val path : String) : Action()
	}

	data class UiState(
		val loadingState : LoadingState = LoadingState.Loading,
		val orderInfo : OrderInfo? = null,
		val goNextPage : Boolean? = null,
		val showOfflineTaskDialog : Boolean? = null,
		val showSignDialog : Int? = null, //1 客户签名  2 接车人签名  3 服务人员签名
	)
}