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.KeyEvent
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.annotation.RequiresApi
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.toInt
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.CollectionVO
import es.verdnatura.presentation.view.feature.sacador.model.PlacementSupplyListVO
import es.verdnatura.presentation.view.feature.sacador.model.SaleVO

@Suppress("UNUSED_ANONYMOUS_PARAMETER")
class EndSacadorFragment(
    var collection: CollectionVO = CollectionVO(0),
    var type: String = ""
) :
    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: Int = 0
    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: Int = 0
    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 = ""
    private var positionUnmarked = -1

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

    private var typeCollectionMissing = ""
    private var positionCollectionMissing = 0
    private var quantityCollectionMissing = 0
    private var positionIncreaseQuantity = 0
    private var quantityIncrease = 0
    private var quantityCollectionSplit = 0
    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 = ""
    private var isScanned: Boolean? = null


    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()
        searchSaleCollection()
        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 {
                        //if (binding.scanInput.text.length > 6){
                        // 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.toInt())
                        } else {
                            //es sale
                            findSale(binding.scanInput.text.toString())
                        }
                    }


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

        hideKeyboards()

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

            sales.clear()
            saleAdapter!!.notifyDataSetChanged()
            searchSaleCollection()
            binding.collectionSwipe.isRefreshing = false
        }
    }

    @RequiresApi(Build.VERSION_CODES.O)
    override fun observeViewModel() {
        with(viewModel) {
            salesList.observe(viewLifecycleOwner, Observer {
                binding.splashProgress.visibility = GONE
                //d("VERDNATURA::","la lista es {$it}")
                createSaleList(it)
            })

            responseItemShelvingUpdate.observe(viewLifecycleOwner, Observer {

                if (!goBack) {
                    if (it.isError) {

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

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

                        goBack = false
                    }

                }
            })

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

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

                    }
                }
                goBack = false
            })


            responseIncQuantity.observe(viewLifecycleOwner, Observer {

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


            responseParkingAdd.observe(viewLifecycleOwner, Observer {
                binding.splashProgress.visibility = GONE
                if (it.isError) {
                    ma.messageWithSound(it.errorMessage, true, false)

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

                }


            })

            responseSplit.observe(viewLifecycleOwner, Observer {
                binding.splashProgress.visibility = GONE
                if (!goBack) {
                    if (it.isError) {
                        ma.messageWithSound(it.errorMessage, isError = true, true)


                    } else {
                       // responseSaleMoveSuccesful()
                        ma.messageWithSound(getString(R.string.splitOk), isError = false, true)
                        setTotalLines()
                    }
                    goBack = false
                }
            })


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

                if (!goBack) {
                    if (it.isError) {
                        ma.messageWithSound(
                            getString(R.string.errorTicketAdd) + it.errorMessage,
                            isError = true,
                            true,
                            isToasted = true
                        )

                    } else {
                        viewModel.sectorCollection_getSale(
                            collection.collectionFk,
                            getDataInt(SECTORFK)
                        )
                    }
                }
            })

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

                if (!goBack) {
                    if (it.isError) {
                        ma.messageWithSound(
                            getString(R.string.errorChangeState) + it.errorMessage,
                            isError = true,
                            true
                        )

                    } else {
                        ma.messageWithSound(getString(R.string.previousOK), isError = false, false)

                    }
                }
                goBack = false
            })
            response.observe(viewLifecycleOwner, Observer {
                binding.splashProgress.visibility = GONE

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

                    } else {
                        ma.messageWithSound(getString(R.string.previousOK), isError = false, false)

                    }
                }
                goBack = false
            })
            responseSaleupdateIsChecked.observe(viewLifecycleOwner, Observer {
                binding.splashProgress.visibility = GONE


                if (!goBack) {
                    if (it.isError) {
                        ma.messageWithSound(
                            getString(R.string.errorChangeState) + it.errorMessage,
                            isError = true,
                            true
                        )

                    } else {
                        if (positionUnmarked != -1) {

                            searchSaleCollection()
                            saleAdapter!!.notifyDataSetChanged()
                            positionUnmarked = -1
                        }

                    }
                }
                goBack = false

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

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

            })

            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(getString(R.string.lineNotExist))
                            if (mperror != null) {
                                mperror?.start()
                            }
                        }
                    }
                }

                goBack2 = false

            })
        }
    }

    private fun responseSaleMoveSuccesful() {

        //Timber.d("responseSaleMove succesful")
        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 =
            getString(R.string.modifiedQuantityPrevious) + sales[positionIncreaseQuantity].quantity + getString(
                R.string.fromItem
            ) + sales[positionIncreaseQuantity].itemFk + getString(R.string.toNewQuantity) + quantityIncrease + getString(
                R.string.fromTicket
            ) + ticket



        sendSalixMessageNew(message, sales[positionIncreaseQuantity].salesPersonFk)*/
        searchSaleCollection()

    }

    //CREATE LIST

    private fun searchSaleCollection() {
        binding.splashProgress.visibility = VISIBLE
        viewModel.sectorCollection_getSale(
            collection.collectionFk,
            vSectorFk = getDataInt(SECTORFK)
        )
    }

    private fun searchTicket(ticketFk: Int) {
        //Log.i(TAG, "Escaneamos ticket en previa" + ticketFk)
        ticket = ticketFk

        if (ticketFk != 0)
            binding.splashProgress.visibility = VISIBLE
        viewModel.sectorCollectionSaleGroup_add(
            ticketFk,
            collection.collectionFk
        )
    }

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

            ma.messageWithSound(
                getString(R.string.scanTicketsForAdd),
                false,
                false,
                getString(R.string.titlePrePicker), isToasted = true
            )

        } else {
            if (ticket == 0) {
                binding.mainToolbar.toolbarTitle.text = collection.collectionFk.toString()
            }
            sales = ArrayList()

            salesList.forEach {
                sales.add(it)
            }

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

            for (s in sales) {

                //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.carros = s.carros.sortedWith(compareBy{it.pickingOrder}).sortedWith(
                        compareByDescending{it.priority})*/
                    s.pickingOrder = s.carros.get(0).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
        }
        if (ticket == 0) {
            binding.mainToolbar.toolbarTitle.text = collection.collectionFk.toString()
        }

        binding.mainToolbar.toolbarSubtitle.text = "" + totalMark + "/" + sales.size
        if (totalMark == sales.size) {
            getString(R.string.ticketCompleted).toast(this.context, Toast.LENGTH_SHORT)

            saleTracking_addPrevOK()

        }

    }

    private fun saleTracking_addPrevOK() {

        binding.splashProgress.visibility = VISIBLE
        viewModel.saleTracking_addPrevOK(
            vSectorCollectionFk = collection.collectionFk
        )


    }

    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

        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) {


        if (sales[position].picked == sales[position].quantity || sales[position].picked == 0) {

            viewModel.saleTracking_updateIsChecked(
                vSaleFk = sales[position].idMovimiento.toInt(),
                vIsChecked = sales[position].picked == sales[position].quantity,
                vIsScanned = isScanned

            )
        }
       /* if (sales[position].picked == 0) {
            viewModel.saleTracking_updateIsChecked(
                vSaleFk = sales[position].idMovimiento.toInt(),
                vIsChecked = sales[position].picked == sales[position].quantity

            )
        }*/
        isScanned = null
    }

    private fun unMarkLine(position: Int) {

        if (sales[position].quantity == sales[position].picked) {
            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].picked = 0
                    saleAdapter!!.notifyDataSetChanged()
                    setListPosition(position)

                    viewModel.itemShelving_updateFromSale(
                        saleFk = sales[position].idMovimiento
                    )
                    positionUnmarked = position
                    //sergio: anterior previa
                    /* viewModel.saleTrackingDel(
                         usuario =getData(USER),
                         password = getData(PASSWORD),
                         saleFk = sales[position].idMovimiento, "saleTracking_del"
                     )*/
                    //sergio: previa se pone después itemshelving_update
                    //saleTrackingReplace(positionUnmarked)
                    //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].saldo!! - sales[position].picked!!)
        } catch (e: Exception) {
        }
        viewModel.itemPlacementSupplyAiming(
            itemFk = sales[position].itemFk,
            quantity = quantityGet,
            shelvingFk = sales[position].carros[shelvingPosition].shelving
        )
    }

    @RequiresApi(Build.VERSION_CODES.O)
    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)) {
                isScanned = false

                if (customDialogList.getValueTwo().isNotEmpty()) {
                    /*Tarea 5109*/
                    try {
                        customDialogList.setValueTwo(
                            itemScanValue(
                                customDialogList.getValueTwo(),
                                "buy",
                                "more"
                            ).toString()
                        )


                        if (checkItemScan(customDialogList.getValueTwo())) {
                            onQuantityOfShelvingSelected(itemShelvingFk)
                            mpok?.start()
                            customDialogList.dismiss()
                        } else {
                            itemShelvingFkStored = itemShelvingFk
                            binding.splashProgress.visibility = View.VISIBLE
                            viewModel.getIdFromCode(
                                code = customDialogList.getValueTwo()
                            )
                            customDialogList.dismiss()
                        }
                    } catch (Ex: Exception) {
                        ma.messageWithSound(Ex.message.toString(), true, true)
                    }
                    scanRequest()
                    hideKeyboards()

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


        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) {
                try {
                    isScanned = event != null && event.action == KeyEvent.ACTION_DOWN && event.keyCode == KeyEvent.KEYCODE_ENTER

                    customDialogList.setValueTwo(
                        itemScanValue(
                            customDialogList.getValueTwo(),
                            "buy",
                            "id"
                        ).toString()
                    )
                    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(
                                code = customDialogList.getValueTwo()
                            )
                            customDialogList.dismiss()
                        }
                    } else {
                        getString(R.string.scanItemValidate).toast(requireContext())
                    }
                } catch (Ex: Exception) {
                    ma.messageWithSound(Ex.message.toString(), true, true)

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

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


            //sergio: se añade línea que actualiza la pantalla. Es posible que falle
            // el itemShelvingSaleSupplyAdd que se actualiza pantalla si falla se actualizará todo

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


            viewModel.itemShelvingSaleSupplyAdd(
                itemShelvingFk = itemShelvingFk,
                saleFk = sales[storedPosition].idMovimiento,
                quantity = customDialogList.getValue().toInt()
            )

        } 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.toDouble() == valueToCheck.toDouble()
    }

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

        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
        }

    }

    //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 = VISIBLE
        binding.mainToolbar.toolbarTitle.text = collection.collectionFk.toString()

        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) {


                    goBack = false
                    /*if (item == iconEraser) {

                    } else*/
                    when (item) {
                        iconParking.drawable -> pasillerosItemClickListener?.onPasillerosItemClickListener(
                            PasillerosItemVO(
                                title = getString(R.string.parking)
                            ), ""
                        )


                    }

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

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

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


    companion object {
        fun newInstance(collection: CollectionVO?, entrypoint: String) = EndSacadorFragment(
            collection!!, entrypoint
        )
    }

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

    override fun onResume() {
        goBack = false
        super.onResume()
    }

    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) {
        try {
            customDialogThreeButtons.setDescription(getString(R.string.txtnuevacantidad))
                .setValue("")
                /* .setOkButton(getString(R.string.titleFaults)) {
                     checkAndCall(
                         position,
                         customDialogThreeButtons.getValue().toInt(),
                         getString(R.string.titleFaults)
                     )

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

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

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

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

 */
                .setOkButtonAdd(getString(R.string.Agregar)) {
                    increaseQuantity(position, customDialogThreeButtons.getValue().toInt())
                    scanRequest()
                    customDialogThreeButtons.dismiss()

                    /*   checkAndCall(
                           position,
                           customDialogThreeButtons.getValue().toInt(),
                           getString(R.string.Agregar)
                       )*/

                }.setKoButton(getString(R.string.cancel)) {
                    scanRequest()
                    customDialogThreeButtons.dismiss()
                }.show()
            customDialogThreeButtons.setFocusDialogValue()
        } catch (ex: Exception) {
            getString(R.string.errorQuantity).toast(context)
        }
    }


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

        viewModel.collectionIncreaseQuantity(
            saleFk = sales[position].idMovimiento,
            quantity = quantity
        )


    }

}
