package it.studiors.dashboard.client.fatturazione;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;

import com.google.gwt.core.client.GWT;
import com.google.gwt.http.client.URL;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.smartgwt.client.data.DataSourceField;
import com.smartgwt.client.data.Record;
import com.smartgwt.client.data.RecordList;
import com.smartgwt.client.data.ResultSet;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.types.AnimationEffect;
import com.smartgwt.client.types.DateDisplayFormat;
import com.smartgwt.client.types.FieldType;
import com.smartgwt.client.types.SelectionAppearance;
import com.smartgwt.client.types.SelectionStyle;
import com.smartgwt.client.types.TitleOrientation;
import com.smartgwt.client.util.BooleanCallback;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.Button;
import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.Dialog;
import com.smartgwt.client.widgets.IButton;
import com.smartgwt.client.widgets.IconButton;
import com.smartgwt.client.widgets.ImgButton;
import com.smartgwt.client.widgets.Window;
import com.smartgwt.client.widgets.events.ButtonClickEvent;
import com.smartgwt.client.widgets.events.ButtonClickHandler;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.events.CloseClickEvent;
import com.smartgwt.client.widgets.events.CloseClickHandler;
import com.smartgwt.client.widgets.events.RightMouseDownEvent;
import com.smartgwt.client.widgets.events.RightMouseDownHandler;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.CheckboxItem;
import com.smartgwt.client.widgets.form.fields.DateItem;
import com.smartgwt.client.widgets.form.fields.SelectItem;
import com.smartgwt.client.widgets.form.fields.TextItem;
import com.smartgwt.client.widgets.form.fields.events.ChangeEvent;
import com.smartgwt.client.widgets.form.fields.events.ChangeHandler;
import com.smartgwt.client.widgets.form.fields.events.ChangedEvent;
import com.smartgwt.client.widgets.form.fields.events.ChangedHandler;
import com.smartgwt.client.widgets.form.fields.events.FocusEvent;
import com.smartgwt.client.widgets.form.fields.events.FocusHandler;
import com.smartgwt.client.widgets.grid.CellFormatter;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.grid.SummaryFunction;
import com.smartgwt.client.widgets.grid.events.DataArrivedEvent;
import com.smartgwt.client.widgets.grid.events.DataArrivedHandler;
import com.smartgwt.client.widgets.layout.HLayout;
import com.smartgwt.client.widgets.layout.VLayout;
import com.smartgwt.client.widgets.menu.IconMenuButton;
import com.smartgwt.client.widgets.menu.Menu;
import com.smartgwt.client.widgets.menu.MenuItem;
import com.smartgwt.client.widgets.menu.events.MenuItemClickEvent;
import com.smartgwt.client.widgets.toolbar.RibbonBar;
import com.smartgwt.client.widgets.toolbar.RibbonGroup;

import it.studiors.dashboard.client.StatManager;
import it.studiors.dashboard.client.db.SqlDSD;
import it.studiors.dashboard.client.gui.ComboGruppi;
import it.studiors.dashboard.client.gui.ComboMagazzini;
import it.studiors.dashboard.client.gui.ComboNegozi;
import it.studiors.dashboard.client.gui.ComboTipologiaDocumentiAcquisto;
import it.studiors.dashboard.client.gui.ListGridSelection;
import it.studiors.dashboard.client.gui.RicercaTipologiaDocumento;
import it.studiors.dashboard.client.gui.comboCliFor;
import it.studiors.dashboard.client.gui.agenda.AgendaEdit;
import it.studiors.dashboard.client.security.SecurityManagerRS;
import it.studiors.dashboard.client.utility.DateUtility;
import it.studiors.dashboard.client.widget.RsWidget;
import it.studiors.dashboard.client.widget.WaitingWindowClose;
import it.studiors.dashboard.shared.FinishEvent;
import it.studiors.dashboard.shared.FinishHandler;
import it.studiors.dashboard.shared.WaitingDialogRPCCall;
import it.studiors.dashboard.shared.security.AutorityConstShared;
import it.studiors.dashboard.shared.utility.CommonFunction;
import it.studiors.dashboard.shared.utility.JscriptUtility;
import it.studiors.dashboard.shared.utility.StringUtil;
import it.studiors.interfacciaXML.entity.Documento;
import it.studiors.interfacciaXML.entity.InfoTestata;
import it.studiors.interfacciaXML.entity.backoffice.TauPosAgendaInterface;
import it.studiors.interfacciaXML.entity.fatturazione.Fatt;
import it.studiors.interfacciaXML.gwtJNI.GlobalConstGwt;
import it.studiors.interfacciaXML.worker.ConstClientiFornitori;
import it.studiors.interfacciaXML.worker.ConstExportInvioDocumenti;
import it.studiors.interfacciaXML.worker.ConstFatturazione;

public class TestTab extends Window
{

    public static final String TAB_ID = "DocumentiAcquisto";

    private ComboGruppi comboGruppi = null;

    private ComboNegozi combopdv = null;

    private comboCliFor comboForn = null;

    private ComboTipologiaDocumentiAcquisto comboTipoDocumento = null;

    private DateItem dataInizio = null;

    private DateItem dataFine = null;

    private DateItem dataDocForn = null;

    private TextItem numDocFornRicerca = null;

    private DateTimeFormat dateFormatter2 = DateTimeFormat.getFormat("dd/MM/yyyy");

    private IconButton buttonSearch = null;

    private IconButton buttonNuovo = null;


    private TestTab instance = null;


    private CheckboxItem checkBoxDataDocForn = null;

    private SelectItem comboFatturazione = null;

    private SelectItem comboLista = null;

    private ComboMagazzini comboMagazzini = null;

    private boolean skipCheckGrpClienteFornitore = false;

    private CheckboxItem checkBoxDocNonConsolidati = null;

    private CheckboxItem checkBoxDocNonControllati = null;

    private boolean isDocumentoDiRifatturazione = false;

    public TestTab()
    {
        instance = this;

        setTitle("Test");
        setShowMinimizeButton(false);
        setShowMaximizeButton(false);
        setShowCloseButton(false);
        setShowFooter(true);

        VLayout vl = new VLayout();
        vl.addMember(getRibbonBar());
        addItem(vl);

        show();
    }

    private RibbonBar getRibbonBar()
    {
        RibbonBar bar = new RibbonBar();
        bar.setWidth100();
        bar.addGroup(getGroupFilter());
        bar.addGroup(getGroupPeriodo());
        bar.addGroup(getGroupButtons());

        return bar;
    }

  

    private RibbonGroup getGroupFilter()
    {
        RibbonGroup grp = new RibbonGroup();
        grp.setTitle("Filtri");
        grp.setTitleAlign(Alignment.LEFT);
        grp.setRowHeight(26);
        grp.setNumRows(3);

        DynamicForm dyn = new DynamicForm();
        combopdv = new ComboNegozi("Pdv", "", RsWidget.codPdv, RsWidget.codiceGruppo, 190);

        comboTipoDocumento = new ComboTipologiaDocumentiAcquisto("Documento", 190);
        comboTipoDocumento.setDefaultToFirstOption(true);
        comboTipoDocumento.addFocusHandler(new FocusHandler()
        {
            @Override
            public void onFocus(FocusEvent event)
            {
                //RsWidget.logClient.info(getClass(), "getSelectDocumentiAcquisto - comboTipoDocumento  addFocusHandler");
                checkBoxDocNonControllati.hide();
            }
        });

        comboTipoDocumento.addChangedHandler(new ChangedHandler()
        {
            @Override
            public void onChanged(ChangedEvent event)
            {
                //RsWidget.logClient.info(getClass(), "getSelectDocumentiAcquisto - comboTipoDocumento  onChanged");
                if (comboTipoDocumento.getValueAsString().equals(ConstFatturazione.CARICOACQUISTO)
                        || comboTipoDocumento.getValueAsString().equals(ConstFatturazione.FATTURA_ACQUISTO))
                {
                    if (comboTipoDocumento.getValueAsString().equals(ConstFatturazione.FATTURA_ACQUISTO))
                    {
                        checkBoxDocNonControllati.show();
                    }
                    else
                    {
                        checkBoxDocNonControllati.hide();
                    }

                    comboFatturazione.hide();

                    if (comboTipoDocumento.getValueAsString().equals(ConstFatturazione.CARICOACQUISTO))
                        comboFatturazione.show();

                    comboLista.show();
                }
                else
                {
                    comboFatturazione.hide();
                    comboLista.hide();
                    checkBoxDocNonControllati.hide();
                }
            }
        });

        comboGruppi = new ComboGruppi("Gruppo", 190);
        comboGruppi.addChangedHandler(new ChangedHandler()
        {

            public void onChanged(ChangedEvent event)
            {
                String gruppo = "";

                if (event.getValue() != null && !event.getValue().toString().equals(""))
                {
                    gruppo = event.getValue().toString();
                }

                combopdv.refreshComboPdv(gruppo);
            }
        });

        comboGruppi.addChangeHandler(new ChangeHandler()
        {

            @Override
            public void onChange(ChangeEvent event)
            {
                if (comboGruppi.getValueAsString() == null || comboGruppi.getValueAsString().equals(""))
                    combopdv.refreshComboPdv("");
            }
        });

        comboLista = new SelectItem();
        comboLista.setTitle("Tipo Vista");
        comboLista.setWidth(150);
        comboLista.setDefaultToFirstOption(true);
        LinkedHashMap maptipo = new LinkedHashMap();
        maptipo.put(GlobalConstGwt.KEY_TIPO_VISTA_DOCUMENTI_ACQUISTO_LISTA_DOCUMENTI,
                GlobalConstGwt.KEY_TIPO_VISTA_DOCUMENTI_ACQUISTO_LISTA_DOCUMENTI);
        maptipo.put(GlobalConstGwt.KEY_TIPO_VISTA_DOCUMENTI_ACQUISTO_RIEPILOGO_PER_FORNITORE,
                GlobalConstGwt.KEY_TIPO_VISTA_DOCUMENTI_ACQUISTO_RIEPILOGO_PER_FORNITORE);
        comboLista.setValueMap(maptipo);
        comboLista.setValue(GlobalConstGwt.KEY_TIPO_VISTA_DOCUMENTI_ACQUISTO_LISTA_DOCUMENTI);

        dyn.setFields(comboGruppi, combopdv, comboLista, comboTipoDocumento);

        DynamicForm dynForn = new DynamicForm();

        comboForn = new comboCliFor("Forn", 210, "F",
                (GlobalConstGwt.TIPOLOGIA_FORNITORI.equals(ConstClientiFornitori.TIPOLOGIA_FORNITORI_DI_CENTRALE)
                        || GlobalConstGwt.TIPOLOGIA_FORNITORI
                                .equals(ConstClientiFornitori.TIPOLOGIA_FORNITORI_DI_GRUPPO)) ? "0" : null,
                true);

        dataDocForn = new DateItem();
        dataDocForn.setWidth(100);
        dataDocForn.setUseTextField(true);
        dataDocForn.setTitle("Del");
        dataDocForn.setDisplayFormat(DateDisplayFormat.TOEUROPEANSHORTDATE);
        dataDocForn.setValue("");

        numDocFornRicerca = new TextItem();
        numDocFornRicerca.setShowTitle(true);
        numDocFornRicerca.setTitle("Doc.");
        numDocFornRicerca.setTooltip("Valore di ricerca");
        numDocFornRicerca.setValue("");
        numDocFornRicerca.setWidth(80);

        DynamicForm dynFornMagaz = new DynamicForm();
        dynFornMagaz.setNumCols(4);
        comboMagazzini = new ComboMagazzini("Mag", 100);

        comboFatturazione = new SelectItem();
        comboFatturazione.setTitle("Fat");
        comboFatturazione.setWidth(100);
        LinkedHashMap map = new LinkedHashMap();
        map.put(GlobalConstGwt.FILTRO_DOCUMENTI_ACQUISTO_TUTTI, GlobalConstGwt.FILTRO_DOCUMENTI_ACQUISTO_TUTTI);
        map.put(GlobalConstGwt.FILTRO_DOCUMENTI_ACQUISTO_FATTURATI, GlobalConstGwt.FILTRO_DOCUMENTI_ACQUISTO_FATTURATI);
        map.put(GlobalConstGwt.FILTRO_DOCUMENTI_ACQUISTO_NON_FATTURATI,
                GlobalConstGwt.FILTRO_DOCUMENTI_ACQUISTO_NON_FATTURATI);
        comboFatturazione.setValueMap(map);
        comboFatturazione.setValue(GlobalConstGwt.FILTRO_DOCUMENTI_ACQUISTO_TUTTI);
        dynFornMagaz.setFields(comboMagazzini, comboFatturazione);

        DynamicForm dynFornOriz = new DynamicForm();
        dynFornOriz.setNumCols(4);

        dynFornOriz.setFields(numDocFornRicerca, dataDocForn);

        dynForn.setFields(comboForn);

        checkBoxDocNonConsolidati = new CheckboxItem();
        checkBoxDocNonConsolidati.setTitle("Documenti non consolidati");

        checkBoxDocNonControllati = new CheckboxItem();
        checkBoxDocNonControllati.setTitle("Documenti non controllati");
        checkBoxDocNonControllati.hide();

        DynamicForm dynNonConsolidatoControllato = new DynamicForm();
        dynNonConsolidatoControllato.setNumCols(4);
        dynNonConsolidatoControllato.setFields(checkBoxDocNonConsolidati, checkBoxDocNonControllati);

        VLayout vl = new VLayout();
        vl.addMembers(dynForn, dynFornOriz, dynFornMagaz, dynNonConsolidatoControllato);

        grp.addControl(dyn);
        grp.addControl(vl);

        return grp;
    }

    private RibbonGroup getGroupPeriodo()
    {
        RibbonGroup grp = new RibbonGroup();
        grp.setTitle("Periodo");
        grp.setTitleAlign(Alignment.LEFT);
        grp.setRowHeight(26);
        grp.setNumRows(4);

        Date today = new Date();

        Date firstDayYearCurrent = new Date();

        // setto inizio con 10 giorni precedenti a oggi
        firstDayYearCurrent.setDate(today.getDate() - 1);

        dataInizio = new DateItem();
        dataInizio.setWidth(100);
        dataInizio.setUseTextField(true);
        dataInizio.setTitle("Dal");
        dataInizio.setDisplayFormat(DateDisplayFormat.TOEUROPEANSHORTDATE);
        dataInizio.setValue(dateFormatter2.format(firstDayYearCurrent));

        dataFine = new DateItem();
        dataFine.setWidth(100);
        dataFine.setUseTextField(true);
        dataFine.setTitle("Al.");
        dataFine.setDisplayFormat(DateDisplayFormat.TOEUROPEANSHORTDATE);
        dataFine.setValue(dateFormatter2.format(today));

        checkBoxDataDocForn = new CheckboxItem();
        checkBoxDataDocForn.setTitle("Data Doc.Forn.");
        checkBoxDataDocForn.setWidth(80);
        checkBoxDataDocForn.setTitleOrientation(TitleOrientation.LEFT);

        DynamicForm dtf = new DynamicForm();
        dtf.setNumCols(2);
        dtf.setFields(dataInizio, dataFine, checkBoxDataDocForn);
        grp.addControl(dtf);

        return grp;
    }

    private RibbonGroup getGroupButtons()
    {
        RibbonGroup grp = new RibbonGroup();
        grp.setTitle("Men&ugrave");
        grp.setTitleAlign(Alignment.LEFT);
        grp.setRowHeight(26);
        grp.setNumRows(4);

        buttonSearch = new IconButton("Cerca");
        buttonSearch.setIcon("[app]dashboardadministration/img/search.png");
        buttonSearch.addClickHandler(new ClickHandler()
        {

            public void onClick(ClickEvent event)
            {
                SC.say("Elabora");
            }
        });

        buttonNuovo = new IconButton("Nuovo");
        buttonNuovo.setIcon("[APP]dashboardadministration/img/plus.png");
        buttonNuovo.addClickHandler(new ClickHandler()
        {

            public void onClick(ClickEvent event)
            {
                if (combopdv.getValue() != null)
                {
                    if (!combopdv.getValueAsString().equals(""))
                    {
                        final String pdv = combopdv.getValueAsString();

                        StatManager.getRpc().SvuotaTmp(RsWidget.utente, comboTipoDocumento.getValueAsString(),
                                new AsyncCallback<Boolean>()
                        {
                            @Override
                            public void onSuccess(Boolean esito)
                            {
                                if (esito)
                                {
                                    FattureEdit pdve = new FattureEdit("", "", pdv, "", "",
                                            comboTipoDocumento.getValueAsString(), false);
                                    pdve.setParenteobj(instance);
                                    pdve.animateShow(AnimationEffect.FADE, null, 50);
                                }
                                else
                                {
                                    RsWidget.logClient.error(CarichiAcquistoManager.class,
                                            "executeListUpdate - errore delete: ");
                                }
                            }

                            @Override
                            public void onFailure(Throwable arg0)
                            {
                                RsWidget.logClient.error(CarichiAcquistoManager.class,
                                        "executeListUpdate - errore delete: ", arg0);
                            }
                        });
                    }
                }
                else
                {
                    SC.say("Inserisci il punto vendita!");
                }
            }
        });

        if (!SecurityManagerRS.isAllowedForRunMe(AutorityConstShared.TAG_NUOVO_DOC_ACQUISTO.getTagOperazione()))
        {
            buttonNuovo.setDisabled(true);
        }

        final Menu menuStampa = new Menu();

        MenuItem itemOrdinaNumDoc = new MenuItem("Ordinato per numero documento",
                "[APP]dashboardadministration/img/print.png");
        itemOrdinaNumDoc.addClickHandler(new com.smartgwt.client.widgets.menu.events.ClickHandler()
        {
            public void onClick(MenuItemClickEvent event)
            {
                SC.say("TES_TESTATA");
            }
        });

        menuStampa.addItem(itemOrdinaNumDoc);
        MenuItem itemOrdinaDescForn = new MenuItem("Ordinato per descrizione fornitore",
                "[APP]dashboardadministration/img/print.png");
        itemOrdinaDescForn.addClickHandler(new com.smartgwt.client.widgets.menu.events.ClickHandler()
        {
            public void onClick(MenuItemClickEvent event)
            {
                SC.say("ORDER BY TES_DESCRIZIONE");
            }
        });
        menuStampa.addItem(itemOrdinaDescForn);

        final IconMenuButton stampaDocumento = new IconMenuButton("Stampa Lista");
        stampaDocumento.setShowMenuIcon(true);
        stampaDocumento.setTooltip("Stampa Lista");
        stampaDocumento.setMenu(menuStampa);
        stampaDocumento.addClickHandler(new ClickHandler()
        {
            @Override
            public void onClick(ClickEvent event)
            {
                stampaDocumento.showMenu();
            }
        });
        stampaDocumento.setTitle("Stampa");
        stampaDocumento.setIcon("[APP]dashboardadministration/img/print.png");

        grp.addControls(buttonSearch, stampaDocumento, buttonNuovo);

        return grp;
    }

    public boolean isSkipCheckGrpClienteFornitore()
    {
        return skipCheckGrpClienteFornitore;
    }

    public void setSkipCheckGrpClienteFornitore(boolean skipCheckGrpClienteFornitore)
    {
        this.skipCheckGrpClienteFornitore = skipCheckGrpClienteFornitore;
    }

    public boolean isDocumentoDiRifatturazione()
    {
        return isDocumentoDiRifatturazione;
    }

    public void setDocumentoDiRifatturazione(boolean isDocumentoDiRifatturazione)
    {
        this.isDocumentoDiRifatturazione = isDocumentoDiRifatturazione;
    }
    
}
