package es.verdnatura.presentation.view.feature.collection.fragment

import android.content.Context
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.map
import com.google.gson.JsonObject
import es.verdnatura.MobileApplication
import es.verdnatura.domain.SalixCallback
import es.verdnatura.domain.formatWithQuotes
import es.verdnatura.domain.toast
import es.verdnatura.domain.userCases.GetItemFromBarcodeUseCase
import es.verdnatura.presentation.base.BaseViewModel
import es.verdnatura.presentation.base.getMessageFromAllResponse
import es.verdnatura.presentation.base.nameofFunction
import es.verdnatura.presentation.common.Event
import es.verdnatura.presentation.common.ResponseItemExistsItemShelvingSale
import es.verdnatura.presentation.common.ResponseItemVO
import es.verdnatura.presentation.common.SaleTrackingReplaceSalix
import es.verdnatura.presentation.common.SaleTrackingSalix
import es.verdnatura.presentation.common.TicketState
import es.verdnatura.presentation.view.feature.collection.ItemVO
import es.verdnatura.presentation.view.feature.collection.SalixSaleQuantity
import es.verdnatura.presentation.view.feature.collection.mapper.map
import es.verdnatura.presentation.view.feature.sacador.model.CollectionTicket
import es.verdnatura.presentation.view.feature.sacador.model.CollectionVO
import es.verdnatura.presentation.view.feature.sacador.model.MistakeTypeListVO
import es.verdnatura.presentation.view.feature.sacador.model.MistakeTypeVO
import es.verdnatura.presentation.view.feature.sacador.model.PlacementSupplyListVO
import es.verdnatura.presentation.view.feature.sacador.model.PlacementSupplyVO
import es.verdnatura.presentation.view.feature.workermistake.model.SaleMistakeSalix
import es.verdnatura.presentation.view.feature.workermistake.model.SaleTrackingDelSalix
import retrofit2.Response

class CollectionViewModel(val context: Context) : BaseViewModel(context) {
    private val getItemFromBarcodeUseCase = GetItemFromBarcodeUseCase(salix)
    private val contextApp = context

    private val _responseState by lazy { MutableLiveData<ResponseItemVO>() }
    val responseState: LiveData<ResponseItemVO>
        get() = _responseState

    private val _collectionTicketList by lazy { MutableLiveData<CollectionVO>() }
    val collectionTicketList: LiveData<CollectionVO>
        get() = _collectionTicketList

    private val _responseExistsItemShelvingSale by lazy { MutableLiveData<ResponseItemExistsItemShelvingSale>() }
    val responseExistsItemShelvingSale: LiveData<ResponseItemExistsItemShelvingSale>
        get() = _responseExistsItemShelvingSale

    val loadExistsResponse: LiveData<Event<ResponseItemExistsItemShelvingSale>> =
        _responseExistsItemShelvingSale.map { Event(it) }

    private val _collectionTicketSalix by lazy { MutableLiveData<CollectionTicket>() }
    val collectionTicketSalix: LiveData<CollectionTicket>
        get() = _collectionTicketSalix

    private val _getSalesResponse by lazy { MutableLiveData<CollectionVO>() }
    val getSalesResponse: LiveData<CollectionVO>
        get() = _getSalesResponse

    val loadCollectionTicketSalix: LiveData<Event<CollectionTicket>> =
        _collectionTicketSalix.map { Event(it) }

    private val _placementSuppleyList by lazy { MutableLiveData<PlacementSupplyListVO>() }
    val placementSuppleyList: LiveData<PlacementSupplyListVO>
        get() = _placementSuppleyList

    private val _response by lazy { MutableLiveData<ResponseItemVO>() }
    val response: LiveData<ResponseItemVO>
        get() = _response

    private val _responseSaleMistakeAdd by lazy { MutableLiveData<ResponseItemVO>() }
    val responseSaleMistakeAdd: LiveData<ResponseItemVO>
        get() = _responseSaleMistakeAdd

    private val _responseItemShelvingSaleSupplyAdd by lazy { MutableLiveData<ResponseItemVO>() }
    val responseItemShelvingSaleSupplyAdd: LiveData<ResponseItemVO>
        get() = _responseItemShelvingSaleSupplyAdd

    private val _responseSaleReplace by lazy { MutableLiveData<ResponseItemVO>() }
    val responseSaleReplace: LiveData<ResponseItemVO>
        get() = _responseSaleReplace

    private val _responseSaleTracking_mark by lazy { MutableLiveData<ResponseItemVO>() }
    val responseSaleTracking_mark: LiveData<ResponseItemVO>
        get() = _responseSaleTracking_mark

    private val _responseConfirmReservedItemShelvingSale by lazy { MutableLiveData<Boolean>() }
    val responseConfirmReservedItemShelvingSale: LiveData<Boolean>
        get() = _responseConfirmReservedItemShelvingSale

    val loadPicked: LiveData<Event<Boolean>> =
        _responseConfirmReservedItemShelvingSale.map { Event(it) }

    private val _responseItemShelvingSale by lazy { MutableLiveData<ResponseItemVO>() }
    val responseItemShelvingSale: LiveData<ResponseItemVO>
        get() = _responseItemShelvingSale

    private val _responseItemShelvingSaleUnPicked by lazy { MutableLiveData<Boolean>() }
    val responseItemShelvingSaleUnPicked: LiveData<Boolean>
        get() = _responseItemShelvingSaleUnPicked

    val loadUnpicked: LiveData<Event<Boolean>> = _responseItemShelvingSaleUnPicked.map { Event(it) }

    private val _responseCollectionAddItem by lazy { MutableLiveData<Boolean>() }
    val responseCollectionAddItem: LiveData<Boolean>
        get() = _responseCollectionAddItem

    private val _responseParking by lazy { MutableLiveData<ResponseItemVO>() }
    val responseParking: LiveData<ResponseItemVO>
        get() = _responseParking

    private val _responsePrint by lazy { MutableLiveData<ResponseItemVO>() }
    val responsePrint: LiveData<ResponseItemVO>
        get() = _responsePrint

    private val _responseDel by lazy { MutableLiveData<ResponseItemVO>() }
    val responseDel: LiveData<ResponseItemVO>
        get() = _responseDel

    private val _responseItemShelvingUpdate by lazy { MutableLiveData<ResponseItemVO>() }
    val responseItemShelvingUpdate: LiveData<ResponseItemVO>
        get() = _responseItemShelvingUpdate

    private val _responseTicketState by lazy { MutableLiveData<TicketState>() }
    val responseTicketState: LiveData<TicketState> = _responseTicketState

    private val _responseUsedShelves by lazy { MutableLiveData<ResponseItemVO>() }
    val responseUsedShelves: LiveData<ResponseItemVO>
        get() = _responseUsedShelves

    private val _responseSaleGroup by lazy { MutableLiveData<ResponseItemVO>() }
    val responseSaleGroup: LiveData<ResponseItemVO>
        get() = _responseSaleGroup

    private val _responseItemShelvingSaleGroup by lazy { MutableLiveData<ResponseItemVO>() }
    val responseItemShelvingSaleGroup: LiveData<ResponseItemVO>
        get() = _responseItemShelvingSaleGroup

    private val _responseTicketClosure by lazy { MutableLiveData<ResponseItemVO>() }
    val responseTicketClosure: LiveData<ResponseItemVO>
        get() = _responseTicketClosure

    private val _responseCollectionUnchecked by lazy { MutableLiveData<ResponseItemVO>() }
    val responseCollectionUnchecked: LiveData<ResponseItemVO>
        get() = _responseCollectionUnchecked

    private val _responseSplit by lazy { MutableLiveData<ResponseItemVO>() }
    val responseSplit: LiveData<ResponseItemVO>
        get() = _responseSplit

    private val _responseNew by lazy { MutableLiveData<ResponseItemVO>() }
    val responseNew: LiveData<ResponseItemVO>
        get() = _responseNew

    private val _responseCode by lazy { MutableLiveData<Int?>() }
    val responseCode: LiveData<Int?>
        get() = _responseCode

    private val _responseIncQuantity by lazy { MutableLiveData<ResponseItemVO>() }
    val responseIncQuantity: LiveData<ResponseItemVO>
        get() = _responseIncQuantity

    private val _mistakeList by lazy { MutableLiveData<MistakeTypeListVO>() }
    val mistakeList: LiveData<MistakeTypeListVO>
        get() = _mistakeList

    private val _item by lazy { MutableLiveData<ItemVO>() }
    val item: LiveData<ItemVO>
        get() = _item

    val loadResponseDel: LiveData<Event<ResponseItemVO>> = _responseDel.map { Event(it) }

    val loadResponseAddItem: LiveData<Event<Boolean>> =
        _responseCollectionAddItem.map { Event(it) }

    val loadResponseSaleTrackingMark: LiveData<Event<ResponseItemVO>> =
        _responseSaleTracking_mark.map { Event(it) }

    val loadResponseItemShelvingUpdate: LiveData<Event<ResponseItemVO>> =
        _responseItemShelvingUpdate.map { Event(it) }

    private val _responseSaleAddPrevOK by lazy { MutableLiveData<ResponseItemVO>() }
    val responseSaleAddPrevOK: LiveData<ResponseItemVO>
        get() = _responseSaleAddPrevOK

    fun getSales(
        collectionFk: Number, print: String, source: String

    ) {
        salix.getSalesFromTicketOrCollection(
            collectionOrTicketFk = collectionFk, print = print != "0", source = source
        ).enqueue(object : SalixCallback<CollectionVO>(context) {
            override fun onError(t: Throwable) {
                _collectionTicketList.value = CollectionVO(
                    0,
                    isError = true,
                    errorMessage = getMessageFromAllResponse(nameofFunction(this), t.message!!)
                )
            }

            override fun onSuccess(response: Response<CollectionVO>) {

                try {
                    _collectionTicketList.value = response.body()?.let { it.map(contextApp) }
                } catch (
                    ex: Exception
                ) {
                    ex.toast(context)
                }

            }
        })
    }

    fun collectionTicketGet(
        collectionFk: Int, sectorFk: Int, print: String, type: String
    ) {

        getSales(collectionFk, print, type)

    }

    fun collectionTicketGetSalix(
        collectionFk: Int,
        print: Boolean,

        ) {
        salix.getCollectionTickets(
            collectionFk, hashMapOf("print" to print)
        ).enqueue(object : SalixCallback<CollectionTicket>(context) {
            override fun onError(t: Throwable) {
                _collectionTicketSalix.value = CollectionTicket(
                    0,
                    isError = true,
                    errorMessage = getMessageFromAllResponse(nameofFunction(this), t.message!!)
                )
            }

            override fun onSuccess(response: Response<CollectionTicket>) {

                if (response.body() != null) {
                    _collectionTicketSalix.value = response.body()?.let { it.map(contextApp) }
                } else {
                    _collectionTicketSalix.value = CollectionTicket(
                        0, isError = true, errorMessage = getMessageFromAllResponse(
                            nameofFunction(this), response.message()
                        )
                    )
                }
            }
        })
    }

    fun collectionGetId(
        ticketFk: Int, sectorFk: Int, print: String, type: String
    ) {
        salix.getCollectionId(
            filter = """{"where":{"ticketFk":$ticketFk},"fields":"collectionFk"}"""
        ).enqueue(object : SalixCallback<List<JsonObject>>(context) {
            override fun onError(t: Throwable) {
                _collectionTicketList.value = CollectionVO(
                    0,
                    isError = true,
                    errorMessage = getMessageFromAllResponse(nameofFunction(this), t.message!!)
                )
            }

            override fun onSuccess(response: Response<List<JsonObject>>) {

                if (response.body()!!.isNotEmpty()) {
                    collectionTicketGet(
                        response.body()!![0].entrySet().first().value.toString().toInt(),
                        sectorFk,
                        print,
                        type
                    )
                } else {
                    _collectionTicketList.value = CollectionVO(
                        0, isError = false
                    )
                }
            }
        })
    }

    fun itemShelvingSaleExists(
        itemShelvingSaleFk: Number, position: Int, quantity: Int

    ) {
        salix.itemShelvingSaleExists(
            itemShelvingSaleFk
        ).enqueue(object : SalixCallback<JsonObject>(context) {

            override fun onSuccess(response: Response<JsonObject>) {
                _responseExistsItemShelvingSale.value = ResponseItemExistsItemShelvingSale(
                    response.body()!!.entrySet().first().value.asBoolean, position, quantity
                )
            }
        })
    }

    fun saleTrackingReplace(
        saleFk: Int,
        originalQuantity: Int,
        code: String,
        isChecked: String,
        buyFk: Long,
        isScanned: Boolean?
    ) {
        salix.saleTrackingUpdate(
            SaleTrackingReplaceSalix(
                saleFk, originalQuantity, code, isChecked != "0", buyFk, isScanned!!
            )
        ).enqueue(object : SalixCallback<Any>(context) {
            override fun onError(t: Throwable) {
                _responseSaleReplace.value = ResponseItemVO(
                    isError = true,
                    errorMessage = getMessageFromAllResponse(nameofFunction(this), t.message!!)
                )
            }

            override fun onSuccess(response: Response<Any>) {
                _responseSaleReplace.value = ResponseItemVO(isError = false, response = "")
            }
        })
    }

    fun saleTracking_mark(
        saleFk: Int,
        originalQuantity: Int,
        code: String,
        isChecked: String,
        buyFk: Long,
        itemShelvingFk: Int,
        quantity: Int,
        isScanned: Boolean?
    ) {
        salix.saleTrackingMark(
            SaleTrackingSalix(
                saleFk = saleFk,
                originalQuantity = originalQuantity,
                code = code,
                isChecked = isChecked != "0",
                buyFk = buyFk,
                itemShelvingFk = itemShelvingFk,
                quantity = quantity,
                isScanned = isScanned!!
            )
        ).enqueue(object : SalixCallback<Any>(context) {
            override fun onError(t: Throwable) {
                _responseSaleTracking_mark.value = ResponseItemVO(
                    isError = true,
                    errorMessage = getMessageFromAllResponse(nameofFunction(this), t.message!!)
                )
            }

            override fun onSuccess(response: Response<Any>) {
                if (!response.isSuccessful) {
                    _responseSaleTracking_mark.value = ResponseItemVO(
                        isError = true, errorMessage = getMessageFromAllResponse(
                            nameofFunction(this), response.message()
                        )
                    )
                } else {
                    _responseSaleTracking_mark.value =
                        ResponseItemVO(isError = false, response = "")
                }
            }
        })
    }

    fun itemShelvingSaleSetQuantity(
        itemShelvingSaleFk: Int,
        quantity: Int,
        isItemShelvingSaleEmpty: Boolean?,
        sectorFk: Int? = null
    ) {
        salix.itemShelvingSaleSetquantitySalix(
            params = arrayListOf(itemShelvingSaleFk, quantity, isItemShelvingSaleEmpty, sectorFk)
        ).enqueue(object : SalixCallback<Any>(context) {

            override fun onSuccess(response: Response<Any>) {
                _responseConfirmReservedItemShelvingSale.value = true

                if (isItemShelvingSaleEmpty == true)
                    _responseCollectionAddItem.value = true

            }
        })
    }

    fun collectionAddWithReservation(
        item: Int, quantity: Int, ticketSelected: Int, saleGroupFk: Int?, sectorFk: Int?
    ) {
        salix.collectionAddWithReservation(
            params = arrayListOf(
                item, quantity, ticketSelected, saleGroupFk, if (sectorFk == -1) null else sectorFk
            )
        ).enqueue(object : SalixCallback<Any>(context) {
            override fun onSuccess(response: Response<Any>) {
                _responseCollectionAddItem.value = true
            }

        })
    }

    fun itemPlacementSupplyAiming(
        shelvingFk: String, quantity: Int, itemFk: Int
    ) {
        salix.itemPlacementSupplyAiming(
            arrayListOf(
                shelvingFk, quantity, itemFk
            ).formatWithQuotes()
        ).enqueue(object : SalixCallback<List<PlacementSupplyVO>>(context) {
            override fun onSuccess(response: Response<List<PlacementSupplyVO>>) {
                if (response.body() != null) {
                    _placementSuppleyList.value = response.body()?.let { PlacementSupplyListVO(it) }
                } else {
                    val listError: ArrayList<PlacementSupplyVO> = ArrayList()
                    listError.add(
                        PlacementSupplyVO(
                            itemShelvingFk = 0,
                            isError = true,
                            errorMessage = getMessageFromAllResponse(
                                nameofFunction(this), response.message()
                            )
                        )
                    )
                    _placementSuppleyList.value = PlacementSupplyListVO(listError)
                }
            }

            override fun onError(t: Throwable) {
                val listError: ArrayList<PlacementSupplyVO> = ArrayList()
                listError.add(
                    PlacementSupplyVO(
                        itemShelvingFk = 0,
                        isError = true,
                        errorMessage = getMessageFromAllResponse(nameofFunction(this), t.message!!)
                    )
                )
                _placementSuppleyList.value = PlacementSupplyListVO(listError)
            }

        })
    }

    fun collectionStickerPrint(
        collectionFk: Int, labelCount: Int?
    ) {
        salix.collectionStickerPrint(
            arrayListOf(
                collectionFk, labelCount
            )
        ).enqueue(object : SalixCallback<Any>(context) {
            override fun onSuccess(response: Response<Any>) {
                _responsePrint.value =
                    ResponseItemVO(isError = false, response = response.message())
            }

            override fun onError(t: Throwable) {
                _responsePrint.value = ResponseItemVO(
                    isError = true,
                    errorMessage = getMessageFromAllResponse(nameofFunction(this), t.message!!)
                )
            }
        })
    }

    fun ticketCollection_setUsedShelves(
        ticketFk: Int, usedShelves: Int
    ) {
        salix.ticketCollectionUpdate(
            """where={"ticketFk":$ticketFk}""", hashMapOf("usedShelves" to usedShelves)
        ).enqueue(object : SalixCallback<Unit>(context) {
            override fun onError(t: Throwable) {

                _responseUsedShelves.value = ResponseItemVO(
                    isError = true,
                    errorMessage = getMessageFromAllResponse(nameofFunction(this), t.message!!)
                )
            }

            override fun onSuccess(response: Response<Unit>) {
                _responseUsedShelves.value = ResponseItemVO(isError = false)

            }
        })
    }

    fun itemShelvingSaleUnpicked(
        itemShelvingSaleFk: Int
    ) {
        salix.itemShelvingSaleUnpicked(
            arrayListOf(
                itemShelvingSaleFk
            )
        ).enqueue(object : SalixCallback<Unit>(context) {

            override fun onSuccess(response: Response<Unit>) {
                _responseItemShelvingSaleUnPicked.value = true
                super.onSuccess(response)
            }
        })
    }

    fun saleTrackingAddPreparedSaleGroup(
        saleGroupFk: Int
    ) {
        salix.saleTrackingAddPreparedSaleGroup(
            arrayListOf(
                saleGroupFk
            )
        ).enqueue(object : SalixCallback<Unit>(context) {
            override fun onError(t: Throwable) {
                _responseSaleGroup.value = ResponseItemVO(
                    isError = true,
                    errorMessage = getMessageFromAllResponse(nameofFunction(this), t.message!!)
                )
            }

            override fun onSuccess(response: Response<Unit>) {
                //Tarea 7926
                updateParkingFromSaleGroup(saleGroupFk)
                _responseSaleGroup.value = ResponseItemVO(isError = false)
            }
        })
    }

    fun updateParkingFromSaleGroup(
        saleGroupFk: Number
    ) {
        salix.saleGroupUpdate(
            id = saleGroupFk, params = hashMapOf("parkingFk" to null)
        ).enqueue(object : SalixCallback<Any>(context) {
            override fun onSuccess(response: Response<Any>) {
            }
        })
    }

    fun itemShelvingSaleSetSaleGroup(
        saleGroupFk: Int
    ) {
        salix.itemShelvingSaleSetSaleGroup(
            arrayListOf(
                saleGroupFk
            )
        ).enqueue(object : SalixCallback<Unit>(context) {
            override fun onError(t: Throwable) {
                _responseItemShelvingSaleGroup.value = ResponseItemVO(
                    isError = true,
                    errorMessage = getMessageFromAllResponse(nameofFunction(this), t.message!!)
                )
            }

            override fun onSuccess(response: Response<Unit>) {
                _responseItemShelvingSaleGroup.value = ResponseItemVO(isError = false)
            }
        })
    }

    fun collectionAddItem(
        itemFk: Int, quantity: Int, ticketFk: Int
    ) {

        //Tarea 6889
        salix.addSale(
            id = ticketFk, barcode = itemFk.toString(), quantity = quantity
        )/*   salix.addSaleByCode(
                          CollectionItemSalix(
                              itemFk.toString(),
                              quantityFk,
                              ticketFk,
                              warehouseFk
                          )
                      )*/

            .enqueue(object : SalixCallback<Any>(context) {
                override fun onError(t: Throwable) {

                    _responseNew.value = ResponseItemVO(
                        isError = true,
                        errorMessage = getMessageFromAllResponse(nameofFunction(this), t.message!!)
                    )
                }

                override fun onSuccess(response: Response<Any>) {
                    _responseNew.value =
                        ResponseItemVO(isError = false, response = response.message()!!)

                }
            })
    }

    fun saleTrackingDel(saleFk: Int) {

        salix.saleTrackingDel(
            SaleTrackingDelSalix(
                saleFk = saleFk, stateCodes = listOf("CHECKED", "OK", "PREPARED")
            )
        ).enqueue(object : SalixCallback<Any>(context) {
            override fun onError(t: Throwable) {
                _responseDel.value = ResponseItemVO(
                    isError = true,
                    errorMessage = getMessageFromAllResponse(nameofFunction(this), t.message!!)
                )
            }

            override fun onSuccess(response: Response<Any>) {
                _responseDel.value =
                    ResponseItemVO(isError = false, response = response.message())
            }
        })
    }

    fun itemShelvingUpdateFromSale(
        saleFk: Int
    ) {
        salix.itemShelvingUpdateFromSale(hashMapOf("saleFk" to saleFk))
            // silex.itemShelving_updateFromSale(saleFk)
            .enqueue(object : SalixCallback<Any>(context) {
                override fun onError(t: Throwable) {
                    _responseItemShelvingUpdate.value = ResponseItemVO(
                        isError = true,
                        errorMessage = getMessageFromAllResponse(nameofFunction(this), t.message!!)
                    )
                }

                override fun onSuccess(response: Response<Any>) {

                    _responseItemShelvingUpdate.value =
                        ResponseItemVO(isError = false, response = response.message()!!)
                }
            })
    }

    fun setParking(
        ticketFk: Int, parking: String
    ) {
        salix.setParking(arrayListOf(ticketFk, parking).formatWithQuotes())
            .enqueue(object : SalixCallback<Any>(context) {
                override fun onSuccess(response: Response<Any>) {
                    _responseParking.value =
                        ResponseItemVO(isError = false, response = response.message())
                }

                override fun onError(t: Throwable) {
                    _responseParking.value = ResponseItemVO(
                        isError = true,
                        errorMessage = getMessageFromAllResponse(nameofFunction(this), t.message!!)
                    )
                }
            })
    }

    fun ticketStateTodaySetState(
        ticketFk: Int, state: String
    ) {
        salix.ticketStateTodaySetState(arrayListOf(ticketFk, state).formatWithQuotes())
            .enqueue(object : SalixCallback<Unit>(context) {
                override fun onSuccess(response: Response<Unit>) {
                    _response.value = ResponseItemVO(isError = false, response = "")
                }

                override fun onError(t: Throwable) {
                    _response.value = ResponseItemVO(
                        isError = true,
                        errorMessage = getMessageFromAllResponse(nameofFunction(this), t.message!!)
                    )
                }
            })
    }

    fun getIdFromCodeSalix(code: String) {
        getItemFromBarcodeUseCase.execute(code).enqueue(object : SalixCallback<Int?>(context) {
            override fun onSuccess(response: Response<Int?>) {
                _responseCode.value = response.body()

            }
        })
    }

    fun collectionIncreaseQuantitySalix(
        saleFk: Int, quantity: String
    ) {
        salix.collectionIncreaseQuantitySalix(
            SalixSaleQuantity(saleId = saleFk, quantity = quantity.toInt())
        ).enqueue(object : SalixCallback<Any>(context) {
            override fun onError(t: Throwable) {
                _responseIncQuantity.value = ResponseItemVO(
                    isError = true, errorMessage = getMessageFromAllResponse(
                        nameofFunction(this), t.message!!
                    )
                )
            }

            override fun onSuccess(response: Response<Any>) {
                super.onSuccess(response)

                _responseIncQuantity.value = ResponseItemVO(
                    isError = false, response = response.message().toString()
                )
            }
        })
    }

    fun saleMistakeAdd(
        saleFk: Int, typeFk: Int
    ) {

        salix.saleMistakeAdd(
            SaleMistakeSalix(
                userFk = (context as MobileApplication).userId!!, saleFk = saleFk, typeFk = typeFk
            )
        ).enqueue(object : SalixCallback<Any>(context) {
            override fun onError(t: Throwable) {
                _responseSaleMistakeAdd.value = ResponseItemVO(
                    isError = true, errorMessage = getMessageFromAllResponse(
                        nameofFunction(this), t.message!!
                    )
                )
            }

            override fun onSuccess(response: Response<Any>) {
                super.onSuccess(response)
                _responseSaleMistakeAdd.value =
                    ResponseItemVO(isError = false, response = response.message())
            }
        })
    }

    fun mistakeType() {
        salix.getMistakeTypes().enqueue(object : SalixCallback<List<MistakeTypeVO>>(context) {
            override fun onSuccess(response: Response<List<MistakeTypeVO>>) {
                if (response.body() != null) {
                    _mistakeList.value = response.body()?.let { MistakeTypeListVO(it) }
                } else {
                    val listError: ArrayList<MistakeTypeVO> = ArrayList()
                    listError.add(MistakeTypeVO(0, ""))
                    _mistakeList.value = MistakeTypeListVO(listError)
                }
            }

            override fun onError(t: Throwable) {
                val listError: ArrayList<MistakeTypeVO> = ArrayList()
                listError.add(MistakeTypeVO(0, ""))
                _mistakeList.value = MistakeTypeListVO(listError)
            }
        })
    }

    fun ticketIsOutClosureZone(
        ticketFk: Int
    ) {
        salix.ticketIsOutClosureZone(
            arrayListOf(ticketFk)
        ).enqueue(object : SalixCallback<Any?>(context) {
            override fun onSuccess(response: Response<Any?>) {
                _responseTicketClosure.value = ResponseItemVO(
                    isError = false,
                    response = response.body()?.toString() ?: "false",
                    errorMessage = ""
                )
            }

            override fun onError(t: Throwable) {
                _responseTicketClosure.value = ResponseItemVO(
                    isError = true, errorMessage = getMessageFromAllResponse(
                        nameofFunction(this), t.message!!
                    )
                )
            }
        })
    }

    fun ticketState(
        ticketFk: Int
    ) {
        salix.ticketState(
            """{"where": {"ticketFk": "$ticketFk"},"include":[{"relation":"user","scope":{"fields":["username"]}}]}"""

        ).enqueue(object : SalixCallback<List<TicketState>>(context) {
            override fun onSuccess(response: Response<List<TicketState>>) {
                _responseTicketState.value = if (response.body()!!.isEmpty()) {
                    TicketState()
                } else {
                    response.body()!![0]
                }
            }

        })
    }

    fun callBackSalix(function: String, params: ArrayList<Any>) {
        salix.executeFunc(
            routine = function, params = params
        ).enqueue(object : SalixCallback<Any>(context) {

            override fun onError(t: Throwable) {
                _responseTicketClosure.value = ResponseItemVO(
                    isError = true, errorMessage = getMessageFromAllResponse(
                        nameofFunction(this), t.message!!
                    )
                )
            }

            override fun onSuccess(response: Response<Any>) {
                _responseTicketClosure.value = ResponseItemVO(
                    isError = false, response = response.body()!!.toString(), errorMessage = ""
                )

            }

        })
    }

    fun hasUncheckedTicket(
        collectionFk: Int
    ) {
        salix.hasUncheckedTicket(collectionFk)
            //silex.collection_getUncheckedTicket(collectionFk)
            .enqueue(object : SalixCallback<String>(context) {
                override fun onError(t: Throwable) {
                    _responseCollectionUnchecked.value = ResponseItemVO(
                        isError = true, errorMessage = getMessageFromAllResponse(
                            nameofFunction(this), t.message!!
                        )
                    )
                }

                override fun onSuccess(response: Response<String>) {
                    if (response.body() != null) {

                        _responseCollectionUnchecked.value = ResponseItemVO(
                            isError = false, response = response.body()!!, errorMessage = ""
                        )
                    } else {
                        _responseCollectionUnchecked.value = ResponseItemVO(
                            isError = true,
                            response = response.body()!!.toString(),
                            errorMessage = getMessageFromAllResponse(
                                nameofFunction(this), response.message()
                            )
                        )
                    }
                }
            })
    }

    fun collection_setState(
        collectionFk: Int, state: String
    ) {
        salix.collectionSetState(
            params = arrayListOf(
                collectionFk, state
            ).formatWithQuotes()
        ).enqueue(object : SalixCallback<Any?>(context) {
            override fun onError(t: Throwable) {

                _responseState.value = ResponseItemVO(
                    isError = true, errorMessage = getMessageFromAllResponse(
                        nameofFunction(this), t.message!!
                    )
                )
                super.onError(t)
            }

            override fun onSuccess(response: Response<Any?>) {
                _responseState.value = ResponseItemVO(isError = false, response = "")
                super.onSuccess(response)
            }
        })
    }

    fun saleTrackingAddPrevOK(
        sectorCollectionFk: Int
    ) {
        salix.saleTrackingAddPrevOK(arrayListOf(sectorCollectionFk))
            .enqueue(object : SalixCallback<Any>(context) {
                override fun onError(t: Throwable) {
                    _responseSaleAddPrevOK.value = ResponseItemVO(
                        isError = true, errorMessage = getMessageFromAllResponse(
                            nameofFunction(this), t.message!!
                        )
                    )

                }

                override fun onSuccess(response: Response<Any>) {
                    _responseSaleAddPrevOK.value = ResponseItemVO(
                        isError = false, errorMessage = "" + getMessageFromAllResponse(
                            nameofFunction(this), response.message()
                        )
                    )
                }
            })
    }

}
