package com.za.ui.servicing.order_confirm


import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.FileUtils
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.ele.EleCarDamagePhotoBean
import com.za.bean.db.ele.EleWorkOrderBean
import com.za.bean.db.order.OrderInfo
import com.za.bean.request.SaveEleOrderRequest
import com.za.bean.request.UpdateTaskBean
import com.za.common.GlobalData
import com.za.common.log.LogUtil
import com.za.common.util.AppFileManager
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 ConfirmEleVm : IServicingVm<ConfirmEleVm.Action, ConfirmEleVm.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.Upload -> upload()
			is Action.UpdateServiceSuccessState -> updateIsServiceSuccess(action.state)
			is Action.UpdateAcceptSignature -> uploadAcceptSignature(action.path)
			is Action.UploadServiceSignature -> updateServiceSignature(action.path)
			is Action.IsChangeBattery -> updateIsChangeBattery(action.isChange)
			is Action.UploadOffline -> uploadOffline()
		}
	}


	private fun updateIsChangeBattery(isChange : Boolean) {
		updateState(uiState.value.copy(eleWorkOrderBean = uiState.value.eleWorkOrderBean?.copy(
			changeBattery = isChange)))
		val eleWorkOrderBean = uiState.value.eleWorkOrderBean?.copy(changeBattery = isChange)
		if (eleWorkOrderBean != null) {
			RoomHelper.db?.eleWorkOrderDao()?.update(eleWorkOrderBean)
		}
	}

	private fun updateIsServiceSuccess(isSuccess : Int) {
		val eleWorkOrderBean = uiState.value.eleWorkOrderBean?.copy(isSuccess = isSuccess)
		updateState(uiState.value.copy(eleWorkOrderBean = eleWorkOrderBean))
		if (eleWorkOrderBean != null) {
			RoomHelper.db?.eleWorkOrderDao()?.update(eleWorkOrderBean)
		}
	}

	private fun updateServiceSignature(path : String) {
		LoadingManager.showLoading()
		val eleWorkOrderBean =
			uiState.value.eleWorkOrderBean?.copy(localServicePeopleSignPath = path)
		if (eleWorkOrderBean != null) {
			RoomHelper.db?.eleWorkOrderDao()?.update(eleWorkOrderBean)
			updateState(uiState.value.copy(eleWorkOrderBean = eleWorkOrderBean))
			LogUtil.print("updateServiceSignature success", eleWorkOrderBean.toJson() ?: "")
		}
		CommonMethod.uploadImage(File(path), success = {
			LoadingManager.hideLoading()
			if (eleWorkOrderBean != null) {
				val ele = eleWorkOrderBean.copy(serverServicePeopleSignPath = it)
				RoomHelper.db?.eleWorkOrderDao()?.update(ele)
				updateState(uiState.value.copy(eleWorkOrderBean = ele))
				LogUtil.print("updateServiceSignature success", ele.toJson() ?: "")
			}
		}, failed = {
			LoadingManager.hideLoading()
			LogUtil.print("updateServiceSignature", "failed==$it")
		})
	}

	private fun uploadAcceptSignature(path : String) {
		LoadingManager.showLoading()
		val eleWorkOrderBean = uiState.value.eleWorkOrderBean?.copy(localAcceptCarSignPath = path)
		if (eleWorkOrderBean != null) {
			RoomHelper.db?.eleWorkOrderDao()?.update(eleWorkOrderBean)
			updateState(uiState.value.copy(eleWorkOrderBean = eleWorkOrderBean))
			LogUtil.print("updateServiceSignature success", eleWorkOrderBean.toJson() ?: "")
		}
		CommonMethod.uploadImage(File(path), success = {
			LoadingManager.hideLoading()
			if (eleWorkOrderBean != null) {
				val ele = eleWorkOrderBean.copy(serverAcceptCarSignPath = it)
				RoomHelper.db?.eleWorkOrderDao()?.update(ele)
				updateState(uiState.value.copy(eleWorkOrderBean = ele))
				LogUtil.print("uploadAcceptSignature success", ele.toJson() ?: "")
			}
		}, failed = {
			LoadingManager.hideLoading()
			LogUtil.print("uploadAcceptSignature", "failed==$it")
		})
	}


	private fun uploadOffline() {
		val eleWorkOrderBean =
			RoomHelper.db?.eleWorkOrderDao()?.getEleWorkOrder(getCurrentOrder()?.taskId ?: 0)
		if (eleWorkOrderBean == null) {
			ToastUtils.showLong("数据获取失败，请返回首页重试！")
			return
		}

		if (uiState.value.eleWorkOrderBean?.serverAcceptCarSignPath.isNullOrBlank()) {
			val signOfflineUpdateTaskBean =
				OfflineUpdateTaskBean(imageLocalPath = uiState.value.eleWorkOrderBean?.localAcceptCarSignPath,
					taskId = getCurrentOrder()?.taskId,
					taskCode = getCurrentOrder()?.taskCode,
					offlineTitle = "电子工单-接车人签字",
					offlineType = 6)
			insertOfflineTask(signOfflineUpdateTaskBean)
		}

		if (uiState.value.eleWorkOrderBean?.serverServicePeopleSignPath.isNullOrBlank()) {
			val signOfflineUpdateTaskBean =
				OfflineUpdateTaskBean(imageLocalPath = uiState.value.eleWorkOrderBean?.localServicePeopleSignPath,
					taskId = getCurrentOrder()?.taskId,
					taskCode = getCurrentOrder()?.taskCode,
					offlineTitle = "电子工单-服务人员签字",
					offlineType = 7)
			insertOfflineTask(signOfflineUpdateTaskBean)
		}

		LoadingManager.showLoading()
		ZdLocationManager.getSingleLocation(success = {
			LoadingManager.hideLoading()
			val offlineUpdateTaskBean = OfflineUpdateTaskBean(taskId = getCurrentOrder()?.taskId,
				taskCode = getCurrentOrder()?.taskCode,
				offlineTitle = "电子工单-客户签字",
				offlineType = 3,
				eleLat = it.latitude,
				eleLng = it.longitude,
				offlineMode = 1,
				isFinish = true,
				tyreNumber = if (uiState.value.isAddSmallWheel == true) {
					uiState.value.wheelNum
				} else null,
				hasSuccess = eleWorkOrderBean.isSuccess,
				recipientSignPath = eleWorkOrderBean.serverAcceptCarSignPath,
				waitstaffSignPath = eleWorkOrderBean.serverServicePeopleSignPath,
				eleState = 3,
				userOrderId = getCurrentOrder()?.userOrderId)
			insertOfflineTask(offlineUpdateTaskBean)
		}, failed = {
			LoadingManager.hideLoading()
			val offlineUpdateTaskBean = OfflineUpdateTaskBean(taskId = getCurrentOrder()?.taskId,
				taskCode = getCurrentOrder()?.taskCode,
				customerSignPath = uiState.value.eleWorkOrderBean?.serverCustomSignPath,
				offlineTitle = "电子工单-车况检查表",
				offlineType = 3,
				eleLat = GlobalData.currentLocation?.latitude,
				eleLng = GlobalData.currentLocation?.longitude,
				offlineMode = 1,
				isFinish = true,
				tyreNumber = if (uiState.value.isAddSmallWheel == true) {
					uiState.value.wheelNum
				} else null,
				hasSuccess = eleWorkOrderBean.isSuccess,
				recipientSignPath = eleWorkOrderBean.serverAcceptCarSignPath,
				waitstaffSignPath = eleWorkOrderBean.serverServicePeopleSignPath,
				eleState = 3,
				userOrderId = getCurrentOrder()?.userOrderId)
			insertOfflineTask(offlineUpdateTaskBean)
		})
		updateCurrentEleWorkOrder(eleWorkOrderBean.copy(orderWorkStatus = 3))
		updateState(uiState.value.copy(goNextPage = UpdateTaskBean(getCurrentOrder()?.taskState),
			orderInfo = getCurrentOrder()))
	}

	private fun upload() {
		val eleWorkOrderBean = uiState.value.eleWorkOrderBean
		if (eleWorkOrderBean == null) {
			ToastUtils.showLong("数据获取失败，请返回首页重试！")
			return
		}

		if (getCurrentOrder()?.flowType != 2 && eleWorkOrderBean.isSuccess == null) {
			showTipDialog("请选择服务是否成功！")
			return
		}

		if (uiState.value.isAddSmallWheel == true && uiState.value.wheelNum == null || uiState.value.wheelNum == 0) {
			showTipDialog("请输入辅助轮个数")
			return
		}

		if (uiState.value.isAddSmallWheel == true && uiState.value.wheelNum != null && uiState.value.wheelNum !! > 4) {
			showTipDialog("辅助轮个数不能超过4个")
			return
		}

		if (! getCurrentOrderOfflineTask().isNullOrEmpty()) {
			uploadOffline()
			return
		}

		if (eleWorkOrderBean.localAcceptCarSignPath.isNullOrBlank() || eleWorkOrderBean.localServicePeopleSignPath.isNullOrBlank()) {
			showTipDialog("请先上传签名！")
			return
		}

		LoadingManager.showLoading()
		ZdLocationManager.getSingleLocation(success = {
			LoadingManager.hideLoading()
			val saveEleOrderRequest = SaveEleOrderRequest(state = 3,
				userOrderId = GlobalData.currentOrder?.userOrderId,
				taskOrderId = GlobalData.currentOrder?.taskId,
				lat = it.latitude,
				lng = it.longitude,
				offlineMode = 0,
				isFinish = true,
				tyreNumber = if (uiState.value.isAddSmallWheel == true) {
					uiState.value.wheelNum
				} else null,
				hasSuccess = eleWorkOrderBean.isSuccess,
				recipientSignPath = eleWorkOrderBean.serverAcceptCarSignPath,
				waitstaffSignPath = eleWorkOrderBean.serverServicePeopleSignPath)
			LoadingManager.showLoading()
			RetrofitHelper.getDefaultService().saveElectronOrder(saveEleOrderRequest)
				.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
				.subscribe(object : BaseObserver<String>() {
					override fun doSuccess(it : String?) {
						LoadingManager.hideLoading()
						updateCurrentEleWorkOrder(eleWorkOrderBean.copy(orderWorkStatus = 3))
						updateState(uiState.value.copy(goNextPage = UpdateTaskBean(getCurrentOrder()?.taskState),
							orderInfo = getCurrentOrder()))
					}

					override fun doFailure(code : Int, msg : String?) {
						LoadingManager.hideLoading()
						if (code == Const.NetWorkException) {
							updateState(uiState.value.copy(showOfflineDialog = true))
						}
						LogUtil.print("eleSign upload failed", msg ?: "")
					}
				})

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

	private fun init() {
		LoadingManager.showLoading()
		CommonMethod.queryElectronOrder(getCurrentOrder(), success = {
			LoadingManager.hideLoading()
			val photoList = RoomHelper.db?.eleCarDamagePhotoDao()
				?.getEleCarDamagePhotos(getCurrentOrder()?.taskId ?: 0)
			updateState(uiState.value.copy(eleWorkOrderBean = it,
				damagePhoto = photoList,
				orderInfo = getCurrentOrder()))

			LogUtil.print("电子表单更新车辆损伤照片", "eleWorkOrderBean==${photoList.toJson()}")

			if (! it.localServicePeopleSignPath.isNullOrBlank() || ! it.serverServicePeopleSignPath.isNullOrBlank()) {
				return@queryElectronOrder
			}

			if (FileUtils.isFileExists(File(AppFileManager.getDriverSignPath(context = ActivityUtils.getTopActivity())))) {
				updateServiceSignature(AppFileManager.getDriverSignPath(context = ActivityUtils.getTopActivity()))
			}

		}, failed = {
			LoadingManager.hideLoading()
			ToastUtils.showShort("数据加载异常，请返回重试！")
		})
	}

	sealed class Action {
		data object Init : Action()
		data class UpdateState(val uiState : UiState) : Action()
		data object Upload : Action()
		data object UploadOffline : Action()
		data class UpdateServiceSuccessState(val state : Int) : Action()
		data class IsChangeBattery(val isChange : Boolean) : Action()
		data class UpdateAcceptSignature(val path : String) : Action()
		data class UploadServiceSignature(val path : String) : Action()
	}

	data class UiState(
		val orderInfo : OrderInfo? = null,
		val eleWorkOrderBean : EleWorkOrderBean? = null,
		val goNextPage : UpdateTaskBean? = null,
		val isGoNextPageDialog : Boolean? = null,
		val showCallPhoneDialog : Boolean? = null,
		val damagePhoto : List<EleCarDamagePhotoBean>? = null,
		val isAddSmallWheel : Boolean? = null,
		val wheelNum : Int? = null,
		val showOfflineDialog : Boolean? = null,
		val showServicePeopleSignDialog : Boolean? = null, //服务人员签名弹窗
	)
}