package com.za.ui.servicing.order_confirm


import com.blankj.utilcode.util.ToastUtils
import com.za.base.BaseVm
import com.za.base.Const
import com.za.base.view.LoadingManager
import com.za.bean.BatteryCostQueryBean
import com.za.bean.BatteryCostQueryRequest
import com.za.bean.UploadChangeBatteryRequest
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.UpdateTaskBean
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.RetrofitHelper
import com.za.room.RoomHelper
import com.za.servicing.R
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.schedulers.Schedulers
import kotlinx.coroutines.flow.MutableStateFlow

class ChangeBatteryVm : BaseVm<ChangeBatteryVm.Action, ChangeBatteryVm.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.UpdateState -> updateState(action.uiState)
            is Action.Upload -> upload()
            is Action.IsChangeBattery -> updateIsChangeBattery(action.isChange)
            is Action.UpdatePhotoTemplate -> updateTemplate()
        }
    }

    private fun updateTemplate() {
        val list = RoomHelper.db?.changeBatteryDao()?.getAllChangeBatteryPhoto(GlobalData.currentOrder?.taskCode
            ?: "")
        updateState(uiState.value.copy(changeBatteryPhoto = list))
    }

    private fun updateIsChangeBattery(isChange: Boolean) {
        updateState(uiState.value.copy(eleWorkOrderBean = uiState.value.eleWorkOrderBean?.copy(changeBattery = isChange)))
        val eleWorkOrderBean = uiState.value.eleWorkOrderBean?.copy(changeBattery = isChange)
        if (eleWorkOrderBean != null) {
            RoomHelper.db?.eleWorkOrderDao()?.update(eleWorkOrderBean)
        }
    }

    private fun upload() {
        if (uiState.value.eleWorkOrderBean?.changeBattery == true) {
            val list = uiState.value.changeBatteryPhoto
            if (list.isNullOrEmpty()) {
                ToastUtils.showLong("更换电瓶照片未拍！")
                return
            }
            list.forEach {
                if (it.photoUploadPath.isNullOrBlank()) {
                    ToastUtils.showLong("${it.photoName}未拍！")
                    return
                }
            }
        }
        batteryCostQuery(false)
    }

    private fun doUpload(isPayment: Boolean?) {
        val list = uiState.value.changeBatteryPhoto
        val uploadChangeBatteryRequest = UploadChangeBatteryRequest(
            userOrderId = uiState.value.orderInfo?.userOrderId,
            replaceBatteryImgList = list?.map { it.photoUploadPath ?: "" },
            hasReplaceBattery = if (uiState.value.eleWorkOrderBean?.changeBattery == true) {
                1
            } else {
                0
            },
            isPayment = isPayment)
        LoadingManager.showLoading()
        RetrofitHelper.getDefaultService().saveReplaceBatteryPhoto(uploadChangeBatteryRequest)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BaseObserver<String>() {
                override fun doSuccess(it: String?) {
                    LoadingManager.hideLoading()
                    LogUtil.print("changeBattery doUpload", it.toJson() ?: "")
                    batteryCostQuery(true)
                }

                override fun doFailure(code: Int, msg: String?) {
                    LoadingManager.hideLoading()
                    ToastUtils.showLong(msg)
                    LogUtil.print("changeBattery doUpload", msg ?: "")
                }
            })
    }

    private fun init() {
        getPhotos()
    }

    private fun batteryCostQuery(isAgainQuery: Boolean = false) {
        LoadingManager.showLoading()
        val batteryCostQueryRequest = BatteryCostQueryRequest(userOrderId = uiState.value.orderInfo?.userOrderId, uiState.value.orderInfo?.taskId)
        RetrofitHelper.getDefaultService().batteryCostQuery(batteryCostQueryRequest)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BaseObserver<BatteryCostQueryBean>() {
                override fun doSuccess(it: BatteryCostQueryBean?) {
                    LoadingManager.hideLoading()
                    if (isAgainQuery) {
                        if (it?.isPayment == true && uiState.value.eleWorkOrderBean?.changeBattery == true) {
//                            ChangeBatteryCostActivity.goChangeBatteryCostActivity(mContext, model.getOrderInfo().userOrderId, model.getOrderInfo().taskId)
                        } else {
                            RoomHelper.db?.changeBatteryDao()?.deleteAll()
                            val eleWorkOrderBean = RoomHelper.db?.eleWorkOrderDao()?.getEleWorkOrder(uiState.value.orderInfo?.taskId
                                ?: 0)
                            eleWorkOrderBean?.copy(changeBattery = false)?.let { it1 -> RoomHelper.db?.eleWorkOrderDao()?.update(it1) }
                            updateState(uiState.value.copy(goNextPage = UpdateTaskBean(uiState.value.orderInfo?.taskState)))
                            LogUtil.print("againQueryIsNeedReceiveMoney", batteryCostQueryRequest.toString())
                            return
                        }
                    }
                    doUpload(it?.isPayment)
                }

                override fun doFailure(code: Int, msg: String?) {
                    LoadingManager.hideLoading()
                    ToastUtils.showShort(msg)
                    LogUtil.print("queryIsNeedReceiveMoney", "code==$code request=$batteryCostQueryRequest")
                }
            })
    }

    private fun getPhotos() {
        val titles = arrayOf("车牌、旧电瓶、新电瓶合照", "新电瓶安装完成照片", "新电瓶二维码照片", "新电瓶电子质保卡照片", "新电瓶安装完成之后仪表盘点亮的照片")
        val tips = arrayOf("将新旧电瓶放置于车辆牌照前方，清晰拍摄车牌照、旧电瓶、新电瓶在一起的合照", "清晰拍摄新电瓶安装完成后的照片",
            "清晰拍摄新电瓶上二维码的照片", "提供新电瓶电子质保卡的截图照片", "清晰拍摄新电瓶安装完成后的仪表盘点亮的照片")
        val photoContracts = arrayOf(R.mipmap.img_old_new_battery,
            R.mipmap.img_change_battery_complate,
            R.mipmap.img_battery_qr,
            R.mipmap.img_battery_quality, R.mipmap.dadianhou)

        val changeBatteryPhotoList = RoomHelper.db?.changeBatteryDao()
            ?.getAllChangeBatteryPhoto(GlobalData.currentOrder?.taskCode ?: "")
        LogUtil.print("changeBatteryPhotoList ", " $changeBatteryPhotoList")
        val eleWorkOrderBean = RoomHelper.db?.eleWorkOrderDao()?.getEleWorkOrder(GlobalData.currentOrder?.taskId
            ?: 0)
        if (changeBatteryPhotoList.isNullOrEmpty()) {
            val list = mutableListOf<PhotoTemplateInfo>()
            titles.forEachIndexed { i, s ->
                val changeBattery = PhotoTemplateInfo(
                    photoName = s,
                    imageTitle = s,
                    doHaveFilm = 1,
                    needWaterMarker = true,
                    myCustomPhotoType = Const.PhotoType.ChangeBattery,
                    taskCode = GlobalData.currentOrder?.taskCode,
                    imageDescription = tips[i],
                    photoUrl = "${photoContracts[i]}")
                list.add(changeBattery)
                RoomHelper.db?.changeBatteryDao()?.insert(changeBattery)
            }
            val changeBatteryPhotoList1 = RoomHelper.db?.changeBatteryDao()
                ?.getAllChangeBatteryPhoto(GlobalData.currentOrder?.taskCode ?: "")
            LogUtil.print("changeBatteryPhotoList1 ", " $changeBatteryPhotoList1")
            updateState(uiState.value.copy(changeBatteryPhoto = RoomHelper.db?.changeBatteryDao()
                ?.getAllChangeBatteryPhoto(GlobalData.currentOrder?.taskCode ?: ""),
                orderInfo = GlobalData.currentOrder,
                eleWorkOrderBean = eleWorkOrderBean))
            return
        }
        updateState(uiState.value.copy(changeBatteryPhoto = changeBatteryPhotoList, orderInfo = GlobalData.currentOrder, eleWorkOrderBean = eleWorkOrderBean))
    }

    sealed class Action {
        data object Init : Action()
        data class UpdateState(val uiState: UiState) : Action()
        data object Upload : Action()
        data class UpdatePhotoTemplate(val photoTemplateInfo: PhotoTemplateInfo) : Action()
        data class IsChangeBattery(val isChange: Boolean) : Action()
    }

    data class UiState(
        val orderInfo: OrderInfo? = null,
        val eleWorkOrderBean: EleWorkOrderBean? = null,
        val goNextPage: UpdateTaskBean? = null,
        val isGoNextPageDialog: Boolean? = null,
        val changeBatteryPhoto: List<PhotoTemplateInfo>? = null,
    )
}