/*
 * Copyright (C) 2023 ctecinf.com.br
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package br.com.ctecinf.nfe;

import br.com.ctecinf.nfe.view.ConfirmarPanel;
import br.com.ctecinf.swing.OptionPane;
import br.com.ctecinf.swing.PleaseWaitDialog;
import br.com.ctecinf.text.MaskFormatter;
import br.com.ctecinf.text.NumberFormatter;
import br.inf.portalfiscal.nfe.v400.autorizacao.TRetEnviNFe;
import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;

/**
 *
 * @author cassio
 */
public class PgtoAntecipado {

    public static final void show() {

        NFCe nfce = new NFCe();

        String cpf = OptionPane.input("CPF", null, new MaskFormatter(MaskFormatter.CPF));

        if (cpf != null) {
            try {
                String nome = OptionPane.input("Nome", null, null);
                nfce.addDest(cpf, nome, null, null);
            } catch (Exception ex) {
                System.err.println(ex);
            }
        }

        Number value = OptionPane.input("Valor do Sinal", 0.00, new NumberFormatter(2));

        if (value == null) {
            return;
        }

        if (value.doubleValue() == 0) {
            OptionPane.error("Valor do produto não pode ser zero.");
            return;
        }

        nfce.setPagamentoAntecipado(value.doubleValue());

        // Total
        double total = value.doubleValue();
        double totalPago = 0;

        // Pagamento
        do {

            String tPag = (String) OptionPane.choice("Forma de pagamento", Constants.FORMAS_PAGAMENTO);

            if (tPag == null) {
                return;
            }

            Cartao cartao = null;

            if (tPag.equals(Constants.FORMA_PGTO_CARTAO_CRED) || tPag.equals(Constants.FORMA_PGTO_CARTAO_DEB)) {

                cartao = OptionPane.choice("Bandeira", Cartao.CARTOES);

                if (cartao.toString().equalsIgnoreCase("outros")) {
                    cartao.setCnpj((String) OptionPane.input("CNPJ da empresa de cartão", null, new MaskFormatter(MaskFormatter.CNPJ)));
                }

                cartao.setcAut((String) OptionPane.input("Número da Autorização", null, null));
            }

            Number vPag = (Number) OptionPane.input("Valor", (total - totalPago), new NumberFormatter(2));

            if (vPag == null) {
                return;
            }

            switch (tPag) {
                case Constants.FORMA_PGTO_DINHEIRO ->
                    nfce.addPagamentoDinheiro(vPag.doubleValue());
                case Constants.FORMA_PGTO_CHEQUE ->
                    nfce.addPagamentoCheque(vPag.doubleValue());
                case Constants.FORMA_PGTO_CARTAO_CRED ->
                    nfce.addPagamentoCartaoCredito(cartao, vPag.doubleValue());
                case Constants.FORMA_PGTO_CARTAO_DEB ->
                    nfce.addPagamentoCartaoDebito(cartao, vPag.doubleValue());
                case Constants.FORMA_PGTO_CREDIARIO ->
                    nfce.addPagamentoCrediario(vPag.doubleValue());
                case Constants.FORMA_PGTO_DEPOSITO ->
                    nfce.addPagamentoDeposito(vPag.doubleValue());
                case Constants.FORMA_PGTO_PIX ->
                    nfce.addPagamentoPix(vPag.doubleValue());
                default ->
                    nfce.addPagamentoOutros(vPag.doubleValue());
            }

            totalPago += vPag.doubleValue();

        } while (totalPago < total);

        // Finalizar NFC-e
        nfce.finalizar(0.00);

        if (OptionPane.confirm(new ConfirmarPanel(nfce))) {

            new PleaseWaitDialog() {

                @Override
                public Object exec() throws Exception {
                    return SEFAZConnection.enviarNFe(nfce);
                }

                @Override
                public void end(Object result) {

                    if (result != null) {

                        TRetEnviNFe retEnviNFe = (TRetEnviNFe) result;

                        if (retEnviNFe.getCStat().equals(Constants.FALHA_LOTE) || retEnviNFe.getCStat().equals(Constants.FALHA_XML)) {

                            OptionPane.error("""
                                             Erro no lote, acessando o validador de XML no SEFAZ para verificar erro.
                                             Usar [Ctrl + v] para colar o XML no validador.""");

                            try {
                                Desktop.getDesktop().browse(URI.create("https://www.sefaz.rs.gov.br/nfe/nfe-val.aspx"));
                            } catch (IOException ex) {
                                System.err.println(ex);
                            }

                        } else {

                            String msg = retEnviNFe.getProtNFe().getInfProt().getCStat() + ": " + retEnviNFe.getProtNFe().getInfProt().getXMotivo();
                            OptionPane.info(msg);
                        }
                    }
                }

            }.start();
        }
    }

}
