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

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.drawable.Drawable
import android.media.MediaPlayer
import android.os.Build
import android.os.Bundle
import android.text.InputType
import android.view.View
import android.view.View.GONE
import android.view.View.VISIBLE
import android.view.inputmethod.EditorInfo
import android.widget.ImageView
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import es.verdnatura.R
import es.verdnatura.databinding.FragmentUbicadorBinding
import es.verdnatura.domain.notNull
import es.verdnatura.domain.toInt
import es.verdnatura.domain.toast
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.*
import es.verdnatura.presentation.view.component.*
import es.verdnatura.presentation.view.feature.main.activity.MainActivity
import es.verdnatura.presentation.view.feature.pasillero.model.PasillerosItemVO
import es.verdnatura.presentation.view.feature.ubicador.adapter.UbicadorAdapter
import es.verdnatura.presentation.view.feature.ubicador.model.ItemUbicadorVO
import java.lang.Boolean.TRUE
import kotlin.math.roundToInt


@Suppress("UNUSED_ANONYMOUS_PARAMETER")
class UbicadorFragment(
    var shelvingFk: String = "",
    var isAutoSelf: Boolean
) : BaseFragment<FragmentUbicadorBinding, UbicadorViewModel>(
    UbicadorViewModel::class
) {

    private var adapter: UbicadorAdapter? = null
    private lateinit var customDialogInput: CustomDialogInput
    private lateinit var customDialogUbicador: CustomDialogUbicador
    private lateinit var customDialogTwoButtons: CustomDialogTwoButtons
    private lateinit var customDialogThreeButtons: CustomDialogThreeButtons
    private var listItems: MutableList<ItemUbicadorVO> = mutableListOf()
    private var listLocalItems: ArrayList<ItemUbicadorVO> = ArrayList()
    private lateinit var customDialog: CustomDialog
    private var deep: Int = 1
    private var parking: String = ""
    private var etiquetas: String = "0"
    private var pasillerosItemClickListener: OnPasillerosItemClickListener? = null
    private var isShelvinLogfromMainScreen = false
    private var modeCheckUbication = false
    private var itemScannedScreen = 0
    var mperror: MediaPlayer? = null
    var mpok: MediaPlayer? = null
    var isBack = false


    companion object {
        fun newInstance(entryPoint: String, autoSelf: Boolean = false) =
            UbicadorFragment(entryPoint, autoSelf)
    }

    override fun getLayoutId(): Int = R.layout.fragment_ubicador
    override fun onPause() {
        super.onPause()
        isBack = true
    }

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

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

        customDialogInput = CustomDialogInput(requireContext())
        customDialog = CustomDialog(requireContext())
        customDialogUbicador = CustomDialogUbicador(requireContext())
        customDialogTwoButtons = CustomDialogTwoButtons(requireContext())

        ma.hideBottomNavigation(GONE)
        binding.mainToolbar.toolbarTitle.text = if (!isAutoSelf) {
            getString(R.string.locator)
        } else {
            getString(R.string.selfConsumption)
        }
        setEvents()
        setToolBar()
        if (!shelvingFk.isNullOrEmpty()) {
            isShelvinLogfromMainScreen = false
            binding.splashProgress.visibility = VISIBLE
            binding.mainToolbar.toolbarTitle.text = shelvingFk
            viewModel.itemShelvingList(shelvingFk)
        } else {
            isShelvinLogfromMainScreen = true

        }

        super.init()
    }

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

    @RequiresApi(Build.VERSION_CODES.O)
    private fun setToolBar() {

        val listIcons: ArrayList<ImageView> = ArrayList()
        val iconAdd = ImageView(context)
        iconAdd.setImageResource(R.drawable.ic_add_black_24dp)
        val iconReload = ImageView(context)
        iconReload.setImageResource(R.drawable.ic_autorenew_black_24dp)
        //Tarea#5052
        val iconReset = ImageView(context)
        iconReset.setImageResource(R.drawable.ic_remove_checks)

        //Tarea#5052
        binding.mainToolbar.switchButton.visibility = VISIBLE
        binding.mainToolbar.switchButton.setOnCheckedChangeListener { buttonView, isChecked ->
            if (binding.mainToolbar.toolbarTitle.text == getString(R.string.titleUbicator)) {
                ma.messageWithSound(getString(R.string.scanShelving), false, false)
                binding.mainToolbar.switchButton.isChecked = false
            } else {
                modeCheckUbication = isChecked
                binding.mainToolbar.toolbarIcons.adapter!!.notifyDataSetChanged()
                binding.mainToolbar.switchButton.tooltipText = if (isChecked)
                    getString(R.string.activateModoChecking) else
                    getString(R.string.allowCheckingMode)
                binding.textinputlayoutMatricula.hint =
                    if (isChecked) getString(R.string.scanItem) else {
                        getString(R.string.scanPlate)

                    }
                if (!isChecked) {
                    listLocalItems.clear()
                    listIcons.remove(iconReset)
                }else{
                    listIcons.add(iconReset)
                }
                binding.mainToolbar.toolbarIcons.adapter!!.notifyDataSetChanged()
            }
        }



        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            iconReload.tooltipText = getTooltip(R.drawable.ic_autorenew_black_24dp)
            iconAdd.tooltipText = getString(R.string.addItemShelving)
            iconReset.tooltipText = getTooltip(R.drawable.ic_remove_checks)

        }
        listIcons.add(iconAdd)
        listIcons.add(iconReload)

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

                    when (item) {
                        iconAdd.drawable -> showAddItem(
                            "",
                            "",
                            "",
                            "",
                            false,
                            ItemUbicadorVO(0),
                            ""
                        )

                        iconReload.drawable -> {

                            if (!shelvingFk.isNullOrEmpty()) {
                                binding.editPrioridad.setText("")
                                binding.splashProgress.visibility = VISIBLE
                                viewModel.itemShelvingList(
                                    shelvingFk
                                )
                            } else {
                                getString(R.string.scanShelving).toast(
                                    requireActivity(),
                                    Toast.LENGTH_SHORT
                                )
                            }
                        }


                        iconReset.drawable -> {
                            if (!shelvingFk.isNullOrBlank()) {
                                customDialog.setTitle(getString(R.string.checkItemShelvingDescrip))
                                    .setDescription(getString(R.string.checkItemShelving))
                                    .setOkButton(getString(R.string.ok)) {
                                        binding.splashProgress.visibility = View.VISIBLE
                                        viewModel.itemShelving_deleteChecked(shelvingFk)
                                        customDialog.dismiss()
                                    }
                                    .setKoButton(getString(R.string.cancel)) {
                                        customDialog.dismiss()

                                    }
                                    .show()
                            } else {
                                ma.messageWithSound(
                                    getString(R.string.scanPlate),
                                    isError = true,
                                    isPlayed = true,
                                    isToasted = true
                                )
                            }
                        }
                    }
                }

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

    @RequiresApi(Build.VERSION_CODES.O)
    @SuppressLint("SetTextI18n")
    private fun setEvents() {
        binding.mainToolbar.backButton.setOnClickListener {
            requireActivity().onBackPressed()
        }

        setTooltips()
        binding.editMatricula.requestFocus()
        binding.editMatricula.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0 || actionId == 5) {
                if (!binding.editMatricula.text.toString().isNullOrEmpty()) {


                    /*Tarea 5336 */
                    if (!modeCheckUbication || (modeCheckUbication && binding.editMatricula.text.toString().length == 3 && !binding.editMatricula.text!![0].isDigit())) {
                        binding.mainToolbar.toolbarTitle.text =
                            binding.editMatricula.text.toString()
                        shelvingFk = binding.editMatricula.text.toString()
                        parking = ""
                        binding.editPrioridad.setText("")
                        binding.splashProgress.visibility = VISIBLE
                        isShelvinLogfromMainScreen = true
                        viewModel.itemShelvingList(
                            binding.editMatricula.text.toString()
                        )
                    } else {

                        /*Tarea#5109*/
                        /*viewModel.getIdFromCode(
                            code = binding.editMatricula.text.toString()
                        )*/
                        try {
                            binding.splashProgress.visibility = VISIBLE
                            viewModel.getIdFromCode(
                                code = itemScanValue(
                                    binding.editMatricula.text.toString(),
                                    "buy",
                                    "more"
                                ).toString()
                            )
                        } catch (Ex: Exception) {
                            ma.messageWithSound(Ex.message.toString(), true, true)
                        }

                    }
                }
                binding.editMatricula.setText("")
                ma.hideKeyboard(binding.editMatricula)
                return@setOnEditorActionListener true
            }

            return@setOnEditorActionListener false
        }

        binding.editPrioridad.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0 || actionId == 5) {
                if (!binding.editPrioridad.text.toString().isNullOrEmpty()) {
                    binding.splashProgress.visibility = VISIBLE
                    viewModel.shelvingPriorityUpdate(
                        binding.editPrioridad.toInt(),
                        shelvingFk
                    )

                }
                ma.hideKeyboard(binding.editPrioridad)
            }

            binding.editMatricula.requestFocus()
            return@setOnEditorActionListener false
        }


        binding.automaticImg.setOnClickListener {
            if (!shelvingFk.isNullOrEmpty())

                ma.onPasillerosItemClickListener(
                    PasillerosItemVO(title = getString(R.string.titleAuto)),
                    //PasillerosItemVO(title = getString(R.string.titleChecker)),
                    entryPoint = shelvingFk
                )
            else
                getString(R.string.scanShelving).toast(
                    requireActivity(),
                    Toast.LENGTH_SHORT
                )
        }

        binding.parkingImg.setOnClickListener {
            if (!shelvingFk.isNullOrBlank()) {
                customDialogInput.setTitle(getString(R.string.parkingShelving))
                    .setValue("")
                    .setOkButton(
                        getString(
                            R.string.parking
                        )
                    ) {
                        viewModel.shelvingPark(
                            shelvingFk,
                            customDialogInput.getValue()
                        )
                        parking = customDialogInput.getValue()
                        binding.mainToolbar.toolbarTitle.text =
                            shelvingFk.uppercase() + getString(R.string.pUppercase) + parking + getString(
                                R.string.label
                            ) + etiquetas
                        customDialogInput.dismiss()
                    }.setKoButton(getString(R.string.cancel)) {
                        customDialogInput.dismiss()
                    }.show()
            } else {

                getString(R.string.errorShelving).toast(
                    requireContext()
                )
            }
            customDialogInput.getEditText().requestFocus()
            ma.hideKeyboard(customDialogInput.getEditText())

            customDialogInput.getEditText()
                .setOnEditorActionListener { v, actionId, event ->
                    if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0) {
                        viewModel.shelvingPark(
                            shelvingFk,
                            customDialogInput.getValue()
                        )
                        customDialogInput.dismiss()
                        parking = customDialogInput.getValue()
                        binding.mainToolbar.toolbarTitle.text =
                            shelvingFk.uppercase() + getString(R.string.pUppercase) + parking + getString(
                                R.string.label
                            ) + etiquetas


                        return@setOnEditorActionListener true
                    }
                    false
                }

        }

        binding.editImg.setOnClickListener {
            if (!shelvingFk.isNullOrBlank()
            ) {
                customDialogInput.setTitle(getString(R.string.changeShelving))
                    .setValue("")
                    .setOkButton(getString(R.string.save)) {
                        if (!customDialogInput.getValue().isNullOrBlank()) {
                            viewModel.shelvingChangeSalix(
                                shelvingFk, customDialogInput.getValue()
                            )
                            shelvingFk = customDialogInput.getValue()
                            binding.mainToolbar.toolbarTitle.text =
                                shelvingFk.uppercase() + getString(R.string.pUppercase) + parking + getString(
                                    R.string.label
                                ) + etiquetas
                        } else {
                            getString(R.string.errorShelving).toast(
                                requireContext()
                            )
                        }
                        customDialogInput.dismiss()
                    }.setKoButton(getString(R.string.cancel)) {
                        customDialogInput.dismiss()
                    }.show()
            } else {
                getString(R.string.errorShelving).toast(
                    requireContext()
                )
            }
            customDialogInput.getEditText().requestFocus()
            ma.hideKeyboard(customDialogInput.getEditText())

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

                        viewModel.shelvingChangeSalix(
                            shelvingFk,
                            customDialogInput.getValue()
                        )
                        shelvingFk = customDialogInput.getValue()
                        binding.mainToolbar.toolbarTitle.text =
                            shelvingFk.uppercase() + getString(R.string.pUppercase) + parking + getString(
                                R.string.label
                            ) + etiquetas

                        customDialogInput.dismiss()
                        return@setOnEditorActionListener true
                    }
                    false
                }

        }

        binding.deleteImg.setOnClickListener {
            if (!shelvingFk.isNullOrBlank()) {
                customDialog.setTitle(getString(R.string.empty))
                    .setDescription(getString(R.string.operationNoReturn))
                    .setOkButton(getString(R.string.empty)) {

                        viewModel.clearShelvingList(
                            shelvingFk
                        )
                        listItems.forEach {
                            it.stickers = "0"
                            it.visible = "0"
                        }
                        if (adapter != null) {
                            adapter!!.notifyDataSetChanged()
                        }
                        customDialog.dismiss()
                    }

                customDialog.setKoButton(getString(R.string.cancel)) {
                    customDialog.dismiss()
                }.show()
            } else {
                getString(R.string.errorShelving).toast(
                    requireContext()
                )

            }

        }
    }

    private fun checkUbications(itemScanned: Int) {
        itemScannedScreen = itemScanned
        val listInt: ArrayList<Int> = ArrayList()

        if (listItems.filter { it.item == itemScanned }.isEmpty()) {
            listInt.add(itemScanned)
        } else {
            listItems.sortedBy { it.isChecked }.forEachIndexed { index, item ->
                if (item.item == itemScanned) {
                    item.checked = true
                    listInt.add(item.item)
                    ma.messageWithSound("", false, true, "", false)
                }
            }

        }
        viewModel.itemShelving_addList(
            shelvingFk,
            "" + listInt + "",
            TRUE,
            getDataInt(WAREHOUSEFK)
        )

        adapter!!.notifyDataSetChanged()
    }

    private fun setTooltips() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            binding.editImg.tooltipText = getTooltip(R.drawable.ic_mode_edit_black_24dp)
            binding.deleteImg.tooltipText =
                getTooltip(R.drawable.ic_delete_forever_black_24dp)
            binding.editPrioridad.tooltipText =
                getString(R.string.changePriority)
            binding.parkingImg.tooltipText =
                getTooltip(R.drawable.ic_local_parking_black_24dp)
            binding.automaticImg.tooltipText =
                getTooltip(R.drawable.ic_flash_auto_black_24dp)


        }
    }

    @SuppressLint("SetTextI18n")
    override fun observeViewModel() {

        with(viewModel) {

            loadShelvingList.observe(viewLifecycleOwner, Observer { event ->
                event.getContentIfNotHandled().notNull {

                    deep = it.list.size
                    if (it.list.isNotEmpty() && it.list.get(0).isError) {
                        binding.splashProgress.visibility = View.GONE
                        ma.messageWithSound(
                            it.list.get(0).errorMessage,
                            it.list.get(0).isError,
                            isPlayed = false
                        )
                    } else {
                        listItems = ArrayList()
                        var contEtiquetas = 0
                        it.list.forEach { item ->
                            try {
                                contEtiquetas += item.stickers.toInt()
                                parking = item.code

                            } catch (e: Exception) {
                            }


                            listItems.add(item)


                        }
                        etiquetas = contEtiquetas.toString()
                        binding.mainToolbar.toolbarTitle.text =
                            shelvingFk.uppercase() + getString(R.string.pUppercase) + parking + getString(
                                R.string.label
                            ) + etiquetas
                        if (it.list.size > 0)
                            binding.editPrioridad.setText(it.list[0].priority)
                        binding.splashProgress.visibility = View.GONE


                        for (item in listItems) {
                            for (localItem in listLocalItems) {
                                if (item.item == localItem.item) {
                                    item.isNew = localItem.isNew
                                    item.checked = localItem.checked
                                    if (item.isNew && item.visible != "0") {
                                        item.isNew = false
                                        item.checked = true
                                    }

                                    binding.locationRecyclerview.postInvalidate()
                                }

                            }
                        }

                        if (!binding.mainToolbar.switchButton.isChecked && listItems.isNotEmpty()) {

                            listItems = listItems.asReversed()

                        }
                        adapter = UbicadorAdapter(
                            listItems.sortedBy { it.isChecked },
                            onPasillerosItemClickListener = pasillerosItemClickListener!!,
                            onVisibleClickListener = object : OnVisibleClickListener {
                                override fun onVisibleClickListener(item: ItemUbicadorVO) {

                                    if (!isAutoSelf) {
                                        showAddItem(
                                            item.item.toString(),
                                            item.packing,
                                            item.stickers,
                                            item.visible,
                                            true,
                                            item,
                                            grouping = if (item.grouping.isNullOrEmpty()) {
                                                ""
                                            } else item.grouping
                                        )

                                    } else {

                                        showAutoSelfConsumption(item)
                                    }

                                }

                            },
                            onMoreClickListener = object : OnMoreClickListener {
                                override fun onMoreClickListener(item: ItemUbicadorVO) {
                                    showMoreOptions(item)
                                }

                            })

                        binding.locationRecyclerview.adapter = adapter
                        binding.locationRecyclerview.layoutManager =
                            LinearLayoutManager(
                                requireContext(),
                                LinearLayoutManager.VERTICAL,
                                false
                            )

                        if (isShelvinLogfromMainScreen) {
                            viewModel.shelvinLog_add(shelvingFk)

                        }
                        if (modeCheckUbication) {
                            listItems.sortedBy { it.isChecked }
                                .forEachIndexed { index, item ->
                                    if (item.item == itemScannedScreen) {
                                        binding.locationRecyclerview.scrollToPosition(
                                            index
                                        )
                                    }
                                }

                        } else {
                            (binding.locationRecyclerview.layoutManager as LinearLayoutManager).scrollToPosition(
                                0
                            )
                        }
                    }
                }
            })
            loadAddList.observe(viewLifecycleOwner) { event ->
                event.getContentIfNotHandled().notNull {
                    binding.splashProgress.visibility = GONE
                    if (it.isError) {
                        ma.messageWithSound(it.errorMessage, it.isError, false)

                    } else {
                        binding.splashProgress.visibility = VISIBLE
                        viewModel.itemShelvingList(shelvingFk)

                    }
                }
            }
            /* responseAddList.observe(viewLifecycleOwner, Observer {
                 binding.splashProgress.visibility = GONE
                 if (it.isError) {
                     ma.messageWithSound(it.errorMessage, it.isError, false)

                 } else {
                     binding.splashProgress.visibility = VISIBLE
                     viewModel.itemShelvingList(shelvingFk)

                 }
             })*/
            response.observe(viewLifecycleOwner, Observer {

                if (it.isError) {
                    binding.splashProgress.visibility = GONE
                    ma.messageWithSound(it.errorMessage, it.isError, true)


                } else {
                    viewModel.itemShelvingList(shelvingFk)
                    ma.messageWithSound("", it.isError, true, isToasted = false)

                }
            })
            responseLog.observe(viewLifecycleOwner, Observer {

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


                } else {
                    isShelvinLogfromMainScreen = false

                }
            })
            loadResponseCode.observe(viewLifecycleOwner) { event ->
                event.getContentIfNotHandled().notNull {
                    binding.splashProgress.visibility = GONE
                    if (it.isError) {
                        ma.messageWithSound(it.errorMessage, it.isError, true)

                    } else {
                        checkUbications(it.response.toDouble().roundToInt())
                    }
                }
            }

            responsepriority.observe(viewLifecycleOwner, Observer {
                if (!isBack) {
                    binding.splashProgress.visibility = GONE
                    ma.messageWithSound(
                        if (it.isError) it.errorMessage else {
                            getString(R.string.priorityChanged)
                        }, it.isError, true
                    )
                }
                isBack = false

            })

            responseMake.observe(viewLifecycleOwner, Observer {
                binding.splashProgress.visibility = GONE
                if (it.isError) {
                    ma.messageWithSound(it.errorMessage, true, true, isToasted = true)
                } else {
                    if (!shelvingFk.isNullOrEmpty()) {

                        binding.mainToolbar.toolbarTitle.text = shelvingFk
                        binding.splashProgress.visibility = VISIBLE
                        viewModel.itemShelvingList(
                            shelvingFk
                        )

                    }
                }
            })
        }

    }

    private fun showAutoSelfConsumption(item: ItemUbicadorVO) {

        customDialogInput.setInputText(InputType.TYPE_CLASS_NUMBER)
        customDialogInput.setTitle(getString(R.string.selfConsumption))
        customDialogInput.setDescription(getString(R.string.quantityTake))
            .setValue("")
            .setOkButton(getString(R.string.take)) {
                try {
                    if (customDialogInput.getValue().toInt() > 0) {
                        binding.splashProgress.visibility = VISIBLE
                        var quantity =
                            if (item.visible.toInt() - customDialogInput.getValue()
                                    .toInt() > 0
                            ) {
                                item.visible.toInt() - customDialogInput.getValue()
                                    .toInt()
                            } else {
                                0
                            }
                        viewModel.itemShelving_selfConsumption(
                            shelvingFk,
                            item.item,
                            quantity
                        )
                    } else {
                        throw Exception("")
                    }
                } catch (err: Exception) {
                    (getString(R.string.errorQuantity).toast(requireContext()))
                }
                customDialogInput.dismiss()

            }.setKoButton(getString(R.string.cancel)) {
                customDialogInput.dismiss()
            }.show()
        customDialogInput.setFocusText()
    }


    private fun showAddItem(
        itemFk: String,
        packing: String,
        etiquetas: String,
        visible: String,
        delete: Boolean,
        itemUbicador: ItemUbicadorVO,
        grouping: String
    ) {
        var title = getString(R.string.newItem)
        if (delete) title = getString(R.string.editItem) + itemFk
        customDialogUbicador.setTitle(title).setItemValue(itemFk)
            .setPackingValue(packing)
            .setGroupingValue(grouping).setEtiquetaValue(etiquetas)
            .setVisibleValue(visible)
            .setOkButton(getString(R.string.save)) {
                var packingUpdate = false

                if (customDialogUbicador.getItemValue().isNullOrEmpty()) {
                    getString(R.string.itemNecessary).toast(context)
                } else {
                    if (packing != customDialogUbicador.getPackingValue() || etiquetas != customDialogUbicador.getEtiquetaValue()) {
                        packingUpdate = true
                    }
                    saveNewItem(
                        customDialogUbicador.getItemValue().toLong(),
                        if (customDialogUbicador.getEtiquetaValue().isNullOrEmpty()) {
                            1
                        } else {
                            customDialogUbicador.getEtiquetaValue().toInt()
                        },
                        if (customDialogUbicador.getPackingValue().isNullOrEmpty()) {
                            null
                        } else {
                            customDialogUbicador.getPackingValue().toInt()
                        },
                        if (customDialogUbicador.getVisibleValue().isNullOrEmpty()) {
                            null
                        } else {
                            customDialogUbicador.getVisibleValue().toInt()
                        },
                        if (delete) packingUpdate else null,
                        itemUbicador.id,
                        if (customDialogUbicador.getGroupingValue().isNullOrEmpty()) {
                            null
                        } else {
                            customDialogUbicador.getGroupingValue().toInt()
                        }
                    )
                }
            }.setKoButton(getString(R.string.close)) {
                customDialogUbicador.dismiss()
            }.show()

        customDialogUbicador.getEditItem().requestFocus()
        ma.hideKeyboard(customDialogUbicador.getEditItem())

        customDialogUbicador.getVisibleItem()
            .setOnEditorActionListener { v, actionId, event ->
                if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0) {
                    var packingUpdate = false
                    if (packing != customDialogUbicador.getPackingValue() || etiquetas != customDialogUbicador.getEtiquetaValue()) {
                        packingUpdate = true
                    }
                    saveNewItem(
                        customDialogUbicador.getItemValue().toInt(),
                        customDialogUbicador.getEtiquetaValue().toInt(),
                        if (customDialogUbicador.getPackingValue().isNullOrEmpty()) {
                            null
                        } else {
                            customDialogUbicador.getPackingValue().toInt()
                        },
                        if (customDialogUbicador.getVisibleValue().isNullOrEmpty()) {
                            null
                        } else {
                            customDialogUbicador.getVisibleValue().toInt()
                        },
                        if (delete) packingUpdate else null,
                        itemUbicador.id,
                        customDialogUbicador.getGroupingValue().toInt()
                    )
                    return@setOnEditorActionListener true
                }
                false
            }

        customDialogUbicador.getEditItem()
            .setOnEditorActionListener { v, actionId, event ->
                if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0) {

                    if (!customDialogUbicador.getItemValue().isNullOrEmpty()) {
                        try {

                            customDialogUbicador.setItemValue(
                                itemScanValue(
                                    customDialogUbicador.getItemValue(),
                                    "buy",
                                    "more"
                                ).toString()
                            )

                        } catch (ex: Exception) {
                            ma.messageWithSound(ex.message.toString(), true, true)
                            customDialogUbicador.setItemValue("")
                        }
                    }

                    return@setOnEditorActionListener true
                }

                customDialogUbicador.getPackingItem().requestFocus()
            }

        customDialogUbicador.getEtiquetaItem()
            .setOnEditorActionListener { v, actionId, event ->
                if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0) {
                    var packingUpdate = false
                    if (packing != customDialogUbicador.getPackingValue() || etiquetas != customDialogUbicador.getEtiquetaValue()) {
                        packingUpdate = true
                    }
                    saveNewItem(
                        customDialogUbicador.getItemValue().toInt(),
                        customDialogUbicador.getEtiquetaValue().toInt(),
                        if (customDialogUbicador.getPackingValue().isNullOrEmpty()) {
                            null
                        } else {
                            customDialogUbicador.getPackingValue().toInt()
                        },
                        if (customDialogUbicador.getVisibleValue().isNullOrEmpty()) {
                            null
                        } else {
                            customDialogUbicador.getVisibleValue().toInt()
                        },
                        if (delete) packingUpdate else null,
                        itemUbicador.id,
                        if (customDialogUbicador.getGroupingValue().isNullOrEmpty()) {
                            null
                        } else {
                            customDialogUbicador.getGroupingValue().toInt()
                        }
                    )
                    return@setOnEditorActionListener true
                }
                false
            }

    }

    private fun saveNewItem(
        itemFk: Number?,
        etiquetas: Int,
        packing: Int?,
        visible: Int?,
        updatePacking: Boolean? = null,
        itemShelvingFk: Int,
        groupingPack: Int?
    ) {
        if (packing != null) {
            if (updatePacking == null) {
                if (itemFk != null && visible != null) {

                    binding.splashProgress.visibility = VISIBLE
                    viewModel.itemShelvingMake(
                        shelvingFk,
                        itemFk,
                        visible,
                        packing,
                        getDataInt(WAREHOUSEFK),
                        groupingPack
                    )

                    customDialogUbicador.setItemValue("").setPackingValue("")
                        .setGroupingValue("")
                        .setEtiquetaValue("").setVisibleValue("")
                    customDialogUbicador.getEditItem().requestFocus()
                    ma.hideKeyboard(customDialogUbicador.getEditItem())
                    customDialogUbicador.dismiss()

                } else if (itemFk != null && etiquetas != null) {
                    val visible_calc = (etiquetas * packing!!.toInt())
                    binding.splashProgress.visibility = VISIBLE
                    viewModel.itemShelvingMake(
                        shelving = shelvingFk,
                        item = itemFk,
                        quantity = visible_calc,
                        packing = packing,
                        warehouse = getDataInt(WAREHOUSEFK),
                        grouping = groupingPack
                    )

                    customDialogUbicador.setItemValue("").setPackingValue("")
                        .setGroupingValue("")
                        .setEtiquetaValue("").setVisibleValue("")
                    customDialogUbicador.getEditItem().requestFocus()
                    ma.hideKeyboard(customDialogUbicador.getEditItem())
                    customDialogUbicador.dismiss()

                } else {
                    getString(R.string.fillFields).toast(
                        (activity as MainActivity),
                        Toast.LENGTH_LONG
                    )
                }
            } else {
                if (itemFk != null && visible != null && !updatePacking) {
                    binding.splashProgress.visibility = VISIBLE
                    viewModel.itemShelvingMakeEdit(
                        visible,
                        packing!!.toInt(),
                        itemShelvingFk,
                        groupingPack

                    )

                    customDialogUbicador.setItemValue("").setPackingValue("")
                        .setGroupingValue("")
                        .setEtiquetaValue("").setVisibleValue("")
                    customDialogUbicador.getEditItem().requestFocus()
                    ma.hideKeyboard(customDialogUbicador.getEditItem())
                    customDialogUbicador.dismiss()

                } else if (itemFk != null && etiquetas != null && updatePacking) {
                    var visible_calc = 0
                    try {
                        visible_calc = (etiquetas * packing.toInt())
                    } catch (e: Exception) {
                    }
                    binding.splashProgress.visibility = VISIBLE
                    viewModel.itemShelvingMakeEdit(
                        visible_calc,
                        packing.toInt(),
                        itemShelvingFk,
                        groupingPack

                    )

                    customDialogUbicador.setItemValue("").setPackingValue("")
                        .setGroupingValue("")
                        .setEtiquetaValue("").setVisibleValue("")
                    customDialogUbicador.getEditItem().requestFocus()
                    ma.hideKeyboard(customDialogUbicador.getEditItem())
                    customDialogUbicador.dismiss()

                } else {
                    getString(R.string.fillFields).toast(
                        (activity as MainActivity),
                        Toast.LENGTH_LONG
                    )
                }
            }

        } else {
            getString(R.string.mandatoryPacking).toast(
                (activity as MainActivity),
                Toast.LENGTH_LONG
            )
        }
    }

    private fun showMoreOptions(item: ItemUbicadorVO) {
        customDialogTwoButtons.setTitle(item.item.toString())
            .setDescription(getString(R.string.selectAction))
            .setOkButton(getString(R.string.transfer)) {
                customDialogInput.setTitle(getString(R.string.shelvingNew))
                    .setDescription(getString(R.string.selectDestiny) + item.item)
                    .setValue("")
                    .setOkButton(getString(R.string.transfer)) {
                        if (customDialogInput.getValue().isNotEmpty()) {
                            binding.splashProgress.visibility = VISIBLE
                            viewModel.itemShelvingTransfer(
                                item.id,
                                customDialogInput.getValue()
                            )
                            listItems.remove(item)
                            adapter!!.notifyDataSetChanged()
                            customDialogInput.dismiss()
                        } else {
                            getString(R.string.wagonIncorrect).toast(requireContext())

                        }

                    }.setKoButton(getString(R.string.cancel)) {
                        customDialogInput.dismiss()
                    }.show()
                customDialogInput.getEditText().requestFocus()
                ma.hideKeyboard(customDialogInput.getEditText())
                customDialogInput.getEditText()
                    .setOnEditorActionListener { v, actionId, event ->
                        if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0) {
                            viewModel.itemShelvingTransfer(
                                item.id,
                                customDialogInput.getValue()
                            )
                            listItems.remove(item)
                            adapter!!.notifyDataSetChanged()
                            customDialogInput.dismiss()
                            return@setOnEditorActionListener true
                        }
                        false
                    }
                customDialogTwoButtons.dismiss()
            }.setOkButtonTwo(getString(R.string.delete)) {
                customDialog.setTitle(getString(R.string.confirm))
                    .setDescription(
                        if (!isAutoSelf) {
                            getString(R.string.itemDeleteConfirm) + item.item + "?"
                        } else {
                            getString(R.string.deleteQuantity) + item.item
                        }
                    )
                    .setOkButton(getString(R.string.delete)) {
                        if (!isAutoSelf) {
                            listItems.remove(item)
                            adapter!!.notifyDataSetChanged()
                            viewModel.itemShelvingDelete(
                                item.id
                            )
                            customDialogTwoButtons.dismiss()
                            customDialog.dismiss()
                        } else {
                            viewModel.itemShelving_selfConsumption(
                                shelvingFk,
                                item.item,
                                0
                            )
                        }
                    }.setKoButton(getString(R.string.cancel)) {
                        customDialog.dismiss()
                        customDialogTwoButtons.dismiss()
                    }.show()

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

