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

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.text.InputType
import android.text.TextWatcher
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.recyclerview.widget.LinearLayoutManager
import es.verdnatura.R
import es.verdnatura.databinding.FragmentUbicadorBinding
import es.verdnatura.domain.ConstAndValues.WAREHOUSEFK
import es.verdnatura.domain.isShelving
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.Action
import es.verdnatura.presentation.common.OnBarcodeRowClickListener
import es.verdnatura.presentation.common.OnMoreClickListenerNew
import es.verdnatura.presentation.common.OnOptionsSelectedListener
import es.verdnatura.presentation.common.OnPasillerosItemClickListener
import es.verdnatura.presentation.common.OnVisibleClickListenerNew
import es.verdnatura.presentation.common.ToolBarAdapterTooltip
import es.verdnatura.presentation.common.itemScanValue
import es.verdnatura.presentation.view.component.CustomDialog
import es.verdnatura.presentation.view.component.CustomDialogInput
import es.verdnatura.presentation.view.component.CustomDialogList
import es.verdnatura.presentation.view.component.CustomDialogTwoButtons
import es.verdnatura.presentation.view.component.CustomDialogUbicadorNew
import es.verdnatura.presentation.view.feature.articulo.adapter.BarcodeAdapter
import es.verdnatura.presentation.view.feature.articulo.model.BarcodeVO
import es.verdnatura.presentation.view.feature.pasillero.model.PasillerosItemVO
import es.verdnatura.presentation.view.feature.ubicador.adapter.UbicadorAdapterNew
import es.verdnatura.presentation.view.feature.ubicador.model.ItemUbicador

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

    private var adapter: UbicadorAdapterNew? = null
    private lateinit var customDialogInput: CustomDialogInput
    private lateinit var customDialogUbicador: CustomDialogUbicadorNew
    private lateinit var customDialogTwoButtons: CustomDialogTwoButtons
    private var listItems: MutableList<ItemUbicador> = mutableListOf()
    private var listLocalItems: ArrayList<ItemUbicador> = ArrayList()
    private lateinit var customDialog: CustomDialog
    private lateinit var customDialogOlder: CustomDialog
    private var parking: String = ""
    private var pasillerosItemClickListener: OnPasillerosItemClickListener? = null
    private var isShelvinLogfromMainScreen = false
    private var modeCheckUbication = false
    private var itemScannedScreen: Long = 0
    private var isBack = false
    var listIcons: ArrayList<ImageView> = ArrayList()
    private lateinit var textWatcher: TextWatcher
    private var buyScanned: String = ""
    private lateinit var customDialogList: CustomDialogList
    private var listShelvings: ArrayList<BarcodeVO> = ArrayList()
    private var listShelvingsAdapter: BarcodeAdapter? = null
    private var locateMultipleShelvings: Boolean = false

    companion object {
        private const val ARG_SHELVINGFK = "shelvingFk"
        private const val ARG_ISAUTOSELF = "autoSelf"
        fun newInstance(shelvingFk: String, isAutoSelf: Boolean = false) =
            UbicadorFragmentNew().apply {
                arguments = Bundle().apply {
                    putString(ARG_SHELVINGFK, shelvingFk)
                    putBoolean(ARG_ISAUTOSELF, isAutoSelf)
                }
            }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            shelvingFk = it.getString(ARG_SHELVINGFK).toString()
            isAutoSelf = it.getBoolean(ARG_ISAUTOSELF)
        }
    }

    /*fun newInstance(entryPoint: String, autoSelf: Boolean = false) =
            UbicadorFragmentNew(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)

    }

    override fun init() {

        setDialogs()
        setEvents()
        setToolBar()

        //setNewIcons()
        ma.hideBottomNavigation(GONE)

        if (shelvingFk.isNotEmpty()) {
            isShelvinLogfromMainScreen = false
            setIconsActions(true)
            setIcons()
            binding.mainToolbar.toolbarTitle.text = shelvingFk
            viewModel.itemShelvingListNew(shelvingFk)
            binding.mainToolbar.switchButton.visibility = VISIBLE
        } else {
            isShelvinLogfromMainScreen = true
            setIconsActions(false)
            //Tarea 7805
            setIcons(true)
        }
        super.init()
    }

    private fun setIconsActions(showIcons: Boolean) {

        binding.layoutIconsActions.visibility = if (showIcons) {
            VISIBLE
        } else {
            GONE
        }

    }

    private fun setDialogs() {
        customDialogInput = CustomDialogInput(requireContext())
        customDialog = CustomDialog(requireContext())
        customDialogOlder = CustomDialog(requireContext())
        customDialogTwoButtons = CustomDialogTwoButtons(requireContext())
    }

    private fun setToolBar() {
        binding.mainToolbar.switchButton.visibility = GONE
        binding.mainToolbar.toolbarTitle.text = if (!isAutoSelf) {
            getString(R.string.locator)
        } else {
            getString(R.string.selfConsumption)
        }
    }

    private fun setIcons(isInitMenu: Boolean = false) {

        listIcons.clear()
        val iconAdd = ImageView(context)
        iconAdd.setImageResource(R.drawable.ic_add_black_24dp)
        val iconAddMultiple = ImageView(context)
        iconAddMultiple.setImageResource(R.drawable.ic_add_multiple)
        val iconReload = ImageView(context)
        iconReload.setImageResource(R.drawable.ic_autorenew_black_24dp)
        val iconReset = ImageView(context)
        iconReset.setImageResource(R.drawable.ic_remove_checks)

        binding.mainToolbar.switchButton.setOnCheckedChangeListener { buttonView, isChecked ->
            if (binding.mainToolbar.toolbarTitle.text == getString(R.string.titleUbicator)) {
                getString(R.string.scanShelving).toast(requireContext())
                binding.mainToolbar.switchButton.isChecked = false
            } else {
                modeCheckUbication = isChecked
                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) {
                    listIcons.removeAt(listIcons.size - 1)
                    binding.mainToolbar.toolbarIcons.adapter!!.notifyItemRemoved(listIcons.size)

                } else {
                    listIcons.add(iconReset)
                    binding.mainToolbar.toolbarIcons.adapter!!.notifyItemInserted(listIcons.size - 1)

                }

                //binding.mainToolbar.toolbarIcons.adapter!!.notifyDataSetChanged()
            }
        }


        iconReload.tooltipText = getTooltip(R.drawable.ic_autorenew_black_24dp)
        iconAdd.tooltipText =
            if (isInitMenu) getString(R.string.addItemMultipleShelving) else getString(R.string.addItemShelving)
        iconAddMultiple.tooltipText = getTooltip(R.drawable.ic_add_multiple)
        iconReset.tooltipText = getTooltip(R.drawable.ic_remove_checks)

        listIcons.add(iconAdd)

        if (!isInitMenu) {
            listIcons.add(iconReload)
        } else {
            listIcons.add(iconAddMultiple)
        }
        locateMultipleShelvings = isInitMenu

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

                    when (item) {
                        iconAdd.drawable -> showAddItemNew(
                            isEditItem = false, null
                        )

                        iconAddMultiple.drawable ->
                            ma.onPasillerosItemClickListener(
                                PasillerosItemVO(
                                    title = R.string.addItemMultipleShelving,
                                ), entryPoint = getString(R.string.addItemMultipleShelving)
                            )

                        iconReload.drawable -> {

                            if (shelvingFk.isNotBlank()) {
                                binding.editPrioridad.setText("")
                                viewModel.itemShelvingListNew(
                                    shelvingFk
                                )
                            } else {
                                getString(R.string.scanShelving).toast(
                                    requireActivity(), Toast.LENGTH_SHORT
                                )
                            }
                        }

                        iconReset.drawable -> {
                            if (shelvingFk.isNotBlank()) {
                                val customDialogReset = CustomDialog(requireContext())
                                customDialogReset.setTitle(getString(R.string.checkItemShelvingDescrip))
                                    .setDescription(getString(R.string.checkItemShelving))
                                    .setOkButton(getString(R.string.ok)) {
                                        viewModel.itemShelvingDeleteChecked(shelvingFk)
                                        customDialogReset.dismiss()
                                    }.setKoButton(getString(R.string.cancel)) {
                                        customDialogReset.dismiss()

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

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

    @SuppressLint("SetTextI18n")
    private fun setEvents() {
        binding.mainToolbar.backButton.setOnClickListener {
            ma.onMyBackPressed()
        }

        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().isNotEmpty()) {
                    setIconsActions(true)
                    setIcons()
                    if (!modeCheckUbication || (modeCheckUbication && (binding.editMatricula.text.toString()
                            .isShelving()) && !binding.editMatricula.text!![0].isDigit())
                    ) {
                        binding.mainToolbar.toolbarTitle.text =
                            binding.editMatricula.text.toString()
                        shelvingFk = binding.editMatricula.text.toString()
                        parking = ""
                        binding.editPrioridad.setText("")
                        isShelvinLogfromMainScreen = true
                        viewModel.itemShelvingListNew(
                            binding.editMatricula.text.toString()
                        )
                    } else {
                        try {
                            buyScanned = itemScanValue(
                                binding.editMatricula.text.toString(), arrayOf("buy"), "more"
                            ).toString()
                            viewModel.getIdFromCode(
                                code = buyScanned
                            )
                        } catch (ex: Exception) {
                            ma.messageWithSound(
                                ex.message.toString(), isError = true, isPlayed = true
                            )
                        }

                    }
                }
                binding.mainToolbar.switchButton.visibility = VISIBLE

                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().isNotEmpty()) {
                    viewModel.shelvingPriorityUpdate(
                        binding.editPrioridad.toInt(), shelvingFk
                    )
                    isBack = false

                }
                ma.hideKeyboard(binding.editPrioridad)
            }

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


        binding.automaticImg.setOnClickListener {
            if (shelvingFk.isNotBlank()) ma.onPasillerosItemClickListener(
                PasillerosItemVO(title = R.string.titleAuto), entryPoint = shelvingFk
            )
            else getString(R.string.scanShelving).toast(
                requireActivity(), Toast.LENGTH_SHORT
            )
        }

        binding.parkingImg.setOnClickListener {
            if (shelvingFk.isNotBlank()) {
                customDialogInput.setTitle(getString(R.string.parkingShelving)).setValue("")
                    .setOkButton(
                        getString(
                            R.string.parking
                        )
                    ) {
                        customDialogActionParking()

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

                    return@setOnEditorActionListener true
                }
                false
            }

        }

        binding.editImg.setOnClickListener {
            if (shelvingFk.isNotBlank()) {
                customDialogInput = CustomDialogInput(requireContext())
                customDialogInput.setTitle(getString(R.string.changeShelving)).setValue("")
                    .setOkButton(getString(R.string.save)) {
                        if (customDialogInput.getValue().isNotBlank()) {
                            customDialogActionChange()
                        } 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) {
                    customDialogActionChange()
                    return@setOnEditorActionListener true
                }
                false
            }

        }

        binding.deleteImg.setOnClickListener {
            if (shelvingFk.isNotBlank()) {
                val customDialogDelete = CustomDialog(requireContext())
                customDialogDelete.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
                            it.available = 0
                        }


                        if (adapter != null) {
                            adapter!!.notifyDataSetChanged()
                        }
                        customDialogDelete.dismiss()
                    }

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

            }

        }
    }

    private fun customDialogActionParking() {
        parking = customDialogInput.getValue()
        //tarea 6964
        viewModel.hasItemOlder(
            shelvingFk, customDialogInput.getValue(),
        )

        customDialogInput.dismiss()
    }

    private fun customDialogActionChange() {
        viewModel.shelvingChangeSalix(
            shelvingFk, customDialogInput.getValue()
        )
        shelvingFk = customDialogInput.getValue()

        customDialogInput.dismiss()
    }

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

        if (listItems.none { it.item == itemScanned }) {
            try {
                listInt.add(buyScanned.toLong())
            } catch (_: Exception) {
            }

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

        }
        if (listInt.isNotEmpty()) {
            viewModel.itemShelvingAddList(
                shelvingFk,
                "" + listInt + "",
                true,
                mobileApplication.dataStoreApp.readDataStoreKey(WAREHOUSEFK)
            )
        }

        adapter!!.notifyDataSetChanged()
    }

    private fun setTooltips() {

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

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

                    if (isShelvinLogfromMainScreen) {
                        viewModel.shelvingLogAdd(shelvingFk)
                    }
                    listItems = ArrayList()
                    val totalStickers = it.list.sumOf { item -> item.stickers }
                    parking = it.list.firstOrNull { item -> item.code != null }?.code ?: ""
                    listItems.addAll(it.list)

                    binding.mainToolbar.toolbarTitle.text =
                        shelvingFk.uppercase() + getString(R.string.pUppercase) + parking + getString(
                            R.string.label
                        ) + totalStickers
                    if (listItems.isNotEmpty()) binding.editPrioridad.setText(it.list[0].priority.toString())

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

                    if (listItems.isNotEmpty()) {
                        binding.deleteImg.visibility = VISIBLE

                    } else {
                        binding.deleteImg.visibility = View.INVISIBLE
                    }
                    setAdapter(listItems)
                    setPosition()

                }
            }
            loadAddList.observe(viewLifecycleOwner) { event ->
                event.getContentIfNotHandled().notNull {
                    viewModel.itemShelvingListNew(shelvingFk)
                }
            }

            /*response.observe(viewLifecycleOwner) {
                viewModel.itemShelvingListNew(shelvingFk)
            }*/
            //parking, isChecked, responseOlder, responseMake Add
            responseUbicator.observe(viewLifecycleOwner) {

                if (shelvingFk.isNotEmpty()) {
                    binding.mainToolbar.toolbarTitle.text = shelvingFk
                    viewModel.itemShelvingListNew(
                        shelvingFk
                    )

                }
            }
            responseLogAdd.observe(viewLifecycleOwner) {
                isShelvinLogfromMainScreen = false
            }
            loadResponseCode.observe(viewLifecycleOwner) { event ->
                event.getContentIfNotHandled().notNull {
                    checkUbications(it.toLong())
                }
            }

            loadAddList.observe(viewLifecycleOwner) {

                if (shelvingFk.isNotEmpty()) {
                    binding.mainToolbar.toolbarTitle.text = shelvingFk
                    viewModel.itemShelvingListNew(
                        shelvingFk
                    )

                }
            }

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

                    if (it.list.isNotEmpty()) {
                        val formattedList = it.list.map { item ->
                            val itemFk = item.itemFk
                            val shelvingFk = item.shelvingFk
                            "$itemFk (${shelvingFk.uppercase()})"
                        }
                        val resultString = formattedList.joinToString(separator = "\n")
                        val finalOutput = "\n$resultString"
                        customDialogOlder.setTitle(getString(R.string.info)).setDescription(
                            getString(
                                R.string.itemOlderInfo, Action.PARKINEAR
                            ) + getString(R.string.listItems) + finalOutput
                        ).setOkButton(
                            getString(R.string.ok)
                        ) {
                            viewModel.setParking(
                                it.originalShelvingFk, it.originalParking
                            )

                            customDialogOlder.dismiss()

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

                    }
                }
            }

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

                    customDialogOlder.setTitle(getString(R.string.info)).setDescription(
                        getString(
                            R.string.itemOlderInfo, responseHasOlder.value!!.action
                        )
                    ).setOkButton(
                        getString(R.string.ok)
                    ) {
                        when (responseHasOlder.value!!.action) {
                            Action.PARKINEAR -> viewModel.setParking(
                                responseHasOlder.value!!.shelvingFkIn, parking
                            )

                            Action.TRANSFERIR -> viewModel.itemShelvingTransfer(
                                responseHasOlder.value!!.itemFk!!,
                                responseHasOlder.value!!.shelvingFkOut!!
                            )
                        }
                        customDialogOlder.dismiss()

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

        }

    }

    private fun setPosition() {
        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
            )
        }
    }

    private fun setAdapter(listItems: MutableList<ItemUbicador>) {
        listItems.sortWith { item1, item2 ->
            val compareItem = item1.item.compareTo(item2.item)
            if (compareItem == 0) {
                item2.visible.compareTo(item1.visible) // Invertir el orden
            } else {
                compareItem
            }
        }
        adapter = UbicadorAdapterNew(listItems.sortedBy { it.isChecked },
            onPasillerosItemClickListener = pasillerosItemClickListener!!,
            onVisibleClickListener = object : OnVisibleClickListenerNew {
                override fun onVisibleClickListener(item: ItemUbicador) {

                    if (!isAutoSelf) {

                        if (item.isChecked == 0) {
                            viewModel.updateIsChecked(itemShelvingFk = item.id)
                        }

                        showAddItemNew(
                            itemUbicador = item, isEditItem = true
                        )
                    } else {

                        showAutoSelfConsumption(item)
                    }

                }

            },
            onMoreClickListener = object : OnMoreClickListenerNew {
                override fun onMoreClickListener(item: ItemUbicador) {
                    showMoreOptions(item)
                }

            })

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

    private fun showAutoSelfConsumption(item: ItemUbicador) {

        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) {
                        val quantity =
                            if (item.visible - customDialogInput.getValue().toInt() > 0) {
                                item.visible - customDialogInput.getValue().toInt()
                            } else {
                                0
                            }
                        viewModel.itemShelvingSelfConsumption(
                            shelvingFk, item.item.toInt(), 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 showAddItemNew(
        isEditItem: Boolean,
        itemUbicador: ItemUbicador?,
    ) {
        customDialogUbicador = CustomDialogUbicadorNew(requireContext())


        if (isEditItem) {
            customDialogUbicador.setTitle(getString(R.string.editItem) + itemUbicador!!.item)
                .setItemValue(itemUbicador.item.toString())
                .setPackingValue(itemUbicador.packing.toString())
                .setVisibleValue(itemUbicador.visible.toString())
                //.setEtiquetaValue((itemUbicador.visible / (itemUbicador.packing ?: 0)).toString())
                .setEtiquetaValue(itemUbicador.stickers.toString())
                .setUnits(
                    if (itemUbicador.stickers != 0) {
                        (itemUbicador.visible % itemUbicador.stickers).toString()
                    } else {
                        "0"
                    }
                ).setOkButton(getString(R.string.save)) {
                    setShowAddItemAction(itemUbicador)
                }.setKoButton(getString(R.string.close)) {
                    customDialogUbicador.dismiss()
                }.show()
        } else {
            customDialogUbicador.setTitle(getString(R.string.newItem))
                .setOkButton(getString(R.string.save)) {
                    setShowAddItemAction(null)
                }.setKoButton(getString(R.string.close)) {
                    customDialogUbicador.dismiss()
                }.show()
        }

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

                if (customDialogUbicador.getItemValue().isNotEmpty()) {
                    try {

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

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

                return@setOnEditorActionListener true
            }

            customDialogUbicador.getPackingItem().requestFocus()
        }

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

    }

    private fun setShowAddItemAction(itemUbicador: ItemUbicador?) {
        try {

            if (customDialogUbicador.getItemValue()
                    .isEmpty() || customDialogUbicador.getPackingValue().isBlank()
            ) {
                getString(R.string.itemAndPackingMandatory).toast(context)
            } else {
                saveItemCall(customDialogUbicador, itemUbicador)
                customDialogUbicador.dismiss()
            }
        } catch (ex: Exception) {
            ex.message.toString().toast(requireContext())
        }
    }

    private fun saveItemCall(
        customDialogUbicador: CustomDialogUbicadorNew,
        itemUbicador: ItemUbicador?,
    ) {

        if (itemUbicador?.id == null) {
            //item nuevo sin shelving
            try {
                if (locateMultipleShelvings) insertShelvingsForUbicator(
                    customDialogUbicador.getItemValue().toLong(),
                    customDialogUbicador.getVisibleValue().toInt(),
                    customDialogUbicador.getPackingValue().toIntOrNull()

                ) else {
                    viewModel.itemShelvingAdd(
                        shelving = shelvingFk,
                        item = customDialogUbicador.getItemValue().toLong(),
                        quantity = customDialogUbicador.getVisibleValue().toInt(),
                        packing = customDialogUbicador.getPackingValue().toIntOrNull(),
                        warehouse = mobileApplication.dataStoreApp.readDataStoreKey(WAREHOUSEFK),
                        grouping = null
                    )
                }

            } catch (ex: Exception) {
                ma.messageWithSound(
                    getString(R.string.reviewData),
                    isError = true,
                    isPlayed = true,
                    isToasted = true
                )
            }
        } else {
            viewModel.itemShelvingMakeEdit(
                customDialogUbicador.getVisibleValue().toIntOrNull()!!,
                customDialogUbicador.getPackingValue().toInt(),
                itemUbicador.id,
                itemUbicador.grouping,
                updateAvailable(
                    itemUbicador.available,
                    customDialogUbicador.getVisibleValue().toIntOrNull(),
                    itemUbicador.visible
                )
            )

        }

    }

    private fun updateAvailable(newAvailable: Int?, newVisible: Int?, oldVisible: Int?): Int {
        val available = newAvailable ?: 0
        val visible = newVisible ?: 0
        val old = oldVisible ?: 0
        return maxOf(available + visible - old, 0)
    }

    private fun insertShelvingsForUbicator(barCode: Number, visible: Int, packing: Int?) {
        if (listShelvings.isNotEmpty()) listShelvings.clear()
        customDialogList = CustomDialogList(requireContext())
        customDialogList.setTitle(
            getString(R.string.shelvingsLocate)
        )
        customDialogList.setDescription(
            getString(R.string.scanShelvingsLocate)
        ).setOkButton(getString(R.string.locate)) {
            listShelvings.forEach {
                viewModel.itemShelvingAdd(
                    shelving = it.code!!,
                    item = barCode,
                    quantity = visible,
                    packing = packing,
                    warehouse = mobileApplication.dataStoreApp.readDataStoreKey(WAREHOUSEFK),
                    grouping = null
                )

            }
            customDialogList.dismiss()

        }.setKoButton(getString(R.string.cancel)) {
            ma.hideKeyboard(customDialogList.getEditText())
            customDialogList.dismiss()

        }.setValue("").show()

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

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

                    try {
                        customDialogList.setValue(
                            itemScanValue(
                                customDialogList.getValue(), arrayOf("saleGroup"), field = "id"
                            ).toString()
                        )
                        if (customDialogList.getValue().isShelving()) {
                            if (listShelvings.firstOrNull { it.code == customDialogList.getValue() } == null) {
                                listShelvings.add(BarcodeVO(code = customDialogList.getValue()))/*viewModel.sectorCollectionSaleGroupAdd(
                                    customDialogList.getValue().toInt(), collectionFk
                                )*/
                            } else {
                                throw Exception(getString(R.string.errorRepeatedShelving))
                            }
                        } else {
                            throw Exception()
                        }

                    } catch (ex: Exception) {
                        ma.messageWithSound(
                            getString(R.string.errorInput),
                            isError = true,
                            isPlayed = true,
                            isToasted = true
                        )
                        listShelvings.removeAt(0)
                    }

                    listShelvingsAdapter!!.notifyItemChanged(0)
                }
                customDialogList.setValue("")
                ma.hideKeyboard(customDialogList.getEditText())
                return@setOnEditorActionListener true
            }
            false
        }

        listShelvingsAdapter = BarcodeAdapter(
            listShelvings, object : OnBarcodeRowClickListener {
                override fun onBarcodeRowClickListener(item: BarcodeVO) {

                }
            }, showDelete = false
        )
        customDialogList.getRecyclerView().adapter = listShelvingsAdapter

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

    }

    private fun setWatcher() {
        customDialogUbicador.addTextWatcher(customDialogUbicador.getPackingItem()) { s ->

            setValueVisible()
        }

        customDialogUbicador.addTextWatcher(customDialogUbicador.getEtiquetaItem()) { s ->

            setValueVisible()
        }

        customDialogUbicador.addTextWatcher(customDialogUbicador.getUnitsItem()) { s ->

            setValueVisible()
        }

    }

    private fun setValueVisible() {
        customDialogUbicador.setVisibleValue("")
        customDialogUbicador.setVisibleValue(
            (((customDialogUbicador.getEtiquetaValue().toIntOrNull()
                ?: 0) * (customDialogUbicador.getPackingValue().toIntOrNull()
                ?: 0)) + (customDialogUbicador.getUnitsValue().toIntOrNull() ?: 0)).toString()
        )
    }

    private fun showMoreOptions(item: ItemUbicador) {
        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)) {
                        customDialogTransferAction(item)

                    }.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) {
                        customDialogTransferAction(item)
                        return@setOnEditorActionListener true
                    }
                    false
                }
                customDialogTwoButtons.dismiss()
            }.setOkButtonTwo(getString(R.string.delete)) {
                val customDialogConfirm = CustomDialog(requireContext())
                customDialogConfirm.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!!.notifyItemRemoved(listItems.indexOf(item))
                        //adapter!!.notifyDataSetChanged()
                        viewModel.itemShelvingDelete(
                            item.id
                        )
                        customDialogTwoButtons.dismiss()
                        customDialogConfirm.dismiss()
                    } else {
                        viewModel.itemShelvingSelfConsumption(
                            shelvingFk, item.item.toInt(), 0
                        )
                        customDialogConfirm.dismiss()
                        customDialogTwoButtons.dismiss()
                    }
                }.setKoButton(getString(R.string.cancel)) {
                    customDialogConfirm.dismiss()
                    customDialogTwoButtons.dismiss()
                }
                customDialogConfirm.show()
            }//Tarea 7763
        /*
                    .setOkButtonThree(getString(R.string.rename)) {
                        customDialogInput.setTitle(getString(R.string.itemNew))
                            .setDescription(getString(R.string.scanItem)).setValue("")
                            .setOkButton(getString(R.string.rename)) {

                                actionRename(item, customDialogInput.getValue())

                            }.setKoButton(getString(R.string.cancel)) {
                                customDialogInput.dismiss()
                                customDialogTwoButtons.dismiss()
                            }.show()
                        customDialogInput.getEditText().setOnEditorActionListener { _, actionId, _ ->
                            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0 || actionId == 5) {

                                actionRename(item, customDialogInput.getValue())
                                return@setOnEditorActionListener true
                            }
                            false
                        }
                        customDialogInput.getEditText().requestFocus()
                    }
        */
        customDialogTwoButtons.setKoButton(getString(R.string.cancel)) {
            customDialogTwoButtons.dismiss()
        }

        customDialogTwoButtons.show()
    }

    private fun actionRename(item: ItemUbicador, itemScan: String) {

        if (itemScan.isNotEmpty()) {

            renameItem(
                item, itemScanValue(
                    itemScan, arrayOf("buy"), "id"
                ).toString().toLong()
            )
            customDialogInput.dismiss()
            customDialogTwoButtons.dismiss()
        } else {
            getString(R.string.scanItem).toast(requireContext())
        }

    }

    private fun renameItem(item: ItemUbicador, barCode: Long) {
        try {
            viewModel.getInfoFromBuy(item.id, buyFk = barCode)
        } catch (ex: Exception) {
            ma.messageWithSound(ex.message.toString(), isError = true, isPlayed = true)

        }

    }

    private fun customDialogTransferAction(item: ItemUbicador) {
        if (customDialogInput.getValue().isNotEmpty()) {
            /*tearea 6964*//*
            viewModel.hasItemOlder(
                shelvingFkIn = shelvingFk,
                shelvingFkOut = customDialogInput.getValue(),
                itemFk = item.id,
                action = Action.TRANSFERIR
            )*/
            viewModel.itemShelvingTransfer(
                item.id, customDialogInput.getValue()
            )
            listItems.remove(item)
            adapter!!.notifyItemRemoved(listItems.indexOf(item))
            //adapter!!.notifyDataSetChanged()
            customDialogInput.dismiss()
        } else {
            getString(R.string.wagonIncorrect).toast(requireContext())

        }
    }
}
