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

import android.content.Context
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.graphics.drawable.GradientDrawable
import android.media.MediaPlayer
import android.os.Bundle
import android.text.InputType
import android.view.Gravity
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.gson.Gson
import es.verdnatura.R
import es.verdnatura.databinding.FragmentCollectionNewBinding
import es.verdnatura.domain.ConstAndValues.BASEURLSALIX
import es.verdnatura.domain.ConstAndValues.PRESACADOR
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.OnPackingClickSaleListener
import es.verdnatura.presentation.common.OnPasillerosItemClickListener
import es.verdnatura.presentation.common.OnSaleClickSaleListener
import es.verdnatura.presentation.common.OnTicketClickSaleListener
import es.verdnatura.presentation.common.ToolBarAdapterTooltip
import es.verdnatura.presentation.common.hideKeyboard
import es.verdnatura.presentation.common.itemScanIsQr
import es.verdnatura.presentation.common.itemScanValue
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.SaleAdapterNew
import es.verdnatura.presentation.view.feature.collection.mapper.map
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.CollectionTicket
import es.verdnatura.presentation.view.feature.sacador.model.Sale
import es.verdnatura.presentation.view.feature.sacador.model.SaleVO
import kotlinx.coroutines.runBlocking
import org.json.JSONObject

@Suppress("UNUSED_ANONYMOUS_PARAMETER")
class CollectionFragmentPickerPreviousNew(
    var collection: CollectionTicket,
    var type: String = PRESACADOR,
    private var hasPickingOrder: Boolean = false
) : BaseFragment<FragmentCollectionNewBinding, CollectionViewModel>(
    CollectionViewModel::class
) {
    private var sales: List<Sale> = listOf()
    private var saleAdapter: SaleAdapterNew? = 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 lateinit var customDialogInput: CustomDialogInput
    private lateinit var customDialogThreeButtons: CustomDialogThreeButtons
    private lateinit var customDialogThreeButtonsQuantity: CustomDialogThreeButtons
    private var ticketSelected: Int = 0
    private lateinit var customDialog: CustomDialog
    var mperror: MediaPlayer? = null
    var mpok: MediaPlayer? = null
    private var storedBackPosition: Int = 0
    private var tickets: ArrayList<String> = ArrayList()
    private var lastScanned: Int = 0
    private var positionUnmarked = -1
    private var isScanned: Boolean? = null
    private var positionConfirm = 0
    private var quantityConfirm = 0
    private lateinit var myGroupList: List<Sale>
    private var quantityReserveToCheckItemScan = 0

    companion object {
        fun newInstance(
            collection: CollectionTicket, type: String, hasPickingOrder: Boolean = false
        ) = CollectionFragmentPickerPreviousNew(collection, type, hasPickingOrder)
    }

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

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

    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 onResume() {
        super.onResume()
        scanRequest()
    }

    override fun init() {
        customDialogList = CustomDialogList(requireContext())
        customDialogInput = CustomDialogInput(requireContext())
        customDialog = CustomDialog(requireContext())
        customDialogThreeButtons = CustomDialogThreeButtons(requireContext())
        customDialogThreeButtonsQuantity = CustomDialogThreeButtons(requireContext())
        ma.hideBottomNavigation(View.GONE)
        println("type $type")
        setEvents()
        setToolBar()
        viewModel.collectionTicketGetSalix(
            collection.collectionFk, print = false
        )

        super.init()
    }

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

        val listIcons: ArrayList<ImageView> = ArrayList()

        val iconAdd = ImageView(context)
        iconAdd.setImageResource(R.drawable.ic_playlist_add_black_24dp)
        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)

        iconAdd.tooltipText = getTooltip(R.drawable.ic_playlist_add_black_24dp)
        iconParking.tooltipText = getTooltip(R.drawable.ic_local_parking_black_24dp)
        iconUpdate.tooltipText = getTooltip(R.drawable.ic_autorenew_black_24dp)

        listIcons.add(iconAdd)
        listIcons.add(iconParking)
        listIcons.add(iconUpdate)

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

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

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

    private fun updateScreen() {
        viewModel.collectionTicketGetSalix(
            collection.collectionFk, print = false
        )
    }

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

    private fun setEvents() {

        binding.mainToolbar.backButton.setOnClickListener {
            ma.onMyBackPressed()
        }
        //ESCANER =========

        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().isNotEmpty()) {
                    binding.scanInput.setText(textScanned_filterDouble(binding.scanInput.text!!.toString()))
                    isScanned =
                        event != null && event.action == KeyEvent.ACTION_DOWN && event.keyCode == KeyEvent.KEYCODE_ENTER
                    if (itemScanIsQr(binding.scanInput.text.toString())) {
                        val myQr = ItemScanned(JSONObject(binding.scanInput.text.toString()))
                        when (myQr.table) {
                            "saleGroup" -> {
                                binding.scanInput.setText(myQr.id.toString())
                            }

                            "buy" -> binding.scanInput.setText(myQr.more)
                        }

                    } else {
                        ma.hideKeyboard(binding.scanInput)
                        findSale(binding.scanInput.text.toString())
                    }
                }
                binding.scanInput.setText("")
                hideKeyboards()
                return@setOnEditorActionListener true
            }
            true
        }

        hideKeyboards()

        //LISTA =========
        binding.collectionSwipe.setOnRefreshListener {
            binding.collectionSwipe.isRefreshing = false
            updateScreen()
            binding.collectionSwipe.isRefreshing = false

        }
    }

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

    override fun observeViewModel() {

        with(viewModel) {

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

                        if (it.tickets.isNotEmpty()) {
                            collection = it
                            createCollectionList()

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

                }
            }
            loadExistsResponse.observe(viewLifecycleOwner) { event ->
                event.getContentIfNotHandled().notNull {
                    if (it.exists) {
                        markLine(it.position, it.quantity, true)
                    } else {
                        getString(R.string.updateSalesReserve).toast(
                            requireContext()
                        )
                        viewModel.collectionTicketGetSalix(collection.collectionFk, false)
                    }
                }
            }/*responseExistsItemShelvingSale.observe(viewLifecycleOwner) {
                if (!goBack) {
                    if (it.exists) {
                        markLine(it.position, it.quantity, true)
                    } else {
                        getString(R.string.updateSalesReserve).toast(
                            requireContext()
                        )
                        viewModel.collectionTicketGetSalix(collection.collectionFk, false)
                    }
                }

            }*/

            loadResponseAddItem.observe(viewLifecycleOwner) { event ->
                event.getContentIfNotHandled().notNull {
                    updateScreen()
                }

            }

            loadPicked.observe(viewLifecycleOwner) { event ->
                event.getContentIfNotHandled().notNull {
                    myGroupList[positionConfirm].isPicked = 1
                    saleAdapter!!.notifyItemChanged(positionConfirm)
                    lm!!.scrollToPositionWithOffset(positionConfirm, 0)
                    //lm!!.scrollToPositionWithOffset(storedBackPosition + 1, 0)
                    setTotalLines()

                }
            }

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

                    myGroupList[positionUnmarked].isPicked = 0
                    myGroupList[positionUnmarked].reservedQuantity = quantityConfirm
                    saleAdapter!!.notifyItemChanged(positionUnmarked)
                    lm!!.scrollToPositionWithOffset(positionUnmarked, 0)

                }
            }

            responseCode.observe(viewLifecycleOwner) {

                if (it == null) {
                    showErrorMessage(text = getString(R.string.codeNotExist))
                    if (mperror != null) mperror?.start()
                } else {
                    if (checkItemScan(it.toString(), positionConfirm)) {
                        scanRequest()
                        customDialogList.dismiss()
                        mpok?.start()
                        markLine(positionConfirm, quantityReserveToCheckItemScan, false)
                    } else {
                        customDialogList.setValueTwo("")
                        showErrorMessage(text = getString(R.string.lineNotExist))
                        if (mperror != null) mperror?.start()
                    }
                }

            }

        }
    }

    private fun createCollectionList() {
        binding.mainToolbar.toolbarTitle.text = collection.collectionFk.toString()

        collection.map(requireContext())
        val salesList: ArrayList<Sale> = ArrayList()

        tickets = ArrayList()
        var observations = ""
        val myPickingFrom = mobileApplication.dataStoreApp.readDataStoreKey<Int>("PICKING_FROM")
        val myPickingTo = mobileApplication.dataStoreApp.readDataStoreKey<Int>("PICKING_TO")
        collection.tickets.forEach { ticket ->

            if (observations.isNotEmpty()) observations = observations + " " + ticket.observations
            ticket.sales.forEach { sale ->

                if (hasPickingOrder) {
                    if (sale.pickingOrder != null && sale.pickingOrder in myPickingFrom..myPickingTo) {
                        salesList.add(sale)
                    }
                } else {
                    salesList.add(sale)
                }

            }
        }
        // sales = salesList.sortedWith(compareBy<Sale> { it.pickingOrderPrevia }.thenBy { it.itemFk })
        //quitar comentarios FALTA AGRUPAR LAS PREVIAS
        myGroupList =
            salesList.sortedWith(compareBy<Sale> { it.pickingOrderPrevia }.thenBy { it.itemFk })
        saleAdapter = SaleAdapterNew(myGroupList, pasillerosItemClickListener!!,

            object : OnSaleClickSaleListener {
                override fun onSaleClick(sale: Sale) {

                    val position =
                        myGroupList.indexOfFirst { it.itemShelvingSaleFk == sale.itemShelvingSaleFk }
                    if (position > -1) {
                        if (sale.isPicked == 1) {
                            unMarkLine(position, myGroupList[position])
                        } else {
                            showScanner(position, sale)
                        }
                    }

                }

            }, object : OnMistakeClickListener {
                override fun onMistakeClickListener(sale: SaleVO) {
                }
            }, object : OnPackingClickSaleListener {
                override fun onPackingClick(sale: Sale) {

                    if (!sale.code.isNullOrEmpty()) ma.onPasillerosItemClickListener(
                        PasillerosItemVO(
                            title = R.string.titleUbicator,
                        ), entryPoint = sale.code
                    )
                }
            }, object : OnTicketClickSaleListener {
                override fun onTicketClickListener(sale: Sale) {
                    val entryPoint = Gson().toJson(
                        mutableMapOf(
                            "entryPoint" to sale.ticketFk, "web" to "${
                                mobileApplication.dataStoreApp.readDataStoreKey<String>(
                                    BASEURLSALIX
                                )
                            }/#!/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()
        setListPosition()
        setScrollListener(lm!!)
        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()
                storedPosition = 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()
        }
    }

    private fun findSale(txtscan: String) {

        var isFoundSale = false
        //Se busca la matricula en las lineas
        for (indice in myGroupList.indices) {
            if (myGroupList[indice].isPicked != 1 && myGroupList[indice].code != null && myGroupList[indice].code!!.uppercase() == txtscan.uppercase()) {
                mpok!!.start()
                isFoundSale = true
                printShelvingResult(indice)
                break
            }
        }

        if (!isFoundSale) mperror!!.start()

    }

    private fun findSale(txtscan: String, position: Int, sale: Sale) {

        storedPosition = position

        if (sale.code!!.uppercase() == txtscan.uppercase()) {
            mpok!!.start()
            printShelvingResult(position)
        } else {
            mperror!!.start()
        }

    }

    private fun markLine(position: Int, quantity: Int, isItemShelvingSaleEmpty: Boolean?) {

        isScanned = null
        positionConfirm = position
        quantityConfirm = quantity

        runBlocking {
            val sectorFk = mobileApplication.dataStoreApp.readDataStoreKey<Int>(SECTORFK)
            viewModel.itemShelvingSaleSetQuantity(
                myGroupList[position].itemShelvingSaleFk,
                quantity,
                isItemShelvingSaleEmpty = isItemShelvingSaleEmpty,
                sectorFk = if (sectorFk == -1) null else sectorFk
            )
        }
        // storedBackPosition = position

    }

    private fun setListPosition() {

        //if (storedPosition == 0 && storedBackPosition == 0) { // se inicia lista, se busca porqué item vamos.
        if (storedPosition == 0) {
            for (indice in myGroupList.indices) {
                if (myGroupList[indice].isPicked == 0) {
                    //storedPosition = indice
                    lm!!.scrollToPositionWithOffset(indice - 1, 0)
                    break
                }
            }

        } else {
            //  lm!!.scrollToPositionWithOffset(storedBackPosition, 0)
            lm!!.scrollToPositionWithOffset(storedPosition, 0)
        }
    }

    private fun unMarkLine(position: Int, sale: Sale) {

        customDialog.setTitle(getString(R.string.unmarkLine)).setDescription(
            getString(R.string.goUnmark) + sale.itemFk + getString(
                R.string.sure
            )
        ).setOkButton(getString(R.string.unmark)) {
            if (!sale.isParent && sale.reservedQuantity == 0 && sale.originalQuantity != sale.saleQuantity) {
                getString(R.string.unmarkError).toast(requireContext())
            } else {
                //storedBackPosition = position
                //storedPosition = position
                // setListPosition()
                viewModel.itemShelvingSaleUnpicked(myGroupList[position].itemShelvingSaleFk)
                sale.isPicked = 0
                positionUnmarked = position
                setTotalLines()
                scanRequest()
            }


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

    }

    private fun printShelvingResult(pos: Int) {

        storedPosition = pos
        customDialogList.getEditTextTwo().inputType = InputType.TYPE_CLASS_TEXT
        customDialogList.getEditTextTwo().setRawInputType(InputType.TYPE_CLASS_NUMBER)
        customDialogList.getEditText().setRawInputType(InputType.TYPE_CLASS_NUMBER)
        customDialogList.getEditTextTwo().requestFocus()
        val shelving = myGroupList[pos].code
        val item = myGroupList[pos].itemFk
        val longName = myGroupList[pos].longName
        val totalReserved = myGroupList[pos].reservedQuantity

        try {
            customDialogList.setTitle("$shelving($item) $totalReserved de $longName").setOkButton(
                getString(
                    R.string.take
                )
            ) {
                customDialogTakeAction(pos, totalReserved, false)

            }.setKoButton(getString(R.string.close)) {
                requireActivity().hideKeyboard(customDialogList.getEditTextTwo())
                customDialogList.dismiss()
                scanRequest()

            }.setHintValue(getString(R.string.quantitySelect)).setValue(totalReserved.toString())
                .setHintValueTwo(getString(R.string.scanItem)).setValueTwo("").show()

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

                    customDialogTakeAction(
                        pos,
                        totalReserved,
                        event != null && event.action == KeyEvent.ACTION_DOWN && event.keyCode == KeyEvent.KEYCODE_ENTER
                    )

                    return@setOnEditorActionListener true

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

    private fun customDialogTakeAction(
        position: Int, totalReserved: Int, isItemScanned: Boolean?
    ) {
        isScanned = isItemScanned
        if (customDialogList.getValueTwo().isNotEmpty()) {

            customDialogList.setValueTwo(
                itemScanValue(
                    customDialogList.getValueTwo(), arrayOf("buy"), "more"
                ).toString()
            )
            val quantityToReserve = customDialogList.getValue().toInt()

            if (quantityToReserve < totalReserved) {

                if (customDialogList.getValueTwo() in myGroupList[position].Barcodes || customDialogList.getValueTwo() == myGroupList[position].itemFk.toString()) {
                    customDialogList.dismiss()
                    showQuestionUbicationEmpty(position, quantityToReserve)
                } else {
                    ma.messageWithSound(
                        message = getString(R.string.errorItem),
                        isError = true,
                        isPlayed = true,
                        isToasted = false
                    )
                }
            }

            if (quantityToReserve > totalReserved) {
                ma.hideKeyboard(customDialogList.getEditTextTwo())
                getString(R.string.quantityHigh).toast(requireContext())
            }
            if (quantityToReserve == totalReserved) {
                try {
                    if (checkItemScan(customDialogList.getValueTwo(), position)) {

                        markLine(position, quantityToReserve, false)

                        mpok?.start()
                        ma.hideKeyboard(customDialogList.getEditTextTwo())
                        customDialogList.dismiss()
                        showTicket(myGroupList[position].ticketFk)

                        scanRequest()

                    } else {

                        quantityReserveToCheckItemScan = quantityToReserve
                        viewModel.getIdFromCodeSalix(
                            code = customDialogList.getValueTwo(),
                        )
                        customDialogList.dismiss()
                    }
                } catch (ex: Exception) {
                    getString(R.string.errorInput).toast(requireContext())
                }

            }

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

    private fun showTicket(ticketFk: Int) {
        val inflater = LayoutInflater.from(requireContext())
        val layout = inflater.inflate(R.layout.ticket_toast_layout, null)
        val text = layout.findViewById<TextView>(R.id.toast_text)
        text.text = "$ticketFk"
        text.setTextColor(requireContext().getColor(R.color.verdnatura_orange_salix))
        text.textSize = 18f
        val background = GradientDrawable()
        background.setColor(Color.parseColor("#000000"))
        background.cornerRadius = 16f
        layout.background = background
        val toast = Toast(requireContext())
        toast.duration = Toast.LENGTH_LONG
        toast.view = layout
        toast.setGravity(Gravity.CENTER, 0, 0)
        toast.show()
    }

    private fun checkItemScan(valueToCheck: String, position: Int): Boolean {
        println("CheckItemScan $valueToCheck")
        val saleToCheck = myGroupList[position]
        println("CheckItemScan saleTocheck$saleToCheck")
        println("CheckItemScan saleTocheck Item ${saleToCheck.itemFk}")
        println("CheckItemScan saleTocheck ItemBarcodes ${saleToCheck.Barcodes}")
        if (saleToCheck.itemFk.toString() == valueToCheck) return true
        else {
            saleToCheck.Barcodes.forEach { barcode ->
                if (barcode == valueToCheck) return true
            }
        }

        return false
    }

    private fun showQuestionUbicationEmpty(position: Int, quantity: Int = 0) {
        customDialogThreeButtonsQuantity.setTitle(
            getString(
                R.string.changeQuantity, quantity, myGroupList[position].itemFk
            )
        ).setDescription(getString(R.string.questionItemShelving, myGroupList[position].itemFk))
            .setValue("").setCustomDialogValue(View.GONE)
        customDialogThreeButtonsQuantity.setOkButtonAdd(text = getString(R.string.yes)) {
            scanRequest()
            customDialogThreeButtonsQuantity.dismiss()
            getString(R.string.errorQuantityShelving).toast(requireContext())
            customDialogThreeButtonsQuantity.dismiss()
            showQuestionUbicationEmpty(position, quantity)
        }.setOkButtonTwo(getString(R.string.no)) {
            scanRequest()
            customDialogThreeButtonsQuantity.dismiss()
            if (quantity == 0) {
                viewModel.itemShelvingSaleExists(
                    myGroupList[position].itemShelvingSaleFk, position, quantity
                )
            } else {
                markLine(position, quantity, true)
            }
        }.setKoButton(getString(R.string.cancel)) {
            scanRequest()
            customDialogThreeButtonsQuantity.dismiss()
        }.show()
        customDialogThreeButtons.setFocusDialogValue()
    }

    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 = InputType.TYPE_CLASS_NUMBER
        customDialogList.getEditText().setRawInputType(InputType.TYPE_CLASS_NUMBER)
        customDialogList.setTitle(getString(R.string.Agregarartículoparaticket) + " " + ticketSelected)
            .setOkButton(getString(R.string.Agregar)) {
                customDialogAddItem()
            }.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()
        requireActivity().hideKeyboard()

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

                    } catch (e: Exception) {
                        ma.messageWithSound(e.message.toString(), isError = true, true)
                    }
                    customDialogList.getEditTextTwo().requestFocus()
                }

                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) {
                customDialogAddItem()
                return@setOnEditorActionListener true

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

        if (customDialogList.getValueTwo().isNotEmpty()) {
            if (ticketSelected == 0) {
                getString(R.string.Seleccionaunticketdelaista).toast(requireContext())
            } else if (customDialogList.getValue().isEmpty() || customDialogList.getValueTwo()
                    .isEmpty()
            ) {
                getString(R.string.Todosloscampossonobligatorios).toast(requireContext())
            } else {
                val saleGroupSelected =
                    collection.tickets.find { it.ticketFk == ticketSelected }?.sales?.get(0)?.saleGroupFk
                        ?: 0

                runBlocking {
                    viewModel.collectionAddWithReservation(
                        customDialogList.getValue().toInt(),
                        customDialogList.getValueTwo().toInt(),
                        ticketSelected,
                        saleGroupFk = saleGroupSelected,
                        sectorFk = mobileApplication.dataStoreApp.readDataStoreKey<Int>(SECTORFK)
                    )
                }
                customDialogList.dismiss()
                hideKeyboards()
                scanRequest()
            }
        } else {
            getString(R.string.scanItem).toast(requireContext())
        }

    }

    private fun toastDisponibility(item: ItemVO) {
        if (item.available.isEmpty()) {
            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() {
        val totalMark = myGroupList.count { it.isPicked == 1 }
        binding.mainToolbar.toolbarTitle.text =
            if (collection.collectionFk != 0) collection.collectionFk.toString() else ""
        binding.mainToolbar.toolbarSubtitle.text =
            getString(R.string.totalsPicker, totalMark, myGroupList.size)
        if (totalMark == myGroupList.size) {
            getString(R.string.Coleccióncompleta).toast(this.context, Toast.LENGTH_SHORT)
            viewModel.saleTrackingAddPrevOK(collection.collectionFk)
        }
    }

    private fun showScanner(index: Int, sale: Sale) {
        customDialogInput.getEditText().inputType = InputType.TYPE_CLASS_TEXT
        customDialogInput.setTitle("" + sale.itemFk)
            .setDescription(getString(R.string.scanWagonForItem))
            .setOkButton(getString(R.string.accept)) {
                findSaleAction(index, sale)
            }.setKoButton(getString(R.string.cancel)) {
                closeCustomDialog(binding.scanInput, customDialogInput)
            }.setValue("").show()


        customDialogInput.getEditText().setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0) {
                findSaleAction(index, sale)
                return@setOnEditorActionListener false
            }
            false
        }
        customDialogInput.getEditText().requestFocus()
    }

    private fun findSaleAction(index: Int, sale: Sale) {
        if (customDialogInput.getValue().isNotEmpty()) {
            findSale(customDialogInput.getValue(), index, sale)
        }
        closeCustomDialog(binding.scanInput, customDialogInput)
    }

    private fun closeCustomDialog(scanInput: EditText, customDialogInput: CustomDialogInput) {
        requireContext().hideKeyboard(customDialogInput.getEditText())
        scanInput.requestFocus()
        customDialogInput.dismiss()
        scanInput.requestFocus()
    }

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