/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.ctecinf.nfe.view;

import br.com.ctecinf.Config;
import br.com.ctecinf.Daruma;
import br.com.ctecinf.Email;
import br.com.ctecinf.Empresa;
import br.com.ctecinf.nfe.Controller;
import br.com.ctecinf.nfe.DanfePDF;
import br.com.ctecinf.nfe.SEFAZConnection;
import br.com.ctecinf.Utils;
import br.com.ctecinf.swing.Image;
import br.com.ctecinf.swing.OptionPane;
import br.com.ctecinf.swing.PleaseWaitDialog;
import br.com.ctecinf.table.Table;
import br.com.ctecinf.table.TableModel;
import br.com.ctecinf.text.MaskFormatter;
import br.com.ctecinf.text.UpperCaseFormatter;
import br.inf.portalfiscal.nfe.v100.evento.TRetEnvEvento;
import br.inf.portalfiscal.nfe.v400.autorizacao.TNfeProc;
import java.awt.BorderLayout;
import java.awt.Desktop;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

/**
 *
 * @author Cássio Conceição
 * @since 29/05/2019
 * @version 201905
 * @see http://ctecinf.com.br/
 */
public class EmitidasPanel extends JPanel implements ActionListener {

    private static final String LABEL_CANCELAR = "Cancelar NFC-e";
    private static final String LABEL_IMPRIMIR = "Imprimir";
    private static final String LABEL_EMAIL = "Enviar por email";
    private static final String LABEL_VISUALIZAR = "Visualizar NFC-e";
    private static final String LABEL_XML = "Arquivo XML";

    private Table table;

    public EmitidasPanel() {
        super(new BorderLayout());
        initUI();
    }

    private void initUI() {

        try {

            TableModel model = Controller.getNFCeEmitidas();

            table = new Table(model);

            add(new JScrollPane(table), BorderLayout.CENTER);

        } catch (Exception ex) {
            OptionPane.error(ex);
        }

        JPanel pButton = new JPanel(new FlowLayout(FlowLayout.RIGHT));

        JButton button = new JButton(LABEL_CANCELAR, Image.parse(Image.CANCEL, 24));
        button.addActionListener(this);
        pButton.add(button);

        button = new JButton(LABEL_IMPRIMIR, Image.parse(Image.PRINT, 24));
        button.addActionListener(this);
        pButton.add(button);

        button = new JButton(LABEL_EMAIL, Image.parse(Image.MAIL, 24));
        button.addActionListener(this);
        pButton.add(button);

        button = new JButton(LABEL_VISUALIZAR, Image.parse(Image.VIEW, 24));
        button.addActionListener(this);
        pButton.add(button);

        button = new JButton(LABEL_XML, Image.parse(Image.EDIT, 24));
        button.addActionListener(this);
        pButton.add(button);

        add(pButton, BorderLayout.NORTH);
    }

    @Override
    public void actionPerformed(ActionEvent e) {

        if (table.getSelectedRow() == -1) {
            OptionPane.alert("Selecione uma NFC-e na lista.");
            return;
        }

        String versao = (String) table.getValueAt(table.getSelectedRow(), 1);
        String cancel = String.valueOf(table.getValueAt(table.getSelectedRow(), 3));
        String inut = String.valueOf(table.getValueAt(table.getSelectedRow(), 4));
        String path = (String) table.getValueAt(table.getSelectedRow(), 6);
        String xml = (String) table.getValueAt(table.getSelectedRow(), 8);
        File file = new File(path);

        if (!file.exists()) {
            try {
                Utils.writeFile(path, xml);
            } catch (IOException ex) {
                OptionPane.error(ex);
                return;
            }
        }

        switch (e.getActionCommand()) {

            case LABEL_CANCELAR:
                cancel(cancel, inut);
                break;
            case LABEL_EMAIL:
                email(path, file, versao, cancel, inut);
                break;
            case LABEL_IMPRIMIR:
                print(cancel, path, versao, inut);
                break;
            case LABEL_VISUALIZAR:
                view(path, cancel, inut);
                break;
            case LABEL_XML:
                try {
                    Desktop.getDesktop().open(file);
                } catch (Exception ex) {
                    OptionPane.error(ex);
                }
                break;
        }
    }

    private void cancel(String cancel, String inut) {

        if (inut.equalsIgnoreCase("NFC-e INUTILIZADA")) {
            OptionPane.info("NFC-e com numeração inutilizada.");
            return;
        }

        if (cancel.equalsIgnoreCase("sim")) {
            OptionPane.info("NFC-e já cancelada.");
            return;
        }

        String chave = String.valueOf(table.getValueAt(table.getSelectedRow(), 4));
        String just = (String) OptionPane.input("Justificativa NFC-e " + table.getValueAt(table.getSelectedRow(), 2), null, new UpperCaseFormatter());

        if (just != null) {

            new PleaseWaitDialog() {
                @Override
                public Object exec() throws Exception {
                    return SEFAZConnection.enviarEventoCancelamento(chave, just);
                }

                @Override
                public void end(Object result) {
                    if (result != null) {
                        TRetEnvEvento ret = (TRetEnvEvento) result;
                        OptionPane.info(ret.getRetEvento().get(0).getInfEvento().getCStat() + ": " + ret.getRetEvento().get(0).getInfEvento().getXMotivo());
                    }
                }
            }.start();
        }
    }

    private void email(String path, File file, String versao, String cancel, String inut) {

        if (inut.equalsIgnoreCase("NFC-e INUTILIZADA")) {
            OptionPane.info("NFC-e com numeração inutilizada.");
            return;
        }

        if (cancel.equalsIgnoreCase("sim")) {
            OptionPane.info("NFC-e cancelada.");
            return;
        }

        String email = (String) OptionPane.input("Email do destinatário", null, null);

        if (email == null) {
            return;
        }

        new PleaseWaitDialog() {

            @Override
            public Object exec() throws Exception {

                File pdf = DanfePDF.createFile(path);

                String msg = "Segue em anexo o arquivo XML da sua NFC-e emitida por " + Empresa.getRazaoSocial() + "\n\n";

                if (versao.trim().equalsIgnoreCase("4.00")) {
                    TNfeProc nfe = Utils.unmarshaller(TNfeProc.class, Utils.readFile(path));
                    msg += "Link para visualizar a NFC-e diretamente no site da SEFAZ.\n";
                    msg += nfe.getNFe().getInfNFeSupl().getQrCode() + "\n\n";
                }

                msg += "Att,\n" + Empresa.getRazaoSocial() + "\nCNPJ " + MaskFormatter.format(Empresa.getCnpj(), "##.###.###/####-##") + "\nFone: " + MaskFormatter.format(Empresa.getFone(), "(##) ####-####");

                Email.send(email, "NFC-e de " + Empresa.getRazaoSocial(), msg, file, pdf);

                return true;
            }

            @Override
            public void end(Object result) {
                if (result != null && (Boolean) result) {
                    OptionPane.success("Email enviado com sucesso.");
                }
            }
        }.start();
    }

    private void print(String cancel, String path, String versao, String inut) {

        if (inut.equalsIgnoreCase("NFC-e INUTILIZADA")) {
            OptionPane.info("NFC-e com numeração inutilizada.");
            return;
        }

        try {

            if (cancel.equalsIgnoreCase("sim")) {

                Daruma p = new Daruma();

                p.iniciarCond();
                p.tamanhoFonte(4);
                p.alinharCentro();
                p.negrito("NFC-e CANCELADA");

                p.novaLinha();

                p.alinharCentro();
                p.negrito("SEM VALOR FISCAL");

                p.novaLinha();

                p.end();
            }

            switch (versao) {

                case "3.10": {
                    br.inf.portalfiscal.nfe.v310.autorizacao.TNfeProc nfe = Utils.unmarshaller(br.inf.portalfiscal.nfe.v310.autorizacao.TNfeProc.class, Utils.readFile(path));
                    Daruma.danfeNFCe(nfe, Config.get("nfe.amb").equals("1") ? Empresa.getCscTokenProd() : Empresa.getCscTokenHomo());
                    break;
                }
                case "4.00": {

                    TNfeProc nfe = Utils.unmarshaller(TNfeProc.class, Utils.readFile(path));

                    if (nfe.getNFe().getInfNFe().getIde().getIndFinal().equals("1")) {
                        Daruma.danfeNFCe4(nfe);
                    }

                    break;
                }
            }

        } catch (Exception ex) {
            OptionPane.error(ex);
        }
    }

    private void view(String path, String cancel, String inut) {

        if (inut.equalsIgnoreCase("NFC-e INUTILIZADA")) {
            OptionPane.info("NFC-e com numeração inutilizada.");
            return;
        }

        if (cancel.equalsIgnoreCase("sim")) {
            OptionPane.info("NFC-e cancelada.");
            return;
        }

        new PleaseWaitDialog() {

            @Override
            public Object exec() throws Exception {
                return DanfePDF.createFile(path);
            }

            @Override
            public void end(Object result) {
                if (result != null) {
                    try {
                        Desktop.getDesktop().open((File) result);
                    } catch (Exception ex) {
                        OptionPane.error(ex);
                    }
                }
            }
        }.start();
    }

}
