package view.facture;

import controller.facture.Facture_Controller;
import controller.facture.Facture_Pdf_Controller;
import controller.history.Application_Controller;
import net.miginfocom.swing.MigLayout;
import org.sig.fw.db.corrida.dao.*;
import org.sig.fw.db.corrida.model.Facture;
import org.sig.fw.db.corrida.model.Facture_Content;
import org.sig.fw.db.corrida.model.Rfp;
import org.sig.fw.layout.component.SButton;
import org.sig.fw.layout.component.SLabel;
import org.sig.fw.layout.contener.SInternalFrame;
import org.sig.fw.layout.pane.SOptionPane;
import org.sig.fw.layout.pane.SPanel;
import org.sig.fw.layout.pane.SScrollPane;
import org.sig.fw.sig.model.Account;
import org.sig.fw.utility.date.SDate;
import org.sig.fw.utility.number.NumberTools;

import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

public class Facture_View extends SInternalFrame 
{
	private static final long serialVersionUID = -1612116510397436656L;
	
	private Facture_Controller ctrl_facture;
	private SLabel jl_dossier_number;
	private SLabel jl_tranche_number;
	private SLabel jl_responsible;
	private SLabel jl_commande_number;
	private SLabel jl_head;
	private SLabel jl_dossier_name;
	private SPanel jp_facture_content;
	private SLabel jl_observation;
	private SLabel jl_factured_date;
	private SLabel jl_product_date;

	private SLabel jl_category;
	private SLabel jl_payment_mode;
	private SLabel jl_caution;
	private SLabel jl_client1;
	private SLabel jl_client1_percent;
	private SLabel jl_client1_amount;
	private SLabel jl_client2;
	private SLabel jl_client2_percent;
	private SLabel jl_client2_amount;
	private SLabel jl_client2_is_payment_direct;
	private SLabel jl_client1_is_payment_direct;
	private SLabel jl_total_ht;
	private SLabel jl_total_tva;
	private SLabel jl_total_net;
	private SButton jb_client2;
	private SButton jb_client1;
	private SButton jb_delete;
	public Facture_View(Facture_Controller ctrl_facture) 
	{
		super("Facture - " + ctrl_facture.getModel().getCommande().getSociety().getName());
		jp_main_content.setBorder(new TitledBorder(null, "", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		setBounds(100, 100, 1370, 710);
		this.ctrl_facture = ctrl_facture;
		jp_main_content.setLayout(new MigLayout("gap 0px 0px, insets 1px 1px", "[][][grow][grow][][60px:60px:60px]", "[][][][grow][]"));
		
		SButton btnNewButton = new SButton("", "Exporter le PDF");
		btnNewButton.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e) 
			{
				List<Facture_Content> lists = new ArrayList<Facture_Content>();
				for(int i = 1; i < jp_facture_content.getComponentCount(); i++)
				{
					if(jp_facture_content.getComponent(i) instanceof Facture_Content_View)
					{
						lists.add(((Facture_Content_View) jp_facture_content.getComponent(i)).getModel());
					}
				}
				new Facture_Pdf_Controller(ctrl_facture.getModel(), lists);
			}
		});
		btnNewButton.setIcon(new ImageIcon(Facture_View.class.getResource("/icons/pdf.png")));
		jp_main_content.add(btnNewButton, "cell 0 0");
		
		SButton button_3 = new SButton("", "Modifier la Facture");
		button_3.addActionListener(new ActionListener() 
		{
			public void actionPerformed(ActionEvent e) 
			{
				if(((Facture) new Facture_DBAO("fact").getWithId(ctrl_facture.getModel().getDbId(),true)).getState().getDbId() != State_DBAO.SOLDE)
				{
					if(new Payment_DBAO("pay").getWithFacture(ctrl_facture.getModel()).size() == 0)
					{
						Account account = new Facture_DBAO("fact").getLock(ctrl_facture.getModel());
						if(account == null || account.equals(ctrl_facture.getApplicationController().getConnectedAccount()))
						{
							if(ctrl_facture.getApplicationController().openView(Application_Controller.ADD_FACTURE_VIEW, ctrl_facture.getModel(), null))
							{
								dispose();
							}
						}
						else
						{
							SOptionPane.showErrorMessage("Ouverture du formulaire de Facture", "La Facture est vérouillée par " + account.getCompleteName());
						}
					}
					else
					{
						SOptionPane.showErrorMessage("Ouverture du formulaire de Facture", "La Facture n'est pas modifiable puisqu'elle possède des paiements");
					}
				}
				else
				{
					SOptionPane.showErrorMessage("Ouverture du formulaire de Facture", "La Facture n'est pas modifiable puisque SOLDE");
				}
			}
		});
		
		jl_head = new SLabel("", SLabel.TYPE_TITLE_BOLD);
		jp_main_content.add(jl_head, "cell 1 0 3 1,alignx center");
		
		jb_delete = new SButton("", "Modifier la Facture");
		jb_delete.addActionListener(new ActionListener() 
		{
			public void actionPerformed(ActionEvent e)
			{
				ctrl_facture.computeCanDelete();
				if(jb_delete.isEnabled())
				{
					int reply = SOptionPane.showYesNoCancelWarning("Suppression", "Voulez-vous vraiment supprimer cette facture ?");
					if(reply == SOptionPane.YES_OPTION)
						ctrl_facture.delete();
				}
				else
				{
					SOptionPane.showErrorMessage("Suppression", "<html>Impossible de supprimer la facture.<br>Soit la commande possède plusieur factures.<br>Soit la facture possède des paiements.<br>Soit la facture est bloqué par un autre utilisateur.</html>");
				}
			}
		});
		jb_delete.setIcon(new ImageIcon(Facture_View.class.getResource("/icons/remove.png")));
		jp_main_content.add(jb_delete, "cell 4 0");
		button_3.setIcon(new ImageIcon(Facture_View.class.getResource("/icons/modify.png")));
		jp_main_content.add(button_3, "cell 5 0,alignx right");
		
		SPanel panel = new SPanel();
		panel.setBorder(new TitledBorder(null, "Donn\u00E9es BDDC", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		jp_main_content.add(panel, "cell 0 1 2 1,grow");
		panel.setLayout(new MigLayout("gap 5px 0px, insets 1px 1px", "[][][]", "[][][][]"));
		
		SLabel lblNewLabel = new SLabel("N\u00B0 Dossier", SLabel.TYPE_COMMUN);
		panel.add(lblNewLabel, "cell 0 0");
		
		jl_dossier_number = new SLabel("", SLabel.TYPE_COMMUN);
		panel.add(jl_dossier_number, "cell 1 0");
		
		SButton button = new SButton("", "Ouvrir BDDC");
		button.setIcon(new ImageIcon(Facture_View.class.getResource("/org/sig/fw/bddclink/icon/sondefor_little.png")));
		panel.add(button, "cell 2 0,growx");
		
		SLabel label2 = new SLabel("Tranche", SLabel.TYPE_COMMUN);
		panel.add(label2, "cell 0 1");
		
		jl_tranche_number = new SLabel("", SLabel.TYPE_COMMUN);
		panel.add(jl_tranche_number, "cell 1 1");
		
		SButton button_1 = new SButton("", "Ouvrir BDDC");
		button_1.setIcon(new ImageIcon(Facture_View.class.getResource("/org/sig/fw/bddclink/icon/sondefor_little.png")));
		panel.add(button_1, "cell 2 1,growx");
		
		SLabel label_1 = new SLabel("Responsable", SLabel.TYPE_COMMUN);
		panel.add(label_1, "cell 0 2");
		
		jl_responsible = new SLabel("", SLabel.TYPE_COMMUN);
		panel.add(jl_responsible, "cell 1 2 2 1");
		
		SLabel label_2 = new SLabel("N\u00B0 Commande", SLabel.TYPE_COMMUN);
		panel.add(label_2, "cell 0 3");
		
		jl_commande_number = new SLabel("", SLabel.TYPE_COMMUN);
		panel.add(jl_commande_number, "cell 1 3");
		
		SButton button_2 = new SButton("", "Ouvrir la Commande");
		button_2.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e) 
			{
				ctrl_facture.getApplicationController().openView(Application_Controller.COMMANDE_VIEW, ctrl_facture.getModel().getCommande(), null);
			}
		});
		button_2.setIcon(new ImageIcon(Facture_View.class.getResource("/icons/logo_corrida_20x20.png")));
		panel.add(button_2, "cell 2 3");
		
		SPanel panel_1 = new SPanel();
		panel_1.setBorder(new TitledBorder(null, "Donn\u00E9es de la Facture", TitledBorder.LEADING, TitledBorder.TOP, null, Color.BLACK));
		jp_main_content.add(panel_1, "cell 2 1,grow");
		panel_1.setLayout(new MigLayout("gap 5px 5px, insets 1px 1px", "[][grow]", "[][][][][][]"));
		
		SLabel lblNewLabel_1 = new SLabel("Observation", SLabel.TYPE_COMMUN);
		panel_1.add(lblNewLabel_1, "cell 0 0");
		
		jl_observation = new SLabel("New label", SLabel.TYPE_COMMUN);
		panel_1.add(jl_observation, "cell 1 0,alignx right,aligny top");
		
		SLabel label = new SLabel("Date de Facturation", 0);
		panel_1.add(label, "cell 0 1");
		
		jl_factured_date = new SLabel("", 0);
		panel_1.add(jl_factured_date, "cell 1 1");
		
		SLabel label_6 = new SLabel("Date de Production", 0);
		panel_1.add(label_6, "cell 0 2,alignx left");
		
		jl_product_date = new SLabel("", 0);
		jl_product_date.setText("");
		panel_1.add(jl_product_date, "cell 1 2");
		
		SLabel label_3 = new SLabel("Cat\u00E9gorie", 0);
		panel_1.add(label_3, "cell 0 3");
		
		jl_category = new SLabel("", 0);
		panel_1.add(jl_category, "cell 1 3");
		
		SLabel label_4 = new SLabel("Mode de Paiement", 0);
		panel_1.add(label_4, "cell 0 4");
		
		jl_payment_mode = new SLabel("", 0);
		panel_1.add(jl_payment_mode, "cell 1 4");
		
		jl_caution = new SLabel("", 0);
		panel_1.add(jl_caution, "cell 0 5 2 1");
		
		SPanel panel_4 = new SPanel();
		panel_4.setBorder(new TitledBorder(null, "Clients", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		jp_main_content.add(panel_4, "cell 3 1 3 1,grow");
		panel_4.setLayout(new MigLayout("gap 5px 5px, insets 1px 1px", "[][grow][grow][grow][grow]", "[grow][grow]"));
		
		jb_client1 = new SButton("", "Ouvrir la vue Client");
		jb_client1.setIcon(new ImageIcon(Facture_View.class.getResource("/icons/logo_corrida_20x20.png")));
		panel_4.add(jb_client1, "cell 0 0");
		
		jl_client1 = new SLabel("", 0);
		panel_4.add(jl_client1, "cell 1 0");
		
		jl_client1_percent = new SLabel("", 0);
		panel_4.add(jl_client1_percent, "cell 2 0");
		
		jl_client1_amount = new SLabel("", 0);
		panel_4.add(jl_client1_amount, "cell 3 0");
		
		jl_client1_is_payment_direct = new SLabel("", 0);
		panel_4.add(jl_client1_is_payment_direct, "cell 4 0");
		
		jb_client2 = new SButton("", "Ouvrir la vue Client");
		jb_client2.setIcon(new ImageIcon(Facture_View.class.getResource("/icons/logo_corrida_20x20.png")));
		panel_4.add(jb_client2, "cell 0 1");
		
		jl_client2 = new SLabel("", 0);
		panel_4.add(jl_client2, "cell 1 1");
		
		jl_client2_percent = new SLabel("", 0);
		panel_4.add(jl_client2_percent, "cell 2 1");
		
		jl_client2_amount = new SLabel("", 0);
		panel_4.add(jl_client2_amount, "cell 3 1");
		
		jl_client2_is_payment_direct = new SLabel("", 0);
		panel_4.add(jl_client2_is_payment_direct, "cell 4 1");
		
		SPanel panel_2 = new SPanel();
		panel_2.setBorder(new TitledBorder(null, "Nom", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		jp_main_content.add(panel_2, "cell 0 2 6 1,grow");
		panel_2.setLayout(new MigLayout("gap 1px 1px, insets 1px 1px", "[grow]", "[]"));
		
		jl_dossier_name = new SLabel("", SLabel.TYPE_COMMUN_BOLD);
		panel_2.add(jl_dossier_name, "cell 0 0,alignx center");
		
		SPanel panel_3 = new SPanel();
		panel_3.setBorder(new TitledBorder(null, "Contenu", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		jp_main_content.add(panel_3, "cell 0 3 6 1,grow");
		panel_3.setLayout(new MigLayout("gap 1px 1px, insets 1px 1px", "[grow]", "[grow]"));
		
		SScrollPane scrollPane = new SScrollPane();
		panel_3.add(scrollPane, "cell 0 0,grow");
		
		jp_facture_content = new SPanel();
		scrollPane.setViewportView(jp_facture_content);
		jp_facture_content.setLayout(new MigLayout("gap 0px 0px, insets 0px 0px", "[grow]", "[]"));
		
		SPanel panel_5 = new SPanel();
		panel_5.setBorder(new TitledBorder(null, "Total", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		jp_main_content.add(panel_5, "cell 3 4 3 1,alignx right,growy");
		panel_5.setLayout(new MigLayout("", "[][grow]", "[][][]"));
		
		SLabel label_5 = new SLabel("HT", 0);
		panel_5.add(label_5, "cell 0 0");
		
		jl_total_ht = new SLabel("", 0);
		panel_5.add(jl_total_ht, "cell 1 0,alignx right");
		
		SLabel label_7 = new SLabel("TVA", 0);
		panel_5.add(label_7, "cell 0 1");
		
		jl_total_tva = new SLabel("", 0);
		panel_5.add(jl_total_tva, "cell 1 1,alignx right");
		
		SLabel label_9 = new SLabel("NET", 0);
		panel_5.add(label_9, "cell 0 2");
		
		jl_total_net = new SLabel("", 0);
		panel_5.add(jl_total_net, "cell 1 2,alignx right");

		SwingUtilities.invokeLater(new Runnable()
		{
			@Override
			public void run() 
			{
				ctrl_facture.computeCanDelete();
				insertData();
			}
		});
	}
	
	public void setDeleteEnabled(boolean enabled)
	{
		this.jb_delete.setEnabled(enabled);
	}

	public void insertData()
	{
		Facture fac = ctrl_facture.getModel();
		
		jl_head.setText("Facture N° " + fac.getFactureNumber());
		
		jl_dossier_number.setText(fac.getCommande().getDossier().getReferenceNumber());
		jl_tranche_number.setText(Integer.toString(fac.getCommande().getTrancheNumber()));
		jl_responsible.setText(fac.getCommande().getConstructionSite().getResponsible().getName());
		jl_commande_number.setText(fac.getCommande().getCommandeNumber());
		
		jl_dossier_name.setText(fac.getCommande().getDossier().getLocalisation() + " / " + fac.getCommande().getDossier().getName());
		
		jp_facture_content.removeAll();
		jp_facture_content.repaint();
		Facture_Content_View ccvhead = new Facture_Content_View(null);
		jp_facture_content.add(ccvhead, "cell 0 0, growx");
		List<Facture_Content> facture_contents = new Facture_Content_DBAO("fc").getAllWithFacture(fac);
		for(int i = 0; i < facture_contents.size(); i++)
		{
			Facture_Content_View ccv = new Facture_Content_View(facture_contents.get(i));
			jp_facture_content.add(ccv, "cell 0 " + (i+1) + ", growx");
		}
		jp_facture_content.repaint();
		jp_facture_content.revalidate();	
		
		jl_observation.setText("<html>"+fac.getObservation()+"</html>");
		jl_factured_date.setText(fac.getFacturedDate().getFormattedDate(SDate.FORMAT_FR));
		jl_product_date.setText(fac.getProductDate().getFormattedDate(SDate.FORMAT_FR));
		jl_category.setText(fac.getCategory().getName());
		jl_payment_mode.setText(fac.getPaymentMode().getShortValue());
		jl_caution.setText(fac.getCautionJoin() ? "Caution bancaire jointe" : "");
		
		if(fac != null)
		{
			List<Rfp> rfps = new Rfp_DBAO("rfp").getWithFacture(fac);
			Rfp rfp1 = rfps.get(0);
			
			jl_client1.setText(rfp1.getPayer().getCorridaClient().getCompany());
			jl_client1_amount.setText(NumberTools.getNumberFormat(2).format(rfp1.getPercent()*fac.getAmountNet()/100) + " €");
			jl_client1_percent.setText(NumberTools.getNumberFormat(2).format(rfp1.getPercent())+ " %");
			jl_client1_is_payment_direct.setText(rfp1.getDirectPayment() ? "Paiement Direct" : "");
			jb_client1.addActionListener(new ActionListener() 
			{
				@Override
				public void actionPerformed(ActionEvent e) 
				{
					ctrl_facture.getApplicationController().openView(Application_Controller.CLIENT, rfp1.getPayer().getCorridaClient(), null);					
				}
			});
			
			if(rfps.size() > 1)
			{
				Rfp rfp2 = rfps.get(1);
				
				jl_client2.setText(rfp2.getPayer().getCorridaClient().getCompany());
				jl_client2_amount.setText(NumberTools.getNumberFormat(2).format(rfp2.getPercent()*fac.getAmountNet()/100) + " €");
				jl_client2_percent.setText(NumberTools.getNumberFormat(2).format(rfp2.getPercent())+ " %");
				jl_client2_is_payment_direct.setText(rfp2.getDirectPayment() ? "Paiement Direct" : "");
				jb_client2.addActionListener(new ActionListener() 
				{
					@Override
					public void actionPerformed(ActionEvent e) 
					{
						ctrl_facture.getApplicationController().openView(Application_Controller.CLIENT, rfp2.getPayer().getCorridaClient(), null);					
					}
				});
			}
			else
			{
				jl_client2.setText("");
				jl_client2_amount.setText("");
				jl_client2_percent.setText("");
				jl_client2_is_payment_direct.setText("");
				jb_client2.setVisible(false);
			}
		}
		
		jl_total_ht.setText(NumberTools.getNumberFormat(2).format(fac.getAmountHt()) + " €");
		if(fac.getCommande().getAutoLiquidation())
			jl_total_tva.setText("Auto - Liquidation");
		else
			jl_total_tva.setText(NumberTools.getNumberFormat(2).format(fac.getAmountNet()-fac.getAmountHt()) + " €");
		jl_total_net.setText(NumberTools.getNumberFormat(2).format(fac.getAmountNet()) + " €");
	}
}
