$('#tutorial').on('click', function () {
  $(document).ready(async function () {
    const driver = new Driver({
      doneBtnText: 'Sair',
      closeBtnText: 'Fechar',
      nextBtnText: 'Próximo',
      prevBtnText: 'Anterior',
      allowClose: false,
      animate: true
    });

    driver.defineSteps([{
      element: '#tourGeral',
      popover: {
        title: 'Dados Gerais',
        description: 'Aqui estão os dados gerais da nota.',
        position: 'top'
      }
    },
    {
      element: '#txtCliente',
      popover: {
        title: 'Campos Obrigatórios',
        description: 'Esse é um campo obrigatório, para identificá-los, você verá um * ao lado do nome.',
        position: 'top'
      }
    },
    {
      element: '#txtNatureza',
      popover: {
        title: 'Campos Obrigatórios',
        description: 'Esse é um campo obrigatório, para identificá-los, você verá um * ao lado do nome.',
        position: 'top'
      }
    },
    {
      element: '#txtDeposito',
      popover: {
        title: 'Campos Obrigatórios',
        description: 'Esse é um campo obrigatório, para identificá-los, você verá um * ao lado do nome.',
        position: 'top'
      }
    },
    {
      element: '#avancar1',
      popover: {
        title: 'Botão Avançar',
        description: 'Clique aqui para avançar para a aba itens, onde será possível adicionar itens e após isso, adicionar duplicatas e/ou gravar a nota.',
        position: 'left'
      }
    }
    ]);
    driver.start();
  });
});

$(document).ready(async function () {

  await setarDataAtual('txtDataEmissao');
  await setarDataAtual('txtDataSaida');
  await setarDataAtual('txtDataVenc');

  let usaCstIcms = await verificaCstIcmsOuCsosn();
  let currentFs;
  let nextFs;
  let previousFs;
  let opacity;

  $('.maskDecimais').maskMoney({
    decimal: ".",
    thousands: "",
    precision: 2,
  });

  $(".next").click(async function () {
    let validator = $("#msform").validate();
    let liberado = true;

    if ($(this).attr("id") == "avancar1") {
      validator.element("#txtCliente");
      validator.element("#txtNatureza");
      validator.element("#txtNotaRef");
      validator.element("#txtChaveNotaRef");
      if (!(validator.element("#txtCliente") && validator.element("#txtNatureza") && validator.element("#txtNotaRef") && validator.element("#txtChaveNotaRef"))) {
        liberado = false;
      }
    }

    if (liberado) {
      currentFs = $(this).parent();
      nextFs = $(this).parent().next();
      $("#progressbar li").eq($("fieldset").index(nextFs)).addClass("active");
      nextFs.show();
      currentFs.animate({
        opacity: 0,
      }, {
        step(now) {
          opacity = 1 - now;
          currentFs.css({
            display: "none",
            position: "relative",
          });
          nextFs.css({
            opacity,
          });
        },
        duration: 600,
      });
    }
  });

  $("#msform").validate({
    debug: false,
    ignore: "",
    rules: {
      txtCliente: {
        required: true,
      },
      txtNatureza: {
        required: true,
      },
      txtNotaRef: {
        required: true,
      },
      txtChaveNotaRef: {
        required: true,
      },
      txtCstIcms: {
        required: true,
      },
      txtCstIpi: {
        required: true,
      },
      txtCstPis: {
        required: true,
      },
      txtCstCofins: {
        required: true,
      },
      txtCodNcm: {
        required: true,
      }
    },
    messages: {
      txtCliente: {
        required: "Informe um cliente válido.",
      },
      txtNatureza: {
        required: "Informe uma natureza válida.",
      },
      txtNotaRef: {
        required: "Informe uma nota válida.",
      },
      txtChaveNotaRef: {
        required: "Informe uma chave válida.",
      },
      txtCstIcms: {
        required: "Informe um CST ICMS válido.",
      },
      txtCstIpi: {
        required: "Informe um CST IPI válido.",
      },
      txtCstPis: {
        required: "Informe um CST PIS válido.",
      },
      txtCstCofins: {
        required: "Informe um CST COFINS válido.",
      },
      txtCodNcm: {
        required: "Informe um NCM válido.",
      }
    },
    errorElement: "span",
    errorPlacement(error, element) {
      error.addClass("invalid-feedback");
      element.closest(".form-group").append(error);
    },
    highlight(element) {
      $(element).addClass("is-invalid");
    },
    unhighlight(element) {
      $(element).removeClass("is-invalid");
    },
  });

  $(".previous").click(async function () {
    currentFs = $(this).parent();
    previousFs = $(this).parent().prev();

    $("#progressbar li")
      .eq($("fieldset").index(currentFs))
      .removeClass("active");

    previousFs.show();

    currentFs.animate({
      opacity: 0,
    }, {
      step(now) {
        opacity = 1 - now;

        currentFs.css({
          display: "none",
          position: "relative",
        });
        previousFs.css({
          opacity,
        });
      },
      duration: 600,
    });
  });

  $("#txtCliente").autocompleta(3, `JSON={ "tabela":"entidade", "camposSelect":["CODCLI CHAVE, NOME DESCRICAO, CNPJ"], "where": ["nome <> 'CONSUMIDOR FINAL' and ativo = 'S'"] }`, ["#txtCNPJ"], ["CNPJ"], ["CNPJ"]);
  $('#btn-cliente').pesquisa_serverside(['#txtCliente', '#txtCNPJ'], ['CODCLI', 'CNPJ'], ['NOME', 'CNPJ'], `{"tabela":"entidade", "camposSelect":[ "CODCLI", "NOME", "FANTASIA", "CNPJ" ], "where": ["nome <> 'CONSUMIDOR FINAL' and ativo = 'S'"]}`, 'Pesquisa Cliente');
  $("#btn-limpa-cliente").on("click", function () { $("#txtCliente").val(""); });

  $("#txtNatureza").autocompleta(1, `JSON={ "tabela":"natureza", "camposSelect":["NATUREZA CHAVE, DESCRICAO DESCRICAO"], "where": ["ativo = 'S'"] }`);
  $("#btn-natureza").pesquisa("#txtNatureza", "NATUREZA", "DESCRICAO", `/sisplan/funcoes/v1/pesquisa?JSON={ "tabela":"natureza", "camposSelect":[ "natureza", "descricao" ], "where": ["ativo = 'S'"]}`, "Pesquisa Natureza", "natureza");
  $("#btn-limpa-natureza").on("click", function () { $("#txtNatureza").val(""); });

  $("#txtNotaRef").autocompleta(3, `JSON={ "tabela":"nota", "camposSelect":["FATURA CHAVE, SERIE DESCRICAO"], "where": ["EMP_ID = ${getCookie('emp_id')}"] }`);
  $("#btn-NotaRef").pesquisa("#txtNotaRef", "FATURA", "SERIE", `/sisplan/funcoes/v1/pesquisa?JSON={ "tabela":"nota", "camposSelect":[ "FATURA", "SERIE" ], "where": ["EMP_ID = ${getCookie('emp_id')}"]}`, "Pesquisa Nota", "nota");
  $("#btn-limpa-NotaRef").on("click", function () { $("#txtNotaRef").val(""); limpaCampos(); });

  $("#txtSituacao").autocompleta(1, `JSON={ "tabela":"TABSIT", "camposSelect":["CODIGO CHAVE, DESCRICAO DESCRICAO"], "where": null }`);
  $("#btn-Situacao").pesquisa("#txtSituacao", "CODIGO", "DESCRICAO", `/sisplan/funcoes/v1/pesquisa?JSON={ "tabela":"TABSIT", "camposSelect":[ "CODIGO", "DESCRICAO" ], "where": null}`, "Pesquisa Situação", "TABSIT");
  $("#btn-limpa-Situacao").on("click", function () { $("#txtSituacao").val(""); });

  $("#txtClasseGer").autocompleta(1, `JSON={ "tabela":"CLASSE_GER", "camposSelect":["CODIGO CHAVE, DESCRICAO DESCRICAO"], "where": null }`);
  $("#btn-ClasseGer").pesquisa("#txtClasseGer", "CODIGO", "DESCRICAO", `/sisplan/funcoes/v1/pesquisa?JSON={ "tabela":"CLASSE_GER", "camposSelect":[ "CODIGO", "DESCRICAO" ], "where": null}`, "Pesquisa Classe Gerencial", "CLASSE_GER");
  $("#btn-limpa-ClasseGer").on("click", function () { $("#txtClasseGer").val(""); });

  $("#txtHistorico").autocompleta(1, `JSON={ "tabela":"HISTCP", "camposSelect":["HISTORICO CHAVE, DESCRICAO DESCRICAO"], "where": null }`);
  $("#btn-Historico").pesquisa("#txtHistorico", "HISTORICO", "DESCRICAO", `/sisplan/funcoes/v1/pesquisa?JSON={ "tabela":"HISTCP", "camposSelect":[ "HISTORICO", "DESCRICAO" ], "where": null}`, "Pesquisa Histórico", "HISTCP");
  $("#btn-limpa-Historico").on("click", function () { $("#txtHistorico").val(""); });

  $("#txtBanco").autocompleta(1, `JSON={ "tabela":"CADBAN", "camposSelect":["BANCO CHAVE, NOME_BANCO DESCRICAO"], "where": null }`);
  $("#btn-Banco").pesquisa("#txtBanco", "BANCO", "NOME_BANCO", `/sisplan/funcoes/v1/pesquisa?JSON={ "tabela":"CADBAN", "camposSelect":[ "BANCO", "NOME_BANCO" ], "where": null}`, "Pesquisa Banco", "CADBAN");
  $("#btn-limpa-Banco").on("click", function () { $("#txtBanco").val(""); });

  $("#txtConta").autocompleta(1, `JSON={ "tabela":"CADCONTA", "camposSelect":["CONTA CHAVE, DESCRICAO DESCRICAO"], "where": null }`);
  $("#btn-Conta").pesquisa("#txtConta", "CONTA", "DESCRICAO", `/sisplan/funcoes/v1/pesquisa?JSON={ "tabela":"CADCONTA", "camposSelect":[ "CONTA", "DESCRICAO" ], "where": null}`, "Pesquisa Conta", "CADCONTA");
  $("#btn-limpa-Conta").on("click", function () { $("#txtConta").val(""); });

  if (usaCstIcms) {
    $("#txtCstIcms").autocompleta(1, `JSON={ "tabela":"TABTRI", "camposSelect":["CODIGO CHAVE, DESCRICAO DESCRICAO"], "where": null }`);
    $("#btn-CstIcms").pesquisa("#txtCstIcms", "CODIGO", "DESCRICAO", `/sisplan/funcoes/v1/pesquisa?JSON={ "tabela":"TABTRI", "camposSelect":[ "CODIGO", "DESCRICAO" ], "where": null}`, "Pesquisa CST ICMS", "TABTRI");
  } else {
    $("#txtCstIcms").autocompleta(1, `JSON={ "tabela":"TABCSOSN", "camposSelect":["CODIGO CHAVE, DESCRICAO DESCRICAO"], "where": null }`);
    $("#btn-CstIcms").pesquisa("#txtCstIcms", "CODIGO", "DESCRICAO", `/sisplan/funcoes/v1/pesquisa?JSON={ "tabela":"TABCSOSN", "camposSelect":[ "CODIGO", "DESCRICAO" ], "where": null}`, "Pesquisa CSOSN", "TABCSOSN");
    $('#lblCstIcms').prop('innerText', 'CSOSN *');
    $('#txtCstIcms').prop('placeholder', 'CSOSN *');
  }
  $("#btn-limpa-CstIcms").on("click", function () { $("#txtCstIcms").val(""); });

  $("#txtCstIpi").autocompleta(1, `JSON={ "tabela":"TABIPI", "camposSelect":["CODIGO CHAVE, DESCRICAO DESCRICAO"], "where": null }`);
  $("#btn-CstIpi").pesquisa("#txtCstIpi", "CODIGO", "DESCRICAO", `/sisplan/funcoes/v1/pesquisa?JSON={ "tabela":"TABIPI", "camposSelect":[ "CODIGO", "DESCRICAO" ], "where": null}`, "Pesquisa IPI", "TABIPI");
  $("#btn-limpa-CstIpi").on("click", function () { $("#txtCstIpi").val(""); });

  $("#txtCstPis").autocompleta(1, `JSON={ "tabela":"TABPIS", "camposSelect":["CODIGO CHAVE, DESCRICAO DESCRICAO"], "where": null }`);
  $("#btn-CstPis").pesquisa("#txtCstPis", "CODIGO", "DESCRICAO", `/sisplan/funcoes/v1/pesquisa?JSON={ "tabela":"TABPIS", "camposSelect":[ "CODIGO", "DESCRICAO" ], "where": null}`, "Pesquisa PIS", "TABPIS");
  $("#btn-limpa-CstPis").on("click", function () { $("#txtCstPis").val(""); });

  $("#txtCstCofins").autocompleta(1, `JSON={ "tabela":"TABCOFINS", "camposSelect":["CODIGO CHAVE, DESCRICAO DESCRICAO"], "where": null }`);
  $("#btn-CstCofins").pesquisa("#txtCstCofins", "CODIGO", "DESCRICAO", `/sisplan/funcoes/v1/pesquisa?JSON={ "tabela":"TABCOFINS", "camposSelect":[ "CODIGO", "DESCRICAO" ], "where": null}`, "Pesquisa COFINS", "TABCOFINS");
  $("#btn-limpa-CstCofins").on("click", function () { $("#txtCstCofins").val(""); });

  $("#txtCodNcm").autocompleta(1, `JSON={ "tabela":"TABFIS", "camposSelect":["CODIGO CHAVE, DESCRICAO DESCRICAO"], "where": null }`);
  $("#btn-CodNcm").pesquisa("#txtCodNcm", "CODIGO", "DESCRICAO", `/sisplan/funcoes/v1/pesquisa?JSON={ "tabela":"TABFIS", "camposSelect":[ "CODIGO", "DESCRICAO" ], "where": null}`, "Pesquisa NCM", "TABFIS");
  $("#btn-limpa-CodNcm").on("click", function () { $("#txtCodNcm").val(""); });

  $('#btnDuplicata').on('click', function () { $('#modalDuplicata').modal('show'); });

  $('#btn-confirmar-dup').on('click', function () {
    $('#modalDuplicata').modal('hide');
  });

  $('#btnComplemento').on('click', function () { $('#modalComplemento').modal('show'); });

  $('#btn-confirmar-compl').on('click', function () {
    $('#modalComplemento').modal('hide');
  });

  $('#btnDifal').on('click', function () { $('#modalDifal').modal('show'); });

  $('#btn-confirmar-difal').on('click', function () {
    $('#modalDifal').modal('hide');
  });

  $("#txtNotaRef").on('blur', async function () {
    buscaDadosNotaRef();
  });

  async function buscaDadosNotaRef() {
    const notaRef = pegaChave('#txtNotaRef');
    const serieRef = pegaDescricao('#txtNotaRef');
    if (notaRef == '') {
      limpaCampos();
      return;
    }
    try {
      let json = '';
      if (isChecked('#radioNfe')) {
        json = `JSON={ "tabela":      "NOTA", 
                "camposSelect":["NOTA.CHAVE_NFE", "NOTA.NATUREZA", "NATUREZA.DESCRICAO", "ENTIDADE.NOME", "NOTA.PROTOCOLO_NFE", "NOTA.FINALIDADE_NFE",
                                "NATUREZA.ALIQUOTA" , "NOTA.CODCLI", "NATUREZA.CLATRIB", "NATUREZA.CLAIPI", "NATUREZA.CLAPIS", "NATUREZA.CLACOFINS",
                                "NATUREZA.PERC_DIF", "TABTRI.DESCRICAO DESC_TRI", "TABIPI.DESCRICAO DESC_IPI", "TABPIS.DESCRICAO DESC_PIS",
                                "TABCOFINS.DESCRICAO DESC_COFINS", "NATUREZA.CSOSN", "TABCSOSN.DESCRICAO DESC_CSOSN"
                               ], 
                "leftjoin":    [{"tabela" : "NATUREZA", "condicao" : "NATUREZA.NATUREZA = NOTA.NATUREZA"},
                                {"tabela" : "ENTIDADE", "condicao" : "ENTIDADE.CODCLI = NOTA.CODCLI"},
                                {"tabela" : "TABTRI", "condicao" : "TABTRI.CODIGO = NATUREZA.CLATRIB"},
                                {"tabela" : "TABIPI", "condicao" : "TABIPI.CODIGO = NATUREZA.CLAIPI"},
                                {"tabela" : "TABPIS", "condicao" : "TABPIS.CODIGO = NATUREZA.CLAPIS"},
                                {"tabela" : "TABCOFINS", "condicao" : "TABCOFINS.CODIGO = NATUREZA.CLACOFINS"},
                                {"tabela" : "TABCSOSN", "condicao" : "TABCSOSN.CODIGO = NATUREZA.CSOSN"}
                               ],
                "where":       ["NOTA.FATURA = '${notaRef}' AND NOTA.SERIE = '${serieRef}' AND NOTA.EMP_ID = '${getCookie('emp_id')}'"]
              }`
      } else {
        json = `JSON={ "tabela":      "NOTA_NFCE", 
                "camposSelect":["NOTA_NFCE.CHAVE_NFCE CHAVE_NFE", "NOTA_NFCE.NATUREZA", "NATUREZA.DESCRICAO", "ENTIDADE.NOME", "NOTA_NFCE.PROTOCOLO_NFCE PROTOCOLO_NFE", "1 FINALIDADE_NFE",
                                "NATUREZA.ALIQUOTA" , "NOTA_NFCE.CODCLI", "NATUREZA.CLATRIB", "NATUREZA.CLAIPI", "NATUREZA.CLAPIS", "NATUREZA.CLACOFINS",
                                "NATUREZA.PERC_DIF", "TABTRI.DESCRICAO DESC_TRI", "TABIPI.DESCRICAO DESC_IPI", "TABPIS.DESCRICAO DESC_PIS",
                                "TABCOFINS.DESCRICAO DESC_COFINS", "NATUREZA.CSOSN", "TABCSOSN.DESCRICAO DESC_CSOSN"
                              ], 
                "leftjoin":    [{"tabela" : "NATUREZA", "condicao" : "NATUREZA.NATUREZA = NOTA_NFCE.NATUREZA"},
                                {"tabela" : "ENTIDADE", "condicao" : "ENTIDADE.CODCLI = NOTA_NFCE.CODCLI"},
                                {"tabela" : "TABTRI", "condicao" : "TABTRI.CODIGO = NATUREZA.CLATRIB"},
                                {"tabela" : "TABIPI", "condicao" : "TABIPI.CODIGO = NATUREZA.CLAIPI"},
                                {"tabela" : "TABPIS", "condicao" : "TABPIS.CODIGO = NATUREZA.CLAPIS"},
                                {"tabela" : "TABCOFINS", "condicao" : "TABCOFINS.CODIGO = NATUREZA.CLACOFINS"},
                                {"tabela" : "TABCSOSN", "condicao" : "TABCSOSN.CODIGO = NATUREZA.CSOSN"}
                              ],
                "where":       ["NOTA_NFCE.FATURA = '${notaRef}' AND NOTA_NFCE.SERIE = '${serieRef}' AND NOTA_NFCE.EMP_ID = '${getCookie('emp_id')}'"]
              }`
      }
      const response = await requisicao("GET", "/Sisplan/Funcoes/v1/pesquisa?", json, null);

      const jsonStr = (await response.json()).RESULT[0][0];

      if (jsonStr.PROTOCOLO_NFE == '') {
        msgAlerta('Nota não transmitida.');
        limpaCampos();
        return;
      }

      if (jsonStr.FINALIDADE_NFE == '2') {
        msgAlerta('Nota de complemento, impossível continuar.');
        limpaCampos();
        return;
      }

      $("#txtChaveNotaRef").val(jsonStr.CHAVE_NFE);
      $("#txtAliquota").val(jsonStr.ALIQUOTA);
      $("#txtPercDiferimento").val(jsonStr.PERC_DIF);
      $("#txtDescricao").val('COMPLEMENTO DE ');
      $("#txtDados").val(`NOTA FISCAL COMPLEMENTAR DE \r\nREF NF: ${notaRef},\r\nCHAVE: ${jsonStr.CHAVE_NFE}`);

      insereValor('#txtCliente', jsonStr.CODCLI, jsonStr.NOME);
      insereValor('#txtNatureza', jsonStr.NATUREZA, jsonStr.DESCRICAO);
      insereValor('#txtCstIpi', jsonStr.CLAIPI, jsonStr.DESC_IPI);
      insereValor('#txtCstPis', jsonStr.CLAPIS, jsonStr.DESC_PIS);
      insereValor('#txtCstCofins', jsonStr.CLACOFINS, jsonStr.DESC_COFINS);
      // insereValor('#txtCodNcm', '99', 'NCM');

      if (usaCstIcms) {
        insereValor('#txtCstIcms', jsonStr.CLATRIB, jsonStr.DESC_TRI);
      } else {
        insereValor('#txtCstIcms', jsonStr.CSOSN, jsonStr.DESC_CSOSN);
      }

    } catch (error) {
      console.error(error);
    }
  }

  $('#radioNfe, #radioNfce').on('change', function () {
    limpaCampos();
    $('#btn-NotaRef').unbind();
    if (isChecked('#radioNfe')) {
      $("#txtNotaRef").autocompleta(3, `JSON={ "tabela":"nota", "camposSelect":["FATURA CHAVE, SERIE DESCRICAO"], "where": ["EMP_ID = ${getCookie('emp_id')}"] }`);
      $("#btn-NotaRef").pesquisa("#txtNotaRef", "FATURA", "SERIE", `/sisplan/funcoes/v1/pesquisa?JSON={ "tabela":"nota", "camposSelect":[ "FATURA", "SERIE" ], "where": ["EMP_ID = ${getCookie('emp_id')}"]}`, "Pesquisa Nota", "nota");
    } else {
      $("#txtNotaRef").autocompleta(3, `JSON={ "tabela":"NOTA_NFCE", "camposSelect":["FATURA CHAVE, SERIE DESCRICAO"], "where": ["EMP_ID = ${getCookie('emp_id')}"] }`);
      $("#btn-NotaRef").pesquisa("#txtNotaRef", "FATURA", "SERIE", `/sisplan/funcoes/v1/pesquisa?JSON={ "tabela":"NOTA_NFCE", "camposSelect":[ "FATURA", "SERIE" ], "where": ["EMP_ID = ${getCookie('emp_id')}"]}`, "Pesquisa NFC-e", "NOTA_NFCE");
    }
    $("#txtNotaRef").on('blur', async function () {
      buscaDadosNotaRef();
    });
  });

  function limpaCampos() {
    $('#txtNotaRef').val('');
    $('#txtChaveNotaRef').val('');
    $('#txtCliente').val('');
    $('#txtNatureza').val('');
    $('#txtAliquota').val('');
    $('#txtDados').val('');
    $('#txtPercDiferimento').val('');
    $('#txtDescricao').val('');
    $('#txtCstIcms').val('');
    $('#txtCstIpi').val('');
    $('#txtCstPis').val('');
    $('#txtCstCofins').val('');
    $('#txtCodNcm').val('');
  }

  async function verificaCstIcmsOuCsosn() {
    try {
      const response = await requisicao("GET", "/Sisplan/Funcoes/v1/pesquisa?",
        `JSON={ "tabela":        "EMPRESA", 
                "camposSelect": ["EMP_CRT"],
                "where":        ["EMP_ID = '${getCookie('emp_id')}'"]
              }`, null);

      const jsonStr = (await response.json()).RESULT[0][0];

      if (jsonStr.EMP_CRT == '1') {
        return false;
      }

      return true;

    } catch (error) {
      console.error(error);
    }
  }

  $('#gravar').click(async function () {

    if ($('#txtCstIcms').val() == '' || $('#txtCstIpi').val() == '' || $('#txtCstPis').val() == '' || $('#txtCstCofins').val() == '' || $('#txtCodNcm').val() == '') {
      $('#modalComplemento').modal('show');
      msgAlerta('Favor preencher todos os campos de complemento.')
      return;
    }

    try {
      $.LoadingOverlay('show');

      let nota = {
        NOTAREF: pegaChave('#txtNotaRef'),
        SERIEREF: pegaDescricao('#txtNotaRef'),
        CODCLI: pegaChave('#txtCliente'),
        NATUREZA: pegaChave('#txtNatureza'),
        ALIQUOTA: $('#txtAliquota').val() == '' ? '0' : $('#txtAliquota').val(),
        DTEMISSAO: $('#txtDataEmissao').val(),
        DTSAIDA: $('#txtDataSaida').val(),
        MENSAGEM: $('#txtDados').val(),
        VALICMS: $('#txtValorIcms').val() == '' ? '0' : $('#txtValorIcms').val(),
        BASECALC: $('#txtBaseIcms').val() == '' ? '0' : $('#txtBaseIcms').val(),
        VALIPI: $('#txtValorIpi').val() == '' ? '0' : $('#txtValorIpi').val(),
        BASEIPI: $('#txtBaseIpi').val() == '' ? '0' : $('#txtBaseIpi').val(),
        VALSUBST: $('#txtValorIcmsSt').val() == '' ? '0' : $('#txtValorIcmsSt').val(),
        BASESUBST: $('#txtBaseIcmsSt').val() == '' ? '0' : $('#txtBaseIcms').val(),
        VALPIS: $('#txtValorPis').val() == '' ? '0' : $('#txtValorPis').val(),
        VALCOFINS: $('#txtValorCofins').val() == '' ? '0' : $('#txtValorCofins').val(),
        VALDESPESAS: $('#txtValorDesp').val() == '' ? '0' : $('#txtValorDesp').val(),
        VALFRETE: $('#txtValorFrete').val() == '' ? '0' : $('#txtValorFrete').val(),
        VALOR: $('#txtValorNota').val() == '' ? '0' : $('#txtValorNota').val(),
        VALPRODUTOS: $('#txtValorProdutos').val() == '' ? '0' : $('#txtValorProdutos').val(),
        CONSUMIDORFINAL: $('#checkConsFinal').is(':checked') ? 'Sim' : 'Nao',
        GERARDIFAL: $('#checkGerarDifal').is(':checked') ? 'Sim' : 'Nao',
        TIPFAT: 'C',
        CODREP: '',
        TRANSPORTADORA: '',
        REDESP: '',
        CIF: '9',
        TIPONOTAREF: 'NFE',
        NOTACOMPLEMENTAR: true,

        NOTASREF: [{
          NOTA_REF: pegaChave('#txtNotaRef'),
          SERIE_REF: pegaDescricao('#txtNotaRef'),
          CODCLI_REF: pegaChave('#txtCliente'),
          DATA_REF: `${$('#txtDataEmissao').val()}T00:00:00Z`,
          IND_OPER: '0',
          IND_EMIT: '0',
          TIPO_FISCAL_REF: isChecked('#radioNfe') ? '55' : '65',
          COD_REF: '0',
          PESO: 0,
          VALOR: 0,
          NUM_COO: '',
          SEQ_ECF: '',
          CHAVE_NFE: pegaValor('#txtChaveNotaRef'),
        }],

        ITENS: [{
          CODIGO: '99999999999',
          COR: '0',
          TAMANHO: '0',
          PRECO: 0,
          LOTE: '000000',
          EMPENHO: 'N',
          UNIDADE: 'UN',
          NOTACLIENTE: 'ACERTO',
          NATUREZA: pegaChave('#txtNatureza'),
          PERCICMS: $('#txtAliquota').val() == '' ? '0' : $('#txtAliquota').val(),
          DESCRICAO: $('#txtDescricao').val(),
          CLATRIB: usaCstIcms ? pegaChave('#txtCstIcms') : '',
          CLACSOSN: usaCstIcms ? '' : pegaChave('#txtCstIcms'),
          CLAIPI: pegaChave('#txtCstIpi'),
          CLAPIS: pegaChave('#txtCstPis'),
          CLACOFINS: pegaChave('#txtCstCofins'),
          CLAFIS: pegaChave('#txtCodNcm'),
          QTDE: $('#checkQtdeZerada').is(':checked') ? 0 : 1,
          VALORICMS: $('#txtValorIcmsItem').val() == '' ? '0' : $('#txtValorIcmsItem').val(),
          BASEICMS: $('#txtBaseIcmsItem').val() == '' ? '0' : $('#txtBaseIcmsItem').val(),
          PERCIPI: $('#txtPercIpiItem').val() == '' ? '0' : $('#txtPercIpiItem').val(),
          VALORIPI: $('#txtValorIpiItem').val() == '' ? '0' : $('#txtValorIpiItem').val(),
          BASEIPI: $('#txtBaseIpiItem').val() == '' ? '0' : $('#txtBaseIpiItem').val(),
          VALORICMSST: $('#txtValorIcmsStItem').val() == '' ? '0' : $('#txtValorIcmsStItem').val(),
          BASEICMSST: $('#txtBaseIcmsStItem').val() == '' ? '0' : $('#txtBaseIcmsStItem').val(),
          VALORPIS: $('#txtValorPisItem').val() == '' ? '0' : $('#txtValorPisItem').val(),
          VALORCOFINS: $('#txtValorCofinsItem').val() == '' ? '0' : $('#txtValorCofinsItem').val(),
          VALORDESP: $('#txtValorDespItem').val() == '' ? '0' : $('#txtValorDespItem').val(),
          VALORFRETE: $('#txtValorFreteItem').val() == '' ? '0' : $('#txtValorFreteItem').val(),
          VALOR: $('#txtValorItem').val() == '' ? '0' : $('#txtValorItem').val(),
          VALORLIQ: $('#txtValorLiq').val() == '' ? '0' : $('#txtValorLiq').val(),
          PERCDIF: $('#txtPercDiferimento').val() == '' ? '0' : $('#txtPercDiferimento').val(),
          VALICMSDIF: $('#txtValorDif').val() == '' ? '0' : $('#txtValorDif').val()
        }],

        DUPLICATAS: $('#checkGeraDup').is(':checked') ? [{
          DT_VENCTO: $('#txtDataVenc').val(),
          SITUACAO: pegaChave('#txtSituacao'),
          CLASSE: pegaChave('#txtClasseGer'),
          HISTORICO: pegaChave('#txtHistorico'),
          BANCO: pegaChave('#txtBanco'),
          CONTA_CHEQUE: pegaChave('#txtConta'),
          VALOR: $('#txtValorDup').val() == '' ? '0' : $('#txtValorDup').val(),
          PERCFCP: $('#txtPercPobreza').val() == '' ? '0' : $('#txtPercPobreza').val(),
          // DIF_PERCICMSDEST: $('#txtPercIcmsDest').val() == '' ? '0' : $('#txtPercIcmsDest').val(),
          // DIF_BASEICMSDEST: $('#txtBaseIcmsDest').val() == '' ? '0' : $('#txtBaseIcmsDest').val(),
          // DIF_INDICE: $('#txtIndice').val() == '' ? '0' : $('#txtIndice').val(),
          PERCICMSINT: $('#txtPercIcmsInter').val() == '' ? '0' : $('#txtPercIcmsInter').val(),
          VALFCP: $('#txtValPobreza').val() == '' ? '0' : $('#txtValPobreza').val(),
          VALICMSUFDEST: $('#txtValIcmsDest').val() == '' ? '0' : $('#txtValIcmsDest').val(),
          VALICMSUFREMET: $('#txtValIcmsRem').val() == '' ? '0' : $('#txtValIcmsRem').val()
        }] : []
      };

      const response = await requisicao('POST', '/sisplan/nfe/v1/faturamento?', '', `JSON=${encodeURIComponent(JSON.stringify(nota))}`, 90000);

      if (!response) {
        $.LoadingOverlay('hide');
        return;
      }

      const jsonStr = await response.json();
      if (response.status != 200) {
        $.LoadingOverlay('hide');
        msgErro(jsonStr.mensagem);
        return;
      }

      $.LoadingOverlay('hide');
      toastr
        .success('Cadastro efetuado com sucesso!', 'Confirmação', {
          toastClass: 'alert',
          iconClasses: {
            error: 'alert-error',
            info: 'alert-info',
            success: 'alert-success',
            warning: 'alert-warning',
          },
          positionClass: 'toast-top-center',
          progressBar: true,
          timeOut: 3000,
          fadeOut: 1000,
          onHidden() {
            // window.location.href = `${BASE_URI}/nfeimpressao`;
            parent.document.querySelector('#menu_impressao_nfe .nav-link').click();

            let iframe = parent.document.querySelector('#panel--sisplan_web-nota_complementar iframe');
            let src = iframe.getAttribute("src");
            iframe.setAttribute("src", src);
          },
        })
        .css({
          "margin-top": "20%",
          width: "500px",
          "max-width": "500px",
        });
    } catch (error) {
      console.error(error);
      $.LoadingOverlay("hide");
      msgErro(`Não foi possível gravar os dados da nota complementar: ${error}`);
    }
  });

});