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

import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.graphics.drawable.Drawable
import android.media.MediaPlayer
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.text.InputType
import android.util.Log.d
import android.view.KeyEvent
import android.view.View
import android.view.WindowManager
import android.view.inputmethod.EditorInfo
import android.widget.EditText
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.FragmentCollectionNewBinding
import es.verdnatura.domain.ConstAndValues.BASEURLSALIX
import es.verdnatura.domain.ConstAndValues.CONTROLADOR
import es.verdnatura.domain.ConstAndValues.PRINTERNAME
import es.verdnatura.domain.ConstAndValues.SACADOR
import es.verdnatura.domain.ConstAndValues.SECTORFK
import es.verdnatura.domain.toast
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.*
import es.verdnatura.presentation.view.component.CustomDialog
import es.verdnatura.presentation.view.component.CustomDialogInput
import es.verdnatura.presentation.view.component.CustomDialogList
import es.verdnatura.presentation.view.component.CustomDialogThreeButtons
import es.verdnatura.presentation.view.feature.articulo.adapter.BarcodeAdapter
import es.verdnatura.presentation.view.feature.articulo.model.BarcodeVO
import es.verdnatura.presentation.view.feature.collection.ItemVO
import es.verdnatura.presentation.view.feature.collection.adapter.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.*
import org.json.JSONObject

@Suppress("UNUSED_ANONYMOUS_PARAMETER")
class CollectionFragmentPickerNew(
    var collection: CollectionTicket, var type: String = SACADOR
) : BaseFragment<FragmentCollectionNewBinding, CollectionViewModel>(
    CollectionViewModel::class
) {
    private var sales: List<Sale> = listOf()
    private var salesParent: List<SaleVO> = 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
    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 isMarking = false
    private lateinit var ticketScanTxt: String
    private var lastScanned: Int = 0
    private var buttonPushedGetCollection = false
    private var positionUnmarked = -1
    private var state = 0
    private var originalItemScan: Long = 0
    private var workerFkFromTicket: String? = null
    private var isScanned: Boolean? = null
    private var positionConfirm = 0
    private var quantityConfirm = 0
    private var positionMarkPrevia = 0
    private lateinit var myGroupList: List<Sale>

    companion object {
        fun newInstance(collection: CollectionTicket, type: String) =
            CollectionFragmentPickerNew(collection, type)
    }

    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)
        viewModel.collectionTicketGetSalix(
            collection.collectionFk, print = false
        )
        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)
        binding.splashProgress.visibility = View.VISIBLE
        setEvents()
        setToolBar()
        if (collection.tickets.isNotEmpty()) {
            createCollectionList()
        }
        super.init()
    }

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

    private fun setToolBar() {
        binding.mainToolbar.toolbarSubtitle.visibility = 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 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 iconPhone = ImageView(context)
        iconPhone.setImageResource(R.drawable.phone_call)
        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)
            iconPhone.tooltipText = getTooltip(R.drawable.phone_call)
            iconParking.tooltipText = getTooltip(R.drawable.ic_local_parking_black_24dp)
            iconUpdate.tooltipText = getTooltip(R.drawable.ic_autorenew_black_24dp)

        }
        listIcons.add(iconPrint)
        listIcons.add(iconAdd)
        listIcons.add(iconUpdate)
        listIcons.remove(iconWorker)

        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 = getString(R.string.Parking)
                            ), ""
                        )
                    }

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

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

    private fun markPrevia(saleGroupScanned: String): Boolean {
        println("Sacador saleGroup $saleGroupScanned ")
        try {
            for (indice in sales.indices) {
                println("Sacador saleGroup ${sales[indice].saleGroupFk}")
                if (sales[indice].saleGroupFk != null && sales[indice].saleGroupFk == saleGroupScanned.toInt()) {
                    println("Sacador saleGroup ${sales[indice].itemShelvingSaleFk}")
                    viewModel.itemShelvingSaleSetSaleGroup(saleGroupScanned.toInt())
                    positionMarkPrevia = indice
                    return true
                    mpok!!.start()

                }
            }
        } catch (ex: Exception) {
            return false
        }
        return false
    }

    private fun getCollection() {
        binding.splashProgress.visibility = View.VISIBLE
        if (!buttonPushedGetCollection) {
            viewModel.collection_get(
                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 = getString(R.string.titleUserControlVehicle)),
            workerFkFromTicket.toString()
        )

    }

    private fun setEvents() {

        binding.mainToolbar.backButton.setOnClickListener {
            requireActivity().onBackPressed()
        }
        //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().isNullOrEmpty()) {
                    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" -> {
                                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)
                        }

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

        hideKeyboards()

        //LISTA =========
        binding.collectionSwipe.setOnRefreshListener {
            isMarking = false
            binding.collectionSwipe.isRefreshing = false
            binding.splashProgress.visibility = View.VISIBLE
            viewModel.collectionTicketGet(
                collection.collectionFk,
                mobileApplication.dataStoreApp.readDataStoreKey(SECTORFK),
                print = "0",
                type
            )
            buttonPushedGetCollection = false
            binding.collectionSwipe.isRefreshing = false

        }
    }

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

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

        with(viewModel) {
            binding.splashProgress.visibility = View.GONE
            collectionTicketList.observe(viewLifecycleOwner, Observer {
                if (!it.isError) {
                    if (it.tickets.isNotEmpty()) {
                        //collection = it
                        createCollectionList()
                        workerFkFromTicket = it.tickets.get(0).sales.get(0).workerFk

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

            })

            collectionTicketSalix.observe(viewLifecycleOwner, Observer {
                binding.splashProgress.visibility = View.GONE
                if (!it.isError) {

                    if (it.tickets.isNotEmpty()) {
                        collection = it
                        createCollectionList()
                        workerFkFromTicket = if (it.tickets[0].sales.isNotEmpty()) {
                            it.tickets[0].sales[0].workerFk.toString()
                        } else {
                            ""
                        }

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

            })

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

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

            })

            responseCollectionAddItem.observe(viewLifecycleOwner, Observer {
                if (!goBack) {
                    viewModel.collectionTicketGet(
                        collection.collectionFk,
                        mobileApplication.dataStoreApp.readDataStoreKey(SECTORFK),
                        print = "0",
                        type
                    )

                    goBack = false
                }

            })

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

                if (!goBack) {

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

            })

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

                if (it.isError) {
                    ma.messageWithSound(
                        if (it.isError) it.errorMessage else getString(R.string.confirmReserv),
                        it.isError,
                        it.isError
                    )
                }
                if (!it.isError) {
                    sales[positionConfirm].isPicked = 1
                    saleAdapter!!.notifyDataSetChanged()
                    viewModel.collectionTicketGetSalix(
                        collection.collectionFk, print = false
                    )
                }

            })


            responseItemShelvingSale.observe(viewLifecycleOwner, Observer {
                binding.splashProgress.visibility = View.GONE
                myGroupList[positionConfirm].isPicked = 1
                myGroupList[positionConfirm].reservedQuantity = quantityConfirm
                viewModel.collectionTicketGetSalix(
                    collection.collectionFk, print = false
                )
                lm!!.scrollToPositionWithOffset(positionConfirm, 0)
                //saleAdapter!!.notifyDataSetChanged()
                ma.messageWithSound(
                    "Confirmada acción", it.isError, !it.isError
                )
            })
            responseItemShelvingSaleUnPicked.observe(viewLifecycleOwner, Observer {
                binding.splashProgress.visibility = View.GONE
                myGroupList[positionUnmarked].isPicked = 1
                myGroupList[positionUnmarked].reservedQuantity = quantityConfirm
                viewModel.collectionTicketGetSalix(
                    collection.collectionFk, print = false
                )
                lm!!.scrollToPositionWithOffset(positionUnmarked, 0)
                //saleAdapter!!.notifyDataSetChanged()
                ma.messageWithSound(
                    "Confirmada acción", it.isError, !it.isError
                )
            })
            responseItemShelvingSaleGroup.observe(viewLifecycleOwner, Observer {

                viewModel.collectionTicketGetSalix(
                    collection.collectionFk, print = false
                )
                lm!!.scrollToPositionWithOffset(positionMarkPrevia, 0)

                ma.messageWithSound(
                    "Previa recogida", it.isError, !it.isError
                )
            })

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

                            } else {
                                showErrorMessage(text = getString(R.string.lineNotExist))
                            }


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

                goBack2 = false

            })

        }
    }

    private fun callPicker(extensionNumber: String) {

        try {
            val intent = Intent(Intent.ACTION_DIAL).apply {
                data = Uri.parse("tel:$extensionNumber")
            }
            startActivity(intent)
        } catch (e: Exception) {
            // d("VERDNATURA::" + e.message)
        }

    }

    private fun createCollectionList() {
        state = 0
        binding.mainToolbar.toolbarTitle.text = collection.collectionFk.toString()
        binding.splashProgress.visibility = View.GONE
        collection.map(requireContext())
        var salesList: ArrayList<Sale> = ArrayList()

        tickets = ArrayList()
        var observations = ""
        collection.tickets.forEach { ticket ->

            if (!observations.isNullOrEmpty()) observations =
                observations + " " + ticket.observations
            ticket.sales.forEach { sale ->
                salesList.add(sale)

            }
        }

        sales = salesList.sortedWith(compareBy<Sale> { it.pickingOrder }.thenBy { it.itemFk })

        for (s in sales) {
            println("Sacador sale: ${s.saleFk} saleGRoup: ${s.saleGroupFk} item : ${s.itemFk}")
        }
        //quitar comentarios FALTA AGRUPAR LAS PREVIAS
        myGroupList =
            groupSaleGroup(salesList).sortedWith(compareBy<Sale> { it.pickingOrder }.thenBy { it.itemFk })
        saleAdapter = SaleAdapterNew(
            myGroupList,
            pasillerosItemClickListener!!,
            object : OnQuantityClickSaleListener {

                override fun onQuantityClick(sale: Sale) {
                    sales.forEachIndexed { index, saleVO ->

                        if (saleVO.saleFk == sale.saleFk) {
                            if (sale.isPicked == 1) {
                                showErrorMessage(
                                    title = getString(R.string.info),
                                    text = "Tienes que desmarcar la línea para poder modificar la cantidad"
                                )
                            } else {
                                //  showQuantityDialog(index)
                            }

                        }
                    }

                }
            },
            object : OnSaleClickSaleListener {
                override fun onSaleClick(mysale: Sale) {

                    sales.forEachIndexed { index, sale ->
                        //  println("Sacador la sale es ${sale.saleFk}")
                        // println("Sacador la sale picked es ${sale.isPicked}")
                        // println("Sacador la sale group es ${sale.saleGroupFk}")
                        // println("Sacador la sale reserved es ${sale.reservedQuantity}")
                        if (sale.itemShelvingSaleFk == 0) {
                            println("Sacador Que hacemos en este caso ?? ")
                        } else {
                            if (sale.itemShelvingSaleFk == mysale.itemShelvingSaleFk) {
                                println("Sacador **** itemShelvingSale es ${sale.itemShelvingSaleFk}")
                                println("Sacador **** isPicked es ${sale.isPicked}")
                                println("Sacador **** saleGroup es ${sale.saleGroupFk}")
                                //println("Sacador la sale es ${sale.saleFk}")
                                //println("Sacador la sale picked es ${sale.isPicked}")
                                //println("Sacador la sale group es ${sale.saleGroupFk}")
                                //println("Sacador la sale reserved es ${sale.reservedQuantity}")
                                //println("Sacador la sale dentro es ${sale.saleFk}")
                                if (sale.isPicked != 1 && sale.saleGroupFk == null) {
                                    println("Sacador **** showScanner")
                                    showScanner(index, sale)
                                } else {
                                    println("Sacador **** desmarcar")
                                    unMarkLine(index, sales[index])
                                }

                            }
                        }

                    }
                }

            },
            object : OnMistakeClickListener {
                override fun onMistakeClickListener(sale: SaleVO) {
                }
            },
            object : OnPackingClickSaleListener {
                override fun onPackingClick(sale: Sale) {
                    if (!sale.code.isNullOrEmpty()) ma.onPasillerosItemClickListener(
                        PasillerosItemVO(
                            title = getString(R.string.titleUbicator),
                        ), entryPoint = sale.code!!
                    )
                }
            },
            object : OnTicketClickSaleListener {
                override fun onTicketClickListener(sale: Sale) {
                    var entryPoint = Gson().toJson(
                        mutableMapOf(
                            "entryPoint" to sale.ticketFk,
                            "web" to "${
                                mobileApplication.dataStoreApp.readDataStoreKey<String>(
                                    BASEURLSALIX
                                )
                            }/#!/ticket/${sale.ticketFk}/sale"
                        )
                    )
                    ma.onPasillerosItemClickListener(
                        PasillerosItemVO(
                            title = getString(R.string.titleWebViewer),
                        ), entryPoint = entryPoint
                    )
                }
            },
            type = type
        )


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

        setTotalLines()
        setStoredPosition(true)
        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()
                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 isOk = markPrevia(txtscan)

        if (isOk) {
            //Se ha escanado un ticket y se ha marcado la previa
        } else {
            //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()
                    isOk = true
                    positionMarkPrevia = indice
                    printShelvingResult(indice)
                    break
                }
            }
            if (!isOk) {
                //Si no es previa ni está cogiendo nada se comprueba si es un parking
                if (txtscan.contains("-")) {
                    viewModel.setParking(
                        ticketFk = collection.collectionFk, parking = txtscan
                    )
                } else {
                    mperror!!.start()
                }

            }
        }

    }

    private fun findSale(txtscan: String, position: Int, sale: Sale) {
        println("Sacador La position es $position")
        println("Sacador El escaneado es $txtscan y el code ${sale.code}")

        storedPosition = position

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

    }

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

        state = 0
        isScanned = null
        positionConfirm = position
        quantityConfirm = quantity
        isMarking = true

        viewModel.itemShelvingSaleSetQuantity(
            myGroupList[position].itemShelvingSaleFk, quantity, isItemShelvingSaleEmpty
        )

        //nuevo tema agrupacion sales
        //checkStateParent()
        // var mySale = sales[position].saleFk Ordenar setPosition
        var mySale = sales[position].itemShelvingSaleFk
        for (indice in myGroupList.indices) {
            if (!myGroupList[indice].isParent && myGroupList[indice].itemShelvingSaleFk == mySale) {
                d("VERDNATURA::", "la pos del index de la sale es" + indice)
                storedBackPosition = indice
            }
        }

        //setTotalLines()
    }

    //Tarea #4371

    private fun checkStateParent() {
        for (s in myGroupList) {
            if (s.isParent) {
                var totalLines = s.sonSales.size
                var isPreviousPrepared = s.sonSales.filter { it.semaphore == "1" }.size
                var isPrepared = s.sonSales.filter { it.semaphore == "2" }.size
                var isControlled = s.sonSales.filter { it.semaphore == "1" }.size
                var isPreControlled = s.sonSales.filter { it.semaphore == "4" }.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) {
        d("VERDNATURA::", "Vamos a la pos" + storedBackPosition)
        if (storedPosition == 0 && storedBackPosition == 0) { // se inicia lista, se busca porqué item vamos.
            for (indice in myGroupList.indices) {
                if (myGroupList[indice].isPicked == 0) {
                    //storedPosition = indice
                    lm!!.scrollToPositionWithOffset(storedPosition, 0)
                    break
                }
            }

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

    private fun unMarkLine(position: Int, sale: Sale) {
        state = 0
        customDialog.setTitle(getString(R.string.unmarkLine)).setDescription(
            getString(R.string.goUnmark) + sale.itemFk + getString(
                R.string.sure
            )
        ).setOkButton(getString(R.string.unmark)) {
            sale.isPicked = 0
            saleAdapter!!.notifyDataSetChanged()
            var mySale = sale.saleFk
            for (indice in myGroupList.indices) {
                if (!myGroupList[indice].isParent && myGroupList[indice].saleFk == mySale) {
                    d("VERDNATURA::", "la pos del index de la sale es" + indice)
                    storedBackPosition = indice
                }
            }
            storedBackPosition = position
            setListPosition(position, false)
            viewModel.itemShelvingSaleUnpicked(sales[position].itemShelvingSaleFk)
            println("itemshelvingSale ${sales[position].itemShelvingSaleFk}")
            positionUnmarked = position
            setTotalLines()
            scanRequest()
            customDialog.dismiss()
        }.setKoButton(getString(R.string.cancel)) {
            scanRequest()
            customDialog.dismiss()
        }.show()

    }

    //SHELVINGS

    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()
        var shelving = myGroupList[pos].code
        var item = myGroupList[pos].itemFk
        var longName = myGroupList[pos].longName
        var totalReserved = myGroupList[pos].reservedQuantity
        var itemShelvingFk = myGroupList[pos].itemShelvingSaleFk

        try {
            customDialogList.setTitle("$shelving($item) $totalReserved de $longName").setOkButton(
                getString(
                    R.string.take
                )
            ) {
                customDialogTakeAction(pos, itemShelvingFk, 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,
                        itemShelvingFk,
                        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(), true, true)
        }
    }

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

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

            if (quantityToReserve < totalReserved) {
                customDialogList.dismiss()
                showQuestionUbicationEmpty(position, quantityToReserve)
            }

            if (quantityToReserve > totalReserved) {
                ma.hideKeyboard(customDialogList.getEditTextTwo())
                getString(R.string.quantityHigh).toast(requireContext())
            }

            if (quantityToReserve == totalReserved) {
                originalItemScan = customDialogList.getValueTwo().toLong()
                println("Sacador a checkItemScan")
                if (checkItemScan(customDialogList.getValueTwo())) {

                    onQuantityOfShelvingSelected(
                        itemShelvingFk, quantityToReserve
                    )

                    mpok?.start()
                    ma.hideKeyboard(customDialogList.getEditTextTwo())
                    customDialogList.dismiss()
                    scanRequest()

                } else {
                    itemShelvingFkStored = itemShelvingFk
                    binding.splashProgress.visibility = View.VISIBLE
                    viewModel.getIdFromCodeSalix(
                        code = customDialogList.getValueTwo(),
                    )
                    customDialogList.dismiss()
                }
            }

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

    private fun setStoredPosition(isFromBack: Boolean) {
        setListPosition(storedPosition, isFromBack)
    }

    private fun checkItemScan(valueToCheck: String): Boolean {
        println("Sacador valor a  checkear ${valueToCheck}")
        if (storedPosition >= 0 && sales.size > storedPosition) {
            val saleToCheck = myGroupList[storedPosition]
            println("Sacador valor de la sale a checkear ${saleToCheck}")
            if (saleToCheck.itemFk.toString() == valueToCheck) return true
            else {
                saleToCheck.Barcodes.forEach { barcode ->
                    if (barcode == valueToCheck) return true
                }
            }
        }

        return false
    }

    //Tarea #4371
    private fun onQuantityOfShelvingSelected(itemShelvingFk: Int, quantity: Int = 0) {
        println("Sacador $itemShelvingFk-$quantity")/*     if (myGroupList[storedPosition].reservedQuantity == 0) {
                 showQuestionUbicationEmpty(storedPosition)
             } else {*/
        markLine(storedPosition, quantity, null)
        // }

    }

    private fun showQuestionUbicationEmpty(position: Int, quantity: Int = 0) {
        customDialogThreeButtonsQuantity.setTitle("Cambio de cantidad a $quantity")
            .setDescription("¿Hay unidades del artículo ${sales[position].itemFk} en el carro escaneado?")
            .setValue("").setCustomDialogValue(View.GONE)
        customDialogThreeButtonsQuantity.setOkButtonAdd("SI") {
            scanRequest()
            customDialogThreeButtonsQuantity.dismiss()
            //markLine(position, quantity, false)
            "No puedes seleccionar menos cantidad habiendo en el carro".toast(requireContext())
            customDialogThreeButtonsQuantity.dismiss()
            showQuestionUbicationEmpty(position, quantity)
        }.setOkButtonTwo("NO") {
            scanRequest()
            customDialogThreeButtonsQuantity.dismiss()
            markLine(position, quantity, true)
        }.setKoButton("CANCELAR") {
            scanRequest()
            customDialogThreeButtonsQuantity.dismiss()
        }.show()
        customDialogThreeButtons.setFocusDialogValue()
    }

    //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 = 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().isNullOrEmpty()) {
                    try {
                        customDialogList.setValue(
                            itemScanValue(
                                customDialogList.getValue(), "buy", "more"
                            ).toString()
                        )

                    } catch (e: Exception) {
                        ma.messageWithSound(e.message.toString(), 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().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.collectionAddWithReservation(
                    customDialogList.getValue().toInt(),
                    customDialogList.getValueTwo().toInt(),
                    ticketSelected
                )

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

    }

    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 (it.isPicked == 1) {
                totalMark += 1/* } else if (it.reservedQuantity == 0) {
                     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()


            changeTicketState()

        }
    }

    //ESTADOS
    private fun changeTicketState() {

        tickets.forEach {
            viewModel.ticketStateTodaySetState(
                ticketFk = it.toInt(), state = "PREPARED"
            )
        }

    }

    //OTROS
    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().isNullOrEmpty()) {
            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()
    }

    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
            )

        }

    }

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

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

        for ((key, value) in myMap.entries) {
            if (key == null) { // 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 = //= value[0]
                        Sale(
                            level = value[0].level,
                            isPicked = value[0].isPicked,
                            parkingCode = "Líneas : ${value.size}",
                            pickingOrder = value[0].pickingOrder,
                            workerFk = value[0].workerFk,
                            originalQuantity = value[0].originalQuantity,
                            saleQuantity = 0,
                            saleFk = value[0].saleFk,
                            saleGroupFk = value[0].saleGroupFk,
                            semaphore = value[0].semaphore,
                            ticketFk = value[0].ticketFk,
                            itemFk = value[0].saleGroupFk!!,
                            isAdded = value[0].isAdded,
                            hasMistake = value[0].hasMistake,
                            origin = value[0].origin,
                            size = value[0].size,
                            itemShelvingSaleFk = value[0].itemShelvingSaleFk,
                            longName = value[0].parkingCode ?: ""
                        )

                    //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<Sale>
                    mySale.sonSales =
                        value.sortedWith(compareBy { it.isPicked }) as MutableList<Sale>/*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
    }

}


