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

import android.app.AlertDialog
import android.content.Intent
import android.graphics.drawable.Drawable
import android.os.Build
import android.view.View
import android.view.View.GONE
import android.view.inputmethod.EditorInfo
import android.widget.ImageView
import androidx.annotation.RequiresApi
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.gson.Gson
import es.verdnatura.R
import es.verdnatura.databinding.FragmentItemCardBinding
import es.verdnatura.domain.toast
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.*
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.feature.articulo.adapter.BarcodeAdapter
import es.verdnatura.presentation.view.feature.articulo.adapter.ItemCardAdapter
import es.verdnatura.presentation.view.feature.articulo.model.BarcodeVO
import es.verdnatura.presentation.view.feature.articulo.model.ItemCardRowVO
import es.verdnatura.presentation.view.feature.articulo.model.ItemCardVO
import es.verdnatura.presentation.view.feature.articulo.model.ItemPackingType
import es.verdnatura.presentation.view.feature.imageview.activity.ImageViewActivity
import es.verdnatura.presentation.view.feature.pasillero.model.PasillerosItemVO

class ItemCardFragment(
    var itemFk: String = ""
) : BaseFragment<FragmentItemCardBinding, ItemCardViewModel>(ItemCardViewModel::class) {

    private var urlLarge: String = ""
    private var titleImage: String = ""
    private var user = ""
    private var password = ""
    private var warehouseFk = ""
    private var adapter: ItemCardAdapter? = null
    private var barcodeAdapter: BarcodeAdapter? = null
    private var listItemsRow: ArrayList<ItemCardRowVO> = ArrayList()
    private var listBarcodes: ArrayList<BarcodeVO> = ArrayList()
    private var itemsPackingType: ArrayList<ItemPackingType> = ArrayList()


    private var itemInfoG: ItemCardVO? = null

    companion object {
        fun newInstance(entryPoint: String) = ItemCardFragment(entryPoint)
    }

    // private lateinit var customDialog: CustomDialog
    private lateinit var customDialogInput: CustomDialogInput
    private lateinit var customDialogList: CustomDialogList
    private lateinit var customDialogTwo: CustomDialogTwoButtons


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

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

        binding.itemcardLayout.visibility =GONE
        ma.hideBottomNavigation(GONE)

        setEvents()
        binding.mainToolbar.toolbarTitle.text = getString(R.string.titleItemConsult)
        customDialogInput = CustomDialogInput(requireContext())
        customDialogList = CustomDialogList(requireContext())
        customDialogTwo = CustomDialogTwoButtons(requireContext())


        if (!itemFk.isNullOrEmpty()) {
            getItemCard(itemFk)
        }
        setToolBar()
        super.init()


    }

    private fun setToolBar() {

        binding.mainToolbar.toolbarIcons.visibility = GONE


        val listIcons: ArrayList<ImageView> = ArrayList()
        val iconReload = ImageView(context)
        iconReload.setImageResource(R.drawable.ic_autorenew_black_24dp)
        val iconHistory = ImageView(context)
        iconHistory.setImageResource(R.drawable.ic_history_black_24dp)
        val iconSalix = ImageView(context)
        iconSalix.setImageResource(R.drawable.ic_logo_salix)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            iconReload.tooltipText = getTooltip(R.drawable.ic_autorenew_black_24dp)
            iconHistory.tooltipText = getTooltip(R.drawable.ic_history_black_24dp)
            iconSalix.tooltipText= getTooltip(R.drawable.ic_logo_salix)
        }
        listIcons.add(iconSalix)
        listIcons.add(iconReload)
        listIcons.add(iconHistory)


        binding.mainToolbar.toolbarIcons.adapter =
            ToolBarAdapterTooltip(listIcons, object : OnOptionsSelectedListener {


                override fun onOptionsItemSelected(item: Drawable) {

                    when (item) {
                        iconReload.drawable -> {
                            binding.splashProgress.visibility = View.VISIBLE
                            getItemCard(itemFk)
                        }
                        iconHistory.drawable -> {
                            if (itemFk.isNullOrEmpty()) {
                                getString(R.string.scanItem).toast(requireActivity())
                            } else {
                                ma.onPasillerosItemClickListener(
                                    PasillerosItemVO(title = getString(R.string.titleHistorical)),
                                    itemInfoG!!.id
                                )

                            }

                        }
                        iconSalix.drawable -> {
                            binding.splashProgress.visibility = View.VISIBLE
                            //getItemCard(itemFk)

                           // ma.openFragmentWeb(itemInfoG!!.id)
                            var itemId=itemInfoG!!.id
                            var entryPoint =  Gson().toJson(mutableMapOf("entryPoint" to  itemId, "web" to "https://salix.verdnatura.es/#!/item/$itemId/summary"))
                            ma.onPasillerosItemClickListener(
                                PasillerosItemVO(title = getString(R.string.titleWebViewer),
                            ), entryPoint = entryPoint)

                        }
                    }

                }

            })


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


    private fun setEvents() {
        //edit_itemFk.requestFocus()
        binding.editItemFk.requestFocus()
        //edit_itemFk.setOnEditorActionListener { v, actionId, event ->
        binding.editItemFk.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0 || actionId == 5) {
                //if (!edit_itemFk.text.toString().isNullOrEmpty())
                if (!binding.editItemFk.text.toString().isNullOrEmpty())
                    getItemCard(binding.editItemFk.text.toString())
                binding.editItemFk.setText("")
                ma.hideKeyboard(binding.editItemFk)
                return@setOnEditorActionListener true
            }
            false
        }

        binding.mainToolbar.backButton.setOnClickListener {

            requireActivity().onBackPressed()
        }

        binding.itemcardImage.setOnClickListener {

            val i = Intent(activity, ImageViewActivity::class.java)
            i.putExtra(getString(R.string.url), urlLarge)
            i.putExtra(getString(R.string.title), titleImage)
            startActivity(i)
        }
    }

    private fun getItemCard(itemFk: String) {

        user = getData(USER)
        password = getData(PASSWORD)
        warehouseFk = getData(WAREHOUSEFK)

        this.itemFk = itemFk

        binding.splashProgressTwo.visibility = View.VISIBLE
        viewModel.getItemCard(itemFk, warehouseFk, user, password)
        binding.splashProgress.visibility = View.VISIBLE


        var working_in_test = false //sergio:No posar a true fins que Salix puje versió 8.3

        if (working_in_test) {
            viewModel.getItemPackingTypeSalix(getData(TOKEN))
        } else {
            viewModel.getItemPackingType(getData(USER), getData(PASSWORD))
        }
    }

    override fun observeViewModel() {
        with(viewModel) {
            itemcard.observe(viewLifecycleOwner, Observer {

                if (it.isError) {
                    binding.itemcardLayout.visibility = GONE
                    binding.splashProgressTwo.visibility = GONE
                    binding.mainToolbar.toolbarTitle.text = getString(R.string.itemCard)
                    ma.messageWithSound(it.errorMessage, true, false)

                } else {
                    if (!it.id.isNullOrEmpty()) {
                        binding.itemcardLayout.visibility = View.VISIBLE
                        setItemCard(it)
                        binding.mainToolbar.toolbarIcons.visibility = View.VISIBLE
                    } else {
                        binding.splashProgressTwo.visibility = GONE
                        binding.itemcardLayout.visibility = GONE
                        binding.mainToolbar.toolbarTitle.text = getString(R.string.itemCard)
                        ma.messageWithSound(
                            getString(R.string.itemNotFound),
                            true,
                            false,
                            getString(R.string.noResults)
                        )

                    }

                }
            })

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

                createItemTypeTypeList(it.list)
            })

            response.observe(viewLifecycleOwner, Observer {
                binding.splashProgress.visibility = GONE
                if (it.isError) {
                    ma.messageWithSound(it.errorMessage, true, false)
                } else {
                    getItemCard(itemFk)
                }

            })
        }
    }

    private fun createItemTypeTypeList(list: List<ItemPackingType>) {
        itemsPackingType.clear()
        list.forEach { item ->
            if (!item.isError) {
                try {
                    itemsPackingType.add(ItemPackingType(item.code, item.description))

                } catch (e: Exception) {
                }
            }
        }
    }


    private fun setItemCard(itemInfo: ItemCardVO) {
        itemInfoG = itemInfo
        binding.mainToolbar.toolbarTitle.text = itemInfo.id + "-" + itemInfo.longName
        titleImage = itemInfo.id + "-" + itemInfo.longName
        binding.itemcardImage.loadUrl(itemInfo.urlImage200)
        urlLarge = itemInfo.urlImage
        binding.itemcardTag1.text = itemInfo.size
        binding.itemcardTag2.text = itemInfo.value5
        binding.itemcardTag3.text = itemInfo.value6
        binding.itemcardTag4.text = itemInfo.value7 + " " + itemInfo.origin
        binding.itemcardBuyer.text =itemInfo.buyer
        listItemsRow = ArrayList()

        //sergio itemcard por item_getInfo
        /* listItemsRow.add(
             ItemCardRowVO(
                 title = getString(R.string.total),
                 value = itemInfo.total,
                 isEditable = false
             )
         )*/
        listItemsRow.add(
            ItemCardRowVO(
                title = getString(R.string.total),
                value = itemInfo.visible,
                isEditable = false
            )
        )

        listItemsRow.add(
            ItemCardRowVO(
                title = getString(R.string.Disponible),
                value = itemInfo.available,
                isEditable = false
            )
        )

        //sergio itemcard por item_getInfo
        /* listItemsRow.add(
             ItemCardRowVO(
                 title = getString(R.string.Ubicado),
                 value = itemInfo.enAltillo,
                 isEditable = false
             )
         )*/
        listItemsRow.add(
            ItemCardRowVO(
                title = getString(R.string.Ubicado),
                value = itemInfo.vVisibleItemShelving,
                isEditable = false
            )
        )

        //sergio itemcard por item_getInfo
        /* listItemsRow.add(
             ItemCardRowVO(
                 title = getString(R.string.SINUBICAR),
                 value = itemInfo.enNicho,
                 isEditable = false,
                 action = "itemStockUpdate"
             )
         )*/
        listItemsRow.add(
            ItemCardRowVO(
                title = getString(R.string.SINUBICAR),
                value = itemInfo.unlocated,
                isEditable = false,
                action = "itemStockUpdate"
            )
        )
        listItemsRow.add(
            ItemCardRowVO(
                title = getString(R.string.itemCost),
                value = itemInfo.itemCost,
                isEditable = false,
                action = ""
            )
        )

        //EDITABLES

        listItemsRow.add(
            ItemCardRowVO(
                title = getString(R.string.titleSimilarItems),
                isEditable = true,
                action = "itemProposal"
            )
        )
        listItemsRow.add(
            ItemCardRowVO(
                title = getString(R.string.DARALTA),
                value = "",
                isEditable = true,
                action = "itemStockUpdateAdd"
            )
        )
        listItemsRow.add(
            ItemCardRowVO(
                title = getString(R.string.DARBAJA),
                value = "",
                isEditable = true,
                action = "itemStockUpdateRemove"
            )
        )
        listItemsRow.add(
            ItemCardRowVO(
                title = getString(R.string.BuscarItem),
                value = "",
                isEditable = true,
                action = "buscarItem"
            )
        )
        //listItemsRow.add(ItemCardRowVO(title = "NICHO",value = itemInfo.nicho,isEditable = true, action = "itemPlacementSave"))
        // listItemsRow.add(ItemCardRowVO(title = "RESERVA",value = itemInfo.reserva,isEditable = true, action = "itemPlacementSave"))
        listItemsRow.add(
            ItemCardRowVO(
                title = getString(R.string.Grouping),
                value = itemInfo.grouping,
                isEditable = true,
                action = "updateGrouping"
            )
        )
        listItemsRow.add(
            ItemCardRowVO(
                title = getString(R.string.Packing),
                value = itemInfo.packing,
                isEditable = true,
                action = "updatePacking"
            )
        )
       //sergio: quitar de back cuando ya tengan la app actualizada todos
       listItemsRow.add(
            ItemCardRowVO(
                title = getString(R.string.stems),
                value = itemInfo.stems,
                isEditable = true,
                action = "itemSaveStem"
            )
        )
        listItemsRow.add(
            ItemCardRowVO(
                title = getString(R.string.Referencia),
                value = itemInfo.reference,
                isEditable = true,
                action = "item_saveReference"
            )
        )
        listItemsRow.add(
            ItemCardRowVO(
                title = getString(R.string.Barcode),
                barcodes = itemInfo.barcodes,
                isEditable = true,
                action = "toBarcode"
            )
        )

        //sergio para itemTypePacking
      /*  listItemsRow.add(
            ItemCardRowVO(
                title = getString(R.string.tipodeencajado),
                value = itemInfo.itemPackingTypeFk,
                isEditable = true,
                action = "updateSector"
            )
        )*/
        // listItemsRow.add(ItemCardRowVO(title = "Artículos similares",value = itemInfo.itemPackingTypeFk,isEditable = true, action = "itemProposal"))


        listBarcodes = itemInfo.barcodes as ArrayList<BarcodeVO>

        adapter = ItemCardAdapter(listItemsRow, object : OnItemCardRowClickListener {
            override fun onItemCardRowClickListener(item: ItemCardRowVO) {

                if (item.action == "itemProposal") {

                    ma.onPasillerosItemClickListener(
                        PasillerosItemVO(
                            title = getString(R.string.titleSearchSimilarItems)
                        ), itemFk
                    )

                } else {
                    if (item.action == "updateSector") {
                        showDialogSelectItemTypePacking()
                    } else {
                        if (item.action != "toBarcode" && item.action != "buscarItem" && item.action != "itemStockUpdateAdd" && item.action != "itemStockUpdateRemove") {
                            customDialogInput.setTitle(item.title!!)
                                .setDescription(getString(R.string.currentVAlue) + if(item.value.isNullOrEmpty()) "" else{item.value})
                                .setOkButton(getString(R.string.save)) {
                                    ma.hideKeyboard(customDialogInput.getEditText())
                                    editItemCardRow(item, customDialogInput.getValue())
                                    customDialogInput.dismiss()

                                }.setKoButton(getString(R.string.cancel)) {
                                    ma.hideKeyboard(customDialogInput.getEditText())
                                    customDialogInput.dismiss()
                                }.setValue("").show()
                            customDialogInput.getEditText().requestFocus()
                            customDialogInput.getEditText()
                                .setOnEditorActionListener { _, actionId, _ ->

                                    if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0) {
                                        if (!customDialogInput.getValue().isNullOrEmpty())
                                            editItemCardRow(item, customDialogInput.getValue())
                                        customDialogInput.setValue("")
                                        customDialogInput.dismiss()
                                        ma.hideKeyboard(customDialogInput.getEditText())
                                        return@setOnEditorActionListener true
                                    }
                                    false
                                }
                        } else if (item.action == "toBarcode") {
                            //BARCODE ROW
                            prepareBarcodeDialog(item)
                        } else if (item.action == "buscarItem") {
                            ma.onPasillerosItemClickListener(
                                PasillerosItemVO(
                                    title = getString(R.string.titleItemSearch)
                                ), itemFk
                            )
                        } else if (item.action == "itemStockUpdateAdd") {
                            customDialogInput.setTitle(item.title!!)
                                .setDescription(getString(R.string.quantityToRegister))
                                .setOkButton(getString(R.string.save)) {
                                    ma.hideKeyboard(customDialogInput.getEditText())
                                    editItemCardRow(item, customDialogInput.getValue())
                                    customDialogInput.dismiss()

                                }.setKoButton(getString(R.string.cancel)) {
                                    ma.hideKeyboard(customDialogInput.getEditText())
                                    customDialogInput.dismiss()
                                }.setValue("").show()
                            customDialogInput.getEditText().requestFocus()
                            customDialogInput.getEditText()
                                .setOnEditorActionListener { _, actionId, _ ->
                                    if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0) {
                                        if (!customDialogInput.getValue().isNullOrEmpty())
                                            editItemCardRow(item, customDialogInput.getValue())
                                        customDialogInput.setValue("")
                                        customDialogInput.dismiss()
                                        ma.hideKeyboard(customDialogInput.getEditText())
                                        return@setOnEditorActionListener true
                                    }
                                    false
                                }
                        } else if (item.action == "itemStockUpdateRemove") {
                            customDialogInput.setTitle(item.title!!)
                                .setDescription(getString(R.string.quantityToUnregister))
                                .setOkButton(getString(R.string.save)) {
                                    ma.hideKeyboard(customDialogInput.getEditText())
                                    editItemCardRow(item, customDialogInput.getValue())
                                    customDialogInput.dismiss()

                                }.setKoButton(getString(R.string.cancel)) {
                                    ma.hideKeyboard(customDialogInput.getEditText())
                                    customDialogInput.dismiss()
                                }.setValue("").show()
                            customDialogInput.getEditText().requestFocus()
                            customDialogInput.getEditText()
                                .setOnEditorActionListener { _, actionId, _ ->
                                    if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0) {
                                        if (!customDialogInput.getValue().isNullOrEmpty())
                                            editItemCardRow(item, customDialogInput.getValue())
                                        customDialogInput.setValue("")
                                        customDialogInput.dismiss()
                                        ma.hideKeyboard(customDialogInput.getEditText())
                                        return@setOnEditorActionListener true
                                    }
                                    false
                                }
                        }
                    }
                }
            }
        })
        //itemcard_recyclerview.adapter = adapter
        binding.itemcardRecyclerview.adapter = adapter
        //itemcard_recyclerview.layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
        binding.itemcardRecyclerview.layoutManager =
            LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
        binding.scrollView.post {
            val position = IntArray(2)
            binding.itemcardImage.getLocationInWindow(position)
            binding.scrollView.scrollTo(0, position[1])
        }
        binding.splashProgressTwo.visibility = GONE
    }

    private fun editItemCardRow(item: ItemCardRowVO, value: String) {

        when (item.action) {
            // cau:sergio itemTrash x itemStock Update . No se utiliza esta funicón
            // "itemStockUpdate" -> prepareItemStockUpdate(item,value)
            "itemStockUpdateAdd" -> prepareItemStockUpdate2(item, value)
            "itemStockUpdateRemove" -> prepareItemStockUpdate2(item, value)
            /* "itemPlacementSave" -> viewModel.itemPlacementSave(
                 itemFk = itemFk,
                 warehouseFk = warehouseFk,
                 user = user,
                 password = password,
                 value = value,
                 "itemPlacementSave"
             )*/
            "updateGrouping" -> viewModel.updateGrouping(
                itemFk = itemFk,
                user = user,
                password = password,
                value = value,
                warehouseFk = warehouseFk
            )
            "updatePacking" -> viewModel.updatePacking(
                itemFk = itemFk,
                user = user,
                password = password,
                value = value,
                warehouseFk = warehouseFk
            )
            "itemSaveStem" -> viewModel.item_saveStems(
                itemFk = itemFk,
                user = user,
                password = password,
                value = value
            )
            "item_saveReference" -> viewModel.item_saveReference(
                itemFk = itemFk,
                user = user,
                password = password,
                value = value
            )


        }
        if (item.action != "itemStockUpdate" && item.action != "itemStockUpdateRemove" && item.action != "itemStockUpdateAdd")
        // changeOfflineValue(item,value, listBarcodes)
            showProgress()
    }

    //sergio: changeOffLineValue solo hace visible el progress

    private fun showProgress() {
        binding.splashProgress.visibility = View.VISIBLE
    }

    /* private fun changeOfflineValue(item:ItemCardRowVO,newValue:String, barcodes:List<BarcodeVO>){

         binding.splashProgress.visibility = View.VISIBLE

        //sergio: esta parte ya estaba comentada
          /*var i = 0
         var position = 0
         listItemsRow.forEach {
             if (it.title == item.title) {
                 position = i
             }
             i = i.plus(1)
         }
         if (listItemsRow.get(position).title != "BARCODE") listItemsRow.get(position).value = newValue
         else listItemsRow.get(position).barcodes = barcodes
         adapter?.notifyDataSetChanged()*/
     }*/

    /* private fun prepareItemStockUpdate(itemB:ItemCardRowVO,value:String){

         //sergio: cau: no se llama a esta función itemTrash itemStockUpdate
         try{

             if (itemB.value!!.toInt() > value.toInt()) {
                 customDialogTwo.setTitle(itemB.title!!).setDescription("Indica la causa de eliminar stock:").setOkButton("Falta"){
                     viewModel.itemStockUpdate(itemFk = itemFk,warehouseFk = warehouseFk,user = user,password = password,newValue = value,isTrash = "0")
                     changeOfflineValue(itemB,value, listBarcodes)
                     customDialogTwo.dismiss()

                 }.setOkButtonTwo("Basura"){
                     viewModel.itemStockUpdate(itemFk = itemFk,warehouseFk = warehouseFk,user = user,password = password,newValue = value,isTrash = "1")
                     changeOfflineValue(itemB,value, listBarcodes)
                     customDialogTwo.dismiss()

                 }.setKoButton(getString(R.string.cancel)){

                     customDialogTwo.dismiss()
                 }.show()
             }else{
                 changeOfflineValue(itemB,value, listBarcodes)
                 viewModel.itemStockUpdate(itemFk = itemFk,warehouseFk = warehouseFk,user = user,password = password,newValue = value,isTrash = "0")
             }
         }catch (e:Exception){
             binding.itemcardLayout.visibility = View.GONE
             customDialog.setTitle(getString(R.string.error)).setDescription("El elemento introducido no es un número").setKoButton(getString(R.string.cancel)){
                 customDialog.dismiss()
             }.show()
         }

     }*/

    private fun prepareItemStockUpdate2(itemB: ItemCardRowVO, value: String) {
        try {
            value.toInt()

            if (itemB.action == "itemStockUpdateRemove") {
                customDialogTwo.setTitle(itemB.title!!)
                    .setDescription(getString(R.string.deleteStock))
                    .setOkButton(getString(R.string.fault)) {
                        viewModel.itemTrash(
                            itemFk = itemFk,
                            warehouseFk = warehouseFk,
                            user = user,
                            password = password,
                            newValue = value,
                            isTrash = "0"

                        )
                        //changeOfflineValue(itemB,value, listBarcodes)
                        showProgress()
                        customDialogTwo.dismiss()

                    }.setOkButtonTwo(getString(R.string.trash)) {
                        viewModel.itemTrash(
                            itemFk = itemFk,
                            warehouseFk = warehouseFk,
                            user = user,
                            password = password,
                            newValue = value,
                            isTrash = "1"

                        )
                        //changeOfflineValue(itemB,value, listBarcodes)
                        showProgress()
                        customDialogTwo.dismiss()

                    }.setKoButton(getString(R.string.cancel)) {

                        customDialogTwo.dismiss()
                    }.show()
            } else {
                //changeOfflineValue(itemB,value, listBarcodes)
                showProgress()
                viewModel.itemTrash(
                    itemFk = itemFk,
                    warehouseFk = warehouseFk,
                    user = user,
                    password = password,
                    newValue = (value.toInt() * -1).toString(),
                    isTrash = "0"

                )
            }
        } catch (e: Exception) {
            //  binding.itemcardLayout.visibility = View.GONE
            ma.messageWithSound(getString(R.string.errorNotNumber), true, true)

        }
    }

    private fun prepareBarcodeDialog(itemB: ItemCardRowVO) {

        customDialogList.setTitle(getString(R.string.barcodes)).setOkButton(getString(R.string.save)) {
            ma.hideKeyboard(customDialogList.getEditText())
            if (!customDialogList.getValue().isEmpty())
                updateBarcode(customDialogList.getValue(), "0", itemB)
            customDialogList.dismiss()

        }.setKoButton(getString(R.string.close)) {
            ma.hideKeyboard(customDialogList.getEditText())
            customDialogList.dismiss()
        }.setValue("").show()


        ma.hideKeyboard(customDialogList.getEditText())
        customDialogList.getEditText().setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0) {
                if (!customDialogList.getValue().isNullOrEmpty())
                    updateBarcode(customDialogList.getValue(), "0", itemB)
                customDialogList.setValue("")
                customDialogList.dismiss()
                ma.hideKeyboard(customDialogList.getEditText())
                return@setOnEditorActionListener true
            }
            false
        }

        barcodeAdapter = BarcodeAdapter(listBarcodes, object : OnBarcodeRowClickListener {
            override fun onBarcodeRowClickListener(item: BarcodeVO) {
                updateBarcode(item.code!!, "1", itemB)
            }
        })
        customDialogList.getRecyclerView().adapter = barcodeAdapter

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

    private fun updateBarcode(code: String, delete: String, item: ItemCardRowVO) {
        if (delete == "1") {
            var i = 0
            var posDelete = 0
            listBarcodes.forEach {
                if (it.code == code)
                    posDelete = i
                i += 1
            }
            listBarcodes.removeAt(posDelete)
        } else {
            listBarcodes.add(BarcodeVO(code))
        }

        // var working_in_test=false //sergio:Revisar como borrar directamente en Salix o crear proc en back para borrar.

        if (delete == "0") {
            viewModel.barcodesEditSalix(
                token = getData(TOKEN),
                itemFk = itemInfoG!!.id,
                barCodeValue = code,

                )
        } else {
            viewModel.barcodesEdit(
                itemFk = itemInfoG!!.id,
                user = user,
                password = password,
                value = code,
                delete = delete,
            )
        }
        barcodeAdapter!!.notifyDataSetChanged()

        showProgress()
    }

    private fun showDialogSelectItemTypePacking() {

        var array = arrayOfNulls<String>(itemsPackingType.size)
        for (indice in array.indices) {
            array[indice] =
                itemsPackingType[indice].code + " : " + itemsPackingType[indice].description
        }
        val builder = AlertDialog.Builder(this.context)
        builder.setTitle(getString(R.string.mensajeseleccionencajado))
            .setItems(
                array
            ) { _, position ->

                updateItemPackingType(itemsPackingType[position].code)

            }

        builder.create().show()
    }

    private fun updateItemPackingType(itemPackingType: String) {
        binding.splashProgress.visibility = View.VISIBLE

        /* var working_in_test=true //sergio: en proves app
         if (working_in_test){*/
        viewModel.updatePackingTypeSalix(
            getData(TOKEN),
            this.itemFk,
            itemPackingType
        )/*}else{
            viewModel.updatePackingType(
                this.itemFk,
                user,
                password,
                itemPackingType,
                "item_updatePackingType"
            )
        }*/
    }

}


