package com.za.ui.servicing.destination_photo

import com.alibaba.fastjson.JSONObject
import com.amap.api.location.AMapLocation
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.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.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 DestinationPhotoVm : IServicingVm<DestinationPhotoVm.Action, DestinationPhotoVm.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()
            is Action.UpdateOffline -> updateOffline()
        }
    }

    private fun updateTemplate() {
        getCurrentPhotoTemplate(success = { updateState(uiState.value.copy(photoTemplateList = it)) })
    }


    private fun updateOffline() {
        uiState.value.photoTemplateList?.forEachIndexed { index, photoTemplateInfo ->
            if (photoTemplateInfo.photoType == 2) {
                return@forEachIndexed
            }

            if (!photoTemplateInfo.photoLocalWaterMarkerPath.isNullOrBlank() && photoTemplateInfo.photoUploadPath.isNullOrBlank()) {
                val offlineUpdateTaskBean = OfflineUpdateTaskBean(
                    realTakePhotoTime = photoTemplateInfo.realTakePhotoTime,
                    photoSource = photoTemplateInfo.photoSource,
                    time = photoTemplateInfo.time,
                    imageLat = photoTemplateInfo.lat,
                    imageLng = photoTemplateInfo.lng,
                    imageAddress = photoTemplateInfo.address,
                    imageIndex = index,
                    needWater = photoTemplateInfo.needWaterMarker,
                    needPhoneBrand = photoTemplateInfo.needShowPhoneBrand,
                    imageLocalPath = photoTemplateInfo.photoLocalPath,
                    advanceTime = uiState.value.orderInfo?.advanceTime,
                    photoLocalWaterMarkerPath = photoTemplateInfo.photoLocalWaterMarkerPath,
                    offlineMode = 1,
                    taskId = uiState.value.orderInfo?.taskId,
                    userOrderId = uiState.value.orderInfo?.userOrderId,
                    taskCode = uiState.value.orderInfo?.taskCode,
                    offlineTitle = "${photoTemplateInfo.imageTitle}",
                    offlineType = 2)
                insertOfflineTask(offlineUpdateTaskBean)
            }
        }

        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["lat"] = item.lat
                jsonObject["lng"] = item.lng
                jsonObject["address"] = item.address
                tempPhotoList.add(jsonObject.toJSONString())
            }
        }

        LoadingManager.showLoading()
        ZdLocationManager.getSingleLocation(isNeedAddress = true,
            success = {
                LoadingManager.hideLoading()
                doUploadOfflineTask(it, tempPhotoList = tempPhotoList)
            }, failed = {
                LoadingManager.hideLoading()
                ToastUtils.showShort(it)
                LogUtil.print("$tag updateOffline", "定位获取失败$it")
            })
    }

    private fun doUploadOfflineTask(it: AMapLocation?, tempPhotoList: ArrayList<String?>) {
        val taskRequest = UpdateTaskRequest(type = "DEST_PHOTO",
            taskId = GlobalData.currentOrder?.taskId,
            userId = GlobalData.driverInfoBean?.userId,
            flowType = GlobalData.currentOrder?.flowType,
            vehicleId = GlobalData.driverInfoBean?.vehicleId,
            currentState = "DESTPHOTO",
            offlineMode = 0,
            operateTime = System.currentTimeMillis().toString(),
            lat = it?.latitude,
            lng = it?.longitude,
            address = it?.address,
            templatePhotoInfoList = tempPhotoList.toList())

        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,
            flowType = taskRequest.flowType,
            templatePhotoInfoList = taskRequest.templatePhotoInfoList,
            updateTaskAddress = taskRequest.address,
            advanceTime = uiState.value.orderInfo?.advanceTime,
            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()))
    }

    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
            }
        }

        //先判断是否有离线任务
        if (!getCurrentOrderOfflineTask().isNullOrEmpty()) {
            updateOffline()
            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()) {
                updateState(uiState.value.copy(showOfflineDialog = true))
                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 = "DEST_PHOTO",
                taskId = GlobalData.currentOrder?.taskId,
                userId = GlobalData.driverInfoBean?.userId,
                flowType = GlobalData.currentOrder?.flowType,
                vehicleId = GlobalData.driverInfoBean?.vehicleId,
                currentState = "DESTPHOTO",
                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)
        })
    }

    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() {
        getCurrentPhotoTemplate({
            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 object UpdateOffline : 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,
                       val photoTemplateList: List<PhotoTemplateInfo>? = null)
}