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

import android.content.Context
import android.graphics.drawable.Drawable
import android.media.MediaPlayer
import android.os.Build
import android.os.Bundle
import android.view.View
import android.view.View.GONE
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.ImageView
import android.widget.Toast
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import es.verdnatura.R
import es.verdnatura.databinding.FragmentPreSacadorBinding
import es.verdnatura.domain.ConstAndValues.PRESACADOR
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.main.activity.MainActivity
import es.verdnatura.presentation.view.feature.pasillero.model.PasillerosItemVO
import es.verdnatura.presentation.view.feature.presacador.adapter.PreSacadorAdapter
import es.verdnatura.presentation.view.feature.presacador.model.PreSacadorItemVO
import es.verdnatura.presentation.view.feature.sacador.model.PlacementSupplyListVO
import es.verdnatura.presentation.view.feature.sacador.model.SaleVO


@Suppress("UNUSED_ANONYMOUS_PARAMETER")
class PreSacadorFragment :
    BaseFragment<FragmentPreSacadorBinding, PreSacadorViewModel>(PreSacadorViewModel::class) {
    var mperror: MediaPlayer? = null
    var mpok: MediaPlayer? = null

    //private var sales: ArrayList<PreSacadorItemVO> = ArrayList()
    private lateinit var sales: MutableList<PreSacadorItemVO>
    private lateinit var customDialog: CustomDialog
    private lateinit var customDialogList: CustomDialogList
    private var saleAdapter: PreSacadorAdapter? = null
    private var ticket: String = ""
    private var lm: LinearLayoutManager? = null
    private var pasillerosItemClickListener: OnPasillerosItemClickListener? = null
    private var storedPosition: Int = 0
    private var storedBackPosition: Int = 0
    private var storedShelvingPosition: Int = 0
    private var itemShelvingFkStored: String = ""
    private var goBack: Boolean = false
    private var goBack2: Boolean = false
    private var listPlacementSupply: ArrayList<BarcodeVO> = ArrayList()
    private var placementSupplyAdapter: BarcodeAdapter? = null
    private lateinit var customDialogInputParking: CustomDialogInput
    private lateinit var customDialogInput: CustomDialogInput
    private lateinit var customDialogThreeButtons: CustomDialogThreeButtons
    private var ticketFk = ""
    private var originalScanned = ""

    fun changevariables() {
        TODO("Refactor llevar variables i deixar soles una com positionToChange i quantityToChange")
    }

    private var typeCollectionMissing = ""
    private var positionCollectionMissing = 0
    private var quantityCollectionMissing = ""
    private var positionIncreaseQuantity = 0
    private var quantityIncrease = ""
    private var quantityCollectionSplit = ""
    private var positionCollectionSplit = 0

    // private val listIcons:ArrayList<ImageView> = ArrayList()

    //sergio: se añada para leer el articulo leido que era el buyFk
    private var originalItemScan: String = ""

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

    override fun onCreate(savedInstanceState: Bundle?) {

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

        super.onCreate(savedInstanceState)
    }


    override fun init() {
        customDialog = CustomDialog(requireContext())
        customDialogList = CustomDialogList(requireContext())
        customDialogInput = CustomDialogInput(requireContext())
        customDialogInputParking = CustomDialogInput(requireContext())
        customDialogThreeButtons = CustomDialogThreeButtons(requireContext())
        binding.splashProgress.visibility = GONE
        binding.mainToolbar.toolbarTitle.text = getString(R.string.getticketpre)
        setToolBar()
        setEvents()


        super.init()
    }

    private fun setEvents() {
        binding.mainToolbar.backButton.setOnClickListener {
            requireActivity().onBackPressed()

        }
        //ESCANER =========
        hideKeyboards()
        binding.scanInput.requestFocus()
        binding.scanInput.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0 || actionId == 5) {

                if (!binding.scanInput.text.toString().isNullOrEmpty()) {

                    // originalScanned=binding.scanInput.text

                    if (binding.scanInput.text.contains("-")) {

                        //es parking
                        pasillerosItemClickListener?.onPasillerosItemClickListener(
                            PasillerosItemVO(
                                title = getString(R.string.Parking)
                            ), ""
                        )
                        // parkingTicket(binding.scanInput.text.toString())
                    } else {
                        // miramos si el primer digito es un numero de esta manera sabemos que no es una matrícula que sería el findsale
                        if (binding.scanInput.text.first().isDigit()) {
                            //es ticket
                            ticketFk = binding.scanInput.text.toString()
                            searchTicket(binding.scanInput.text.toString())
                        } else {
                            //es sale
                            findSale(binding.scanInput.text.toString())
                        }
                    }


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

        hideKeyboards()

        //LISTA =========
        binding.collectionSwipe.setOnRefreshListener {
            binding.splashProgress.visibility = View.VISIBLE
            searchTicket(ticket)
            binding.collectionSwipe.isRefreshing = false
        }
    }

    override fun observeViewModel() {
        with(viewModel) {
            salesList.observe(viewLifecycleOwner, Observer {
                binding.splashProgress.visibility = GONE
                createSaleList(it)
            })

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

            responseSalixMessage.observe(viewLifecycleOwner, Observer {
                if (it.isError) {
                    ma.messageWithSound(
                        getString(R.string.rocketKO) + it.errorMessage,
                        it.isError,
                        false
                    )

                }
            })

            responseIncQuantity.observe(viewLifecycleOwner, Observer {

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

            })


            responseParkingAdd.observe(viewLifecycleOwner, Observer {
                binding.splashProgress.visibility = GONE
                if (it.isError) {
                    ma.messageWithSound(it.errorMessage, true, false)
                    /* customDialog.setTitle(getString(R.string.error)).setDescription(it.errorMessage)
                         .setOkButton(getString(R.string.accept)) {
                             customDialog.dismiss()
                         }.show()*/
                } else {
                    if (mpok != null) mpok!!.start()
                    getString(R.string.saleParked).toast(requireContext())
                }
            })

            responseSaleTrackingUpdate.observe(viewLifecycleOwner, Observer {

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

                try {
                    sales.clear()
                } catch (e: Exception) {

                }


            })

            responseSaleMove.observe(viewLifecycleOwner, Observer {

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

                } else {
                    responseSaleMoveSuccesful()
                }

            })
            responseMissingTrash.observe(viewLifecycleOwner, Observer {

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

                } else {
                    missingTrashSuccesful()
                }
            })

            responseCode.observe(viewLifecycleOwner, Observer {
                binding.splashProgress.visibility = 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 {
                            customDialogList.setValueTwo("")
                            //showErrorMessage("El resultado del procedimiento barcodeToItem de la etiqueta escaneada es: " +it.response)
                            showErrorMessage(getString(R.string.lineNotExists))
                            if (mperror != null) {
                                mperror?.start()
                            }
                        }
                    }
                }

                goBack2 = false

            })
        }
    }

    private fun responseSaleMoveSuccesful() {
        try {
            sales[positionCollectionSplit].saldo = quantityCollectionSplit.toInt()
        } catch (e: Exception) {
            sales[positionCollectionSplit].saldo = 0
        }
        //sales[position].startQuantity = quantity

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


        //enviar mensaje a salix
        val ticket =
            "[" + sales[positionCollectionSplit].id + "](https://salix.verdnatura.es/#!/ticket/" + sales[positionCollectionSplit].id + "/summary)"
        val message =
            getString(R.string.splitSent) + sales[positionCollectionSplit].itemFk + " getString(R.string.fromTicket) " + ticket
        /*  viewModel.sendChekingPresence(
              token = getData(TOKEN),
              workerId = sales[positionCollectionSplit].salesPersonFk,
              message = message,
              "sendChekingPresence"
          )*/
        sendSalixMessageNew(message, sales[positionCollectionSplit].salesPersonFk)

    }


    private fun incresaseSuccesful() {


        try {
            sales[positionIncreaseQuantity].saldo = quantityIncrease.toInt()
        } catch (e: Exception) {
            sales[positionIncreaseQuantity].saldo = 0
        }

        saleAdapter?.notifyDataSetChanged()

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

        sendSalixMessageNew(message, sales[positionIncreaseQuantity].salesPersonFk)
    }


    private fun missingTrashSuccesful() {

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


        try {
            sales[positionCollectionMissing].saldo = quantityCollectionMissing.toInt()
        } catch (e: Exception) {
            sales[positionCollectionMissing].saldo = 0
        }

        if (quantityCollectionMissing == "0")
            markLine(positionCollectionMissing)




        saleAdapter!!.notifyDataSetChanged()


        var message = ""

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

        when (typeCollectionMissing) {

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


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


            "reject" -> {
                var quantityOriginal = totalQuantity.toInt() + quantityCollectionMissing.toInt()
                message =
                    "Se ha modificado desde previa la cantidad de  " + quantityOriginal + " del artículo " + sales[positionCollectionMissing].itemFk + " a nueva cantidad: " + quantityCollectionMissing + " del ticket " + ticket

            }
        }

        //sendSalixMessageNew(message, sales[positionCollectionMissing].trabajador)
        sendSalixMessageNew(message, sales[positionCollectionMissing].salesPersonFk)


    }

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

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

    //CREATE LIST
    private fun searchTicket(ticketFk: String) {
        //Log.i(TAG, "Escaneamos ticket en previa")
        ticket = ticketFk
        binding.splashProgress.visibility = View.VISIBLE

        //Timber.d("ticket:" + ticket)
        viewModel.ticketToPrePrepare(
            usuario = getData(USER),
            getData(PASSWORD),
            ticketFk = ticketFk,
            sectorFk = getData(SECTORFK)
        )
    }

    private fun createSaleList(salesList: List<PreSacadorItemVO>) {
        binding.splashProgress.visibility = GONE
        if (salesList.isNullOrEmpty()) {

            ma.messageWithSound(
                "No hemos podido obtener movimientos para el ticket escaneado",
                true,
                false,
                "Pre Sacador"
            )

            /*  customDialog.setTitle("Pre Sacador")
                  .setDescription("No hemos podido obtener movimientos para el ticket escaneado")
                  .setKoButton(getString(R.string.cancel)) {
                      customDialog.dismiss()
                  }.show()*/
        } else {
            binding.mainToolbar.toolbarTitle.text = ticket
            sales = ArrayList()

            salesList.forEach {
                sales.add(it)
            }

            //sergio: se tiene que ordenar por el pickingOrder del primer carro (Pako)

            for (s in sales) {
                // Log.d("VERDNATURA::","sales "+s.longName)
                // Log.d("VERDNATURA::","sales "+s.salesPersonFk)
                //sergio: para que no de error si no hay carros. Ya está asignado a 0 el pickingorder si no hay item en el carro
                if (!s.carros.isNullOrEmpty()) {
                    s.pickingOrder = s.carros.get(0).pickingOrder
                }
            }


           // var sortedSales = sales.sortedBy { it.pickingOrder }

            //sergio: Se ordena las sales por ellas mismas con With 
            sales.sortWith(compareBy({ it.pickingOrder }))

            lm = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)

            saleAdapter = PreSacadorAdapter(
                sales,
                pasillerosItemClickListener!!,
                object : OnQuantityClickListener {
                    override fun onQuantityClick(sale: SaleVO) {
                        sales.forEachIndexed { index, saleVO ->
                            if (saleVO.idMovimiento == sale.saleFk) {
                                showQuantityDialog(index)
                            }
                        }
                    }

                },
                object :
                    OnSaleClickListener {
                    override fun onSaleClick(sale: SaleVO) {
                        //sales.forEachIndexed { index, saleVO ->
                        sales.forEachIndexed { index, saleVO ->
                            if (saleVO.idMovimiento == sale.saleFk) {
                                if (saleVO.quantity != saleVO.picked) {
                                    showScanner(index, saleVO)
                                } else {
                                    unMarkLine(index)
                                }
                            }
                        }
                    }
                })
            binding.fragmentSacadorCollections.adapter = saleAdapter
            binding.fragmentSacadorCollections.layoutManager = lm

            setTotalLines()
            if (storedPosition != 0)
                setListPosition(storedPosition)
            else if (storedBackPosition != 0)
                setListPosition(storedBackPosition)

            setScrollListener(lm!!)
        }
    }

    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 setTotalLines() {
        var totalMark = 0
        sales.forEach {
            if (it.saldo == it.picked)
                totalMark += 1
        }
        binding.mainToolbar.toolbarTitle.text = ticket
        binding.mainToolbar.toolbarSubtitle.text = "" + totalMark + "/" + sales.size
        if (totalMark == sales.size) {
            getString(R.string.ticketCompleted).toast(this.context, Toast.LENGTH_SHORT)
        }

    }

    private fun setListPosition(position: Int) {
        storedPosition = position

        binding.fragmentSacadorCollections.addViewObserver {
            lm!!.scrollToPositionWithOffset(position, 0)

        }

    }

    //SEARCH AND MARK
    private fun findSale(txtscan: String) {
        var index = 0
        var isBreak = false
        var isOk = false
        //Timber.tag("VERDNATURA::").d("Entramos a buscar")
        for (saleVO in sales) {
            //Timber.tag("VERDNATURA::").d("El item buscado es " + saleVO.itemFk)
            if (saleVO.quantity != saleVO.picked) {
                //1- Por carro
                var shelvingIndex = 0
                for (placementVO in saleVO.carros) {
                    //Timber.tag("VERDNATURA::").d("La matric " + placementVO.shelving)
                    if (txtscan.uppercase() == placementVO.shelving.uppercase()) {
                        if (mpok != null) mpok!!.start()
                        isOk = true
                        showShelving(index, shelvingIndex)
                        isBreak = true
                        break
                    }
                    shelvingIndex += 1
                }
                if (isBreak) break
            }
            index += 1
        }

        if (!isOk) {
            if (mperror != null) {
                mperror!!.start()
            }
            ("getString(R.string.itemScanetNotFound)" + txtscan).toast(requireContext())
        }

    }

    private fun findSale(txtscan: String, position: Int) {
        var index = 0
        var isBreak = false
        var isOk = false

        val saleVO = sales[position]

        if (saleVO.quantity != saleVO.picked) {
            //1- Por carro
            var shelvingIndex = 0
            for (placementVO in saleVO.carros) {
                if (txtscan.uppercase() == placementVO.shelving.uppercase()) {
                    if (mpok != null) mpok!!.start()
                    isOk = true
                    showShelving(position, shelvingIndex)
                    isBreak = true
                    break
                }
                shelvingIndex += 1
            }
        }
        index += 1


        if (!isOk) {
            if (mperror != null) {
                mperror!!.start()
            }
            ("getString(R.string.itemScanetNotFound)" + txtscan).toast(requireContext())
        }

    }

    private fun markLine(position: Int) {

        saleAdapter!!.notifyDataSetChanged()
        setListPosition(position)
        saleTrackingReplace(position)
        setTotalLines()
    }


    private fun saleTrackingReplace(position: Int) {
        viewModel.saleTrackingReplace(
            usuario = getData(USER),
            password = getData(PASSWORD),
            saleFk = sales[position].idMovimiento,
            vIsChecked = if (sales[position].picked == sales[position].quantity) "1" else "0",
            vOriginalQuantity = sales[position].picked.toString(),
            vStateFk = PRESACADOR,
            vBuyFk = originalItemScan

        )

        viewModel.saleTrackingReplace(
            usuario = getData(USER),
            password = getData(PASSWORD),
            saleFk = sales[position].idMovimiento,
            vIsChecked = if (sales[position].picked == sales[position].quantity) "1" else "0",
            vOriginalQuantity = sales[position].picked.toString(),
            vStateFk = PRESACADOR,
            vBuyFk = originalItemScan

        )


    }

    private fun unMarkLine(position: Int) {

        if (sales[position].quantity == sales[position].picked) {
            customDialog.setTitle("Desmarcar linea")
                .setDescription("Vas a desmarcar la linea: " + sales[position].itemFk + " ¿Estás seguro?")
                .setOkButton("Desmarcar") {
                    sales[position].picked = 0
                    saleAdapter!!.notifyDataSetChanged()
                    setListPosition(position)

                    viewModel.saleTrackingDel(
                        usuario = getData(USER),
                        password = getData(PASSWORD),
                        saleFk = sales[position].idMovimiento
                    )
                    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 = View.VISIBLE
        var quantityGet = "0"
        try {
            quantityGet = (sales[position].saldo - sales[position].picked).toString()
        } catch (e: Exception) {
        }
        viewModel.itemPlacementSupplyAiming(
            usuario = getData(USER),
            password = getData(PASSWORD),
            itemFk = sales[position].itemFk,
            quantity = quantityGet,
            shelvingFk = sales[position].carros[shelvingPosition].shelving

        )
    }

    private fun printShelvingResult(placementSupplyListVO: PlacementSupplyListVO) {
        var shelving = ""
        var item = ""
        var longName = ""
        var total = "0"
        var itemShelvingFk = "0"
        if (!placementSupplyListVO.list.isEmpty()) {
            val placement = placementSupplyListVO.list[0]
            shelving = placement.shelving
            item = placement.itemFk
            longName = placement.longName
            total = placement.total
            itemShelvingFk = placement.itemShelvingFk
        }
        listPlacementSupply = ArrayList()
        placementSupplyListVO.list.forEach {
            listPlacementSupply.add(BarcodeVO(code = it.proposal))
        }

        customDialogList.setTitle("$shelving($item) $total del $longName")
            .setOkButton(getString(R.string.take)) {


                if (customDialogList.getValueTwo().isNotEmpty()) {


                    if (checkItemScan(customDialogList.getValueTwo())) {
                        onQuantityOfShelvingSelected(itemShelvingFk)
                        mpok?.start()
                        customDialogList.dismiss()
                    } else {
                        itemShelvingFkStored = itemShelvingFk
                        binding.splashProgress.visibility = View.VISIBLE


                        viewModel.getIdFromCode(
                            usuario = getData(USER),
                            password = getData(PASSWORD),
                            code = customDialogList.getValueTwo()
                        )

                        customDialogList.dismiss()
                    }
                    scanRequest()
                    hideKeyboards()
                } else {
                    "getString(R.string.scanItemValidate) validar".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()


        customDialogList.getEditTextTwo().post(Runnable {
            customDialogList.getEditTextTwo().requestFocusFromTouch()
            val lManager: InputMethodManager =
                requireActivity().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            lManager.hideSoftInputFromWindow(
                customDialogList.getEditTextTwo().windowToken,
                InputMethodManager.SHOW_FORCED
            )
        })

        customDialogList.getEditTextTwo().setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0 || actionId == 5) {


                originalItemScan = customDialogList.getValueTwo()
                ////Log.i("VERDNATURA:","el item original es $originalItemScan")

                if (customDialogList.getValueTwo().isNotEmpty()) {
                    if (checkItemScan(customDialogList.getValueTwo())) {
                        onQuantityOfShelvingSelected(itemShelvingFk)
                        mpok?.start()
                        customDialogList.dismiss()
                    } else {
                        itemShelvingFkStored = itemShelvingFk
                        binding.splashProgress.visibility = View.VISIBLE
                        viewModel.getIdFromCode(
                            usuario = getData(USER),
                            password = getData(PASSWORD),
                            code = customDialogList.getValueTwo()
                        )
                        customDialogList.dismiss()
                    }
                } else {
                    "getString(R.string.scanItemValidate) validar".toast(requireContext())
                }
                scanRequest()
                hideKeyboards()
                return@setOnEditorActionListener true

            }
            false
        }

        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 onQuantityOfShelvingSelected(itemShelvingFk: String) {
        //1 - MODIFICAR CANTIDAD DEL CARRO
        try {
            val shelvingVisible = sales[storedPosition].carros[storedShelvingPosition].stockTotal

            sales[storedPosition].carros[storedShelvingPosition].stockTotal =
                (shelvingVisible.toInt() - customDialogList.getValue().toInt()).toString()

            viewModel.itemShelvingSaleSupplyAdd(
                usuario = getData(USER),
                password = getData(PASSWORD),
                itemShelvingFk = itemShelvingFk,
                saleFk = sales[storedPosition].idMovimiento,
                quantity = customDialogList.getValue()
            )

        } catch (e: Exception) {
        }

        //2- MODIFICAR EL PICKED DEL SALE
        try {
            sales[storedPosition].picked =
                sales[storedPosition].picked + customDialogList.getValue().toInt()
        } catch (e: Exception) {
        }

        //3- MARCAR LINEA
        markLine(storedPosition)


    }

    private fun checkItemScan(valueToCheck: String): Boolean {
        val saleToCheck = sales[storedPosition]
        return saleToCheck.itemFk == valueToCheck
    }

    /*  private fun showScannerParking(ticket: String) {

          customDialogInputParking.setTitle("Parking").setDescription("Escanea el parking")
              .setOkButton(getString(R.string.accept)) {
                  if (!customDialogInputParking.getValue().isNullOrEmpty()) {
                      //findSale(customDialogInput.getValue(),index)
                      parkingTicket(ticket, customDialogInputParking.getValue())

                  }
                  customDialogInputParking.setValue("")
                  scanRequest()
                  customDialogInputParking.dismiss()
                  hideKeyboards()
              }.setKoButton(getString(R.string.cancel)) {
              customDialogInputParking.dismiss()
          }.setValue("").show()
          customDialogInputParking.getEditText().requestFocus()
          customDialogInputParking.getEditText().setOnEditorActionListener { v, actionId, event ->
              if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0) {
                  if (!customDialogInputParking.getValue().isNullOrEmpty()) {
                      parkingTicket(ticket, customDialogInputParking.getValue())
                  }
                  customDialogInputParking.setValue("")
                  scanRequest()
                  customDialogInputParking.dismiss()
                  hideKeyboards()
                  return@setOnEditorActionListener true
              }
              false
          }

      }*/

    /*private fun showScannerTicket() {

        customDialogInput.setTitle("Ticket a aparcar").setDescription("Escanea el ticket a aparcar")
            .setOkButton(getString(R.string.accept)) {
                if (!customDialogInput.getValue().isNullOrEmpty()) {
                    showScannerParking(customDialogInput.getValue())

                }
                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)
                    showScannerParking(customDialogInput.getValue())
                }
                customDialogInput.setValue("")
                scanRequest()
                customDialogInput.dismiss()
                hideKeyboards()
                return@setOnEditorActionListener true
            }
            false
        }

    }*/

    private fun showScanner(index: Int, sale: PreSacadorItemVO) {

        customDialogInput.setTitle("" + sale.itemFk)
            .setDescription("Escanea el carro para el item seleccionado")
            .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
        }

    }

    //OPTIONS
    private fun print() {
        /*  viewModel.collectionStickerPrint(
              usuario = user,
              password = password,
              collectionFk = ticket,
              sectorFk = sectorFk,"collectionSticker_print"
          )
          ////Log.i("VERDNATURA:","La collection es $ticket, sectorFk $sectorFk, user $user i pass $password")
          (getString(R.string.Imprimiendo) + SectorDescription).toast(requireContext())*/


    }

    //OTROS
    private fun setToolBar() {
        binding.mainToolbar.toolbarSubtitle.visibility = View.VISIBLE

        val listIcons: ArrayList<ImageView> = ArrayList()

        val iconParking = ImageView(context)
        iconParking.setImageResource(R.drawable.ic_local_parking_black_24dp)

        val iconEraser = ImageView(context)
        iconEraser.setImageResource(R.drawable.previous_delete)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            iconParking.tooltipText = getTooltip(R.drawable.ic_local_parking_black_24dp)
            iconEraser.tooltipText = getTooltip(R.drawable.previous_delete)

        }

        //listIcons.add(iconEraser)
        listIcons.add(iconParking)


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

                    when (item) {
                        iconParking.drawable -> pasillerosItemClickListener?.onPasillerosItemClickListener(
                            PasillerosItemVO(
                                title = "Parking"
                            ), ""
                        )

                    }

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

    private fun reviewSales() {

    }

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

    private fun hideKeyboards() {
        requireActivity().hideKeyboard()
    }


    companion object {
        fun newInstance() = PreSacadorFragment()
    }

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

    override fun onPause() {
        // goBack = true //SERGIO: se quita porque si no no entra la primera vez
        goBack2 = true
        super.onPause()
    }

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


    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 TrashMissingReject(
        position: Int,
        quantity: String,
        typeCollectionTrashMissingReject: String
    ) {
        typeCollectionMissing = typeCollectionTrashMissingReject
        positionCollectionMissing = position
        quantityCollectionMissing = quantity

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

        viewModel.collectionMissingTrash(
            usuario = getData(USER),
            password = getData(PASSWORD),
            saleFk = sales[position].idMovimiento,
            quantity = totalQuantity.toString(),
            warehouseFk = getData(WAREHOUSEFK),
            type = "FALSE",
            originalQuantity = quantity
        )

    }

    //FALTAS / BASURA / SPLIT
    private fun showQuantityDialogOld(position: Int) {
        customDialogThreeButtons.setDescription(getString(R.string.txtnuevacantidad)).setValue("")
            .setOkButton(getString(R.string.titleFaults)) {
                if (customDialogThreeButtons.getValue().trim().isNullOrEmpty()) {
                    getString(R.string.Indicanuevacantidad).toast(requireContext())
                } else {
                    trash(position, customDialogThreeButtons.getValue())
                    scanRequest()
                    customDialogThreeButtons.dismiss()
                }
            }.setOkButtonTwo(getString(R.string.BasuraRechazar)) {
                if (customDialogThreeButtons.getValue().trim().isNullOrEmpty()) {
                    getString(R.string.Indicanuevacantidad).toast(requireContext())
                } else {
                    missing(position, customDialogThreeButtons.getValue())
                    scanRequest()
                    customDialogThreeButtons.dismiss()
                }
            }.setOkButtonThree(getString(R.string.Reject)) {
                if (customDialogThreeButtons.getValue().trim().isNullOrEmpty()) {
                    getString(R.string.Indicanuevacantidad).toast(requireContext())
                } else {
                    reject(position, customDialogThreeButtons.getValue())
                    scanRequest()
                    customDialogThreeButtons.dismiss()
                }

            }.setOkButtonFour("Split") {
                if (customDialogThreeButtons.getValue().trim().isNullOrEmpty()) {
                    getString(R.string.Indicanuevacantidad).toast(requireContext())
                } else {
                    split(position, customDialogThreeButtons.getValue())
                    scanRequest()
                    customDialogThreeButtons.dismiss()
                }

            }.setOkButtonAdd(getString(R.string.Agregar)) {
                if (customDialogThreeButtons.getValue().trim().isNullOrEmpty()) {
                    getString(R.string.Indicanuevacantidad).toast(requireContext())
                } else {
                    increaseQuantity(position, customDialogThreeButtons.getValue())
                    scanRequest()
                    customDialogThreeButtons.dismiss()
                }
            }.setKoButton(getString(R.string.cancel)) {
                scanRequest()
                customDialogThreeButtons.dismiss()
            }.show()
    }

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

        positionCollectionSplit = position
        quantityCollectionSplit = quantity

        var totalQuantity: Int = 0
        try {
            totalQuantity = sales[position].saldo.toInt() - quantity.toInt()
        } catch (e: Exception) {
        }
        viewModel.saleMove(
            usuario = getData(USER),
            password = getData(PASSWORD),
            saleFk = sales[position].idMovimiento,
            quantity = totalQuantity.toString(),
            originalQuantity = sales[position].quantity.toString()
        )
        /*
         try {
             sales[position].saldo = quantity.toInt()
         } catch (e: Exception) {
             sales[position].saldo = 0
         }


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


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

    }

    private fun trash(position: Int, quantity: String) {
        var totalQuantity: Int = 0
        try {
            totalQuantity = sales[position].saldo.toInt() - quantity.toInt()
        } catch (e: Exception) {
        }
        viewModel.collectionMissingTrash(
            usuario = getData(USER),
            password = getData(PASSWORD),
            saleFk = sales[position].idMovimiento,
            quantity = totalQuantity.toString(),
            warehouseFk = getData(WAREHOUSEFK),
            type = "FALSE",
            originalQuantity = quantity
        )
        //sales[position].originalQuantity = quantity
        try {
            sales[position].saldo = quantity.toInt()
        } catch (e: Exception) {
            sales[position].saldo = 0
        }
        //sales[position].startQuantity = quantity
        saleAdapter!!.notifyDataSetChanged()
        if (quantity == "0")
            markLine(position)


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

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

        //sales[position].startQuantity = quantity

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


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

    private fun reject(position: Int, quantity: String) {
        var totalQuantity: Int = 0
        try {
            totalQuantity = sales[position].saldo.toInt() - quantity.toInt()
        } catch (e: Exception) {
        }
        viewModel.collectionMissingTrash(
            usuario = getData(USER),
            password = getData(PASSWORD),
            saleFk = sales[position].idMovimiento,
            quantity = totalQuantity.toString(),
            warehouseFk = getData(WAREHOUSEFK),
            type = "reject",
            originalQuantity = quantity
        )

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

        try {
            sales[position].saldo = quantity.toInt()
        } catch (e: Exception) {
            sales[position].saldo = 0
        }
        //sales[position].startQuantity = quantity
        saleAdapter!!.notifyDataSetChanged()
        if (quantity == "0")
            markLine(position)


    }

    private fun increaseQuantityOld(position: Int, quantity: String) {
        viewModel.collectionIncreaseQuantity(
            usuario = getData(USER),
            password = getData(PASSWORD),
            saleFk = sales[position].idMovimiento,
            quantity = quantity
        )
        try {

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

            //Log.d("VERDNATURA","el trabajador es "+sales[position].salesPersonFk)
            try {
                sales[position].saldo = quantity.toInt()
            } catch (e: Exception) {
                sales[position].saldo = 0
            }
        } catch (e: Exception) {
        }
        saleAdapter?.notifyDataSetChanged()


    }

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

        viewModel.collectionIncreaseQuantity(
            usuario = getData(USER),
            password = getData(PASSWORD),
            saleFk = sales[position].idMovimiento,
            quantity = quantity
        )


    }

}
