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


import android.content.Context
import android.content.Intent
import android.graphics.drawable.Drawable
import android.media.MediaPlayer
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.speech.SpeechRecognizer
import android.view.View
import android.view.View.GONE
import android.view.View.VISIBLE
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.ImageView
import android.widget.Toast
import androidx.core.view.isVisible
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import es.verdnatura.R
import es.verdnatura.databinding.FragmentCollectionBinding
import es.verdnatura.domain.ConstAndValues.CONTROLADOR
import es.verdnatura.domain.ConstAndValues.OK
import es.verdnatura.domain.ConstAndValues.PRECHECKER
import es.verdnatura.domain.ConstAndValues.SACADOR
import es.verdnatura.domain.toast
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.*
import es.verdnatura.presentation.view.component.CustomDialog
import es.verdnatura.presentation.view.component.CustomDialogInput
import es.verdnatura.presentation.view.component.CustomDialogList
import es.verdnatura.presentation.view.component.CustomDialogThreeButtons
import es.verdnatura.presentation.view.feature.articulo.adapter.BarcodeAdapter
import es.verdnatura.presentation.view.feature.articulo.model.BarcodeVO
import es.verdnatura.presentation.view.feature.collection.ItemVO
import es.verdnatura.presentation.view.feature.collection.adapter.SaleAdapter
import es.verdnatura.presentation.view.feature.main.activity.MainActivity
import es.verdnatura.presentation.view.feature.pasillero.model.PasillerosItemVO
import es.verdnatura.presentation.view.feature.sacador.model.*
import timber.log.Timber


@Suppress("UNUSED_ANONYMOUS_PARAMETER")
class CollectionFragment(
    var collection: CollectionVO = CollectionVO(),
    var type: String = SACADOR
) : BaseFragment<FragmentCollectionBinding, CollectionViewModel>(CollectionViewModel::class) {

    private lateinit var dataMessageSalix: DataMessageSalix
    private var sales: List<SaleVO> = listOf()
    private var saleAdapter: SaleAdapter? = null
    private var lm: LinearLayoutManager? = null
    private var storedPosition: Int = 0
    private var pasillerosItemClickListener: OnPasillerosItemClickListener? = null
    private lateinit var customDialogList: CustomDialogList
    private var placementSupplyAdapter: BarcodeAdapter? = null
    private var listPlacementSupply: ArrayList<BarcodeVO> = ArrayList()
    private var storedShelvingPosition: Int = 0
    private lateinit var customDialogInput: CustomDialogInput
    private lateinit var customDialogThreeButtons: CustomDialogThreeButtons
    private var ticketSelected: String = ""
    private lateinit var customDialog: CustomDialog
    private var goBack: Boolean = false
    private var goBack2: Boolean = false
    private var goMistakeBack: Boolean = false
    var mperror: MediaPlayer? = null
    var mpok: MediaPlayer? = null
    private var itemShelvingFkStored: String = ""
    private var storedBackPosition: Int = 0
    private var tickets: ArrayList<String> = ArrayList()
    private var mistakeSale: SaleVO? = null
    private var positionIncreaseQuantity = 0
    private var positionReject = 0
    private var quantityIncrease = ""
    private var quantityReject = ""
    private var typeCollectionMissing = ""
    private var positionCollectionMissing = 0
    private var quantityCollectionMissing = ""
    private var isMarking = false
    private var positionCollectionSplit = 0
    private var quantityCollectionSplit = ""
    private lateinit var ticketToParking: String
    private lateinit var ticketScanTxt: String

    private var itemShelvingSaleSupplyAddCall = -1
    private var saleTrackingCall = -1

    //private var myKM: KeyguardManager? = null
    private var positionUnmarked = -1

    private var state = 0

    private var mIsListening = false
    private var placementPicked: PlacementVO? = null

    private var lastPlacementPicked: PlacementVO? = null

    private var originalItemScan: String = ""
    private var workerFkFromTicket = ""

    private var  itemShelvingTracking_mark:String=""

    companion object {
        fun newInstance(collection: CollectionVO, type: String) =
            CollectionFragment(collection, type)
    }

    override fun onAttach(context: Context) {
        if (context is OnPasillerosItemClickListener) pasillerosItemClickListener = context
        super.onAttach(context)
    }

    override fun getLayoutId(): Int = R.layout.fragment_collection

    override fun onCreate(savedInstanceState: Bundle?) {

        mperror = MediaPlayer.create((activity as MainActivity), R.raw.error)
        mpok = MediaPlayer.create((activity as MainActivity), R.raw.ok)


        if (type.equals(CONTROLADOR)) {

            //sergio: comprueba si viene de la pantalla de controlador
            viewModel.ticket_checkFullyControlled(
                getData(USER),
                getData(PASSWORD),
                collection.collectionFk

            )
            workerFkFromTicket = collection.tickets.get(0).sales.get(0).workerFk
        }

        if (collection.tickets.isEmpty()) {

            viewModel.collectionTicketGet(
                getData(USER),
                getData(PASSWORD),
                collection.collectionFk,
                getData(SECTORFK),
                type
            )
        }


        super.onCreate(savedInstanceState)
    }

    override fun onResume() {

        super.onResume()
        scanRequest()
    }

    override fun init() {
        customDialogList = CustomDialogList(requireContext())
        customDialogInput = CustomDialogInput(requireContext())
        customDialog = CustomDialog(requireContext())
        customDialogThreeButtons = CustomDialogThreeButtons(requireContext())
        ma.hideBottomNavigation(View.GONE)
        binding.splashProgress.visibility = VISIBLE

        setEvents()
        setToolBar()

        if (collection.tickets.isNotEmpty()) {
            createCollectionList()
        }


        super.init()
    }

    override fun onPause() {
        super.onPause()
        goBack = true
        goBack2 = true
        goMistakeBack = true

    }

    private fun setToolBar() {
        binding.mainToolbar.toolbarSubtitle.visibility = VISIBLE
        binding.mainToolbar.toolbarIcons.visibility = VISIBLE
        binding.mainToolbar.backButton.visibility = VISIBLE

        if (!collection.collectionFk.isNullOrEmpty()) {
            binding.mainToolbar.toolbarTitle.text = collection.collectionFk
        }


        val listIcons: ArrayList<ImageView> = ArrayList()
        val iconPrint = ImageView(context)
        iconPrint.setImageResource(R.drawable.ic_print_black_24dp)
        val iconAdd = ImageView(context)
        iconAdd.setImageResource(R.drawable.ic_playlist_add_black_24dp)
        val iconWorker = ImageView(context)
        iconWorker.setImageResource(R.drawable.ic_worker)
        val iconPhone = ImageView(context)
        iconPhone.setImageResource(R.drawable.phone_call)
        val iconParking = ImageView(context)
        iconParking.setImageResource(R.drawable.ic_local_parking_black_24dp)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

            iconPrint.tooltipText = getTooltip(R.drawable.ic_print_black_24dp)
            iconAdd.tooltipText = getTooltip(R.drawable.ic_playlist_add_black_24dp)
            iconWorker.tooltipText = getTooltip(R.drawable.ic_worker)
            iconPhone.tooltipText = getTooltip(R.drawable.phone_call)
            iconParking.tooltipText = getTooltip(R.drawable.ic_local_parking_black_24dp)
        }


        if (type.equals("CHECKER")) {
            listIcons.add(iconPhone)
        }


        listIcons.add(iconWorker)
        listIcons.add(iconPrint)
        listIcons.add(iconAdd)
        if (type.equals(PRECHECKER)) {
            listIcons.add(iconParking)
            listIcons.remove(iconPrint)
        }


        binding.mainToolbar.toolbarIcons.adapter =
            ToolBarAdapterTooltip(listIcons, object : OnOptionsSelectedListener {
                override fun onOptionsItemSelected(item: Drawable) {

                    when (item) {
                        iconPrint.drawable -> print()
                        iconAdd.drawable -> addItem()
                        iconWorker.drawable -> showUser()
                        iconPhone.drawable -> getExtensionFromUser()
                        iconParking.drawable -> pasillerosItemClickListener?.onPasillerosItemClickListener(
                            PasillerosItemVO(
                                title = getString(R.string.Parking)
                            ), ""
                        )
                    }

                }
            })
        binding.mainToolbar.toolbarIcons.layoutManager =
            LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false)
    }

    private fun getExtensionFromUser() {


        binding.splashProgress.visibility = VISIBLE

        /*  var working_in_test = true // sergio: en proves app

          if (working_in_test) {*/
        goMistakeBack = false
        viewModel.sip_getExtensionSalix(getData(TOKEN), workerFkFromTicket)
        /* } else {
             viewModel.sip_getExtension(
                 getData(USER),
                 getData(PASSWORD), workerFkFromTicket, "sip_getExtension"
             )
         }*/


    }

    private fun scanRequest() {
        binding.scanInput.requestFocus()
        hideKeyboards()
    }

    private fun showUser() {

        ma.onPasillerosItemClickListener(
            PasillerosItemVO(title = getString(R.string.titleUserControlVehicle)),
            workerFkFromTicket
        )

    }

    private fun setEvents() {

        binding.mainToolbar.backButton.setOnClickListener {
            requireActivity().onBackPressed()
        }
        //ESCANER =========
        hideKeyboards()
        /* if (type.equals(CONTROLADOR)){
             binding.scanInput.inputType= InputType.TYPE_CLASS_NUMBER
         }*/
        binding.scanInput.requestFocus()
        binding.scanInput.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0 || actionId == 5) {//ID=0 ACTION_NEXT  ID=5 ACTION_UNESPECEFIED)
                if (!binding.scanInput.text.toString().isNullOrEmpty()) {


                    //sergio:para ver si ha marcado dos veces el mismo ticket
                    binding.scanInput.setText(textScanned_filterDouble(binding.scanInput.text!!.toString()))

                    findSale(binding.scanInput.text.toString())

                }
                binding.scanInput.setText("")
                hideKeyboards()
                return@setOnEditorActionListener true
            }
            true
        }

        hideKeyboards()

        //LISTA =========
        binding.collectionSwipe.setOnRefreshListener {

            isMarking = false
            binding.collectionSwipe.isRefreshing = false
            // if (type != PRECHECKER) {
            binding.splashProgress.visibility = VISIBLE
            viewModel.collectionTicketGet(
                getData(USER),
                getData(PASSWORD),
                collection.collectionFk,
                getData(SECTORFK),
                type
            )
            binding.collectionSwipe.isRefreshing = false
            //}
        }
    }

    private fun hideKeyboards() {
        try {
            requireActivity().hideKeyboard()
        } catch (e: Exception) {
        }
    }


    private fun showKeyboards() {
        try {
            requireActivity().showKeyboard()
        } catch (e: Exception) {
        }
    }

    private fun showKeyboardsIN() {
        try {
            requireActivity().showKeyboardIn()
        } catch (e: Exception) {
        }
    }

    override fun observeViewModel() {
        with(viewModel) {
            binding.splashProgress.visibility = GONE
            collectionTicketList.observe(viewLifecycleOwner, Observer {

                if (!it.isError) {
                    if (it.tickets.isNotEmpty()) {
                        collection = it
                        createCollectionList()
                        workerFkFromTicket = it.tickets.get(0).sales.get(0).workerFk

                    } else {
                        binding.mainToolbar.toolbarSubtitle.text = "0/0"
                    }
                } else {
                    customDialog.setTitle(getString(R.string.error)).setDescription(it.errorMessage)
                        .setOkButton(getString(R.string.accept)) {
                            customDialog.dismiss()
                            if (activity != null) requireActivity().onBackPressed()
                        }.show()
                }

            })

            responseUsedShelves.observe(viewLifecycleOwner, Observer {
                binding.splashProgress.visibility = GONE

                if (!goBack) {
                    ma.messageWithSound(
                        if (it.isError) it.errorMessage else getString(R.string.savedShelves),
                        it.isError, true
                    )
                }

            })
            responseParking.observe(viewLifecycleOwner, Observer {
                binding.splashProgress.visibility = GONE

                if (!goBack) {
                    binding.splashProgress.visibility = GONE
                    ma.messageWithSound(
                        if (it.isError) it.errorMessage else getString(R.string.Aparcado),
                        it.isError, true
                    )
                }

            })

            responsePrint.observe(viewLifecycleOwner, Observer {
                binding.splashProgress.visibility = GONE

                if (!goBack) {

                    if (it.isError) {
                        ma.messageWithSound(
                            it.errorMessage,
                            it.isError, true
                        )
                    }
                }

            })

            responseSplit.observe(viewLifecycleOwner) {
                binding.splashProgress.visibility = GONE

                if (!goBack) {

                    if (it.isError) {
                        ma.messageWithSound(
                            it.errorMessage,
                            it.isError, true
                        )
                    } else {
                        ma.messageWithSound(
                            getString(R.string.splitOk),
                            it.isError, true
                        )
                        responseSaleMoveSuccesful()
                    }
                }

            }



            responseItem_updatePackingShelve.observe(viewLifecycleOwner, Observer {
                binding.splashProgress.visibility = GONE
                ma.messageWithSound(
                    if (it.isError) it.errorMessage else getString(R.string.packingSave),
                    it.isError, !it.isError
                )
                if (!it.isError) {
                    viewModel.collectionTicketGet(
                        getData(USER),
                        getData(PASSWORD),
                        collection.collectionFk,
                        getData(SECTORFK),
                        type
                    )
                }

            })

            responseSaleGroup.observe(viewLifecycleOwner, Observer {

                if (it.isError) {

                    ma.messageWithSound(it.errorMessage, true, true)
                } else {
                    ma.messageWithSound(getString(R.string.previousCollected), false, true)
                    binding.splashProgress.visibility = VISIBLE
                    viewModel.collectionTicketGet(
                        getData(USER),
                        getData(PASSWORD),
                        collection.collectionFk,
                        getData(SECTORFK),
                        type
                    )
                }
            })
            placementSuppleyList.observe(viewLifecycleOwner, Observer {
                binding.splashProgress.visibility = GONE
                if (!goBack) printShelvingResult(it)
                goBack = false
            })

            item.observe(viewLifecycleOwner, Observer {
                binding.splashProgress.visibility = GONE
                if (!goBack) toastDisponibility(it)
                goBack = false
            })

            responseNew.observe(viewLifecycleOwner, Observer {
                binding.splashProgress.visibility = View.GONE
                // if (!goBack) {
                if (it.isError) {
                    customDialog.setTitle(getString(R.string.disponibility))
                        .setDescription(getString(R.string.errorCollectionNew) + it.errorMessage)
                        .setKoButton(getString(R.string.close)) {
                            scanRequest()
                            customDialog.dismiss()
                        }.show()
                } else {

                    binding.splashProgress.visibility =
                        VISIBLE


                    if (!goBack) {
                        sendSalixMessage(
                            item = dataMessageSalix.item,
                            ticketFk = dataMessageSalix.ticket,
                            quantity = dataMessageSalix.quantity,
                            salePerson = dataMessageSalix.personSale
                        )
                        viewModel.collectionTicketGet(
                            getData(USER),
                            getData(PASSWORD),
                            collection.collectionFk,
                            getData(SECTORFK),
                            type
                        )

                        //  //Log.i("VERDNATURA:","La collection es ${collection.collectionFk}")
                    }
                }
                // }

                goBack = false

            })

            responseCode.observe(viewLifecycleOwner, Observer {
                binding.splashProgress.visibility = View.GONE
                if (!goBack2) {
                    if (it.isError) {
                        customDialog.setTitle(getString(R.string.error))
                            .setDescription(it.errorMessage)
                            .setKoButton(getString(R.string.close)) {
                                scanRequest()
                                customDialog.dismiss()
                            }.show()
                    } else {
                        if (checkItemScan(it.response)) {
                            scanRequest()
                            customDialogList.dismiss()
                            mpok?.start()
                            onQuantityOfShelvingSelected(itemShelvingFkStored)
                        } else {
                            var value = customDialogList.getValueTwo()
                            customDialogList.setValueTwo("")

                            if (it.response.isEmpty()) {
                                showErrorMessage("Código artículo no existe. Por favor remite foto del artículo al dpto informática para comprobar si el código buyFk ha sido borrado")
                                viewModel.debug_add(
                                    getData(USER),
                                    getData(PASSWORD),
                                    "buy_deletedFromApp",
                                    value + "-" + sales[storedPosition].itemFk + "-" + getData(
                                        USERFK
                                    )
                                )
                            } else {
                                showErrorMessage(getString(R.string.lineNotExist))
                            }


                            if (mperror != null) mperror?.start()
                        }
                    }
                }

                goBack2 = false

            })

            responseMissingTrash.observe(viewLifecycleOwner, Observer {

                if (!goBack) {
                    if (it.isError) {
                        ma.messageWithSound(it.errorMessage, isError = true, true)

                    } else {

                        missingTrashSuccesful()

                    }
                } //sergio:esto ya estaba
                /* binding.splashProgress.visibility = View.VISIBLE
                     viewModel.collectionTicketGet(user,password,collection.collectionFk,getData(SECTORFK))*/
            })


            responseIncQuantity.observe(viewLifecycleOwner, Observer {

                if (it.isError) {
                    ma.messageWithSound(it.errorMessage, isError = true, true)

                } else {
                    if (!goBack) {
                        incresaseSuccesful()
                    } else {
                        goBack = false
                    }
                }

            })

            responseSaleMove.observe(viewLifecycleOwner, Observer {

                if (it.isError) {
                    ma.messageWithSound(it.errorMessage, isError = true, true)

                } else {
                    if (!goBack)
                        responseSaleMoveSuccesful()
                    goBack = false
                }

            })
            responseGetExtensionFromUserId.observe(viewLifecycleOwner, Observer {

                binding.splashProgress.visibility = GONE

                if (it.isError) {
                    if (!goMistakeBack)
                        ma.messageWithSound(
                            getString(R.string.noSIP) + it.errorMessage + getString(R.string.user) + workerFkFromTicket,
                            isError = true,
                            true
                        )

                } else {
                    if (!goMistakeBack)
                        callPicker(it.response)

                }
                goMistakeBack = true
            })


            mistakeList.observe(viewLifecycleOwner, Observer {
                binding.splashProgress.visibility = GONE
                /*sergio:se quita y se pone esta comprobacion porque si no aparece de nuevo otra vez al volver atrás */

                if (!goMistakeBack)
                    showMistakeList(it.list)
                goMistakeBack = true
            })
            //sergio: para si hay algun ticket por revisar antes de parkinear
            responsecheckfully.observe(viewLifecycleOwner, Observer {
                binding.splashProgress.visibility = View.GONE
                if (it.isError) {
                    ma.messageWithSound(it.errorMessage, it.isError, false)

                } else {
                    //sergio: devuelve false si no hay para revisar y <> false.
                    if (it.response != "false") {

                        customDialog.setTitle(getString(R.string.warning))
                            .setDescription(getString(R.string.pendingReview) + it.response)
                            .setOkButton(getString(R.string.accept)) {
                                customDialog.dismiss()

                            }
                            .setKoButton(getString(R.string.review)) {
                                binding.splashProgress.visibility = View.VISIBLE
                                viewModel.collectionTicketGet(
                                    getData(USER),
                                    getData(PASSWORD),
                                    it.response,
                                    getData(SECTORFK),
                                    type
                                )
                                customDialog.dismiss()
                            }
                        customDialog.show()
                    }
                    // if (!goBack)navigateToCollectionList(it)
                    //goBack = false
                }
            })
            responseCollectionUnchecked.observe(viewLifecycleOwner, Observer {
                binding.splashProgress.visibility = View.GONE
                if (it.isError) {
                    ma.messageWithSound(it.errorMessage, it.isError, false)

                } else {
                    //sergio: devuelve false si no hay para revisar y <> false.
                    if (it.response != "false") {

                        customDialog.setTitle(getString(R.string.warning))
                            .setDescription(getString(R.string.pendingReviewParking) + (it.response))
                            .setOkButton(getString(R.string.accept)) {
                                customDialog.dismiss()

                            }
                            .setKoButton(getString(R.string.review)) {
                                binding.splashProgress.visibility = View.VISIBLE
                                viewModel.collectionTicketGet(
                                    getData(USER),
                                    getData(PASSWORD),
                                    it.response,
                                    getData(SECTORFK),
                                    type
                                )
                                customDialog.dismiss()
                            }
                        customDialog.show()
                    } else {
                        viewModel.parking(
                            getData(USER),
                            getData(PASSWORD),
                            ticketFk = tickets[0],
                            parking = ticketScanTxt
                        )
                    }
                    // if (!goBack)navigateToCollectionList(it)
                    //goBack = false
                }
            })
            responseDel.observe(viewLifecycleOwner, Observer {

                if (it.isError) {
                    binding.splashProgress.visibility = GONE
                    if (!goBack) {

                        ma.messageWithSound(it.errorMessage, it.isError, false)

                    }
                } else {

                    viewModel.collectionTicketGet(
                        getData(USER),
                        getData(PASSWORD),
                        collection.collectionFk,
                        getData(SECTORFK),
                        type
                    )

                    goBack = false
                }

            })



            responseItemShelvingUpdate.observe(viewLifecycleOwner, Observer {

                if (it.isError) {

                    if (!goBack) {

                        ma.messageWithSound(it.errorMessage, it.isError, false)

                    }


                } else {
                    viewModel.saleTrackingDel(
                        getData(USER),
                        getData(PASSWORD),
                        saleFk = sales[positionUnmarked].saleFk
                    )

                    goBack = false
                }
            })

            responseSaleReplace.observe(viewLifecycleOwner, Observer {
            binding.splashProgress.visibility=GONE

                if (it.isError) {

                    if (!goBack) {

                        ma.messageWithSound(it.errorMessage, it.isError, true)

                    }


                } else {

                    saleAdapter!!.notifyDataSetChanged()
                    setListPosition(storedPosition, false)

                    goBack = false
                }
            })
            ////Tarea #4371
            responseSaleTracking_mark.observe(viewLifecycleOwner, Observer {
                binding.splashProgress.visibility = GONE
                if (it.isError) {

                    if (!goBack) {

                        ma.messageWithSound(it.errorMessage, it.isError, true)

                        binding.splashProgress.visibility=VISIBLE

                        viewModel.collectionTicketGet(
                            getData(USER),
                            getData(PASSWORD),
                            collection.collectionFk,
                            getData(SECTORFK),
                            type
                        )
                    }


                } else {
                   // pintar línea
                    saleAdapter!!.notifyDataSetChanged()
                    setListPosition(storedPosition, false)

                    goBack = false
                }
            })


            responseItemShelvingSaleSupplyAdd.observe(viewLifecycleOwner, Observer {

                if (it.isError) {

                    if (!goBack) {

                        ma.messageWithSound(it.errorMessage, it.isError, true)

                    }


                } else {
                    /* viewModel.saleTrackingDel(
                         getData(USER),
                         getData(PASSWORD),
                         saleFk = sales[positionUnmarked].saleFk
                     )*/

                    goBack = false
                }
            })


            responseSalixMessage.observe(viewLifecycleOwner, Observer {


                if (it.isError) {

                    if (!goBack) {
                        ma.messageWithSound(
                            getString(R.string.rocketKO) + it.errorMessage,
                            it.isError,
                            false
                        )
                    } else {
                        goBack = false
                    }


                }
            })


        }
    }

    private fun responseSaleMoveSuccesful() {
        sales[positionCollectionSplit].quantity = quantityCollectionSplit

        if (quantityCollectionSplit == "0")
            markLine(positionCollectionSplit, type)
        saleAdapter!!.notifyDataSetChanged()

        val ticket =
            "[" + sales[positionCollectionSplit].ticketFk + "](https://salix.verdnatura.es/#!/ticket/" + sales[positionCollectionSplit].ticketFk + "/summary)"
        val message =
            getString(R.string.splitSent) + sales[positionCollectionSplit].itemFk + getString(R.string.fromTicket) + ticket

        sendSalixMessageNew(message, sales[positionCollectionSplit].salePersonFk)

    }

    private fun callPicker(extensionNumber: String) {


        try {
            val intent = Intent(Intent.ACTION_DIAL).apply {
                data = Uri.parse("tel:$extensionNumber")
            }

            startActivity(intent)
        } catch (e: Exception) {
            // d("VERDNATURA::" + e.message)
        }


    }

    private fun getSalePerson(ticketFk: String): String {

        var salePerson = ""
        for (it in sales) {
            if (it.ticketFk.equals(ticketFk)) {
                salePerson = it.salePersonFk
                break
            }
        }
        return salePerson
    }

    private fun sendSalixMessage(
        item: String,
        ticketFk: String,
        quantity: String,
        salePerson: String
    ) {
        val ticket =
            "[" + ticketFk + "](https://salix.verdnatura.es/#!/ticket/" + ticketFk + "/summary)"
        val message =
            getString(R.string.itemAdded) + item + getString(R.string.with) + quantity + getString(R.string.unityTicket) + ticket


        /*    d("VERDNATURA:","el comercial es " + salePerson)
            d("VERDNATURA:","el item  es " + item)
            d("VERDNATURA:","el ticket es es " + ticketFk)
            d("VERDNATURA:","la cantidad es " + quantity)*/

        viewModel.sendChekingPresence(
            token = getData(TOKEN),
            workerId = salePerson,
            message = message
        )
    }

    //CREATE LIST
    private fun createCollectionList() {
        state = 0
        /* if (type == SACADOR && getData(VOZ) != "NO") {
             // initialize()
             speak("Colección cargada, diga listo para empezar.")
         }*/

        binding.mainToolbar.toolbarTitle.text = collection.collectionFk


        binding.splashProgress.visibility = View.GONE
        var salesList: ArrayList<SaleVO> = ArrayList()
        tickets = ArrayList()
        var observations = ""
        collection.tickets.forEach { ticket ->
            ticket.sales.forEach { saleVO ->
                if (type == SACADOR && saleVO.quantity != "0") {
                    salesList.add(saleVO)
                    if (tickets.firstOrNull { it == saleVO.ticketFk }.isNullOrEmpty())
                        tickets.add(saleVO.ticketFk)
                } else if (type == CONTROLADOR) {
                    salesList.add(saleVO)
                    if (tickets.firstOrNull { it == saleVO.ticketFk }.isNullOrEmpty())
                        tickets.add(saleVO.ticketFk)
                }//Refactor #4030//
                else if (type == PRECHECKER) {
                    if (saleVO.saleGroupFk != "") {
                        salesList.add(saleVO)
                        if (tickets.firstOrNull { it == saleVO.ticketFk }.isNullOrEmpty())
                            tickets.add(saleVO.ticketFk)
                    }
                }
            }

            observations = observations + " " + ticket.observations
        }


        sales = salesList.sortedWith(compareBy({ it.saleOrder }))


        if (type == CONTROLADOR) {
            sales = salesList.sortedWith(compareBy({ it.picked }))

        }
        //pruebas sergio
        // sales = salesList.sortedWith(compareBy({it.placements.get(0).created}))
        //sales = salesList.sortedWith(compareBy({it.placements.get(0).placement}))
        // SalesSorter()

        /* for (s in sales) {
             Log.d(
                 "VERDNATURA::",
                 "La sale es ${s.saleFk} El item es ${s.itemFk} y su picked ${s.picked} y saleorder ${s.saleOrder}"
             )
         }*/

        saleAdapter =
            SaleAdapter(sales, pasillerosItemClickListener!!, object : OnQuantityClickListener {

                override fun onQuantityClick(sale: SaleVO) {

                    sales.forEachIndexed { index, saleVO ->
                        if (saleVO.saleFk == sale.saleFk) {
                            if (type != "PRECHECKER") {
                                showQuantityDialog(index)
                            }

                        }
                    }

                }
            }, object : OnSaleClickListener {
                override fun onSaleClick(sale: SaleVO) {

                    sales.forEachIndexed { index, saleVO ->
                        if (saleVO.saleFk == sale.saleFk) {

                            if (type == CONTROLADOR || type == PRECHECKER) {// sergio:cuidado , esta es de lo último para marcar colores
                                markLine(index, type)
                                /// Log.i("VERDNATURA:","marcamos linea")
                            } else if (type == SACADOR) {

                                if (sale.isPrepared == "0" || sale.isPrepared.isNullOrEmpty()) {
                                    showScanner(index, sale)
                                } else {
                                    unMarkLine(index, OK)
                                }

                            }
                        }

                    }
                }

            }, object : OnMistakeClickListener {
                override fun onMistakeClickListener(sale: SaleVO) {
                    if (type != "PRECHECKER") {
                        binding.splashProgress.visibility =
                            VISIBLE
                        mistakeSale = sale
                        goMistakeBack = false
                        viewModel.mistakeType(
                            usuario = getData(USER),
                            getData(PASSWORD)
                        )
                    }
                }
            }, object : onPackingClickListener {
                override fun onPackingClick(sale: SaleVO) {
                    item_updatePackingShelve(sale.itemFk)
                }
            }
            )

        lm = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
        binding.fragmentSacadorCollections.adapter = saleAdapter
        binding.fragmentSacadorCollections.layoutManager = lm
        setTotalLines()

        if (storedPosition != 0)
            setListPosition(storedPosition, true)
        else if (storedBackPosition != 0)
            setListPosition(storedBackPosition, true)

        setScrollListener(lm!!)
        //sergio: se quita porque se realiza desde triggers
        // changeInitTicketState()

        printObservations(observations)
    }

    private fun setScrollListener(lm: LinearLayoutManager) {
        binding.fragmentSacadorCollections.addOnScrollListener(object :
            RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                storedBackPosition = lm.findFirstVisibleItemPosition()
                super.onScrolled(recyclerView, dx, dy)
            }
        })
    }

    private fun printObservations(observations: String) {
        if (observations.trim().isNotEmpty()) {
            customDialog.setTitle(getString(R.string.observations)).setDescription(observations)
                .setOkButton(getString(R.string.accept)) {
                    customDialog.hide()
                    customDialog.dismiss()
                }.show()
        }
    }

    //SEARCH AND MARK
    private fun findSale(txtscan: String) {
        goBack = false
        var index = 0
        var isBreak = false
        var isOk = false
        goBack = false
        goBack2 = false


        if (type == SACADOR) {
            for (saleVO in sales) {
                //sergio: pita si encuentra ticket o el saleGroupFk
                //Log.i("VERDNATURA:","SE busca en sales ${saleVO.ticketFk}")
                //canviar el titcket per salegroup i enviar a pako saleTracking_add (saleGroupFk) i refrescar pantalla.
                //d("El salegroup es " + saleVO.saleGroupFk)
                if (saleVO.saleGroupFk == txtscan) {
                    // if (saleVO.ticketFk == txtscan ) {
                    isOk = true
                    viewModel.saleTracking_add(
                        getData(USER),
                        getData(PASSWORD),
                        txtscan
                    )
                    if ((isOk) && mpok != null) {
                        mpok!!.start()
                    }

                    break

                }

                if (saleVO.isPrepared != "1" && saleVO.isPreviousPrepared != "1") {
                    //1- Por itemFk
                    /* if (txtscan == saleVO.itemFk){
                         mpok!!.start()
                         isOk = true
                         markLine(index,type)
                         break
                     }*/
                    //2- Por carro
                    if (saleVO.placements != null) {
                        var shelvingIndex = 0
                        for (placementVO in saleVO.placements) {
                            // para comprobar si es igual a una matricula
                            if (placementVO.shelving != null && placementVO.visible != null && txtscan.uppercase() == placementVO.shelving.uppercase() && placementVO.visible != "(0)") {
                                if (mpok != null) mpok!!.start()
                                isOk = true
                                //////Log.i("VERDNATURA:","encontrado producto")
                                showShelving(index, shelvingIndex)
                                isBreak = true
                                break
                            }
                            shelvingIndex += 1
                        }
                        if (isBreak) break
                    }

                    //3- Por barcode
                    /*saleVO.Barcodes.forEach { barcode ->
                        if (txtscan == barcode){
                            mpok!!.start()
                            isOk = true
                            markLine(index,type)
                            isBreak = true
                        }
                    }
                    if (isBreak) break*/
                }
                index += 1
            }
            if (!isOk) {
                if (txtscan.contains("-")) {
                    if (tickets.size > 0) {


                        viewModel.parking(
                            getData(USER),
                            getData(PASSWORD),
                            ticketFk = tickets[0],
                            parking = txtscan
                        )

                    }
                    Timber.i("La coleccion es %s", tickets[0])
                    /* if (mpok != null) mpok!!.start()
                     "Ticket aparcado".toast(requireContext())*/
                } else {
                    if (mperror != null) mperror!!.start()
                }

            }
        } else if (type == CONTROLADOR || type == PRECHECKER) {

            // checkSaleGroup()

            for (saleVO in sales) {
                //0-Salegroup

                if (saleVO.isControlled == "0") {
                    //1- Por itemFk
                    if (txtscan == saleVO.itemFk) {
                        if (mpok != null) mpok!!.start()
                        isOk = true
                        markLine(index, type)
                        break
                    }
                    //2- Por barcode
                    saleVO.Barcodes.forEach { barcode ->
                        if (txtscan == barcode) {
                            if (mpok != null) mpok!!.start()
                            isOk = true
                            markLine(index, type)
                            isBreak = true
                        }
                    }

                    if (isBreak) break
                }
                index += 1
            }
            //Lo escaneado no encontrado miramos si es parking o ticket
            if (!isOk) {
                if (txtscan.contains("-")) {

                    //  Log.d("VERDNATURA::", "VAMOS A PARKING DESDE PANTALLA CONTROLADOR")

                    if (tickets.size > 0) {

                        ticketToParking = tickets[0]
                        ticketScanTxt = txtscan
                        //#tarea4107
                        viewModel.collection_getUncheckedTicket(
                            getData(USER),
                            getData(PASSWORD),
                            collectionFk = tickets[0]
                        )

                        //  Log.d("VERDNATURA::", "LA COLECTION ES ${tickets[0]}")

                        /* viewModel.parking(
                             getData(USER),
                             getData(PASSWORD),
                             ticketFk = tickets[0],
                             parking = txtscan
                         )*/
                    }
                    /* if (mpok != null) mpok!!.start()
                     getString(R.string.Ticketaparcado).toast(requireContext())*/
                } else {
                    binding.splashProgress.visibility =
                        VISIBLE
                    storedPosition = 0
                    storedBackPosition = 0
                    //  if (type != PRECHECKER) {
                    isMarking = false
                    viewModel.collectionTicketGet(
                        getData(USER),
                        getData(PASSWORD),
                        txtscan,
                        getData(SECTORFK),
                        type
                    )

                    if (type.equals(CONTROLADOR)) {
                        viewModel.ticket_checkFullyControlled(
                            getData(USER),
                            getData(PASSWORD),
                            txtscan

                        )
                    }
                    //  } else {
                    //    binding.splashProgress.visibility = View.GONE
                    //}
                    ////Log.i("VERDNATURA:","La collection es ${txtscan}")
                }
            }
        }

    }

    /*private fun checkSaleGroup(txtscan: String) {

        for (i in sales.indices) {
            if (sales[i].saleGroupFk == txtscan) {
                markLine(i, type)
            }

        }
    }*/

    private fun findSale(txtscan: String, position: Int) {
        var isOk = false
        if (type == SACADOR) {
            var saleVO = sales[position]

            if (saleVO.isPrepared != "1" && saleVO.isPreviousPrepared != "1") {
                //1- Por itemFk
                /*if (txtscan == saleVO.itemFk){
                    if (mpok != null) mpok!!.start()
                    isOk = true
                    markLine(position,type)

                }*/
                if (!isOk) {
                    //2- Por carro
                    var shelvingIndex = 0
                    for (placementVO in saleVO.placements) {
                        if (txtscan.uppercase() == placementVO.shelving.uppercase()) {
                            if (mpok != null) mpok!!.start()
                            isOk = true
                            showShelving(position, shelvingIndex)
                            break
                        }
                        shelvingIndex += 1
                    }
                }
                /*
                if (!isOk){
                    //3- Por barcode
                    saleVO.Barcodes.forEach { barcode ->
                        if (txtscan == barcode){
                            if (mpok != null) mpok!!.start()
                            isOk = true
                            markLine(position,type)
                        }
                    }
                }*/
            }
            if (!isOk) {
                if (txtscan.contains("-")) {
                    tickets.forEach {
                        viewModel.parking(
                            getData(USER),
                            getData(PASSWORD),
                            ticketFk = it,
                            parking = txtscan
                        )
                    }
                    /* if (mpok != null) mpok!!.start()
                     "Ticket aparcado".toast(requireContext())*/

                } else {
                    if (mperror != null) mperror!!.start()
                }

            }
        }

    }

    //Tarea #4371
    private fun markLine(position: Int, newType: String) {
        state = 0
        //////Log.i("VERDNATURA:","Marcamos linea y enviamos saleTracking")
        if (type == SACADOR) {
            sales[position].isPrepared = if (sales[position].isPrepared == "1") "0" else "1"
            if (sales[position].isPrepared == "1") {
                sales[position].pickedQuantity = sales[position].quantity
            }

        } else if (type == CONTROLADOR)
            sales[position].isControlled = if (sales[position].isControlled == "1") "0" else "1"

        if (type == PRECHECKER) {
            sales[position].isPreControlled =
                if (sales[position].isPreControlled == "1") "0" else "1"

        }
        //Tarea #4371 se quita y se deja en el response de viewmodel saleTracking_mark
        //saleAdapter!!.notifyDataSetChanged()
        //setListPosition(position, false)

        if (type==SACADOR){
            saleTracking_mark(position, newType)
            //saleTrackingReplace(position,newType)
        }else{
            saleTrackingReplace(position,newType)
        }
        isMarking = true
        setTotalLines()
    }

    private fun setListPosition(position: Int, isFromBack: Boolean) {
        storedPosition = position
        if (type == SACADOR || (type == CONTROLADOR && (getData(SECTORDESCRIP).uppercase() == getString(
                R.string.sectorALGEMESI
            ) || getData(SECTORDESCRIP).uppercase() == getString(
                R.string.sectorALGEMESINEW
            )))
        ) {
            if (binding.fragmentSacadorCollections != null) {
                binding.fragmentSacadorCollections.addViewObserver {
                    lm!!.scrollToPositionWithOffset(position, 0)
                }
            }

        } else if (isFromBack) {
            if (binding.fragmentSacadorCollections != null) {
                binding.fragmentSacadorCollections.addViewObserver {
                    lm!!.scrollToPositionWithOffset(position, 0)
                }
            }
        }

    }

    private fun saleTrackingReplace(position: Int, type: String) {

        //Tarea #4371 se quita para ver si funciona correctamente
        binding.splashProgress.visibility=VISIBLE
       viewModel.saleTrackingReplace(
            getData(USER),
            getData(PASSWORD),
            saleFk = sales[position].saleFk,
            vIsChecked = if (type == SACADOR) sales[position].isPrepared else if (type == CONTROLADOR) sales[position].isControlled else if (type == "PRECHECKER") sales[position].isPreControlled else "1",
            vOriginalQuantity = sales[position].pickedQuantity,
            vStateFk = if (type == CONTROLADOR) "CHECKED" else if (type == "PRECHECKER") "PREVIOUS_CONTROL" else type,//type.toString(),
            vBuyFk = originalItemScan

        )

    }



    //Tarea #4371 se quita para ver si funciona correctamente
    private fun saleTracking_mark(position: Int, type: String) {

        binding.splashProgress.visibility= VISIBLE

         viewModel.saleTracking_mark(
             getData(USER),
             getData(PASSWORD),
             saleFk = sales[position].saleFk,
             vIsChecked = if (type == SACADOR) sales[position].isPrepared else if (type == CONTROLADOR) sales[position].isControlled else if (type == "PRECHECKER") sales[position].isPreControlled else "1",
             vOriginalQuantity = sales[position].pickedQuantity,
             vStateFk = if (type == CONTROLADOR) "CHECKED" else if (type == "PRECHECKER") "PREVIOUS_CONTROL" else type,//type.toString(),
             vBuyFk = originalItemScan,
             vItemShelvingFk = itemShelvingTracking_mark,
             vQuantity=customDialogList.getValue()


         )

    }
    private fun unMarkLine(position: Int, newType: String) {
        state = 0
        if (sales[position].isPrepared == "1") {
            customDialog.setTitle(getString(R.string.unmarkLine))
                .setDescription(getString(R.string.goUnmark) + sales[position].itemFk + getString(R.string.sure))
                .setOkButton(getString(R.string.unmark)) {
                    sales[position].isPrepared = "0"
                    sales[position].pickedQuantity = "0"
                    saleAdapter!!.notifyDataSetChanged()
                    setListPosition(position, false)
                    if (type != PRECHECKER) {


                        binding.splashProgress.visibility = VISIBLE
                        viewModel.itemShelving_updateFromSale(
                            getData(USER),
                            getData(PASSWORD),
                            sales[position].saleFk,
                            sales[position].quantity
                        )
                        positionUnmarked = position

                        /*    viewModel.saleTrackingDel(
                                getData(USER),
                                getData(PASSWORD),
                                saleFk = sales[position].saleFk,
                                "saleTracking_del"
                            )*/


                    }
                    setTotalLines()
                    scanRequest()
                    customDialog.dismiss()
                }.setKoButton(getString(R.string.cancel)) {
                    scanRequest()
                    customDialog.dismiss()
                }.show()
        }

    }

    //SHELVINGS
    private fun showShelving(position: Int, shelvingPosition: Int) {
        storedShelvingPosition = shelvingPosition
        storedPosition = position
        binding.splashProgress.visibility = VISIBLE
        var quantityGet = "0"
        try {
            quantityGet =
                (sales[position].quantity.toInt() - sales[position].pickedQuantity.toInt()).toString()
        } catch (e: Exception) {
        }
        //Log.i("VERDNATURA:","Aparece  para enviar")
        viewModel.itemPlacementSupplyAiming(
            getData(USER),
            getData(PASSWORD),
            itemFk = sales[position].itemFk,
            quantity = quantityGet,
            shelvingFk = sales[position].placements[shelvingPosition].shelving

        )
    }

    private fun printShelvingResult(placementSupplyListVO: PlacementSupplyListVO) {
        //////Log.i("VERDNATURA:","Print CustomDialog")
        var shelving = ""
        var item = ""
        var longName = ""
        var total = "0"
        var itemShelvingFk = "0"
        if (!placementSupplyListVO.list.isEmpty()) {
            var placement: PlacementSupplyVO? = null
            placementSupplyListVO.list.forEach { placementVO ->
                if (placementVO.stock != "0" && placement == null)
                    placement = placementVO
            }
            if (placement != null) {
                shelving = placement!!.shelving
                item = placement!!.itemFk
                longName = placement!!.longName
                total = placement!!.total
                itemShelvingFk = placement!!.itemShelvingFk
            }

        }
        listPlacementSupply = ArrayList()
        placementSupplyListVO.list.forEach {
            if (it.stock != "0")
                listPlacementSupply.add(BarcodeVO(code = it.proposal))
            //////Log.i("VERDNATURA:","Array de placementsupply")
        }
        try {
            // Log.i("VERDNATURA:","Pulso COGER-1")
            customDialogList.setTitle("$shelving($item) $total de $longName").setOkButton(
                getString(
                    R.string.take
                )
            ) {
                if (customDialogList.getValueTwo().isNotEmpty()) {
                    if (isNumber(customDialogList.getValue()) && isNumber(total) && customDialogList.getValue()
                            .toInt() > total.toInt()
                    ) {
                        getString(R.string.quantityHigh).toast(requireContext())
                    } else if (isNumber(customDialogList.getValue())) {
                        originalItemScan = customDialogList.getValueTwo()
                        // Log.i("VERDATURA","Le pasamos el siguiente item $originalItemScan que es el escaneado")
                        if (checkItemScan(customDialogList.getValueTwo())) {
                            onQuantityOfShelvingSelected(itemShelvingFk)
                            //Log.i("VERDNATURA:","Cantidad seleccionada")
                            mpok?.start()
                            ReviewQuantityForRefreshingAndSorting(
                                customDialogList.getValue().toInt(),
                                sales[storedPosition].quantity.toInt(),
                                sales[storedPosition].pickedQuantity.toInt()
                            )
                            customDialogList.dismiss()
                        } else {
                            itemShelvingFkStored = itemShelvingFk
                            binding.splashProgress.visibility =
                                VISIBLE


                            viewModel.getIdFromCodeSalix(
                                token = getData(TOKEN),
                                code = customDialogList.getValueTwo(),
                            )
                            /* } else {
                                 viewModel.getIdFromCode(
                                     usuario = getData(USER),
                                     password = getData(PASSWORD),
                                     code = customDialogList.getValueTwo(), "barcodeToItem"
                                 )
                             }*/

                            customDialogList.dismiss()
                        }
                        scanRequest()
                        hideKeyboards()
                    } else {
                        getString(R.string.quantityError).toast(requireContext())
                    }


                } else {
                    getString(R.string.scanItemValidate).toast(requireContext())
                }

            }.setKoButton(getString(R.string.close)) {
                scanRequest()
                hideKeyboards()
                customDialogList.dismiss()
            }.setHintValue(getString(R.string.quantitySelect)).setValue(total)
                .setHintValueTwo(getString(R.string.scanItem))
                .setValueTwo("").show()
        } catch (e: Exception) {
            //////Log.i("VERDNATURA:","${e.message.toString()}")
        }
        try {
            customDialogList.getEditTextTwo().post(Runnable {
                customDialogList.getEditTextTwo().requestFocusFromTouch()
                if (activity != null) {
                    val lManager: InputMethodManager =
                        requireActivity().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                    lManager.hideSoftInputFromWindow(
                        customDialogList.getEditTextTwo().windowToken,
                        InputMethodManager.SHOW_FORCED
                    )
                }

            })
        } catch (e: Exception) {
        }
        try {
            customDialogList.getEditTextTwo().setOnEditorActionListener { v, actionId, event ->
                if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0 || actionId == 5) {

                    // Log.i("VERDNATURA:","Comprobando COGER-1")
                    if (customDialogList.getValueTwo().isNotEmpty()) {
                        try {
                            if (isNumber(customDialogList.getValue()) && customDialogList.getValue()
                                    .toInt() > total.toInt()
                            ) {
                                getString(R.string.quantityHigh).toast(requireContext())
                            } else if (isNumber(customDialogList.getValue())) {
                                originalItemScan = customDialogList.getValueTwo()

                                if (checkItemScan(customDialogList.getValueTwo())) {
                                    onQuantityOfShelvingSelected(itemShelvingFk)
                                    mpok?.start()
                                    ReviewQuantityForRefreshingAndSorting(
                                        customDialogList.getValue().toInt(),
                                        sales[storedPosition].quantity.toInt(),
                                        sales[storedPosition].pickedQuantity.toInt()
                                    )
                                    //  SalesSorter(sales)

                                    customDialogList.dismiss()
                                } else {
                                    itemShelvingFkStored = itemShelvingFk
                                    binding.splashProgress.visibility = View.VISIBLE


                                    viewModel.getIdFromCodeSalix(
                                        getData(TOKEN),
                                        code = customDialogList.getValueTwo()
                                    )
/*
                                    } else {
                                        viewModel.getIdFromCode(
                                            getData(USER),
                                            getData(PASSWORD),
                                            code = customDialogList.getValueTwo(), "barcodeToItem"
                                        )
                                    }*/
                                    customDialogList.dismiss()
                                    scanRequest()
                                }
                            } else {
                                getString(R.string.quantityError).toast(requireContext())
                            }

                        } catch (e: Exception) {

                        }

                    } else {
                        getString(R.string.scanItemValidate).toast(requireContext())
                    }
                    scanRequest()
                    hideKeyboards()
                    return@setOnEditorActionListener true

                }
                false
            }
        } catch (e: Exception) {
        }

        placementSupplyAdapter =
            BarcodeAdapter(listPlacementSupply, object : OnBarcodeRowClickListener {
                override fun onBarcodeRowClickListener(item: BarcodeVO) {
                    placementSupplyListVO.list.forEach {
                        if (it.proposal == item.code) {
                            customDialogList.setValue(it.total)
                            total = it.total
                            itemShelvingFk = it.itemShelvingFk
                        }
                    }

                }
            }, showDelete = false)

        customDialogList.getRecyclerView().adapter = placementSupplyAdapter

        customDialogList.getRecyclerView().layoutManager =
            LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)

    }

    private fun ReviewQuantityForRefreshingAndSorting(
        quantityPicking: Int,
        quantityTotal: Int,
        quantityPicked: Int
    ) {

        /* Log.i("VERDNATURA::","Picking"+quantityPicking)
         Log.i("VERDNATURA::","Total"+quantityTotal)
         Log.i("VERDNATURA::","Now picked"+quantityPicked)*/

        if (quantityPicked < quantityTotal) {

            //  SalesSorter()
            // Log.i("VERDNATURA::","Lanzamos collection para que refresque adaptador y ordene")
            viewModel.collectionTicketGet(
                getData(USER),
                getData(PASSWORD),
                collection.collectionFk,
                getData(SECTORFK),
                type
            )

        }

    }


    private fun checkItemScan(valueToCheck: String): Boolean {

        if (storedPosition >= 0 && sales.size > storedPosition) {
            val saleToCheck = sales[storedPosition]

            if (saleToCheck.itemFk == valueToCheck)
                return true
            else {
                saleToCheck.Barcodes.forEach { barcode ->
                    if (barcode == valueToCheck)
                        return true
                }
            }
        }
        return false
    }

    //Tarea #4371
    private fun onQuantityOfShelvingSelected(itemShelvingFk: String, quantity: String = "0") {
        //1 - MODIFICAR CANTIDAD DEL CARRO
        try {
            val shelvingVisible =
                sales[storedPosition].placements[storedShelvingPosition].visible.substring(
                    1,
                    sales[storedPosition].placements[storedShelvingPosition].visible.indexOf(")")
                )

            if (quantity == "0") {
                sales[storedPosition].placements[storedShelvingPosition].visible =
                    "(" + (shelvingVisible.toInt() - customDialogList.getValue()
                        .toInt()).toString() + ")"
            } else {
                sales[storedPosition].placements[storedShelvingPosition].visible =
                    "(" + (shelvingVisible.toInt() - quantity.toInt()).toString() + ")"
            }
            //Tarea #4371 se quita para ver si funciona correctamente
         /*viewModel.itemShelvingSaleSupplyAdd(
                getData(USER),
                getData(PASSWORD),
                itemShelvingFk = itemShelvingFk,
                saleFk = sales[storedPosition].saleFk,
                quantity = if (quantity != "0") quantity else customDialogList.getValue()

            )*/


        } catch (e: Exception) {
        }

        //2- MODIFICAR EL PICKED DEL SALE
        try {
            if (quantity == "0") {
                sales[storedPosition].pickedQuantity =
                    (sales[storedPosition].pickedQuantity.toInt() + customDialogList.getValue()
                        .toInt()).toString()
            } else {
                sales[storedPosition].pickedQuantity =
                    (sales[storedPosition].pickedQuantity.toInt() + quantity
                        .toInt()).toString()
            }
        } catch (e: Exception) {
        }

        //3- MARCAR LINEA

        //Tarea #4371
         itemShelvingTracking_mark = itemShelvingFk

        if (sales[storedPosition].pickedQuantity != sales[storedPosition].quantity) {
            sales[storedPosition].isPrepared = "1"
            markLine(storedPosition, OK)
        } else {
            markLine(storedPosition, type)
        }

    }

    //OPTIONS
    private fun print() {

        if (ma.havePrinter() && ma.haveSector()) {
            viewModel.collectionStickerPrint(
                getData(USER),
                getData(PASSWORD),
                collectionFk = collection.collectionFk,
                sectorFk = getData(SECTORFK)
            )
            (getString(R.string.Imprimiendo) + getData(PRINTERNAME)).toast(requireContext())
        } else {

            ma.messageWithSound(
                getString(R.string.printerFault),
                isError = true,
                true,
                getString(R.string.printError),
                false
            )

        }

    }

    private fun addItem() {
        listPlacementSupply = ArrayList()
        collection.tickets.forEach {
            listPlacementSupply.add(BarcodeVO(code = it.ticketFk))
        }
        if (listPlacementSupply.size == 1) {
            ticketSelected = listPlacementSupply[0].code!!
        }

        customDialogList.setTitle(getString(R.string.Agregarartículoparaticket) + " " + ticketSelected)
            .setOkButton(getString(R.string.Agregar)) {
                if (ticketSelected.isNullOrEmpty()) {
                    getString(R.string.Seleccionaunticketdelaista).toast(requireContext())
                } else if (customDialogList.getValue()
                        .isNullOrEmpty() || customDialogList.getValueTwo().isNullOrEmpty()
                ) {
                    getString(R.string.Todosloscampossonobligatorios).toast(requireContext())
                } else {
                    binding.splashProgress.visibility =
                        VISIBLE

                    //sergio datos para mensaje salix

                    dataMessageSalix = DataMessageSalix(
                        ticket = ticketSelected,
                        item = customDialogList.getValue(),
                        quantity = customDialogList.getValueTwo(),
                        personSale = getSalePerson(ticketSelected)
                    )

                    viewModel.collectionAddItem(
                        getData(USER),
                        getData(PASSWORD),
                        itemFk = customDialogList.getValue(),
                        ticketFk = ticketSelected,
                        quantityFk = customDialogList.getValueTwo(),
                        warehouseFk = getData(WAREHOUSEFK)
                    )


                    scanRequest()
                    customDialogList.dismiss()
                }

            }.setKoButton(getString(R.string.close)) {
                scanRequest()
                customDialogList.dismiss()
            }.setHintValue(getString(R.string.Artículo)).setValue("")
            .setHintValueTwo(getString(R.string.Cantidad)).setValueTwo("").show()

        customDialogList.getEditText().requestFocus()
        hideKeyboards()

        customDialogList.getEditText().setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0 || actionId == 5) {
                if (!customDialogList.getValue().isNullOrEmpty()) {
                    customDialogList.getEditTextTwo().requestFocus()
                }
                hideKeyboards()
                return@setOnEditorActionListener true
            }
            false
        }

        customDialogList.getEditTextTwo().setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0 || actionId == 5) {
                if (!customDialogList.getValueTwo().isNullOrEmpty()) {
                    if (ticketSelected.isNullOrEmpty()) {
                        getString(R.string.Seleccionaunticketdelaista).toast(requireContext())
                    } else if (customDialogList.getValue()
                            .isNullOrEmpty() || customDialogList.getValueTwo().isNullOrEmpty()
                    ) {
                        getString(R.string.Todosloscampossonobligatorios).toast(requireContext())
                    } else {
                        binding.splashProgress.visibility =
                            VISIBLE

                        dataMessageSalix = DataMessageSalix(
                            ticket = ticketSelected,
                            item = customDialogList.getValue(),
                            quantity = customDialogList.getValueTwo(),
                            personSale = getSalePerson(ticketSelected)
                        )

                        viewModel.collectionAddItem(
                            getData(USER),
                            getData(PASSWORD),
                            itemFk = customDialogList.getValue(),
                            ticketFk = ticketSelected,
                            quantityFk = customDialogList.getValueTwo(),
                            warehouseFk = getData(WAREHOUSEFK)
                        )
                        scanRequest()
                        customDialogList.dismiss()
                    }
                }
                hideKeyboards()
                return@setOnEditorActionListener true
                scanRequest()
                customDialogList.dismiss()
            }
            false
        }

        placementSupplyAdapter =
            BarcodeAdapter(listPlacementSupply, object : OnBarcodeRowClickListener {
                override fun onBarcodeRowClickListener(item: BarcodeVO) {
                    customDialogInput.setTitle(getString(R.string.ArtículoparaTicket) + " " + item.code!!)
                    ticketSelected = item.code!!
                    customDialogList.setTitle(getString(R.string.Agregarartículoparaticket) + " " + ticketSelected)
                }
            }, showDelete = false)

        customDialogList.getRecyclerView().adapter = placementSupplyAdapter

        customDialogList.getRecyclerView().layoutManager =
            LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)

    }

    /* private fun showDisponibility() {

         customDialogInput.setTitle(getString(R.string.Verdisponible))
             .setDescription(getString(R.string.Escaneaetiqueta))
             .setOkButton(getString(R.string.Buscar)) {
                 try {
                     if (binding.splashProgress != null) {
                         binding.splashProgress.visibility = View.VISIBLE
                     }

                 } catch (e: Exception) {
                 }

                 hideKeyboards()
                 viewModel.itemGetAvailable(
                     usuario = user,
                     password = password,
                     itemFk = customDialogInput.getValue(),
                     warehouseFk = warehouseFk,
                     "item_GetVisibleAvailable"
                 )
                 scanRequest()
                 customDialogInput.dismiss()

             }.setKoButton(getString(R.string.cancel)) {
             if (binding.splashProgress != null) {
                 binding.splashProgress.visibility = View.GONE
             }
             hideKeyboards()
             scanRequest()
             customDialogInput.dismiss()
         }.setValue("").show()
         customDialogInput.getEditText().requestFocus()
         customDialogInput.getEditText().setOnEditorActionListener { v, actionId, event ->
             if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0) {
                 if (!customDialogInput.getValue().isNullOrEmpty()) {
                     if (binding.splashProgress != null) binding.splashProgress.visibility = View.VISIBLE
                     viewModel.itemGetAvailable(
                         usuario = user,
                         password = password,
                         itemFk = customDialogInput.getValue(),
                         warehouseFk = warehouseFk
                     ,"item_GetVisibleAvailable")
                 }
                 customDialogInput.setValue("")
                 scanRequest()
                 customDialogInput.dismiss()
                 hideKeyboards()
                 return@setOnEditorActionListener true
             }
             false
         }
     }*/

    private fun toastDisponibility(item: ItemVO) {
        if (item.available.isNullOrEmpty()) {
            item.available = "0"
        }
        customDialog.setTitle(getString(R.string.itemPoints) + item.id)
            .setDescription(getString(R.string.available) + ":" + item.available)
            .setOkButton(getString(R.string.accept)) {
                scanRequest()
                customDialog.dismiss()
            }.show()

    }

    private fun setTotalLines() {

        var totalMark = 0
        sales.forEach {
            if (type == SACADOR) {
                if (it.isPrepared == "1" || it.isControlled == "1" || it.isPreviousPrepared == "1") {
                    totalMark += 1
                } else if (it.quantity == "0") {
                    totalMark += 1
                }
            } else if (type == CONTROLADOR) {
                if (it.isControlled == "1" || it.isControlled == "2")
                    totalMark += 1

            }//Refactor #4030
            else if (type == PRECHECKER) {
                if (it.isPreControlled == "1") {
                    totalMark += 1
                }

            }
        }

        if (binding.mainToolbar.toolbarTitle != null) binding.mainToolbar.toolbarTitle.text =
            if (collection.collectionFk != null) collection.collectionFk else ""
        if (binding.mainToolbar.toolbarSubtitle != null && totalMark != null) binding.mainToolbar.toolbarSubtitle.text =
            "" + totalMark + "/" + sales.size

        if (totalMark == sales.size) {
            getString(R.string.Coleccióncompleta).toast(this.context, Toast.LENGTH_SHORT)
            if (!goBack)
                ticketCollection_setUsedShelves()
            goBack = false

            changeTicketState()


        }
    }


    private fun ticketCollection_setUsedShelves() {


        if (type.equals("CHECKER") && (isMarking && (getData(SECTORDESCRIP).uppercase() != getString(
                R.string.sectorALGEMESI
            ) && getData(SECTORDESCRIP).uppercase() != getString(
                R.string.sectorALGEMESINEW
            )
                    ))
        ) {


            customDialogInput.setTitle(getString(R.string.shlevesNumber))
                .setDescription(getString(R.string.shlevesNumberTicket))
                .setOkButton(getString(R.string.accept)) {
                    if (!customDialogInput.getValue().isNullOrEmpty()) {

                        binding.splashProgress.visibility = VISIBLE
                        viewModel.ticketCollection_setUsedShelves(
                            getData(USER),
                            getData(PASSWORD),
                            ticketFk = collection.collectionFk,
                            usedShelves = customDialogInput.getValue()
                        )
                        hideKeyboards()
                        //  showKeyboards()

                    }
                    customDialogInput.setValue("")
                    customDialogInput.dismiss()
                    showKeyboards()
                    //hideKeyboards()
                    //showKeyboards()
                }.setKoButton(getString(R.string.cancel)) {
                    customDialogInput.dismiss()
                    // hideKeyboards()
                    showKeyboards()
                }.setValue("").show()

            customDialogInput.setInputText()
            // customDialogInput.currentFocus
            customDialogInput.setFocusText()
            showKeyboards()

            customDialogInput.getEditText().setOnEditorActionListener { v, actionId, event ->
                if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0) {
                    if (!customDialogInput.getValue().isNullOrEmpty()) {

                        binding.splashProgress.visibility = VISIBLE
                        viewModel.ticketCollection_setUsedShelves(
                            getData(USER),
                            getData(PASSWORD),
                            ticketFk = collection.collectionFk,
                            usedShelves = customDialogInput.getValue()
                        )
                        hideKeyboards()
                    }
                    customDialogInput.setValue("")
                    scanRequest()
                    customDialogInput.dismiss()
                    hideKeyboards()
                    return@setOnEditorActionListener true
                }
                false
            }


        }


    }

    private fun item_updatePackingShelve(itemFk: String) {


        isMarking = false
        customDialogInput.setTitle(getString(R.string.packetNumberShelves))
            .setDescription(getString(R.string.packetIndicate))
            .setOkButton(getString(R.string.accept)) {
                if (!customDialogInput.getValue().isNullOrEmpty()) {

                    binding.splashProgress.visibility = VISIBLE
                    viewModel.item_updatePackingShelve(
                        getData(USER),
                        getData(PASSWORD),
                        vSelf = itemFk,
                        vPacking = customDialogInput.getValue()
                    )
                    hideKeyboards()
                    //showKeyboards()

                }
                customDialogInput.setValue("")
                customDialogInput.dismiss()
                // hideKeyboards()
                showKeyboards()
            }.setKoButton(getString(R.string.cancel)) {

                customDialogInput.dismiss()
                //hideKeyboards()
                showKeyboards()
            }.setValue("").show()

        customDialogInput.setInputText()
        customDialogInput.currentFocus
        customDialogInput.setFocusText()
        showKeyboards()

        customDialogInput.getEditText().setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0) {
                if (!customDialogInput.getValue().isNullOrEmpty()) {

                    binding.splashProgress.visibility = VISIBLE
                    viewModel.ticketCollection_setUsedShelves(
                        getData(USER),
                        getData(PASSWORD),
                        ticketFk = collection.collectionFk,
                        usedShelves = customDialogInput.getValue()
                    )

                }
                customDialogInput.setValue("")
                scanRequest()
                customDialogInput.dismiss()
                hideKeyboards()
                return@setOnEditorActionListener true
            }
            false
        }

    }

    private fun showBottomNavigation(visibilitiy: Int) {
        //requireActivity().main_bottom_navigation.visibility = visibilitiy
    }

    //FALTAS / BASURA / SPLIT
    private fun showQuantityDialog(position: Int) {
        customDialogThreeButtons.setDescription(getString(R.string.txtnuevacantidad)).setValue("")
            .setOkButton(getString(R.string.titleFaults)) {
                checkAndCall(
                    position,
                    customDialogThreeButtons.getValue(),
                    getString(R.string.titleFaults)
                )

            }.setOkButtonTwo(getString(R.string.BasuraRechazar)) {

                checkAndCall(
                    position,
                    customDialogThreeButtons.getValue(),
                    getString(R.string.BasuraRechazar)
                )

            }.setOkButtonThree(getString(R.string.Reject)) {
                checkAndCall(
                    position,
                    customDialogThreeButtons.getValue(),
                    getString(R.string.Reject)
                )

            }.setOkButtonFour(getString(R.string.Split)) {
                checkAndCall(
                    position,
                    customDialogThreeButtons.getValue(),
                    getString(R.string.Split)
                )


            }.setOkButtonAdd(getString(R.string.Agregar)) {
                checkAndCall(
                    position,
                    customDialogThreeButtons.getValue(),
                    getString(R.string.Agregar)
                )

            }.setKoButton(getString(R.string.cancel)) {
                scanRequest()
                customDialogThreeButtons.dismiss()
            }.show()
    }

    private fun checkAndCall(position: Int, value: String, action: String) {
        if (value.trim().isNullOrEmpty()) {
            getString(R.string.Indicanuevacantidad).toast(requireContext())
        } else {

            when (action) {
                getString(R.string.Agregar) -> increaseQuantity(position, value)
                getString(R.string.BasuraRechazar) -> TrashMissingReject(position, value, "TRUE")
                getString(R.string.titleFaults) -> TrashMissingReject(position, value, "FALSE")
                getString(R.string.Reject) -> TrashMissingReject(position, value, "reject")
                getString(R.string.Split) -> split(position, value)

            }

            scanRequest()
            customDialogThreeButtons.dismiss()
        }
    }

    private fun split(position: Int, quantity: String) {

        //sergio: SPLIT SALIX

        quantityCollectionSplit = quantity
        positionCollectionSplit = position

        var totalQuantity: Int = 0
        try {
            totalQuantity = sales[position].quantity.toInt() - quantity.toInt()
        } catch (e: Exception) {
        }

        //var working_in_test = true

        viewModel.transferSalesSalix(
            getData(TOKEN),
            ticketFk = sales[position].ticketFk,
            saleFk = sales[position].saleFk,
            quantity = totalQuantity.toString()
        )


        /* sales[position].quantity = quantity

      if (quantity == "0")
          markLine(position, type)
      saleAdapter!!.notifyDataSetChanged()

      //enviar mensaje a salix
      val ticket =
          "[" + sales[position].ticketFk + "](https://salix.verdnatura.es/#!/ticket/" + sales[position].ticketFk + "/summary)"
      val message =
          "Se ha enviado a Split el articulo " + sales[position].itemFk + " del ticket " + ticket
      viewModel.sendChekingPresence(
          token = getData(TOKEN),
          workerId = sales[position].salePersonFk,
          message = message, "sendChekingPresence"
      )*/

    }

    private fun TrashMissingReject(
        position: Int,
        quantity: String,
        typeCollectionTrashMissingReject: String
    ) {
        typeCollectionMissing = typeCollectionTrashMissingReject
        positionCollectionMissing = position
        quantityCollectionMissing = quantity

        var totalQuantity: Int = 0
        try {
            totalQuantity = sales[position].quantity.toInt() - quantity.toInt()
        } catch (e: Exception) {
        }

        viewModel.collectionMissingTrash(
            getData(USER),
            getData(PASSWORD),
            saleFk = sales[position].saleFk,
            quantity = totalQuantity.toString(),
            warehouseFk = getData(WAREHOUSEFK),
            type = typeCollectionTrashMissingReject,
            originalQuantity = quantity
        )
        /*   sales[position].quantity = quantity
           saleAdapter!!.notifyDataSetChanged()
           if (quantity == "0")
               markLine(position, type)

   */
    }

    /* private fun trash(position: Int, quantity: String) {
         var totalQuantity: Int = 0
         try {
             totalQuantity = sales[position].quantity.toInt() - quantity.toInt()
         } catch (e: Exception) {
         }
         viewModel.collectionMissingTrash(
             usuario = user,
             password = password,
             saleFk = sales[position].saleFk,
             quantity = totalQuantity.toString(),
             warehouseFk = warehouseFk,
             type = "FALSE",
             originalQuantity = quantity,
             callFunction = "collectionMissingTrash"
         )

         sales[position].quantity = quantity
         saleAdapter!!.notifyDataSetChanged()
         if (quantity == "0")
             markLine(position, type)


         //enviar mensaje a salix
         val ticket =
             "[" + sales[position].ticketFk + "](https://salix.verdnatura.es/#!/ticket/" + sales[position].ticketFk + "/summary)"
         val message =
             "Se ha enviado a Faltas la cantidad de " + totalQuantity + getString(R.string.fromItem) + sales[position].itemFk + "  ticket " + ticket
         viewModel.sendChekingPresence(
             token = token,
             workerId = sales[position].salePersonFk,
             message = message, "sendChekingPresence"
         )
     }

     private fun missing(position: Int, quantity: String) {
         var totalQuantity: Int = 0
         try {
             totalQuantity = sales[position].quantity.toInt() - quantity.toInt()
         } catch (e: Exception) {
         }
         viewModel.collectionMissingTrash(
             usuario = user,
             password = password,
             saleFk = sales[position].saleFk,
             quantity = totalQuantity.toString(),
             warehouseFk = warehouseFk,
             type = "TRUE",
             originalQuantity = quantity,
             callFunction = "collectionMissingTrash",
         )
         //sales[position].originalQuantity = quantity
         sales[position].quantity = quantity
         //sales[position].startQuantity = quantity

         if (quantity == "0")
             markLine(position, type)
         saleAdapter!!.notifyDataSetChanged()

         //enviar mensaje a salix
         val ticket =
             "[" + sales[position].ticketFk + "](https://salix.verdnatura.es/#!/ticket/" + sales[position].ticketFk + "/summary)"
         val message =
             "Se ha enviado a Basura " + totalQuantity + getString(R.string.fromItem) + sales[position].itemFk + "  ticket " + ticket
         viewModel.sendChekingPresence(
             token = token,
             workerId = sales[position].salePersonFk,
             message = message,
             "sendChekingPresence"
         )
     }

     private fun reject(position: Int, quantity: String) {
         positionReject = position
         quantityReject = quantity

         var totalQuantity: Int = 0
         try {
             totalQuantity = sales[position].quantity.toInt() - quantity.toInt()
         } catch (e: Exception) {
         }
         viewModel.collectionMissingTrash(
             usuario = user,
             password = password,
             saleFk = sales[position].saleFk,
             quantity = totalQuantity.toString(),
             warehouseFk = warehouseFk,
             type = "reject",
             originalQuantity = quantity
         )

         //sales[position].originalQuantity = quantity
         sales[position].quantity = quantity
         //sales[position].startQuantity = quantity


         saleAdapter!!.notifyDataSetChanged()
         if (quantity == "0")
             markLine(position, type)

         //enviar mensaje a salix
         /* val ticket =
              "[" + sales[position].ticketFk + "](https://salix.verdnatura.es/#!/ticket/" + sales[position].ticketFk + "/summary)"
          val message =
              "Se ha modificado la cantidad original " + sales[position].originalQuantity + " del artículo " + sales[position].itemFk + " a nueva cantidad: " + sales[position].quantity + " del ticket " + ticket
          viewModel.sendChekingPresence(
              token = token,
              workerId = sales[position].salePersonFk,
              message = message, "sendChekingPresence"
          )*/
     }*/

    private fun missingTrashSuccesful() {

        var message = ""

        sales[positionCollectionMissing].quantity = quantityCollectionMissing
        saleAdapter!!.notifyDataSetChanged()
        if (quantityCollectionMissing == "0")
            markLine(positionCollectionMissing, type)

        var totalQuantity: Int = 0
        try {
            totalQuantity =
                sales[positionCollectionMissing].originalQuantity.toInt() - quantityCollectionMissing.toInt()
        } catch (e: Exception) {
        }

        saleAdapter!!.notifyDataSetChanged()

        val ticket =
            "[" + sales[positionCollectionMissing].ticketFk + "](https://salix.verdnatura.es/#!/ticket/" + sales[positionCollectionMissing].ticketFk + "/summary)"


        when (typeCollectionMissing) {

            "TRUE" -> {
                message =
                    "Se ha enviado a Basura " + totalQuantity + getString(R.string.fromItem) + sales[positionCollectionMissing].itemFk + "  ticket " + ticket

            }
            "FALSE" -> {
                message =
                    "Se ha enviado a Faltas la cantidad de " + totalQuantity + getString(R.string.fromItem) + sales[positionCollectionMissing].itemFk + "  ticket " + ticket

            }
            "reject" -> {
                message =
                    "Se ha modificado la cantidad de  " + sales[positionCollectionMissing].originalQuantity + " del artículo " + sales[positionCollectionMissing].itemFk + " a nueva cantidad: " + sales[positionCollectionMissing].quantity + " del ticket " + ticket

            }
        }

        //sergio:ahora desde encajado
        // sendSalixMessageNew(message, sales[positionCollectionMissing].salePersonFk)

        binding.splashProgress.visibility = VISIBLE
        viewModel.collectionTicketGet(
            getData(USER),
            getData(PASSWORD),
            collection.collectionFk,
            getData(SECTORFK),
            type
        )

    }

    private fun incresaseSuccesful() {
        try {
            //val quantityPicked = (quantity.toInt() - sales[position].quantitytoInt()).toString()

            // sergio: se añade linea para que se actualice la originalQuantity
            //sales[positionIncreaseQuantity].originalQuantity = quantityIncrease

            sales[positionIncreaseQuantity].quantity = quantityIncrease

        } catch (e: Exception) {
        }
        saleAdapter?.notifyDataSetChanged()
        //enviar mensaje a salix

        val ticket =
            "[" + sales[positionIncreaseQuantity].ticketFk + "](https://salix.verdnatura.es/#!/ticket/" + sales[positionIncreaseQuantity].ticketFk + "/summary)"
        val message =
            "Se ha modificado la cantidad original " + sales[positionIncreaseQuantity].originalQuantity + " del artículo " + sales[positionIncreaseQuantity].itemFk + " a nueva cantidad: " + sales[positionIncreaseQuantity].quantity + " del ticket " + ticket


        //sergio: ahora desde encajadores
        // sendSalixMessageNew(message, sales[positionIncreaseQuantity].salePersonFk)

        sales[positionIncreaseQuantity].originalQuantity = quantityIncrease


    }


    private fun sendSalixMessageNew(message: String, workerId: String) {

        viewModel.sendChekingPresence(
            token = getData(TOKEN),
            workerId = workerId,
            message = message

        )
    }

    private fun increaseQuantity(position: Int, quantity: String) {
        positionIncreaseQuantity = position
        quantityIncrease = quantity

        /*  var working_in_test = true // sergio: en proves app

        if (!working_in_test) {
             viewModel.collectionIncreaseQuantity(
                 getData(USER),
                 getData(PASSWORD),
                 saleFk = sales[position].saleFk,
                 quantity = quantity, "collection_increaseQuantity"
             )

         } else {*/
        viewModel.collectionIncreaseQuantitySalix(
            getData(TOKEN),
            saleFk = sales[position].saleFk,
            quantity = quantity
        )
        /* }*/


    }

    //ESTADOS
    private fun changeTicketState() {
        if (type == CONTROLADOR) {
            tickets.forEach {
                viewModel.ticket_setState(
                    usuario = getData(USER),
                    password = getData(PASSWORD),
                    ticketFk = it,
                    state = "CHECKED"
                )
            }
        } else if (type == SACADOR) {
            tickets.forEach {
                viewModel.ticket_setState(
                    usuario = getData(USER),
                    password = getData(PASSWORD),
                    ticketFk = it,
                    state = "PREPARED"
                )
            }
////Refactor #4030

        } else if (type == PRECHECKER) {
            tickets.forEach {
                viewModel.ticket_setState(
                    usuario = getData(USER),
                    password = getData(PASSWORD),
                    ticketFk = it,
                    state = "PREVIOUS_CONTROLLED"
                )
            }
        }
    }

    /*  private fun changeInitTicketState() {
          if (type == CONTROLADOR) {
              tickets.forEach {
                  viewModel.collectionUpdateState(
                      getData(USER),
                      getData(PASSWORD),
                      collectionFk = it,
                      state = ON_CHECKING, "collection_updateState"
                  )
              }
          } else if (type == SACADOR) {
              tickets.forEach {
                  viewModel.collectionUpdateState(
                      getData(USER),
                      getData(PASSWORD),
                      collectionFk = it,
                      state = ON_PREPARATION, "collection_updateState"
                  )
              }
          }
      }*/

    //OTROS
    private fun showScanner(index: Int, sale: SaleVO) {

        //Timber.d("VERDNATURA-Entrant en el show scanner al punxar sobre la sale")
        customDialogInput.setTitle("" + sale.itemFk)
            .setDescription(getString(R.string.scanWagonForItem))
            .setOkButton(getString(R.string.accept)) {
                if (!customDialogInput.getValue().isNullOrEmpty()) {
                    findSale(customDialogInput.getValue(), index)
                }
                customDialogInput.setValue("")
                scanRequest()
                customDialogInput.dismiss()
                hideKeyboards()
            }.setKoButton(getString(R.string.cancel)) {
                customDialogInput.dismiss()
            }.setValue("").show()
        customDialogInput.getEditText().requestFocus()
        customDialogInput.getEditText().setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0) {
                if (!customDialogInput.getValue().isNullOrEmpty()) {
                    findSale(customDialogInput.getValue(), index)
                }
                customDialogInput.setValue("")
                scanRequest()
                customDialogInput.dismiss()
                hideKeyboards()
                return@setOnEditorActionListener true
            }
            false
        }

    }

    private fun showErrorMessage(text: String) {
        customDialog.setTitle(getString(R.string.errorMarkLine)).setDescription(text)
            .setKoButton(getString(R.string.close)) {
                customDialog.dismiss()
            }.show()
    }

    private fun showMistakeList(list: List<MistakeTypeVO>) {
        binding.splashProgress.visibility = GONE
        listPlacementSupply = ArrayList()
        list.forEach {
            listPlacementSupply.add(BarcodeVO(code = it.description))
        }


        customDialogList.setTitle(getString(R.string.errorCause))
            .setKoButton(getString(R.string.cancel)) {
                scanRequest()
                hideKeyboards()
                customDialogList.dismiss()
            }.hideDialog().show()


        placementSupplyAdapter =
            BarcodeAdapter(listPlacementSupply, object : OnBarcodeRowClickListener {
                override fun onBarcodeRowClickListener(item: BarcodeVO) {
                    list.forEach {
                        if (it.description == item.code) {
                            viewModel.saleMistakeAdd(
                                usuario = getData(USER),
                                password = getData(PASSWORD),
                                vSaleFk = mistakeSale?.saleFk!!,
                                vUserFk = mistakeSale?.workerFk!!,
                                vTypeFk = it.id
                            )


                            getString(R.string.errorRegistered).toast(requireContext())
                            customDialogList.dismiss()
                        }
                    }

                }
            }, showDelete = false)

        customDialogList.getRecyclerView().adapter = placementSupplyAdapter

        customDialogList.getRecyclerView().layoutManager =
            LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
    }

    fun isNumber(num: String): Boolean {
        var numberInt = 0
        try {
            numberInt = num.toInt()
            return true
        } catch (e: Exception) {
            return false
        }
    }

    //VOZ
    override fun onResults(results: Bundle) {
        super.onResults(results)
        //Log.i("Speech", "onResults")
        val matches = results
            .getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)
        if (matches != null) {
            //Log.i("RESPUESTA", matches[0])
            mIsListening = false
            mSpeechRecognizer!!.cancel()
            getText(matches[0])
        }
    }

    private fun getText(text: String) {
        val pos = checkText(text)
        when (pos) {
            NEW_COLLECTION -> {

            }
            CANCEL -> {

            }
            LISTO -> {
                state += 1
                //speakOrder()
            }
            VOLVER -> {

            }
            REPITE -> {
                // speakOrder()
            }
            OTRO -> {
                //  speak("Orden no registrada")
            }
            FALTA -> {
                // speak("Orden no registrada")
            }
            //else -> speak("Orden no registrada")
        }
    }

    /*private fun speakOrder() {
        if (type == SACADOR) {
            if (state == 0) {
                //speak("Colección cargada.")
            } else {
                var index = 0
                for (sale in sales) {
                    if (sale.isPrepared == "0" && sale.isPreviousPrepared == "0" && sale.isControlled == "0") {
                        if (state == 1) {
                            //cantar pasillo
                            if (sale.placements.size > 0) {
                                var placementIndex = 0
                                for (placement in sale.placements) {
                                    var visible = placement.visible
                                    visible = visible.replace("(", "")
                                    visible = visible.replace(")", "")
                                    var quantityVisible = 0
                                    try {
                                        quantityVisible = visible.toInt()
                                    } catch (e: Exception) {
                                    }

                                    if (quantityVisible > 0) {
                                        val pasillo = placement.placement.subSequence(
                                            0,
                                            sale.placements[0].placement.indexOf("-")
                                        ).toString()
                                        val sector = placement.placement.subSequence(
                                            sale.placements[0].placement.indexOf("-") + 1,
                                            sale.placements[0].placement.length
                                        ).toString()
                                        var letras: ArrayList<Char> = ArrayList()
                                        val carro = placement.shelving
                                        var carroSeparate: StringBuilder = StringBuilder("")
                                        for (l in carro) {
                                            carroSeparate.append(l)
                                            carroSeparate.append(" ")
                                        }


                                        placementPicked = placement
                                        storedShelvingPosition = placementIndex

                                        if (lastPlacementPicked == null || lastPlacementPicked!!.placement != placement.placement) {
                                            lastPlacementPicked = placement
                                            try {
                                               // speak("Pasillo " + pasillo.toInt() + ", Sector " + sector.toInt() + ",  " + carroSeparate.toString())
                                            } catch (e: Exception) {
                                               // speak("Pasillo " + pasillo + " Sector " + sector + " Carro " + carro)
                                            }
                                        } else if (lastPlacementPicked != null && lastPlacementPicked!!.shelving != placement.shelving) {
                                           // speak(" Carro " + carro)
                                        } else {
                                            state = 2
                                            speakOrder()
                                        }

                                        break
                                    }

                                    placementIndex += 1
                                }

                            } else {
                               // speak("El item " + sale.itemFk + " no se encuentra disponible. Se necesita actuación manual.")
                            }

                        } else if (state == 2) {
                            //cantar articulo
                            try {
                                val item = sale.itemFk
                                val cantidad =
                                    sale.quantity.toInt() - sale.pickedQuantity.toInt()
                                val listtext = sale.longName.split(" ")
                                var nombre: String
                                if (listtext.isNotEmpty()) {
                                    nombre = listtext.get(0) + " " + sale.color
                                } else {
                                    nombre = sale.longName + " " + sale.color
                                }

                                //speak("Item " + item.toInt() + " " + nombre + " , Cantidad: " + cantidad)
                            } catch (e: Exception) {
                                //speak("Se necesita actuación manual")
                            }
                        } else if (state == 3) {
                            //marcar linea
                            var visible = placementPicked!!.visible
                            visible = visible.replace("(", "")
                            visible = visible.replace(")", "")
                            var quantityVisible = 0
                            try {
                                quantityVisible = visible.toInt()
                            } catch (e: Exception) {
                            }

                            var needPicked = 0
                            try {
                                needPicked = sale.quantity.toInt() - sale.pickedQuantity.toInt()
                            } catch (e: Exception) {
                            }

                            storedPosition = index
                            if (quantityVisible < needPicked) {
                                onQuantityOfShelvingSelected(
                                    itemShelvingFk = placementPicked!!.shelving,
                                    quantity = quantityVisible.toString()
                                )
                            } else {
                                onQuantityOfShelvingSelected(
                                    itemShelvingFk = placementPicked!!.shelving,
                                    quantity = needPicked.toString()
                                )
                            }

                            state = 0
                            //speak("Acción registrada. Diga listo para continuar")
                           // speak("Registrada")

                        }

                        break

                    }

                    index += 1
                }

                if (index >= sales.size) {
                    //speak("Colección completada.")
                }
            }
        }
    }*/

    override fun onDestroy() {
        cancelSpeech()
        super.onDestroy()
    }

}
