package com.za.ui.servicing.departure_photo

import com.alibaba.fastjson.JSONObject
import com.blankj.utilcode.util.ToastUtils
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.UpdateTaskBean
import com.za.bean.request.UpdateTaskRequest
import com.za.common.GlobalData
import com.za.common.log.LogUtil
import com.za.ext.toJson
import com.za.net.CommonMethod
import com.za.service.location.ZdLocationManager
import kotlinx.coroutines.flow.MutableStateFlow

class DeparturePhotoVm : IServicingVm<DeparturePhotoVm.Action, DeparturePhotoVm.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 -> updateTask()
			is Action.UpdateState -> updateState(action.uiState)
			is Action.UpdatePhotoTemplate -> updateTemplate()
		}
	}

	private fun updateTemplate() {
		getDeparturePhotoTemplate(success = {
			updateState(uiState.value.copy(photoTemplateList = it))
		}, failure = { ToastUtils.showShort(it) })
	}

	private fun updateTask() {
		if (uiState.value.photoTemplateList.isNullOrEmpty()) {
			ToastUtils.showShort("现场照片不能为空！")
			return
		}

		//先检查照片是否是为空
		uiState.value.photoTemplateList?.forEach {
			if (it.photoType == 2) {
				return@forEach
			}
			if (it.doHaveFilm == 1 && it.photoLocalWaterMarkerPath.isNullOrBlank()) {
				ToastUtils.showLong("请上传 ${it.imageTitle}！！")
				return
			}
		}

		uiState.value.photoTemplateList?.forEach {
			if (it.photoType == 2) {
				return@forEach
			}
			if (it.photoUploadStatus == 4) {
				ToastUtils.showLong("${it.photoName}正在上传,请等待照片上传完成！")
				return
			}
			if (! it.photoLocalWaterMarkerPath.isNullOrBlank() && it.photoUploadPath.isNullOrBlank()) {
				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["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(isNeedAddress = true, success = {
			LoadingManager.hideLoading()
			val taskRequest = UpdateTaskRequest(type = "START",
				taskId = getCurrentOrder()?.taskId,
				userId = GlobalData.driverInfoBean?.userId,
				vehicleId = GlobalData.driverInfoBean?.vehicleId,
				currentState = GlobalData.currentOrder?.taskState,
				offlineMode = 0,
				operateTime = System.currentTimeMillis().toString(),
				lat = it.latitude,
				lng = it.longitude,
				address = it.address,
				templatePhotoInfoList = tempPhotoList.toList())
			doUploadTask(request = taskRequest)
		}, failed = {
			LoadingManager.hideLoading()
			ToastUtils.showShort(it)
			LogUtil.print("$tag updateTask", "定位获取失败==$it")
		})
	}

	private fun doUploadTask(request : UpdateTaskRequest) {
		LoadingManager.showLoading()
		CommonMethod.updateTask(request, success = {
			LoadingManager.hideLoading()
			updateOrder(getCurrentOrder()?.copy(taskState = it?.nextState))
			updateState(uiState.value.copy(goNextPage = it, orderInfo = getCurrentOrder()))
			LogUtil.print("$tag doUploadTask", "状态更新成功==$request")
		}, failed = { msg, code ->
			LoadingManager.hideLoading()
			ToastUtils.showShort(msg)
			LogUtil.print("$tag doUploadTask", "状态更新失败==${request.toJson()} msg==$msg")
		})
	}

	private fun init() {
		getDeparturePhotoTemplate(success = {
			updateState(uiState.value.copy(photoTemplateList = it, orderInfo = getCurrentOrder()))
		}, failure = { ToastUtils.showShort(it) })
	}


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

	data class UiState(val orderInfo : OrderInfo? = null,
		val verifyValue : String? = null,
		val goNextPage : UpdateTaskBean? = null,
		val isGoNextPageDialog : Boolean? = null,
		val showCallPhoneDialog : Boolean? = null,
		val photoTemplateList : List<PhotoTemplateInfo>? = null)
}