package com.za.ui.servicing.order_give_up


import androidx.compose.ui.util.fastForEachIndexed
import com.alibaba.fastjson.JSONObject
import com.blankj.utilcode.util.ToastUtils
import com.za.base.BaseVm
import com.za.base.view.LoadingManager
import com.za.bean.db.ele.EleWorkOrderBean
import com.za.bean.db.order.OrderInfo
import com.za.bean.db.order.PhotoTemplateInfo
import com.za.bean.request.GiveUpTaskRequest
import com.za.bean.request.SaveEleOrderRequest
import com.za.bean.request.UpdatePhotoRequest
import com.za.bean.request.UploadPhotoBean
import com.za.common.GlobalData
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.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 OrderGiveUpVm : BaseVm<OrderGiveUpVm.Action, OrderGiveUpVm.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.UpdateTask -> {
				when (uiState.value.giveUpType) {
					0 -> giveUp()
					1 -> giveUpFromServer()
					2 -> giveUpFromGoPreview()
				}
			}

			is Action.UpdateState -> updateState(action.uiState)
			is Action.UpdatePhotoTemplate -> updateTemplate()
			is Action.UploadSign -> uploadSign(action.signPath)
		}
	}

	private fun uploadSign(path : String?) {
		if (path.isNullOrBlank()) {
			ToastUtils.showLong("照片路径为空，请重新签名！")
			return
		}

		CommonMethod.uploadImage(File(path), success = { it ->
			val eleWorkOrderBean = uiState.value.eleWorkOrderBean
			if (eleWorkOrderBean == null) {
				updateState(uiState.value.copy(serverServicePeopleSignPath = it))
			} else {
				val ele = eleWorkOrderBean.copy(serverServicePeopleSignPath = it,
					localServicePeopleSignPath = path)
				RoomHelper.db?.eleWorkOrderDao()?.update(ele)
				updateState(uiState.value.copy(eleWorkOrderBean = ele,
					serverServicePeopleSignPath = it))
			}
		}, failed = {
			ToastUtils.showShort("签名上传失败，请重新签名")
		})
	}

	private fun updateTemplate() {
		val list = RoomHelper.db?.photoTemplateDao()?.getOrderPhotoTemplateFromTaskNodeAndTaskId(
			18100,
			uiState.value.orderInfo?.taskId ?: 0)
		updateState(uiState.value.copy(photoTemplateList = list))
	}

	private fun giveUpFromServer() {
		if (uiState.value.photoTemplateList.isNullOrEmpty()) {
			ToastUtils.showShort("作业照片不能为空！")
			return
		}

		//校验必拍照片是否拍摄
		uiState.value.photoTemplateList?.forEach {
			if (it.doHaveFilm == 1 && it.photoUploadPath.isNullOrBlank() && it.photoType != 2) {
				ToastUtils.showLong("请上传${it.imageTitle}")
				return
			}
		}

		LoadingManager.showLoading()
		uiState.value.photoTemplateList?.fastForEachIndexed { i, item ->
			if (item.photoUploadPath.isNullOrBlank()) {
				return@fastForEachIndexed
			}
			val jsonObject = JSONObject()
			jsonObject["realTakePhotoTime"] = item.realTakePhotoTime ?: ""
			jsonObject["photoSource"] = item.photoSource
			jsonObject["time"] = item.time
			jsonObject["sort"] = item.sort
			jsonObject["lat"] = item.lat
			jsonObject["path"] = item.photoUploadPath
			jsonObject["lng"] = item.lng
			jsonObject["address"] = item.address

			val request = UpdatePhotoRequest(taskId = uiState.value.taskId,
				taskState = "GIVEUP",
				picturePosition = i + 1,
				picturePath = item.photoUploadPath,
				imgInfo = jsonObject.toJSONString())

			RetrofitHelper.getDefaultService().addPhoto(request).subscribeOn(Schedulers.io())
				.observeOn(AndroidSchedulers.mainThread())
				.subscribe(object : BaseObserver<UploadPhotoBean>() {
					override fun doSuccess(it : UploadPhotoBean?) {
						LoadingManager.hideLoading()
					}

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

		updateState(uiState.value.copy(orderGiveUpSuccess = true))
		GlobalData.clearOrderCache(uiState.value.orderInfo?.taskId ?: uiState.value.taskId ?: 0)
	}

	private fun giveUpFromGoPreview() {
		if (uiState.value.photoTemplateList.isNullOrEmpty()) {
			ToastUtils.showShort("作业照片不能为空！")
			return
		}

		//校验必拍照片是否拍摄
		uiState.value.photoTemplateList?.forEach {
			if (it.doHaveFilm == 1 && it.photoUploadPath.isNullOrBlank() && it.photoType != 2) {
				ToastUtils.showLong("请上传${it.imageTitle}")
				return
			}
		}

		val tempPhotoList = arrayListOf<String?>()
		uiState.value.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["time"] = item.time
				jsonObject["sort"] = item.sort
				jsonObject["lat"] = item.lat
				jsonObject["path"] = item.photoUploadPath
				jsonObject["lng"] = item.lng
				jsonObject["address"] = item.address
				tempPhotoList.add(jsonObject.toJSONString())
			}
		}

		LoadingManager.showLoading()
		ZdLocationManager.getSingleLocation(isNeedAddress = true, success = {
			LoadingManager.hideLoading()
			val taskRequest = GiveUpTaskRequest(taskId = GlobalData.currentOrder?.taskId,
				userId = GlobalData.driverInfoBean?.userId,
				vehicleId = GlobalData.driverInfoBean?.vehicleId,
				lat = it.latitude,
				address = it.address,
				pushGiveUpFlag = 1,
				lng = it.longitude,
				templatePhotoInfoList = tempPhotoList.toList())
			doGiveUpTask(request = taskRequest)
		}, failed = {
			LoadingManager.hideLoading()
			ToastUtils.showShort(it)
		})
	}

	private fun giveUp() {
		uploadEleWorkOrder {
			if (uiState.value.photoTemplateList.isNullOrEmpty()) {
				ToastUtils.showShort("作业照片不能为空！")
				return@uploadEleWorkOrder
			}

			//校验必拍照片是否拍摄
			uiState.value.photoTemplateList?.forEach {
				if (it.doHaveFilm == 1 && it.photoUploadPath.isNullOrBlank() && it.photoType != 2) {
					ToastUtils.showLong("请上传${it.imageTitle}")
					return@uploadEleWorkOrder
				}
			}

			val tempPhotoList = arrayListOf<String?>()
			uiState.value.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["time"] = item.time
					jsonObject["sort"] = item.sort
					jsonObject["lat"] = item.lat
					jsonObject["path"] = item.photoUploadPath
					jsonObject["lng"] = item.lng
					jsonObject["address"] = item.address
					tempPhotoList.add(jsonObject.toJSONString())
				}
			}

			LoadingManager.showLoading()
			ZdLocationManager.getSingleLocation(success = {
				LoadingManager.hideLoading()
				val taskRequest = GiveUpTaskRequest(taskId = GlobalData.currentOrder?.taskId,
					userId = GlobalData.driverInfoBean?.userId,
					vehicleId = GlobalData.driverInfoBean?.vehicleId,
					lat = it.latitude,
					address = it.address,
					lng = it.longitude,
					templatePhotoInfoList = tempPhotoList.toList())
				doGiveUpTask(request = taskRequest)
			}, failed = {
				LoadingManager.hideLoading()
				ToastUtils.showShort(it)
			})
		}
	}


	private fun uploadEleWorkOrder(success : () -> Unit) {
		val eleWorkOrderBean = uiState.value.eleWorkOrderBean
		if (uiState.value.serverServicePeopleSignPath.isNullOrBlank()) {
			ToastUtils.showShort("请填写签名")
			return
		}
		LoadingManager.showLoading()
		val saveEleOrderRequest = SaveEleOrderRequest(taskOrderId = uiState.value.orderInfo?.taskId,
			userOrderId = uiState.value.orderInfo?.userOrderId,
			state = 3,
			hasSuccess = eleWorkOrderBean?.isSuccess,
			waitstaffSignPath = uiState.value.serverServicePeopleSignPath)
		RetrofitHelper.getDefaultService().saveElectronOrder(saveEleOrderRequest)
			.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
			.subscribe(object : BaseObserver<String>() {
				override fun doSuccess(it : String?) {
					LoadingManager.hideLoading()
					if (eleWorkOrderBean != null) {
						RoomHelper.db?.eleWorkOrderDao()
							?.update(eleWorkOrderBean.copy(orderWorkStatus = 3))
						updateState(uiState.value.copy(eleWorkOrderBean = eleWorkOrderBean.copy(
							orderWorkStatus = 3)))
					}
					success()
				}

				override fun doFailure(code : Int, msg : String?) {
					LoadingManager.hideLoading()
					LogUtil.print("订单放弃 失败", msg ?: "")
				}
			})
	}


	private fun doGiveUpTask(request : GiveUpTaskRequest) {
		LoadingManager.showLoading()
		RetrofitHelper.getDefaultService().giveUpTask(request).subscribeOn(Schedulers.io())
			.observeOn(Schedulers.io()).subscribe(object : BaseObserver<String>() {
				override fun doSuccess(it : String?) {
					LoadingManager.hideLoading()
					updateState(uiState.value.copy(orderGiveUpSuccess = true))
					GlobalData.clearOrderCache(uiState.value.orderInfo?.taskId
						?: uiState.value.taskId ?: 0)
				}

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

	// TODO("订单放弃的推送需要再加个 userOrderId的参数，否则，无法请求到照片模版")
	private fun init() {
		if (uiState.value.orderInfo != null) {
			val eleWorkOrderBean = RoomHelper.db?.eleWorkOrderDao()
				?.getEleWorkOrder(uiState.value.orderInfo?.taskId ?: 0)
			val photoTemplateList = RoomHelper.db?.photoTemplateDao()
				?.getOrderPhotoTemplateFromTaskNodeAndTaskId(18100,
					taskId = uiState.value.orderInfo?.taskId ?: 0)
			if (photoTemplateList.isNullOrEmpty()) {
				CommonMethod.fetchPhotoTemplate(uiState.value.orderInfo, success = {
					val data = RoomHelper.db?.photoTemplateDao()?.getOrderPhotoTemplateFromTaskNode(
						18100,
						uiState.value.orderInfo?.userOrderId ?: 0)

					updateState(uiState.value.copy(photoTemplateList = handlerData(data),
						eleWorkOrderBean = eleWorkOrderBean))
				}, failed = {
					ToastUtils.showShort(it)
				})
			} else {
				updateState(uiState.value.copy(photoTemplateList = handlerData(photoTemplateList),
					eleWorkOrderBean = eleWorkOrderBean))
			}

			LogUtil.print("订单放弃", "photoTemplateList==${photoTemplateList?.toJson()}")
			return
		}

		if (GlobalData.currentOrder?.taskId == uiState.value.taskId) {
			updateState(uiState.value.copy(orderInfo = GlobalData.currentOrder))
		}

		val eleWorkOrderBean =
			RoomHelper.db?.eleWorkOrderDao()?.getEleWorkOrder(uiState.value.orderInfo?.taskId ?: 0)
		val photoTemplateList = RoomHelper.db?.photoTemplateDao()
			?.getOrderPhotoTemplateFromTaskNodeAndTaskId(18100,
				taskId = uiState.value.orderInfo?.taskId ?: 0)
		if (photoTemplateList.isNullOrEmpty()) {
			CommonMethod.fetchPhotoTemplate(uiState.value.orderInfo, success = {
				val data = RoomHelper.db?.photoTemplateDao()
					?.getOrderPhotoTemplateFromTaskNodeAndTaskId(18100, uiState.value.taskId ?: 0)
				updateState(uiState.value.copy(photoTemplateList = handlerData(data),
					eleWorkOrderBean = eleWorkOrderBean))
			}, failed = {
				ToastUtils.showShort(it)
			})
		} else {
			updateState(uiState.value.copy(photoTemplateList = handlerData(photoTemplateList),
				eleWorkOrderBean = eleWorkOrderBean))
		}

		LogUtil.print("订单放弃", "photoTemplateList==${photoTemplateList?.toJson()}")

	}

	//0不展示 1 判断是否到达现场 是展示 不是不展示  其他都是展示
	private fun handlerData(originDta : List<PhotoTemplateInfo>?) : List<PhotoTemplateInfo> {
		val list = arrayListOf<PhotoTemplateInfo>()
		originDta?.forEach {
			if (it.showPingAnGiveUpPhoto == 0) {
				return@forEach
			}
			if (it.showPingAnGiveUpPhoto == 1) {
				if (uiState.value.orderInfo?.taskState == "VERIFY" || uiState.value.orderInfo?.taskState == "EXAMINE") {
					list.add(it)
					return@forEach
				}
				return@forEach
			}
			list.add(it)
		}
		return list
	}

	sealed class Action {
		data object Init : Action()
		data object UpdateTask : Action()
		data class UploadSign(val signPath : String?) : Action()
		data class UpdatePhotoTemplate(val photoTemplateInfo : PhotoTemplateInfo) : Action()
		data class UpdateState(val uiState : UiState) : Action()
	}

	data class UiState(val orderInfo : OrderInfo? = null,
		val taskId : Int? = null,
		val giveUpType : Int? = null,
		val serverServicePeopleSignPath : String? = null,
		val orderGiveUpSuccess : Boolean? = null,
		val isGoNextPageDialog : Boolean? = null,
		val eleWorkOrderBean : EleWorkOrderBean? = null,
		val photoTemplateList : List<PhotoTemplateInfo>? = null)
}