package com.za.ui.servicing.verify

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.order.OrderInfo
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.getNextStatus
import com.za.ext.toJson
import com.za.net.CommonMethod
import com.za.offline.OfflineUpdateTaskBean
import com.za.service.location.ZdLocationManager
import kotlinx.coroutines.flow.MutableStateFlow

class VerifyOrderVm : IServicingVm<VerifyOrderVm.Action, VerifyOrderVm.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.UploadOffline -> uploadOffline()
        }
    }

    private fun uploadOffline(taskRequest: UpdateTaskRequest? = null) {
        if (taskRequest != null) {
            val offlineUpdateTaskBean = OfflineUpdateTaskBean(
                type = taskRequest.type,
                taskId = taskRequest.taskId,
                userId = taskRequest.userId,
                vehicleId = taskRequest.vehicleId,
                currentState = taskRequest.currentState,
                offlineMode = 1,
                operateTime = taskRequest.operateTime,
                updateTaskLat = taskRequest.lat,
                updateTaskLng = taskRequest.lng,
                updateTaskAddress = taskRequest.address,
                taskCode = uiState.value.orderInfo?.taskCode,
                userOrderId = uiState.value.orderInfo?.userOrderId,
                offlineTitle = "验证资格",
                offlineType = 1)
            insertOfflineTask(offlineUpdateTaskBean)
            updateOrder(getCurrentOrder()?.copy(taskState = getCurrentOrder()?.getNextStatus()))
            updateState(uiState.value.copy(goNextPage = UpdateTaskBean(nextState = getCurrentOrder()?.taskState), orderInfo = getCurrentOrder()))
            return
        }
        ZdLocationManager.getSingleLocation(isNeedAddress = false,
            success = { it ->
                val temp = UpdateTaskRequest(
                    type = "VERIFY",
                    taskId = GlobalData.currentOrder?.taskId,
                    userId = GlobalData.driverInfoBean?.userId,
                    vehicleId = GlobalData.driverInfoBean?.vehicleId,
                    currentState = GlobalData.currentOrder?.taskState,
                    offlineMode = 0,
                    newCarCode = if (uiState.value.orderInfo?.verifyType == 5) {
                        uiState.value.verifyValue
                    } else {
                        ""
                    },
                    content = if (uiState.value.orderInfo?.verifyType == 5) {
                        uiState.value.verifyValue
                    } else {
                        uiState.value.orderInfo?.verifyValue
                    },
                    operateTime = System.currentTimeMillis().toString(),
                    lat = it.latitude,
                    lng = it.longitude)

                val offlineUpdateTaskBean = OfflineUpdateTaskBean(
                    type = temp.type,
                    taskId = temp.taskId,
                    userId = temp.userId,
                    vehicleId = temp.vehicleId,
                    currentState = temp.currentState,
                    offlineMode = 1,
                    operateTime = temp.operateTime,
                    updateTaskLat = temp.lat,
                    updateTaskLng = temp.lng,
                    updateTaskAddress = temp.address,
                    taskCode = uiState.value.orderInfo?.taskCode,
                    userOrderId = uiState.value.orderInfo?.userOrderId,
                    offlineTitle = "验证资格",
                    offlineType = 1)
                insertOfflineTask(offlineUpdateTaskBean)
                updateOrder(getCurrentOrder()?.copy(taskState = getCurrentOrder()?.getNextStatus()))
                updateState(uiState.value.copy(goNextPage = UpdateTaskBean(nextState = getCurrentOrder()?.taskState), orderInfo = getCurrentOrder()))
            }, failed = {
                ToastUtils.showShort(it)
            })
    }

    private fun updateTask() {

        if (uiState.value.orderInfo?.verifyType == 5 && uiState.value.verifyValue.isNullOrBlank()) {
            ToastUtils.showShort("验证信息不能为空！")
            return
        }

        LoadingManager.showLoading()
        ZdLocationManager.getSingleLocation(success = {
            LoadingManager.hideLoading()
            val taskRequest = UpdateTaskRequest(
                type = "VERIFY",
                taskId = GlobalData.currentOrder?.taskId,
                userId = GlobalData.driverInfoBean?.userId,
                vehicleId = GlobalData.driverInfoBean?.vehicleId,
                currentState = GlobalData.currentOrder?.taskState,
                offlineMode = 0,
                newCarCode = if (uiState.value.orderInfo?.verifyType == 5) {
                    uiState.value.verifyValue
                } else {
                    ""
                },
                content = if (uiState.value.orderInfo?.verifyType == 5) {
                    uiState.value.verifyValue
                } else {
                    uiState.value.orderInfo?.verifyValue
                },
                operateTime = System.currentTimeMillis().toString(),
                lat = it.latitude,
                lng = it.longitude)

            if (!getCurrentOrderOfflineTask().isNullOrEmpty()) {
                uploadOffline(taskRequest)
                return@getSingleLocation
            }
            doUploadTask(request = taskRequest)
        }, failed = {
            LoadingManager.hideLoading()
            ToastUtils.showShort(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()))
        }, failed = { msg, code ->
            LoadingManager.hideLoading()
            ToastUtils.showShort(msg)
            if (code == Const.NetWorkException) {
                updateState(uiState.value.copy(showOfflineDialog = true))
            }
            LogUtil.print("$tag doUploadTask", "状态更新失败==${request.toJson()} msg==$msg")
        })
    }

    private fun init() {
        updateState(uiState = uiState.value.copy(orderInfo = getCurrentOrder()))
    }

    sealed class Action {
        data object Init : Action()
        data object UpdateTask : Action()
        data class UpdateState(val uiState: UiState) : Action()
        data object UploadOffline : 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 showOfflineDialog: Boolean? = null,
    )
}