package com.za.ui.servicing.ele_sign

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.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 io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.schedulers.Schedulers
import kotlinx.coroutines.flow.MutableStateFlow
import java.io.File

class EleSignVm : IServicingVm<EleSignVm.Action, EleSignVm.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.UploadSignature -> uploadSignature(action.path)
			is Action.UploadOffline -> uploadOffline()
		}
	}


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

		if (uiState.value.eleWorkOrderBean?.serverCustomSignPath.isNullOrBlank()) {
			val signOfflineUpdateTaskBean =
				OfflineUpdateTaskBean(imageLocalPath = uiState.value.eleWorkOrderBean?.localCustomSignPath,
					taskId = getCurrentOrder()?.taskId,
					taskCode = getCurrentOrder()?.taskCode,
					offlineTitle = "电子工单-客户签名照片",
					offlineType = 5)
			insertOfflineTask(signOfflineUpdateTaskBean)
		}


		val offlineUpdateTaskBean = OfflineUpdateTaskBean(taskId = getCurrentOrder()?.taskId,
			taskCode = getCurrentOrder()?.taskCode,
			customerSignPath = uiState.value.eleWorkOrderBean?.serverCustomSignPath,
			offlineTitle = "电子工单-车况检查表",
			offlineType = 3,
			eleState = 2,
			userOrderId = getCurrentOrder()?.userOrderId)
		insertOfflineTask(offlineUpdateTaskBean)
		updateCurrentEleWorkOrder(eleWorkOrderBean.copy(orderWorkStatus = 2))
		updateState(uiState.value.copy(goNextPage = UpdateTaskBean(getCurrentOrder()?.taskState),
			orderInfo = getCurrentOrder()))
	}

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

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

		if (uiState.value.eleWorkOrderBean?.localCustomSignPath.isNullOrBlank()) {
			ToastUtils.showLong("签名照不能为空！！")
			return
		}

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

		if (! uiState.value.eleWorkOrderBean?.localCustomSignPath.isNullOrBlank() && uiState.value.eleWorkOrderBean?.serverCustomSignPath.isNullOrBlank()) {
			showTipDialog("请先上传签名！")
			return
		}

		val saveEleOrderRequest = SaveEleOrderRequest(state = 2,
			userOrderId = getCurrentOrder()?.userOrderId,
			taskOrderId = getCurrentOrder()?.taskId,
			customerSignPath = uiState.value.eleWorkOrderBean?.serverCustomSignPath)

		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 = 2))
					updateState(uiState.value.copy(goNextPage = UpdateTaskBean(getCurrentOrder()?.taskState),
						orderInfo = getCurrentOrder()))
				}

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

	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==${it.toJson()}")
		}, 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 UploadSignature(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 showOfflineDialog : Boolean? = null,
		val damagePhoto : List<EleCarDamagePhotoBean>? = null,
	)
}