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

import android.app.AlertDialog
import android.content.Context
import android.graphics.drawable.Drawable
import android.media.MediaPlayer
import android.os.Build
import android.os.Bundle
import android.os.Parcelable
import android.text.InputType.TYPE_CLASS_NUMBER
import android.text.InputType.TYPE_CLASS_TEXT
import android.util.Log.d
import android.view.KeyEvent
import android.view.KeyEvent.ACTION_DOWN
import android.view.View.GONE
import android.view.View.VISIBLE
import android.view.WindowManager
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 com.google.gson.Gson
import es.verdnatura.R
import es.verdnatura.databinding.FragmentCollectionBinding
import es.verdnatura.domain.ConstAndValues.CONTROLADOR
import es.verdnatura.domain.ConstAndValues.OK
import es.verdnatura.domain.ConstAndValues.PRECHECKER
import es.verdnatura.domain.ConstAndValues.PRINTERNAME
import es.verdnatura.domain.ConstAndValues.SACADOR
import es.verdnatura.domain.ConstAndValues.SECTORDESCRIP
import es.verdnatura.domain.ConstAndValues.SECTORFK
import es.verdnatura.domain.notNull
import es.verdnatura.domain.toast
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.ItemScanned
import es.verdnatura.presentation.common.OnBarcodeRowClickListener
import es.verdnatura.presentation.common.OnMistakeClickListener
import es.verdnatura.presentation.common.OnOptionsSelectedListener
import es.verdnatura.presentation.common.OnPackingClickListener
import es.verdnatura.presentation.common.OnPasillerosItemClickListener
import es.verdnatura.presentation.common.OnQuantityClickListener
import es.verdnatura.presentation.common.OnSaleClickListener
import es.verdnatura.presentation.common.OnTicketClickListener
import es.verdnatura.presentation.common.ToolBarAdapterTooltip
import es.verdnatura.presentation.common.addViewObserver
import es.verdnatura.presentation.common.hideKeyboard
import es.verdnatura.presentation.common.itemScanIsQr
import es.verdnatura.presentation.common.itemScanValue
import es.verdnatura.presentation.common.showKeyboard
import es.verdnatura.presentation.common.showKeyboardIn
import es.verdnatura.presentation.view.component.CustomDialog
import es.verdnatura.presentation.view.component.CustomDialogInput
import es.verdnatura.presentation.view.component.CustomDialogList
import es.verdnatura.presentation.view.component.CustomDialogThreeButtons
import es.verdnatura.presentation.view.feature.articulo.adapter.BarcodeAdapter
import es.verdnatura.presentation.view.feature.articulo.model.BarcodeVO
import es.verdnatura.presentation.view.feature.collection.ItemVO
import es.verdnatura.presentation.view.feature.collection.adapter.SaleAdapter
import es.verdnatura.presentation.view.feature.main.activity.MainActivity
import es.verdnatura.presentation.view.feature.pasillero.model.PasillerosItemVO
import es.verdnatura.presentation.view.feature.sacador.model.CollectionVO
import es.verdnatura.presentation.view.feature.sacador.model.MistakeTypeVO
import es.verdnatura.presentation.view.feature.sacador.model.PlacementSupplyListVO
import es.verdnatura.presentation.view.feature.sacador.model.PlacementSupplyVO
import es.verdnatura.presentation.view.feature.sacador.model.PlacementVO
import es.verdnatura.presentation.view.feature.sacador.model.SaleVO
import org.json.JSONObject

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

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

    private var itemShelvingSaleSupplyAddCall = -1
    private var saleTrackingCall = -1
    private var lastScanned: Int = 0
    private var buttonPushedGetCollection = false
    private var positionUnmarked = -1
    private var state = 0
    private var mIsListening = false
    private var placementPicked: PlacementVO? = null
    private var lastPlacementPicked: PlacementVO? = null
    private var originalItemScan: Long = 0
    private var workerFkFromTicket: String? = null
    private var itemShelvingTracking_mark: Int = 0
    private var recylerViewState: Parcelable? = null
    private var isScanned: Boolean? = null
    private var canChangeState = true
    private var allTicketsChecked = false

    private lateinit var myGroupList: List<SaleVO>

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

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

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

    override fun onCreate(savedInstanceState: Bundle?) {

        mperror = MediaPlayer.create((activity as MainActivity), R.raw.error)
        mpok = MediaPlayer.create((activity as MainActivity), R.raw.ok)
        if (type.equals(CONTROLADOR)) {
            //sergio: comprueba si viene de la pantalla de controlador
            //Tarea #4280
            viewModel.ticketIsOutClosureZone(
                collection.collectionFk

            )
            viewModel.ticketState(collection.collectionFk)
            try {
                workerFkFromTicket = collection.tickets[0].sales[0].workerFk
            } catch (ex: Exception) {
                getString(R.string.ticketWithoutWorker).toast(requireContext())
            }

        }

        if (collection.tickets.isEmpty()) {
            viewModel.collectionTicketGet(
                collection.collectionFk,
                mobileApplication.dataStoreApp.readDataStoreKey(SECTORFK),
                print = "0",
                type
            )
        }
        super.onCreate(savedInstanceState)
    }

    override fun onResume() {
        super.onResume()
        scanRequest()
    }

    override fun init() {

        customDialogList = CustomDialogList(requireContext())
        customDialogInput = CustomDialogInput(requireContext())
        customDialog = CustomDialog(requireContext())
        customDialogThreeButtons = CustomDialogThreeButtons(requireContext())
        ma.hideBottomNavigation(GONE)

        setEvents()
        setToolBar()
        if (collection.tickets.isNotEmpty()) {
            createCollectionList()
        }
        super.init()
    }

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

    }

    private fun setToolBar() {
        binding.mainToolbar.toolbarSubtitle.visibility = VISIBLE
        binding.mainToolbar.toolbarIcons.visibility = VISIBLE
        binding.mainToolbar.backButton.visibility = VISIBLE
        collection.collectionFk.let {
            binding.mainToolbar.toolbarTitle.text = collection.collectionFk.toString()
        }

        val listIcons: ArrayList<ImageView> = ArrayList()
        val iconPrint = ImageView(context)
        iconPrint.setImageResource(R.drawable.ic_print_black_24dp)
        val iconAdd = ImageView(context)
        iconAdd.setImageResource(R.drawable.ic_playlist_add_black_24dp)
        val iconViewCollection = ImageView(context)
        iconViewCollection.setImageResource(R.drawable.ic_collection)
        val iconWorker = ImageView(context)
        iconWorker.setImageResource(R.drawable.ic_worker)
        val iconParking = ImageView(context)
        iconParking.setImageResource(R.drawable.ic_local_parking_black_24dp)
        val iconUpdate = ImageView(context)
        iconUpdate.setImageResource(R.drawable.ic_autorenew_black_24dp)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            iconPrint.tooltipText = getTooltip(R.drawable.ic_print_black_24dp)
            iconAdd.tooltipText = getTooltip(R.drawable.ic_playlist_add_black_24dp)
            iconViewCollection.tooltipText = getTooltip(R.drawable.ic_collection)
            iconParking.tooltipText = getTooltip(R.drawable.ic_local_parking_black_24dp)
            iconUpdate.tooltipText = getTooltip(R.drawable.ic_autorenew_black_24dp)

        }
        listIcons.add(iconPrint)
        if (type == CONTROLADOR) {
            listIcons.add(iconViewCollection)
            binding.previaButton.visibility = VISIBLE
            binding.previaButton.setOnClickListener {
                showPrevia()
            }
            listIcons.add(iconWorker)
        }

        listIcons.add(iconAdd)

        if (type == SACADOR) {
            listIcons.add(iconUpdate)
            listIcons.remove(iconWorker)
        }

        if (type == PRECHECKER) {
            listIcons.add(iconParking)
            listIcons.remove(iconPrint)
        }

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

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

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

    private fun updateScreen() {
        canChangeState = false

        viewModel.collectionTicketGet(
            collection.collectionFk,
            mobileApplication.dataStoreApp.readDataStoreKey(SECTORFK),
            print = "0",
            type
        )
    }

    private fun markPrevia(saleGroupScanned: String): Boolean {

        for (indice in sales.indices) {
            if (!sales[indice].saleGroupFk.isNullOrEmpty() && sales[indice].saleGroupFk == saleGroupScanned) {

                when (type) {
                    CONTROLADOR -> markLine(indice, type)
                    SACADOR -> {
                        viewModel.saleTrackingAddPreparedSaleGroup(
                            saleGroupScanned.toInt()
                        )
                        return true
                    }

                }
                if (mpok != null) {
                    mpok!!.start()
                }

            }
        }
        return false
    }

    private fun showPrevia() {
        customDialogList.getEditText().setRawInputType(TYPE_CLASS_NUMBER)
        customDialogList.setTitle(getString(R.string.scanPreviousTicket))
            .setOkButton(getString(R.string.end)) {
                ma.hideKeyboard(customDialogList.getEditText())
                customDialogList.dismiss()

            }.setValue("").show()

        customDialogList.getEditText().requestFocus()
        ma.hideKeyboard(customDialogList.getEditText())

        customDialogList.getEditText().setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0 || actionId == 5 || actionId == 6) {
                if (customDialogList.getValue().isNotEmpty()) {
                    ma.hideKeyboard(customDialogList.getEditText())
                    try {
                        val saleGroupScanned = itemScanValue(
                            customDialogList.getValue(),
                            arrayOf("saleGroup"),
                            "id"
                        ).toString()
                        isScanned =
                            event != null && event.action == ACTION_DOWN && event.keyCode == KeyEvent.KEYCODE_ENTER
                        markPrevia(saleGroupScanned)
                        customDialogList.dismiss()
                    } catch (ex: Exception) {
                        ma.messageWithSound(
                            message = ex.message.toString(),
                            isError = true,
                            isPlayed = true,
                            isToasted = true
                        )
                    }

                }
                customDialogList.setValue("")
                ma.hideKeyboard(customDialogList.getEditText())
                return@setOnEditorActionListener true
            }
            false
        }
        hideKeyboard()
    }

    private fun getCollection() {

        if (!buttonPushedGetCollection) {
            //Tarea 3520
            viewModel.collectionGetId(
                collection.collectionFk,
                mobileApplication.dataStoreApp.readDataStoreKey(SECTORFK),
                print = "0",
                type
            )
            buttonPushedGetCollection = true
        } else {
            viewModel.collectionTicketGet(
                lastScanned,
                mobileApplication.dataStoreApp.readDataStoreKey(SECTORFK),
                print = "0",
                type

            )
            buttonPushedGetCollection = false
        }
        lastScanned = collection.collectionFk
    }

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

    private fun showUser() {

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

    }

    private fun setEvents() {

        binding.mainToolbar.backButton.setOnClickListener {
            ma.onMyBackPressed()
        }
        //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) {//ID=0 ACTION_NEXT  ID=5 ACTION_UNESPECEFIED)
                if (!binding.scanInput.text.toString().isNullOrEmpty()) {

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

                    //de momento solo está el qr de artículo
                    isScanned =
                        event != null && event.action == ACTION_DOWN && event.keyCode == KeyEvent.KEYCODE_ENTER

                    if (itemScanIsQr(binding.scanInput.text.toString())) {

                        var myQr = ItemScanned(JSONObject(binding.scanInput.text.toString()))

                        when (myQr.table) {
                            "saleGroup" -> {
                                if (type == CONTROLADOR) {
                                    markPrevia(myQr.id.toString())
                                } else {
                                    binding.scanInput.setText(myQr.id.toString())
                                    findSale(binding.scanInput.text.toString())
                                }
                            }

                            "buy" -> binding.scanInput.setText(myQr.more)
                            "ticket" -> findSale(myQr.id.toString())

                        }

                    } else {
                        findSale(binding.scanInput.text.toString())
                    }

                    buttonPushedGetCollection = false

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

        hideKeyboards()

        //LISTA =========
        binding.collectionSwipe.setOnRefreshListener {
            canChangeState = false
            isMarking = false
            binding.collectionSwipe.isRefreshing = false
            // if (type != PRECHECKER) {

            viewModel.collectionTicketGet(
                collection.collectionFk,
                mobileApplication.dataStoreApp.readDataStoreKey(SECTORFK),
                print = "0",
                " "
            )
            buttonPushedGetCollection = false
            binding.collectionSwipe.isRefreshing = false
            //}
        }
    }

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

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

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

    @RequiresApi(Build.VERSION_CODES.O)
    override fun observeViewModel() {
        with(viewModel) {

            collectionTicketList.observe(viewLifecycleOwner, Observer {

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

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

            })

            responseUsedShelves.observe(viewLifecycleOwner, Observer {

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

            })
            responseParking.observe(viewLifecycleOwner, Observer {

                if (!goBack) {

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

            })

            responsePrint.observe(viewLifecycleOwner, Observer {

                if (!goBack) {

                    if (it.isError) {
                        ma.messageWithSound(
                            it.errorMessage, it.isError, true
                        )
                    } else {
                        (getString(R.string.Imprimiendo) + mobileApplication.dataStoreApp.readDataStoreKey<String>(
                            PRINTERNAME
                        )).toast(
                            requireContext()
                        )
                    }
                }

            })

            responseSplit.observe(viewLifecycleOwner) {

                if (!goBack) {

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

            }

            responseSaleGroup.observe(viewLifecycleOwner, Observer {

                if (it.isError) {

                    ma.messageWithSound(it.errorMessage, true, true)
                } else {
                    ma.messageWithSound(getString(R.string.previousCollected), false, true)

                    viewModel.collectionTicketGet(
                        collection.collectionFk,
                        mobileApplication.dataStoreApp.readDataStoreKey(SECTORFK),
                        print = "0",
                        type
                    )
                }
            })
            placementSuppleyList.observe(viewLifecycleOwner, Observer {

                if (!goBack) printShelvingResult(it)
                goBack = false
            })

            item.observe(viewLifecycleOwner, Observer {

                if (!goBack) toastDisponibility(it)
                goBack = false
            })

            responseNew.observe(viewLifecycleOwner, Observer {

                // if (!goBack) {
                if (it.isError) {
                    customDialog.setTitle(getString(R.string.disponibility))
                        .setDescription(getString(R.string.errorCollectionNew) + it.errorMessage)
                        .setKoButton(getString(R.string.close)) {
                            scanRequest()
                            customDialog.dismiss()
                        }.show()
                } else {

                    if (!goBack) {

                        viewModel.collectionTicketGet(
                            collection.collectionFk,
                            mobileApplication.dataStoreApp.readDataStoreKey(SECTORFK),
                            print = "0",
                            type
                        )

                    }
                }

                goBack = false

            })

            responseCode.observe(viewLifecycleOwner, Observer {

                if (!goBack2) {
                    if (it == null) {
                        customDialog.setTitle(getString(R.string.error))
                        showErrorMessage(getString(R.string.codeNotExist))
                    } else {
                        if (checkItemScan(it.toString())) {
                            scanRequest()
                            customDialogList.dismiss()
                            mpok?.start()
                            onQuantityOfShelvingSelected(itemShelvingFkStored)
                        } else {

                            showErrorMessage(getString(R.string.lineNotExist))

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

                goBack2 = false

            })
            responseTicketState.observe(viewLifecycleOwner) {

                if (!goBack) {
                    if ((it.code == "ON_CHECKING" || it.code == "CHECKED") && it.user.id != mobileApplication.userId) {
                        var customDialogWarningChecking = CustomDialog(requireContext())
                        customDialogWarningChecking.setTitle(getString(R.string.info))
                        customDialogWarningChecking.setDescription(
                            if (it.code == "ON_CHECKING") {
                                getString(R.string.checkingByUser, it.user.username)
                            } else {
                                getString(R.string.checkedByUser, it.user.username)
                            }
                        ).setOkButton(getString(R.string.aware)) {
                            customDialogWarningChecking.dismiss()
                        }.show()
                    }
                }

            }

            responseTicketClosure.observe(viewLifecycleOwner, Observer {

                if (!goBack) {
                    if (it.response.toBoolean()) {
                        var customDialogWarning = CustomDialog(requireContext())
                        customDialogWarning.setTitle(getString(R.string.urgentWarning))
                        customDialogWarning.setDescription(getString(R.string.ticketWarning))
                            .setOkButton(getString(R.string.aware)) {
                                customDialogWarning.dismiss()
                            }.show()
                    }
                }

            })

            responseIncQuantity.observe(viewLifecycleOwner, Observer {

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

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

            })

            responseSaleMistakeAdd.observe(viewLifecycleOwner, Observer {

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

                    } else {
                        ma.messageWithSound(
                            getString(R.string.errorRegistered), isError = false, false
                        )
                        goBack = true
                    }

                }
            })


            mistakeList.observe(viewLifecycleOwner, Observer {

                if (!goMistakeBack) showMistakeList(it.list)
                goMistakeBack = true
            })
            //sergio: para si hay algun ticket por revisar antes de parkinear

            responseCollectionUnchecked.observe(viewLifecycleOwner, Observer {
                if (it.isError) {
                    ma.messageWithSound(it.errorMessage, it.isError, false)

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

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

                            }.setKoButton(getString(R.string.review)) {
                                viewModel.collectionTicketGet(
                                    it.response.toInt(),
                                    mobileApplication.dataStoreApp.readDataStoreKey(SECTORFK),
                                    print = "0",
                                    type
                                )
                                customDialog.dismiss()
                            }
                        customDialog.show()
                    } else {
                        viewModel.setParking(
                            ticketFk = tickets[0].toInt(), parking = ticketScanTxt
                        )
                    }
                    // if (!goBack)navigateToCollectionList(it)
                    //goBack = false
                }
            })

            loadResponseDel.observe(viewLifecycleOwner) { event ->
                event.getContentIfNotHandled().notNull {
                    if (it.isError) {

                        if (!goBack) {

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

                        }
                    } else {

                        viewModel.collectionTicketGet(
                            collection.collectionFk,
                            mobileApplication.dataStoreApp.readDataStoreKey(SECTORFK),
                            print = "0",
                            type
                        )

                        goBack = false
                    }
                }
            }

            /*     responseDel.observe(viewLifecycleOwner, Observer {

                     if (it.isError) {

                         if (!goBack) {

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

                         }
                     } else {

                         viewModel.collectionTicketGet(
                             collection.collectionFk,
                             mobileApplication.dataStoreApp.readDataStoreKey(SECTORFK),
                             print = "0",
                             type
                         )

                         goBack = false
                     }

                 })*/

            loadResponseItemShelvingUpdate.observe(viewLifecycleOwner) { event ->
                event.getContentIfNotHandled().notNull {

                    canChangeState = !it.isError
                    if (it.isError) {
                        ma.messageWithSound(it.errorMessage, it.isError, false)

                    } else {
                        viewModel.saleTrackingDel(
                            saleFk = sales[positionUnmarked].saleFk
                        )
                    }
                }
            }


            responseSaleReplace.observe(viewLifecycleOwner, Observer {

                if (it.isError) {

                    if (!goBack) {

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

                        viewModel.collectionTicketGet(
                            collection.collectionFk,
                            mobileApplication.dataStoreApp.readDataStoreKey(SECTORFK),
                            print = "0",
                            type
                        )
                    }

                } else {

                    if (type != PRECHECKER) {
                        saleAdapter!!.notifyDataSetChanged()
                    }
                    goBack = false
                }
            })



            loadResponseSaleTrackingMark.observe(viewLifecycleOwner) { event ->
                event.getContentIfNotHandled().notNull {

                    if (it.isError) {

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

                            viewModel.collectionTicketGet(
                                collection.collectionFk,
                                mobileApplication.dataStoreApp.readDataStoreKey(SECTORFK),
                                print = "0",
                                type
                            )
                        }

                    } else {
                        // pintar línea

                        saleAdapter!!.notifyDataSetChanged()

                        ReviewQuantityForRefreshingAndSorting(
                            sales[storedPosition].quantity!!.toInt(),
                            sales[storedPosition].pickedQuantity!!.toInt()
                        )
                        goBack = false
                    }

                }
            }


            responseItemShelvingSaleSupplyAdd.observe(viewLifecycleOwner, Observer {

                if (it.isError) {

                    if (!goBack) {

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

                    }

                } else {
                    goBack = false
                }
            })

        }
    }

    //CREATE LIST
    private fun createCollectionList() {

        state = 0
        binding.mainToolbar.toolbarTitle.text = collection.collectionFk.toString()

        var salesList: ArrayList<SaleVO> = ArrayList()
        tickets = ArrayList()
        var observations = ""
        collection.tickets.forEach { ticket ->
            // if (!ticket.sales.isNullOrEmpty()){
            ticket.sales.forEach { saleVO ->
                if (type == SACADOR && saleVO.quantity != 0) {
                    salesList.add(saleVO)
                    if (tickets.firstOrNull { it == saleVO.ticketFk }.isNullOrEmpty()) tickets.add(
                        saleVO.ticketFk
                    )
                } else if (type == CONTROLADOR) {
                    salesList.add(saleVO)
                    //Tarea 6607
                    /* if (saleVO.cel2.contains("pack de")) {
                         saleVO.packingChecked =
                             saleVO.cel2.substringBefore("pack de").trim().toInt()
                     } else {
                         saleVO.packingChecked = 1
                     }*/
                    if (tickets.firstOrNull { it == saleVO.ticketFk }.isNullOrEmpty()) tickets.add(
                        saleVO.ticketFk
                    )
                } else if (type == PRECHECKER) {
                    if (saleVO.saleGroupFk != "") {
                        salesList.add(saleVO)
                        if (tickets.firstOrNull { it == saleVO.ticketFk }
                                .isNullOrEmpty()) tickets.add(saleVO.ticketFk)
                    }
                }
            }

            observations =
                observations.takeIf { !it.isNullOrBlank() }?.plus(" ${ticket.observations}") ?: ""
        }

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

        if (type == CONTROLADOR || type == PRECHECKER) {
            sales = salesList.sortedWith(compareBy({ it.picked }))
            myGroupList = groupSaleGroup(salesList).sortedWith(compareBy({ it.picked }))

        }

        /*    if (type == CONTROLADOR) {
                            myGroupList.sortedByDescending{ it.isAdded }.sortedWith(
                                compareBy { it.picked })
                        } else {
                            myGroupList
                        },*/
        saleAdapter = SaleAdapter(
            myGroupList,
            pasillerosItemClickListener!!,
            object : OnQuantityClickListener {

                override fun onQuantityClick(sale: SaleVO) {

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

                        }
                    }

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

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

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

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

                            }
                        }

                    }
                }

            },
            object : OnMistakeClickListener {
                override fun onMistakeClickListener(sale: SaleVO) {
                    //Tarea #4969

                    viewModel.mistakeType()
                    mistakeSale = sale
                    goMistakeBack = false

                }
            },
            object : OnPackingClickListener {
                override fun onPackingClick(sale: SaleVO) {
                }
            },
            object : OnTicketClickListener {
                override fun onTicketClickListener(sale: SaleVO) {
                    if (type == CONTROLADOR) {
                        //var ticketFk = sale.ticketFk

                        var entryPoint = Gson().toJson(
                            mutableMapOf(
                                "entryPoint" to sale.ticketFk, "web" to "${
                                    mobileApplication.dataStoreApp.getServerSalix()
                                }/#!/ticket/${sale.ticketFk}/sale"
                            )
                        )
                        ma.onPasillerosItemClickListener(
                            PasillerosItemVO(
                                title = R.string.titleWebViewer,
                            ), entryPoint = entryPoint
                        )
                    }
                }
            },
            type = type
        )




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


        binding.fragmentSacadorCollections.adapter = saleAdapter

        binding.fragmentSacadorCollections.layoutManager = lm
        setTotalLines()
        //Tarea #4628
        if (type == CONTROLADOR) {
            setListPosition(storedBackPosition, true)
            setScrollListener(lm!!)
        }
        //CAU ISMAELCT
        else {

            if (type == SACADOR) {
                setStoredPosition(true)
            } else {
                if (storedPosition != 0) setListPosition(storedPosition, true)
                else if (storedBackPosition != 0) setListPosition(storedBackPosition, true)

            }
        }

        printObservations(observations)
    }

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

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

    //SEARCH AND MARK

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

        if (type == SACADOR) {
            isOk = markPrevia(txtscan)
            for (saleVO in sales) {
                if (isOk) break

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

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

                        viewModel.setParking(
                            ticketFk = tickets[0].toInt(), parking = txtscan
                        )

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

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

            try {

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

                    if (saleVO.isControlled == "0") {
                        //1- Por itemFk
                        if (txtscan == saleVO.itemFk.toString()) {
                            if (mpok != null) mpok!!.start()
                            isOk = true
                            //Tarea 6067
                            //   if (saleVO.packingChecked == 1) {
                            markLine(index, type)
                            // } else {
                            //   saleVO.packingChecked = saleVO.packingChecked - 1
                            //}
                            //saleAdapter!!.notifyDataSetChanged()
                            break
                        }
                        //2- Por barcode
                        saleVO.barcodes.forEach { barcode ->

                            if (txtscan == barcode) {
                                if (mpok != null) mpok!!.start()
                                isOk = true
                                //Tarea 6067
                                //if (saleVO.packingChecked == 1) {
                                markLine(index, type)
                                //} else {
                                //   saleVO.packingChecked = saleVO.packingChecked - 1
                                //}
                                saleAdapter!!.notifyDataSetChanged()
                                isBreak = true
                            }
                        }

                        if (isBreak) break
                    }
                    index += 1
                }
            } catch (ex: Exception) {
                getString(R.string.errorInput).toast(requireContext())
            }
            //Lo escaneado no encontrado miramos si es parking o ticket
            if (!isOk) {
                if (txtscan.contains("-")) {

                    if (tickets.size > 0) {

                        ticketToParking = tickets[0]
                        ticketScanTxt = txtscan
                        //#tarea4107
                        viewModel.hasUncheckedTicket(
                            collectionFk = tickets[0].toInt()
                        )
                    }

                } else {

                    storedPosition = 0
                    storedBackPosition = 0
                    //  if (type != PRECHECKER) {
                    isMarking = false

                    try {
                        var myScan = txtscan.toInt()

                        var hasItemSales = sales.any {
                            it.itemFk == txtscan.toInt()
                        }
                        if (!hasItemSales) {

                            viewModel.collectionTicketGet(
                                myScan,
                                mobileApplication.dataStoreApp.readDataStoreKey(SECTORFK),
                                print = "0",
                                type
                            )


                            if (type.equals(CONTROLADOR)) {

                                viewModel.ticketIsOutClosureZone(
                                    myScan
                                )
                                //Tarea 6458
                                viewModel.ticketState(myScan)

                            }
                        } else {
                            mperror!!.start()
                        }

                    } catch (ex: Exception) {

                        getString(R.string.errorInput).toast(requireContext())
                    }

                }
            }
        }
    }

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

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

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

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

            }
        }

    }

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

                if (sales[position].cel2.contains("pack de")){
                    sales[position].packingChecked =  sales[position].cel2.substringBefore("pack de").trim().toInt()}
            }*/

            saleAdapter!!.notifyDataSetChanged()
            saleTrackingReplace(position, newType)
            setListPosition(position, false)/*  } else {
                  sales[position].packingChecked = sales[position].packingChecked - 1
                  saleAdapter!!.notifyDataSetChanged()
              }*/

            //En primera instancia coge el primer elemento hijo para realizar la copia y según se va interactuando con las sales ya se actualiza el
            // estado del padre
            checkStateParent()

        }

        if (type == PRECHECKER) {
            sales[position].isPreControlled =
                if (sales[position].isPreControlled == "1") "0" else "1"
            checkStateParent()
            saleAdapter!!.notifyDataSetChanged()
            saleTrackingReplace(position, newType)
            setListPosition(position, false)

        }

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

        if (type == SACADOR) {
            saleTracking_mark(position, newType)
            //saleTrackingReplace(position,newType)
        } /*else {
            saleAdapter!!.notifyDataSetChanged()
            saleTrackingReplace(position, newType)
            setListPosition(position, false)
        }*/
        isMarking = true
        setTotalLines()
    }

    private fun checkStateParent() {
        for (s in myGroupList) {
            if (s.isParent) {
                var totalLines = s.sonSales.size
                var isPreviousPrepared = s.sonSales.filter { it.isPreviousPrepared == "1" }.size
                var isPrepared = s.sonSales.filter { it.isPrepared == "1" }.size
                var isControlled = s.sonSales.filter { it.isControlled == "1" }.size
                var isPreControlled = s.sonSales.filter { it.isPreControlled == "1" }.size
                if (totalLines == isPreviousPrepared) {
                    s.isPreviousPrepared = "1"
                } else {
                    s.isPreviousPrepared = "0"
                }
                if (totalLines == isPrepared) {
                    s.isPrepared = "1"
                } else {
                    s.isPrepared = "0"
                }
                if (totalLines == isControlled) {
                    s.isControlled = "1"
                } else {
                    s.isControlled = "0"
                }
                if (totalLines == isPreControlled) {
                    s.isPreControlled = "1"
                } else {
                    s.isPreControlled = "0"
                }

            }
        }

    }

    private fun setListPosition(position: Int, isFromBack: Boolean) {
        storedPosition = position
        //tarea #4628, se asigna storedBackPosition
        storedBackPosition = position

        if (type == SACADOR || mobileApplication.dataStoreApp.readDataStoreKey<String>(
                SECTORDESCRIP
            ).uppercase() == getString(
                R.string.sectorALGEMESINEW
            ) || type == PRECHECKER
        ) {
            var myPosition = position

            if (type == CONTROLADOR && mobileApplication.dataStoreApp.readDataStoreKey<String>(
                    SECTORDESCRIP
                ).uppercase() == getString(
                    R.string.sectorALGEMESINEW
                )
            ) {
                if (position > 0) {
                    var totalPrevias = 0

                    for (s in myGroupList) {
                        if (s.isParent) {
                            totalPrevias += s.sonSales.size
                            myPosition = position - totalPrevias + 1

                        }

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

            }

        } else if (isFromBack) {

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

    }

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

        //Tarea #4371 se quita para ver si funciona correctamente
        viewModel.saleTrackingReplace(
            saleFk = sales[position].saleFk,
            isChecked = if (type == SACADOR) sales[position].isPrepared else if (type == CONTROLADOR) sales[position].isControlled else if (type == "PRECHECKER") sales[position].isPreControlled else "1",
            originalQuantity = sales[position].pickedQuantity!!,
            code = if (type == CONTROLADOR) "CHECKED" else if (type == "PRECHECKER") "PREVIOUS_CONTROL" else type,//type.toString(),
            buyFk = originalItemScan,
            isScanned = isScanned

        )

    }

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

        viewModel.run {
            saleTracking_mark(
                saleFk = sales[position].saleFk,
                isChecked = if (type == SACADOR) sales[position].isPrepared else if (type == CONTROLADOR) sales[position].isControlled else if (type == "PRECHECKER") sales[position].isPreControlled else "1",
                originalQuantity = sales[position].pickedQuantity!!,
                code = if (type == CONTROLADOR) "CHECKED" else if (type == "PRECHECKER") "PREVIOUS_CONTROL" else type,//type.toString(),
                buyFk = originalItemScan,
                itemShelvingFk = itemShelvingTracking_mark,
                quantity = customDialogList.getValue().toInt(),
                isScanned = isScanned

            )
        }
        isScanned = null

    }

    private fun unMarkLine(position: Int, newType: String) {

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

                    viewModel.itemShelvingUpdateFromSale(
                        sales[position].saleFk
                    )
                    positionUnmarked = position

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

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

    }

    //SHELVINGS
    private fun showShelving(position: Int, shelvingPosition: Int) {
        storedShelvingPosition = shelvingPosition
        storedPosition = position

        var quantityGet = 0
        try {
            quantityGet = (sales[position].quantity!! - sales[position].pickedQuantity!!.toInt())
        } catch (e: Exception) {
        }
        //Log.i("VERDNATURA:","Aparece  para enviar")
        viewModel.itemPlacementSupplyAiming(
            itemFk = sales[position].itemFk,
            quantity = quantityGet,
            shelvingFk = sales[position].placements[shelvingPosition].shelving

        )
    }

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

        }
        listPlacementSupply = ArrayList()
        placementSupplyListVO.list.forEach {
            if (it.stock != "0") listPlacementSupply.add(BarcodeVO(code = it.proposal))
            //////Log.i("VERDNATURA:","Array de placementsupply")
        }
        try {
            // Log.i("VERDNATURA:","Pulso COGER-1")
            customDialogList.setTitle("$shelving($item) $total de $longName").setOkButton(
                getString(
                    R.string.take
                )
            ) {

                if (customDialogList.getValueTwo().isNotEmpty()) {
                    isScanned = false/*Tarea #5109*/
                    customDialogList.setValueTwo(
                        itemScanValue(
                            customDialogList.getValueTwo(), arrayOf("buy"), "more"
                        ).toString()
                    )



                    if (isNumber(customDialogList.getValue()) && isNumber(total) && customDialogList.getValue()
                            .toInt() > total.toInt()
                    ) {
                        getString(R.string.quantityHigh).toast(requireContext())
                    } else if (isNumber(customDialogList.getValue())) {
                        originalItemScan = customDialogList.getValueTwo().toLong()
                        // Log.i("VERDATURA","Le pasamos el siguiente item $originalItemScan que es el escaneado")
                        if (checkItemScan(customDialogList.getValueTwo())) {
                            onQuantityOfShelvingSelected(itemShelvingFk)
                            //Log.i("VERDNATURA:","Cantidad seleccionada")
                            mpok?.start()/* Se quita para comprobar al final de saleTracking_mark
                             ReviewQuantityForRefreshingAndSorting(
                                 customDialogList.getValue().toInt(),
                                 sales[storedPosition].quantity!!.toInt(),
                                 sales[storedPosition].pickedQuantity.toInt()
                             )*/
                            customDialogList.dismiss()
                        } else {
                            itemShelvingFkStored = itemShelvingFk


                            viewModel.getIdFromCodeSalix(
                                code = customDialogList.getValueTwo(),
                            )

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

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

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

            })
        } catch (e: Exception) {
        }
        try {
            customDialogList.getEditTextTwo().setRawInputType(TYPE_CLASS_NUMBER)

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

                    /*Tarea 4729*/
                    isScanned =
                        event != null && event.action == ACTION_DOWN && event.keyCode == KeyEvent.KEYCODE_ENTER

                    customDialogList.setValueTwo(
                        itemScanValue(
                            customDialogList.getValueTwo(), arrayOf("buy"), "more"
                        ).toString()
                    )

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

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

                                    customDialogList.dismiss()
                                } else {
                                    itemShelvingFkStored = itemShelvingFk


                                    viewModel.getIdFromCodeSalix(
                                        code = customDialogList.getValueTwo()
                                    )
                                    customDialogList.dismiss()
                                    scanRequest()
                                }
                            } else {
                                getString(R.string.quantityError).toast(requireContext())
                            }

                        } catch (e: Exception) {

                        }

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

                }
                false
            }
        } catch (e: Exception) {
            ma.messageWithSound(e.message.toString(), true, true)
        }

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

                }
            }, showDelete = false
        )

        customDialogList.getRecyclerView().adapter = placementSupplyAdapter

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

    }

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

        if (quantityPicked < quantityTotal) {

            viewModel.collectionTicketGet(
                collection.collectionFk,
                mobileApplication.dataStoreApp.readDataStoreKey(SECTORFK),
                print = "0",
                type
            )

        } else {
            setStoredPosition(false)

        }

    }

    private fun setStoredPosition(isFromBack: Boolean) {/* if (type == SACADOR) {

             for (indice in myGroupList.indices) {
                 if (myGroupList[indice].isPrepared == "0") {
                     storedPosition = if (indice != 0) {
                         indice - 1
                     } else {
                         indice
                     }
                     break
                 }
             }*/

        setListPosition(storedPosition, isFromBack)
    }

    private fun checkItemScan(valueToCheck: String): Boolean {
        d("VERDNATURA::", "Entramos a ver el checkItem")
        if (storedPosition >= 0 && sales.size > storedPosition) {
            val saleToCheck = sales[storedPosition]

            if (saleToCheck.itemFk.toString() == valueToCheck) return true
            else {
                saleToCheck.barcodes.forEach { barcode ->
                    if (barcode == valueToCheck) return true
                }
            }
        }
        d("VERDNATURA::", "SAlimos de ver el checkItem")
        return false
    }

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

            if (quantity == 0) {
                sales[storedPosition].placements[storedShelvingPosition].visible =
                    "(" + (shelvingVisible.toInt() - customDialogList.getValue()
                        .toInt()).toString() + ")"
            } else {
                sales[storedPosition].placements[storedShelvingPosition].visible =
                    "(" + (shelvingVisible.toInt() - quantity.toInt()).toString() + ")"
            }

        } catch (e: Exception) {
        }

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

        //3- MARCAR LINEA

        //Tarea #4371
        itemShelvingTracking_mark = itemShelvingFk

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

    }

    //OPTIONS
    private fun print() {

        if (ma.havePrinter() && ma.haveSector()) {
            showDialogLabelCount()

        } else {

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

        }

    }

    private fun addItem() {
        listPlacementSupply = ArrayList()
        collection.tickets.forEach {
            listPlacementSupply.add(BarcodeVO(code = it.ticketFk.toString()))
        }
        if (listPlacementSupply.size == 1) {
            ticketSelected = listPlacementSupply[0].code!!.toInt()
        }
        customDialogList.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE)
        customDialogList.getEditTextTwo().inputType = TYPE_CLASS_NUMBER
        customDialogList.getEditText().setRawInputType(TYPE_CLASS_NUMBER)
        customDialogList.setTitle(getString(R.string.Agregarartículoparaticket) + " " + ticketSelected)
            .setOkButton(getString(R.string.Agregar)) {

                if (ticketSelected == 0) {
                    getString(R.string.Seleccionaunticketdelaista).toast(requireContext())
                } else if (customDialogList.getValue()
                        .isNullOrEmpty() || customDialogList.getValueTwo().isNullOrEmpty()
                ) {
                    getString(R.string.Todosloscampossonobligatorios).toast(requireContext())
                } else {

                    viewModel.collectionAddItem(
                        itemFk = customDialogList.getValue().toInt(),
                        ticketFk = ticketSelected,
                        quantity = customDialogList.getValueTwo().toInt()
                    )


                    scanRequest()
                    customDialogList.dismiss()
                }

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

        customDialogList.getEditText().setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0 || actionId == 5) {
                if (!customDialogList.getValue().isNullOrEmpty()) {
                    try {
                        customDialogList.setValue(
                            itemScanValue(
                                customDialogList.getValue(), arrayOf("buy"), "more"
                            ).toString()
                        )

                    } catch (e: Exception) {
                        ma.messageWithSound(e.message.toString(), true, true)
                    }
                    customDialogList.getEditTextTwo().requestFocus()
                }
                //hideKeyboards()
                return@setOnEditorActionListener true

            }
            false

        }


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

                        viewModel.collectionAddItem(
                            itemFk = customDialogList.getValue().toInt(),
                            ticketFk = ticketSelected,
                            quantity = customDialogList.getValueTwo().toInt(),
                        )
                        scanRequest()
                        customDialogList.dismiss()
                    }
                }
                hideKeyboards()
                return@setOnEditorActionListener true
                scanRequest()
                customDialogList.dismiss()
            }
            false
        }

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

        customDialogList.getRecyclerView().adapter = placementSupplyAdapter

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

    }

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

    }

    private fun setTotalLines() {

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

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

            }
        }

        if (binding.mainToolbar.toolbarTitle != null) binding.mainToolbar.toolbarTitle.text =
            if (collection.collectionFk != 0) collection.collectionFk.toString() else ""

        var total = sales.size
        var totalParents = sales.filter { it.isParent }.size
        total = total - totalParents

        if (binding.mainToolbar.toolbarSubtitle != null && totalMark != null) binding.mainToolbar.toolbarSubtitle.text =
            "" + totalMark + "/" + total

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

            if (canChangeState) changeTicketState()
        } else {
            if (allTicketsChecked) {

                sales.forEach {
                    if (it.isControlled == "0") {
                        viewModel.ticketStateTodaySetState(
                            ticketFk = it.ticketFk.toInt(), state = "ON_CHECKING"
                        )
                    }
                }
                allTicketsChecked = false
            }
        }
    }

    private fun ticketCollection_setUsedShelves() {

        var sectorDesciption = mobileApplication.dataStoreApp.readDataStoreKey<String>(
            SECTORDESCRIP
        )
        if (type.equals("CHECKER") && (isMarking && (sectorDesciption.uppercase() != getString(
                R.string.sectorALGEMESI
            ) && sectorDesciption.uppercase() != getString(
                R.string.sectorALGEMESINEW
            )))
        ) {

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

                        viewModel.ticketCollection_setUsedShelves(
                            ticketFk = collection.collectionFk,
                            usedShelves = customDialogInput.getValue().toInt()
                        )
                        hideKeyboards()
                        //  showKeyboards()

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

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

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

                        viewModel.ticketCollection_setUsedShelves(
                            ticketFk = collection.collectionFk,
                            usedShelves = customDialogInput.getValue().toInt()
                        )
                        hideKeyboards()
                    }
                    customDialogInput.setValue("")
                    scanRequest()
                    customDialogInput.dismiss()
                    hideKeyboards()
                    return@setOnEditorActionListener true
                }
                false
            }

        }

    }

//FALTAS / BASURA / SPLIT

    private fun showQuantityDialog(position: Int) {
        try {

            customDialogThreeButtons.setDescription(getString(R.string.itemSaleQuantity))
                .setValue("").setOkButtonAdd(getString(R.string.modify)) {
                    try {
                        increaseQuantity(position, customDialogThreeButtons.getValue().toInt())
                        scanRequest()
                        customDialogThreeButtons.dismiss()
                    } catch (ex: Exception) {
                        ma.messageWithSound(
                            message = getString(R.string.errorInputQuantity),
                            isPlayed = true,
                            isError = true,
                            isToasted = true
                        )
                    }

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

    private fun missingTrashSuccesful() {

        var message = ""

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

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

        saleAdapter!!.notifyDataSetChanged()


        viewModel.collectionTicketGet(
            collection.collectionFk,
            mobileApplication.dataStoreApp.readDataStoreKey(SECTORFK),
            print = "0",
            type
        )

    }

    private fun incresaseSuccesful() {
        try {
            //val quantityPicked = (quantity.toInt() - sales[position].quantitytoInt()).toString()
            // sergio: se añade linea para que se actualice la originalQuantity
            //sales[positionIncreaseQuantity].originalQuantity = quantityIncrease

            sales[positionIncreaseQuantity].quantity = quantityIncrease

        } catch (e: Exception) {
        }
        saleAdapter?.notifyDataSetChanged()

        sales[positionIncreaseQuantity].originalQuantity = quantityIncrease

    }

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

        viewModel.collectionIncreaseQuantitySalix(
            saleFk = sales[position].saleFk, quantity = quantity.toString()
        )

    }

    //ESTADOS
    private fun changeTicketState() {
        if (type == CONTROLADOR) {
            tickets.forEach {
                viewModel.ticketStateTodaySetState(
                    ticketFk = it.toInt(), state = "CHECKED"
                )
            }
            allTicketsChecked = true
        } else if (type == SACADOR) {
            tickets.forEach {
                viewModel.ticketStateTodaySetState(
                    ticketFk = it.toInt(), state = "PREPARED"
                )
            }
////Refactor #4030

        } else if (type == PRECHECKER) {
            tickets.forEach {
                viewModel.ticketStateTodaySetState(
                    ticketFk = it.toInt(), state = "PREVIOUS_CONTROLLED"
                )
            }
        }
    }

    //OTROS
    private fun showScanner(index: Int, sale: SaleVO) {
        customDialogInput.getEditText().inputType = TYPE_CLASS_TEXT
        customDialogInput.setTitle("" + sale.itemFk)
            .setDescription(getString(R.string.scanWagonForItem))
            .setOkButton(getString(R.string.accept)) {
                if (!customDialogInput.getValue().isNullOrEmpty()) {
                    findSale(customDialogInput.getValue(), index)
                }
                customDialogInput.setValue("")
                scanRequest()
                customDialogInput.dismiss()
                hideKeyboards()
            }.setKoButton(getString(R.string.cancel)) {
                customDialogInput.dismiss()
            }.setValue("").show()
        customDialogInput.getEditText().requestFocus()
        customDialogInput.getEditText().setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0) {
                if (!customDialogInput.getValue().isNullOrEmpty()) {
                    findSale(customDialogInput.getValue(), index)
                }
                customDialogInput.setValue("")
                scanRequest()
                customDialogInput.dismiss()
                hideKeyboards()
                return@setOnEditorActionListener true
            }
            false
        }

    }

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

    private fun showDialogLabelCount() {
        //tarea#4672
        var isTicket = false
        for (t in collection.tickets) {
            if (t.ticketFk.toInt() == (collection.collectionFk)) {
                isTicket = true
            }
        }
        if (isTicket) {
            val builder = AlertDialog.Builder(context)
            builder.setTitle(getString(R.string.selectLabeltoPrint))
            val labelCount = arrayOf("1", "2", "3", "4", "5", "6", "7", "8", "9", "10")
            builder.setItems(labelCount) { dialog, which ->
                viewModel.collectionStickerPrint(
                    collectionFk = collection.collectionFk, labelCount = (which + 1)
                )
                (getString(R.string.Imprimiendo) + mobileApplication.dataStoreApp.readDataStoreKey<String>(
                    PRINTERNAME
                )).toast(requireContext())

            }
            val dialog = builder.create()
            dialog.show()
        } else {
            viewModel.collectionStickerPrint(
                collectionFk = collection.collectionFk, null
            )

        }

    }

    private fun showMistakeList(list: List<MistakeTypeVO>) {

        customDialogInput.dismiss()
        //
        listPlacementSupply = ArrayList()
        list.forEach {
            listPlacementSupply.add(BarcodeVO(code = it.description))
        }

        customDialogList.setTitle(getString(R.string.errorCause))
        customDialogList.hideTextInput().setKoButton(getString(R.string.cancel)) {
            scanRequest()
            hideKeyboards()
            listPlacementSupply.clear()
            customDialogList.dismiss()

        }.show()


        placementSupplyAdapter =
            BarcodeAdapter(listPlacementSupply, object : OnBarcodeRowClickListener {
                override fun onBarcodeRowClickListener(item: BarcodeVO) {
                    list.forEach {
                        if (it.description == item.code) {

                            viewModel.saleMistakeAdd(
                                saleFk = mistakeSale?.saleFk!!, typeFk = it.id
                            )


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

                }
            }, showDelete = false)

        customDialogList.getRecyclerView().adapter = placementSupplyAdapter

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

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

    private fun groupSaleGroup(salesList: ArrayList<SaleVO>): MutableList<SaleVO> {
        var myMap = salesList.groupBy { it.saleGroupFk }
        var myList: MutableList<SaleVO> = mutableListOf()

        for ((key, value) in myMap.entries) {
            if (key.isNullOrEmpty()) { // si no tiene saleGroup se añaden las líneas
                for (s in value) {
                    myList.add(s)
                }
            } else { // si tiene saleGroup se crea el padre con el tamaño e indicando que es padre, como ejemplo se toma el primer elemento

                /*crea padre*/
                if (value.size > 1) {
                    var mySale = SaleVO(
                        saleOrder = value[0].saleOrder,
                        workerFk = value[0].workerFk,
                        originalQuantity = null,
                        quantity = null,
                        rgb = null,
                        saleFk = value[0].saleFk,
                        saleGroupFk = value[0].saleGroupFk,
                        isPreControlled = value[0].isPreControlled,
                        isPrepared = value[0].isPrepared,
                        isPreviousPrepared = value[0].isPreviousPrepared,
                        isControlled = value[0].isControlled,
                        line3 = value[0].code ?: "", //6676
                        picked = value[0].picked,
                        ticketFk = value[0].ticketFk,
                        level = value[0].level

                    )//prime elemento//hay que hacer una copia si no queda la referencia
                    mySale.totalSales = value.size //total líneas
                    mySale.isParent = true
                    value as MutableList<SaleVO>
                    mySale.sonSales =
                        value.sortedWith(compareBy { it.picked }) as MutableList<SaleVO>

                    mySale.line1 = "Previa :${mySale.saleGroupFk}"
                    mySale.line2 = "Líneas: ${value.size}"
                    mySale.line3 = value[0].code ?: ""
                    mySale.placements = listOf(PlacementVO(shelving = value[0].code ?: ""))

                    myList.add(mySale)
                } else {
                    for (s in value) {
                        myList.add(s)
                    }
                }

            }

        }

        return myList
    }

}


