package it.integry.integrywmsnative.gest.accettazione_ordine_inevaso.viewmodel;

import android.app.ProgressDialog;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableField;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.text.SpannableString;

import com.annimon.stream.Stream;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import it.integry.integrywmsnative.BR;
import it.integry.integrywmsnative.R;
import it.integry.integrywmsnative.core.CommonConst;
import it.integry.integrywmsnative.core.REST.consumers.ArticoloRESTConsumer;
import it.integry.integrywmsnative.core.REST.consumers.BarcodeRESTConsumer;
import it.integry.integrywmsnative.core.REST.consumers.ColliMagazzinoRESTConsumer;
import it.integry.integrywmsnative.core.REST.consumers.GestSetupRESTConsumer;
import it.integry.integrywmsnative.core.REST.consumers.ISimpleOperationCallback;
import it.integry.integrywmsnative.core.REST.consumers.PrinterRESTConsumer;
import it.integry.integrywmsnative.core.REST.model.Ean128Model;
import it.integry.integrywmsnative.core.REST.model.Ean13PesoModel;
import it.integry.integrywmsnative.core.barcode_reader.BarcodeManager;
import it.integry.integrywmsnative.core.expansion.RunnableArgs;
import it.integry.integrywmsnative.core.model.CommonModelConsts;
import it.integry.integrywmsnative.core.model.MtbAart;
import it.integry.integrywmsnative.core.model.MtbColr;
import it.integry.integrywmsnative.core.model.MtbColt;
import it.integry.integrywmsnative.core.model.secondary.GestioneEnum;
import it.integry.integrywmsnative.core.report.ReportManager;
import it.integry.integrywmsnative.core.settings.SettingsManager;
import it.integry.integrywmsnative.core.utility.UtilityBarcode;
import it.integry.integrywmsnative.core.utility.UtilityDate;
import it.integry.integrywmsnative.core.utility.UtilityExceptions;
import it.integry.integrywmsnative.core.utility.UtilityLogger;
import it.integry.integrywmsnative.core.utility.UtilityProgress;
import it.integry.integrywmsnative.core.utility.UtilityString;
import it.integry.integrywmsnative.gest.accettazione.dto.OrdineAccettazioneDTO;
import it.integry.integrywmsnative.gest.accettazione_ordine_inevaso.AccettazioneOrdineInevasoActivity;
import it.integry.integrywmsnative.gest.accettazione_ordine_inevaso.core.AccettazioneOrdineInevasoHelper;
import it.integry.integrywmsnative.gest.accettazione_ordine_inevaso.core.IOnOrdineAccettazioneRowDispatchCallback;
import it.integry.integrywmsnative.gest.accettazione_ordine_inevaso.core.MainListOrdineAccettazioneAdapter;
import it.integry.integrywmsnative.gest.accettazione_ordine_inevaso.dto.AccettazioneOrdineInevasoOrderBy;
import it.integry.integrywmsnative.gest.accettazione_ordine_inevaso.rest.OrdineAccettazioneInevasoRESTConsumerService;
import it.integry.integrywmsnative.gest.accettazione_ordine_inevaso.views.NoteAggiuntiveNuovaULDialog;
import it.integry.integrywmsnative.ui.StatusBarAlert;
import it.integry.integrywmsnative.view.bottomsheet.interfaces.IOnColloClosedCallback;
import it.integry.integrywmsnative.view.bottomsheet.viewmodel.ArticoliInColloBottomSheetViewModel;
import it.integry.integrywmsnative.view.dialogs.DialogSimpleMessageHelper;
import it.integry.integrywmsnative.view.dialogs.input_quantity.DialogInputQuantity;
import it.integry.integrywmsnative.view.dialogs.input_quantity.QuantityDTO;
import it.integry.plugins.barcode_base_library.model.BarcodeScanDTO;

import static br.com.zbra.androidlinq.Linq.stream;

public class AccettazioneOnOrdineAccettazioneInevasoViewModel implements IOnColloClosedCallback, IOnOrdineAccettazioneRowDispatchCallback {

    public ObservableField<Boolean> isFabVisible = new ObservableField<>();

    private AccettazioneOrdineInevasoActivity mActivity;
    private final ArticoliInColloBottomSheetViewModel mArticoliInColloBottomSheetViewModel;
    private final List<OrdineAccettazioneDTO> mOrders;

    private List<List<OrdineAccettazioneDTO.Riga>> groupedRighe;
    private List<OrdineAccettazioneDTO.Riga> groupedOrdini;

    private AccettazioneOrdineInevasoHelper helper;

    private AccettazioneOrdineInevasoOrderBy.Enum currentOrderBy = AccettazioneOrdineInevasoOrderBy.Enum.COD_ART_FOR;
    private MainListOrdineAccettazioneAdapter mAdapter;

    public AccettazioneOnOrdineAccettazioneInevasoViewModel(AccettazioneOrdineInevasoActivity activity, ArticoliInColloBottomSheetViewModel articoliInColloBottomSheetViewModel, List<OrdineAccettazioneDTO> orders) {
        this.mActivity = activity;
        this.mArticoliInColloBottomSheetViewModel = articoliInColloBottomSheetViewModel;
        this.mOrders = orders;

        this.isFabVisible.set(true);

        this.mActivity.bindings.setVariable(BR.viewmodel, this);

        this.init();
    }

    private void init(){
        mArticoliInColloBottomSheetViewModel.setOnCloseColloCallbackListener(this);
        mArticoliInColloBottomSheetViewModel.setOnItemDeletedCallback(() -> this.refreshOrderBy(false));
        mArticoliInColloBottomSheetViewModel.setOnItemEditedCallback(() -> this.refreshOrderBy(false));

        groupedOrdini = new ArrayList<>();
        for (OrdineAccettazioneDTO ordine : mOrders){
            groupedOrdini.addAll(ordine.ordini);
        }

        helper = new AccettazioneOrdineInevasoHelper(mActivity);

        groupedRighe = helper.getOrdiniRaggruppatiPerCodArtForn(groupedOrdini, true);

        initRecyclerView(groupedRighe);
    }


    private void initRecyclerView(List<List<OrdineAccettazioneDTO.Riga>> groupedRighe){
        //RecyclerView setup
        mActivity.bindings.accettazioneOrdineMainList.setHasFixedSize(true);

        mActivity.bindings.accettazioneOrdineMainList.setLayoutManager(new LinearLayoutManager(mActivity));

        mAdapter = helper.getRightListAdapter(mActivity.bindings.accettazioneEmptyView);

        try {
            helper.updateListModel(AccettazioneOrdineInevasoOrderBy.Enum.COD_ART_FOR, groupedRighe, null);
        } catch (Exception e) {
            UtilityExceptions.defaultException(mActivity, e);
        }

        mAdapter.setOnOrdineRowDispatchCallback(this);
        mActivity.bindings.accettazioneOrdineMainList.setAdapter(mAdapter);
    }

    public void refreshOrderBy(boolean forceHiddenCheck){
        switch (currentOrderBy){
            case COD_ART_FOR:
                groupedRighe = helper.getOrdiniRaggruppatiPerCodArtForn(groupedOrdini, forceHiddenCheck);
                break;
            case DESCR_ART:
                groupedRighe = helper.getOrdiniRaggruppatiPerDescrArt(groupedOrdini, forceHiddenCheck);
                break;

            case RAG_SOC_COM:
                groupedRighe = helper.getOrdiniRaggruppatiPerRagSocCommessa(groupedOrdini, forceHiddenCheck);
                break;

            default:
                break;
        }

        try {
            List<MtbColr> mtbColrs = mArticoliInColloBottomSheetViewModel.mtbColt.get() != null ? mArticoliInColloBottomSheetViewModel.mtbColt.get().getMtbColr() : null;

            helper.updateListModel(currentOrderBy, groupedRighe, mtbColrs);
        } catch (Exception e) {
            UtilityExceptions.defaultException(mActivity, e);
        }
    }

    public void applyFilter(String descriptionText) {

        mActivity.bindings.filteredArtsInListExpandableLayout.expand(true);

        mActivity.bindings.descriptionFilterText.setText(descriptionText);
    }

    public void removeListFilter() {
        for(int i = 0; i < groupedOrdini.size(); i++) {
            groupedOrdini.get(i).setTempHidden(false);
        }

        refreshOrderBy(false);
        mActivity.bindings.filteredArtsInListExpandableLayout.collapse(true);
    }

    public void recoverUL(MtbColt recoveredMtbColt){

        for(int i = 0; i < recoveredMtbColt.getMtbColr().size(); i++){

            MtbColr currentMtbColr = recoveredMtbColt.getMtbColr().get(i);

            /*
            List<OrdineAccettazioneDTO.Riga> foundRows = Stream.of(groupedOrdini)
                    .filter(x -> x.getNumOrd() == currentMtbColr.getNumOrd() &&
                            x.getRigaOrd() == currentMtbColr.getRigaOrd()&&
                            x.getDataOrd().equals(currentMtbColr.getDataOrdD()))
                    .toList();
            */

            List<OrdineAccettazioneDTO.Riga> foundRows = Stream.of(groupedOrdini)
                    .filter(x -> Objects.equals(x.mtbAart.getCodMart(), currentMtbColr.getCodMart()) &&
                            Objects.equals(x.getPartitaMag(), currentMtbColr.getPartitaMag()) &&
                            Objects.equals(x.getCodJcom(), currentMtbColr.getCodJcom()))
                    .toList();


            if(foundRows != null && foundRows.size() > 0){
                OrdineAccettazioneDTO.Riga currentRow = foundRows.get(0);

                currentRow.setHidden(false);
                currentRow.setQtaRiservate(currentRow.getQtaRiservate().subtract(currentMtbColr.getQtaCol()));
            }

        }


        setULToCurrentContext(recoveredMtbColt);
        refreshOrderBy(false);
    }




    public RunnableArgs<BarcodeScanDTO> onScanSuccessfull = data -> {

        ProgressDialog progressDialog = UtilityProgress.createDefaultProgressDialog(mActivity);

        BarcodeManager.disable();

        if(UtilityBarcode.isEtichettaAnonima(data) && !thereIsAnOpenedUL()){
            this.executeEtichettaAnonima(data, progressDialog);
        } else if(UtilityBarcode.isEtichetta128(data)) {
            this.executeEtichettaEan128(data, progressDialog);
        } else if(UtilityBarcode.isEanPeso(data)){
            this.executeEtichettaEanPeso(data, progressDialog);
        } else {
            this.loadArticolo(data.getStringValue(), null, progressDialog);
        }

    };


    private void executeEtichettaAnonima(BarcodeScanDTO barcodeScanDTO, ProgressDialog progressDialog) {
        ColliMagazzinoRESTConsumer.getBySSCC(barcodeScanDTO.getStringValue(), false, false, mtbColt -> {

            if(mtbColt == null) {
                this.createNewUL(UtilityBarcode.getNumColloFromULAnonima(barcodeScanDTO.getStringValue()), CommonConst.Config.DEFAULT_ANONYMOUS_UL_SERIE, progressDialog, true, null);
                BarcodeManager.enable();
            } else {
                progressDialog.dismiss();
                BarcodeManager.enable();
                DialogSimpleMessageHelper.makeWarningDialog(mActivity,
                        new SpannableString(mActivity.getResources().getText(R.string.already_used_anonymous_barcode)),
                        null, null).show();
            }

        }, ex -> {
            UtilityExceptions.defaultException(mActivity, ex, progressDialog);
            BarcodeManager.enable();
        });
    }


    private void executeEtichettaEan128(BarcodeScanDTO barcodeScanDTO, ProgressDialog progressDialog) {
        BarcodeRESTConsumer.decodeEan128(barcodeScanDTO, ean128Model -> {

            String barcodeProd = null;

            if(ean128Model.Sscc != null) barcodeProd = ean128Model.Sscc;
            if(ean128Model.Gtin != null) barcodeProd = ean128Model.Gtin;
            if(ean128Model.Content != null) barcodeProd = ean128Model.Content;


            if(!UtilityString.isNullOrEmpty(barcodeProd)) {
                if (barcodeProd.startsWith("0") || barcodeProd.startsWith("9")) {
                    barcodeProd = barcodeProd.substring(1, barcodeProd.length());
                }
                this.loadArticolo(barcodeProd, ean128Model, progressDialog);
            } else {
                //EAN 128 non completo o comunque mancano i riferimenti al prodotto
                progressDialog.dismiss();
                BarcodeManager.enable();
            }
        }, ex-> {
            UtilityExceptions.defaultException(mActivity, ex, progressDialog);
            BarcodeManager.enable();
        });
    }

    private void executeEtichettaEanPeso(BarcodeScanDTO barcodeScanDTO, ProgressDialog progressDialog) {

        try {
            Ean13PesoModel ean13PesoModel = Ean13PesoModel.fromBarcode(barcodeScanDTO.getStringValue());

            this.loadArticolo(ean13PesoModel.getPrecode(), ean13PesoModel.toEan128(), progressDialog);
        } catch (Exception ex) {
            UtilityExceptions.defaultException(mActivity, ex, progressDialog);
            BarcodeManager.enable();
        }
    }



    private void loadArticolo(String barcodeProd, Ean128Model ean128Model, ProgressDialog progressDialog) {
        if(barcodeProd.length() == 14) {
//            barcodeProd = UtilityBarcode.convertITF14toNeutral(barcodeProd);
            barcodeProd = UtilityBarcode.convertITF14toEAN13(barcodeProd);
        }

        ArticoloRESTConsumer.getByBarcodeProd(barcodeProd, mtbAartList -> {

            if(mtbAartList != null && mtbAartList.size() > 0) {

                if(!thereIsAnOpenedUL()){

                    this.createNewUL(null, null, progressDialog, false, () -> {
                        BarcodeManager.enable();
                        this.searchArtInList(mtbAartList.get(0), ean128Model);
                    });

                } else {
                    this.searchArtInList(mtbAartList.get(0), ean128Model);

                    BarcodeManager.enable();
                    progressDialog.dismiss();
                }

            } else {
                BarcodeManager.enable();
                progressDialog.dismiss();

                DialogSimpleMessageHelper.makeWarningDialog(mActivity,
                        new SpannableString(mActivity.getResources().getText(R.string.no_result_from_barcode)),
                        null, null)
                        .show();
            }

        }, ex -> {
            BarcodeManager.enable();
            UtilityExceptions.defaultException(mActivity, ex, progressDialog);
        });
    }

    private void searchArtInList(MtbAart mtbAart, Ean128Model ean128Model) {
        removeListFilter();

        List<OrdineAccettazioneDTO.Riga> foundRowsList = Stream.of(groupedOrdini)
                .filter(x -> x.getMtbAart().getCodMart().equalsIgnoreCase(mtbAart.getCodMart()) &&
                        (x.isHidden() != null && !x.isHidden()) &&  (x.isTempHidden() != null && !x.isTempHidden()))
                .toList();

        if(foundRowsList.size() == 0) {
            showNoArtFoundDialog();
        } else if(foundRowsList.size() == 1) {
            onOrdineRowDispatch(foundRowsList.get(0), ean128Model);
        } else {
            for(int i = 0; i < groupedOrdini.size(); i++) {
                if(!foundRowsList.contains(groupedOrdini.get(i))) {
                    groupedOrdini.get(i).setTempHidden(true);
                }
            }

            applyFilter("COD: " + mtbAart.getCodMart());
            refreshOrderBy(false);
        }
    }


    private void showNoArtFoundDialog() {
        DialogSimpleMessageHelper.makeWarningDialog(mActivity,
                new SpannableString(mActivity.getResources().getText(R.string.no_result_from_barcode)),
                null, null).show();
    }

    public void showOrderDialog() {

        AlertDialog dialog = new AlertDialog.Builder(mActivity)
                .setTitle(mActivity.getText(R.string.action_orderBy))
                .setSingleChoiceItems(AccettazioneOrdineInevasoOrderBy.descriptions, currentOrderBy.getVal(), (dialog12, which) -> currentOrderBy = AccettazioneOrdineInevasoOrderBy.Enum.fromInt(which))
                .setPositiveButton("Ok", (dialog1, which) -> refreshOrderBy(false))
                .create();
        dialog.show();
    }


    public void createNewUL() {
        this.createNewUL(null, null, null, false, null);
    }

    public void createNewUL(Integer customNumCollo, String customSerCollo, ProgressDialog progress, boolean disablePrint, Runnable onComplete) {

        mActivity.bindings.accettazioneOrdineInevasoFab.close(true);

        if (progress == null){
            progress = UtilityProgress.createDefaultProgressDialog(mActivity);
        }

        ProgressDialog finalProgress = progress;
        NoteAggiuntiveNuovaULDialog.show(mActivity, new NoteAggiuntiveNuovaULDialog.Callback() {
            @Override
            public void onSuccess(String noteString) {

                //Add loading dialog here
                finalProgress.show();

                GestSetupRESTConsumer.getValue("PICKING", "SETUP", "DEFAULT_POSIZIONE_COLLI_ACCETTAZIONE", defaultPosAccettazioneDTO -> {

                    String defaultPosAccettazione = "";
                    if(defaultPosAccettazioneDTO != null && !UtilityString.isNullOrEmpty(defaultPosAccettazioneDTO.value)) defaultPosAccettazione = defaultPosAccettazioneDTO.value;

                    MtbColt mtbColt = new MtbColt();
                    mtbColt .setGestione(GestioneEnum.ACQUISTO)
                            .setPreparatoDa(SettingsManager.i().user.fullname)
                            .setAnnotazioni(noteString)
                            .setPosizione(defaultPosAccettazione)
                            .setOperation(CommonModelConsts.OPERATION.INSERT_OR_UPDATE);

                    if(customNumCollo != null) {
                        mtbColt.setNumCollo(customNumCollo);
                    }

                    if(!UtilityString.isNullOrEmpty(customSerCollo)) {
                        mtbColt.setSerCollo(customSerCollo);
                    }

                    List<String> codAnags =
                            stream(mOrders)
                                    .select(c -> c.codAnag)
                                    .distinct()
                                    .toList();

                    if(codAnags != null && codAnags.size() == 1){
                        mtbColt.setCodAnag(codAnags.get(0));
                    }

                    List<String> rifOrds =
                            stream(mOrders)
                                    .select(c -> c.rifOrd)
                                    .distinct()
                                    .toList();

                    if(rifOrds != null && rifOrds.size() == 1){
                        mtbColt.setRifOrd(rifOrds.get(0));
                    }

                    List<String> numDataOrds =
                            stream(mOrders)
                                    .select(value -> ("" + value.numero) + value.data)
                                    .distinct()
                                    .toList();

                    if(numDataOrds != null && numDataOrds.size() == 1){
                        mtbColt.setNumOrd(mOrders.get(0).numero);
                        mtbColt.setDataOrd(mOrders.get(0).data);

                        try {
                            mtbColt.generaFiltroOrdine();
                        } catch (Exception ex) {
                            DialogSimpleMessageHelper.makeErrorDialog(mActivity, new SpannableString(ex.getMessage()), null, null).show();
                            return;
                        }
                    }


                    ColliMagazzinoRESTConsumer.saveCollo(mtbColt, new ISimpleOperationCallback<MtbColt>() {
                        @Override
                        public void onSuccess(MtbColt value) {

                            value
                                    .setDisablePrint(disablePrint)
                                    .setMtbColr(new ObservableArrayList<>());

                            value.setMtbCols(null);

                            setULToCurrentContext(value);

                            finalProgress.dismiss();

                            new StatusBarAlert.Builder(mActivity)
                                    .autoHide(true)
                                    .withDuration(2500)
                                    .showProgress(false)
                                    .withText(R.string.data_saved)
                                    .withAlertColor(R.color.mainGreen)
                                    .build();

                            if(onComplete != null) onComplete.run();

                        }

                        @Override
                        public void onFailed(Exception ex) {
                            UtilityExceptions.defaultException(mActivity, ex, finalProgress);
                        }
                    });
                }, ex -> UtilityExceptions.defaultException(mActivity, ex, finalProgress));



            }

            @Override
            public void onAbort() {
                finalProgress.dismiss();
            }
        });


    }


    private void setULToCurrentContext(MtbColt mtbColt){
        isFabVisible.set(false);
        mArticoliInColloBottomSheetViewModel.mtbColt.set(mtbColt);
    }

    //Al click di "Mostra UL già create"
    public void showCreatedUL() {

        final ProgressDialog progress = ProgressDialog.show(mActivity, mActivity.getText(R.string.waiting),
                mActivity.getText(R.string.loading) + " ...", true);


        mActivity.bindings.accettazioneOrdineInevasoFab.close(false);

        try {
            OrdineAccettazioneInevasoRESTConsumerService.getBancaliGiaRegistrati(mOrders, mtbColts -> {

                progress.dismiss();

                mActivity.startListaBancaliRegistratiActivity((ArrayList<MtbColt>) mtbColts);

            }, ex -> UtilityExceptions.defaultException(mActivity, ex, progress));
        } catch (Exception ex) {
            UtilityExceptions.defaultException(mActivity, ex, progress);
        }

    }

    @Override
    public void onColloClosed() {
        if(thereIsAnOpenedUL()) {

            final ProgressDialog progress = UtilityProgress.createDefaultProgressDialog(mActivity);
            progress.show();

            if(thereIsAnyRowInUL()) {
                updateDataFine(progress, () -> printCollo(progress));
            } else {
                deleteCollo(progress);
            }

        }

    }

    private void updateDataFine(ProgressDialog progress, Runnable onComplete) {

        MtbColt cloneMtbColt = (MtbColt) mArticoliInColloBottomSheetViewModel.mtbColt.get().clone();
        cloneMtbColt.setOperation(CommonModelConsts.OPERATION.NO_OP);
        cloneMtbColt.setOraFinePrep(new Date());


        ColliMagazzinoRESTConsumer.saveCollo(cloneMtbColt, new ISimpleOperationCallback<MtbColt>() {
            @Override
            public void onSuccess(MtbColt value) {
                onComplete.run();
            }

            @Override
            public void onFailed(Exception ex) {
                UtilityExceptions.defaultException(mActivity, ex, progress);
            }
        });

    }

    private void printCollo(ProgressDialog progress) {
        MtbColt currentMtbColt = mArticoliInColloBottomSheetViewModel.mtbColt.get();

        if(currentMtbColt.getDisablePrint() != null && currentMtbColt.getDisablePrint()){
            postCloseOperations();
            progress.dismiss();
            return;
        }

        PrinterRESTConsumer.getAvailablePrinters(SettingsManager.i().userSession.depo.getCodMdep(), new ISimpleOperationCallback<List<String>>() {
            @Override
            public void onSuccess(List<String> value) {

                if(value.size() > 0) {
                    try{


                        ReportManager.getRightReportNameByMtbColt(currentMtbColt, reportName -> {

                            PrinterRESTConsumer.printCollo(
                                    value.get(0),
                                    currentMtbColt,
                                    1, reportName, () -> {

                                        postCloseOperations();
                                        progress.dismiss();

                                    }, ex -> {

                                        progress.dismiss();
                                        String errorMessage = ex.getMessage();
                                        DialogSimpleMessageHelper.makeErrorDialog(
                                                mActivity,
                                                new SpannableString(errorMessage),
                                                null,
                                                null,
                                                R.string.button_ignore_print,
                                                () -> postCloseOperations()).show();
                                    });

                            }, ex -> UtilityExceptions.defaultException(mActivity, ex, progress)
                        );
                    } catch (Exception ex){
                        UtilityExceptions.defaultException(mActivity, ex, progress);
                    }
                } else {

                    mArticoliInColloBottomSheetViewModel.mtbColt.set(null);
                    isFabVisible.set(true);

                    progress.dismiss();
                    String errorMessage = "Nessuna stampante configurata";
                    DialogSimpleMessageHelper.makeWarningDialog(mActivity, new SpannableString(errorMessage), null, null).show();
                }
            }

            @Override
            public void onFailed(Exception ex) {
                UtilityExceptions.defaultException(mActivity, ex, progress);
            }
        });
    }


    private void deleteCollo(ProgressDialog progress) {

        ColliMagazzinoRESTConsumer.deleteCollo(mArticoliInColloBottomSheetViewModel.mtbColt.get(), () -> {
            mArticoliInColloBottomSheetViewModel.mtbColt.set(null);

            isFabVisible.set(true);

            progress.dismiss();
        }, ex -> UtilityExceptions.defaultException(mActivity, ex, progress)
        );
    }


    public boolean thereIsAnOpenedUL() {
        return mArticoliInColloBottomSheetViewModel.mtbColt.get() != null;
    }
    public boolean thereIsAnyRowInUL() {
        return mArticoliInColloBottomSheetViewModel.mtbColt.get() != null &&
                mArticoliInColloBottomSheetViewModel.mtbColt.get().getMtbColr() != null &&
                mArticoliInColloBottomSheetViewModel.mtbColt.get().getMtbColr().size() > 0;
    }



    private void postCloseOperations() {

        MtbColt mtbColt = mArticoliInColloBottomSheetViewModel.mtbColt.get();

        mArticoliInColloBottomSheetViewModel.mtbColt.set(null);
        isFabVisible.set(true);

        if(mtbColt != null && mtbColt.getMtbColr() != null) {
            for (int i = 0; i < mtbColt.getMtbColr().size(); i++) {

                MtbColr currentRow = mtbColt.getMtbColr().get(i);

                Stream.of(this.groupedOrdini)
                        .filter(x ->
                                x.getQtaDaEvadere().floatValue() > 0 &&
                                x.getMtbAart().getCodMart().equalsIgnoreCase(currentRow.getCodMart()) &&
                                x.getCodJcom().equalsIgnoreCase(currentRow.getCodJcom()) &&
                                x.getRigaOrd() == currentRow.getRigaOrd() &&
                                x.getDataOrd().equals(currentRow.getDataOrdD()) &&
                                x.getNumOrd() == currentRow.getNumOrd()
                        )
                        .forEach(x -> x.setQtaRiservate(x.getQtaRiservate().add(currentRow.getQtaCol())));

            }
        }

        removeListFilter();
        refreshOrderBy(true);

    }

    @Override
    public void onOrdineRowDispatch(final OrdineAccettazioneDTO.Riga item, Ean128Model ean128Model) {
        if(mArticoliInColloBottomSheetViewModel.mtbColt.get() != null){

            List<MtbColr> currentMtbColrs = mArticoliInColloBottomSheetViewModel.mtbColt.get().getMtbColr();

            List<MtbColr> filteredMtbColrs = Stream.of(currentMtbColrs).filter(
                    x -> x.getCodMart().equalsIgnoreCase(item.mtbAart.getCodMart()) &&
                            x.getNumOrd() == item.numOrd &&
                            (x.getCodJcom() != null && x.getCodJcom().equalsIgnoreCase(item.codJcom)) &&
                            x.getRigaOrd() == item.rigaOrd).toList();

            float qtaEvasaInMtbColr = 0;
            for (MtbColr mtbColr : filteredMtbColrs) {
                qtaEvasaInMtbColr += mtbColr.getQtaCol().floatValue();
            }

            float qtaEvasa = item.qtaRiservate + qtaEvasaInMtbColr;

            BigDecimal qtaDaEvadere = item.getQtaOrd().subtract(new BigDecimal(qtaEvasa)).subtract(item.getQtaEvasa());

            DialogInputQuantity.DTO dto = new DialogInputQuantity.DTO()
                    .setBatchLot(item.getPartitaMag())
                    .setCodArtFor(item.getCodArtFor())
                    .setMtbAart(item.getMtbAart())
                    .setQtaOrd(item.getQtaOrd())
                    .setQtaDaEvadere(qtaDaEvadere)
                    .setQtaEvasa(new BigDecimal(qtaEvasa))
                    .setCanPartitaMagBeChanged(true);

            if(ean128Model != null){
                if(!UtilityString.isNullOrEmpty(ean128Model.BatchLot)) {
                    dto.setBatchLot(ean128Model.BatchLot);
                }

                try {
                    if(!UtilityString.isNullOrEmpty(ean128Model.BestBefore)){
                        dto.setDataScad(UtilityDate.recognizeDate(ean128Model.BestBefore));
                    } else if(!UtilityString.isNullOrEmpty(ean128Model.Expiry)) {
                        dto.setDataScad(UtilityDate.recognizeDate(ean128Model.Expiry));
                    }

                } catch (Exception e) {
                    UtilityLogger.errorMe(e);
                }


                if(ean128Model.Count != null && ean128Model.Count > 0) {
                    //if(!UtilityString.isNullOrEmpty(ean128Model.Sscc)) {
                        dto.setNumCnf(ean128Model.Count);
                    //} else {
                    //    dto.setQtaTot(new BigDecimal(ean128Model.Count));
                    //}
                }

                if (ean128Model.NetWeightKg != null && ean128Model.NetWeightKg > 0) {
                    dto.setQtaTot(new BigDecimal(ean128Model.NetWeightKg));
                }

                if(dto.getQtaTot() != null && dto.getQtaTot().floatValue() > 0 && dto.getNumCnf() != null && dto.getNumCnf() > 0) {
                    dto.setQtaCnf(dto.getQtaTot().divide(new BigDecimal(dto.getNumCnf())));
                }

                dto.setCanPartitaMagBeChanged(false);
                dto.setCanDataScadBeChanged(false);
                dto.setShouldAskDataScad(true);
            }

            DialogInputQuantity.makeBase(mActivity, dto, true,  value -> onOrdineRowDispatched(item, value)).show();
        }
    }

    private void onOrdineRowDispatched(OrdineAccettazioneDTO.Riga item, QuantityDTO quantityDTO){

        final ProgressDialog progress = ProgressDialog.show(mActivity, mActivity.getText(R.string.waiting),
                mActivity.getText(R.string.loading) + " ...", true);

        final MtbColr mtbColr = new MtbColr()
                .setCodMart(item.mtbAart.getCodMart())
                .setPartitaMag(quantityDTO.batchLot.get())
                .setDataScadPartita(quantityDTO.expireDate)
                .setQtaCol(new BigDecimal(quantityDTO.qtaTot.get()))
                .setDescrizione(item.descrizioneEstesa)
                .setNumOrd(item.numOrd)
                .setDataOrd(item.getDataOrd())
                .setCodJcom(item.codJcom)
                .setRigaOrd(item.rigaOrd);

        mtbColr.setOperation(CommonModelConsts.OPERATION.INSERT_OR_UPDATE);

        MtbColt cloneMtbColt = (MtbColt) mArticoliInColloBottomSheetViewModel.mtbColt.get().clone();
        cloneMtbColt.setOperation(CommonModelConsts.OPERATION.NO_OP);

        cloneMtbColt.setMtbColr(new ObservableArrayList());
        cloneMtbColt.getMtbColr().add(mtbColr);

        ColliMagazzinoRESTConsumer.saveCollo(cloneMtbColt, new ISimpleOperationCallback<MtbColt>() {
            @Override
            public void onSuccess(MtbColt value) {

                mtbColr
                        .setDataCollo(value.getDataColloS())
                        .setNumCollo(value.getNumCollo())
                        .setGestione(value.getGestione())
                        .setSerCollo(value.getSerCollo())
                        .setRiga(value.getMtbColr().get(0).getRiga())
                        .setUntMis(item.getMtbAart().getUntMis())
                        .setMtbAart(item.getMtbAart());

                //item.setQtaRiservate(item.getQtaRiservate().add(mtbColr.getQtaCol()));

                mArticoliInColloBottomSheetViewModel.mtbColt.get().getMtbColr().add(mtbColr);
                refreshOrderBy(false);

                new StatusBarAlert.Builder(mActivity)
                        .autoHide(true)
                        .withDuration(2500)
                        .showProgress(false)
                        .withText(R.string.data_saved)
                        .withAlertColor(R.color.mainGreen)
                        .build();

                progress.dismiss();
            }

            @Override
            public void onFailed(Exception ex) {
                UtilityExceptions.defaultException(mActivity, ex, progress);
            }
        });
    }
}
