package com.za.ui.servicing.inservice_people_confirm

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.request.DriverFaceCompareRequest
import com.za.bean.request.IaiCompareFaceBean
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.BaseObserver
import com.za.net.CommonMethod
import com.za.net.RetrofitHelper
import com.za.service.location.ZdLocationManager
import com.za.ui.servicing.inservice_people_confirm.InServicePeopleConfirmVm.Action
import com.za.ui.servicing.inservice_people_confirm.InServicePeopleConfirmVm.Action.CompilePeople
import com.za.ui.servicing.inservice_people_confirm.InServicePeopleConfirmVm.UiState
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.schedulers.Schedulers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import java.io.File

class InServicePeopleConfirmVm : IServicingVm<Action, UiState>() {
	private val _uiState = MutableStateFlow(UiState())
	val uiState get() = _uiState as StateFlow<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 CompilePeople -> comparePeople(action.url)

		}
	}


	private fun updateTask() {
		LoadingManager.showLoading()
		ZdLocationManager.getSingleLocation(success = {
			LoadingManager.hideLoading()
			val taskRequest = UpdateTaskRequest(type = "START",
				taskId = getCurrentOrder()?.taskId,
				userId = GlobalData.driverInfoBean?.userId,
				vehicleId = GlobalData.driverInfoBean?.vehicleId,
				currentState = getCurrentOrder()?.taskState,
				offlineMode = 0,
				operateTime = System.currentTimeMillis().toString(),
				lat = it.latitude,
				lng = it.longitude)
			doUploadTask(request = taskRequest)
		}, failed = {
			LoadingManager.hideLoading()
			ToastUtils.showShort(it)
		})
	}

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


	private fun comparePeople(url : String?) {
		if (url.isNullOrBlank()) {
			ToastUtils.showLong("图片路径为空！")
			return
		}
		LoadingManager.showLoading()
		CommonMethod.uploadImage(file = File(url), success = { it ->
			LoadingManager.hideLoading()
			doComparePeople(it)
		}, failed = {
			LoadingManager.hideLoading()
			updateState(uiState.value.copy(showCompareFailedDialog = "$it", compareResult = false))
		})
	}

	private fun doComparePeople(url : String?) {
		val driverFaceCompareRequest =
			DriverFaceCompareRequest(vehicleId = GlobalData.driverInfoBean?.vehicleId,
				driverId = GlobalData.driverInfoBean?.userId,
				photoUrl = url)
		LoadingManager.showLoading()
		RetrofitHelper.getDefaultService().iaiCompareFace(driverFaceCompareRequest)
			.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
			.subscribe(object : BaseObserver<IaiCompareFaceBean>() {
				override fun doSuccess(it : IaiCompareFaceBean?) {
					LoadingManager.hideLoading()
					if (it?.compareResult == true) {
						updateState(uiState.value.copy(compareResult = true))
						LogUtil.print("face", "人脸对比成功：$it")
						return
					}
					updateState(uiState.value.copy(showCompareFailedDialog = "人脸对比失败",
						compareResult = false))
				}

				override fun doFailure(code : Int, msg : String?) {
					LoadingManager.hideLoading()
					updateState(uiState.value.copy(showCompareFailedDialog = "$msg",
						compareResult = false))
					LogUtil.print("face", "人脸对比失败：$msg")
				}
			})
	}

	private fun init() {

	}

	sealed class Action {
		object Init : Action()
		data class CompilePeople(val url : String? = null) : Action()
		object UpdateTask : Action()
	}

	data class UiState(
		val orderInfo : OrderInfo? = null,
		val goNextPage : UpdateTaskBean? = null,
		val compareResult : Boolean? = null,
		val showCompareFailedDialog : String? = null,
	)
}