$(function () {

    recuperaMenus();
    recuperaDados();

    $("#datasPeriodo").daterangepicker({
        opens: "center",
        applyButtonClasses: "btn-apply-date",
        cancelButtonClasses: "btn-cancel-date",
        autoApply: true,
        maxDate: new Date(),
        drops: "auto",
        locale: {
            format: 'DD/MM/YYYY',
            "daysOfWeek": [
                "Dom",
                "Seg",
                "Ter",
                "Qua",
                "Qui",
                "Sex",
                "Sab"
            ],
            "monthNames": [
                "Janeiro",
                "Fevereiro",
                "Março",
                "Abril",
                "Maio",
                "Junho",
                "Julho",
                "Agosto",
                "Setembro",
                "Outubro",
                "Novembro",
                "Dezembro"
            ]
        }
    });

    var statusPayment = {
        "TODOS": {
            "backoffice": "TODOS",
            "traducao": "Todos"
        },
        "PENDENT": {
            "backoffice": "PENDENT",
            "traducao": "Pendente"
        },
        "PROCESSING_PAYMENT": {
            "backoffice": "PROCESSING_PAYMENT",
            "traducao": "Processando"
        },
        // "IN_REVIEW": {
        //     "backoffice": "IN_REVIEW",
        //     "traducao": "Em revisão"
        // },
        "AUTHORIZED": {
            "backoffice": "AUTHORIZED",
            "traducao": "Autorizado"
        },
        // "PARTIAL_PAID": {
        //     "backoffice": "PARTIAL_PAID",
        //     "traducao": "Parcialmente pago"
        // },
        "PAID": {
            "backoffice": "PAID",
            "traducao": "Pago"
        },
        "DENIED": {
            "backoffice": "DENIED",
            "traducao": "Não autorizado"
        },
        "REFUSED": {
            "backoffice": "REFUSED",
            "traducao": "Rejeitado"
        },
        "REFUNDED": {
            "backoffice": "REFUNDED",
            "traducao": "Reembolsado"
        },
        "CHARGEBACK": {
            "backoffice": "CHARGEBACK",
            "traducao": "Chargeback"
        },
        "UNPROCESSED_PAYMENT": {
            "backoffice": "UNPROCESSED_PAYMENT",
            "traducao": "Não processado"
        },
        // "NOPE": {
        //     "backoffice": "NOPE",
        //     "traducao": "Nope"
        // },
        "VOID": {
            "backoffice": "VOID",
            "traducao": "Recusado"
        }
    };

    var dados = JSON.parse(sessionStorage.getItem('dados'));

    var chave = "";
    var valor = "";

    if (dados.parceiro.tipo_parceiro === "Credenciado") {
        chave = "servicePoint=";
        valor = dados.parceiro.service_point;
    } else {
        chave = "sourceKeys=";
        valor = dados.parceiro.source_key;
    }

    $("#reloadTransactions").on("click", function () {

        $("#btnProximaPagina, #btnUltimaPagina, #btnPrimeiraPagina, #btnPaginaAnterior").prop("disabled", true);
        $("#formPesquisaLivre")[0].reset();
        $("#pesquisaLivre").removeClass("input-active");
        
        resetFiltersForm();

        montaListaTransacoes(chave, valor, 1);

    });

    $("body").on("click", ".abre-options", function () {
        $(".options").hide();
        $(this).parent().find(".options").show();
    });

    // fecha options
    $("body").click(function (e) {
        var condicao = $(e.target).is(".options *") || $(e.target).is(".options") || $(e.target).is(".abre-options *") || $(e.target).is(".abre-options");

        if (!condicao) {
            $(".options").hide();
        }
    });

    $("body").on("click", "li.abre-modal", function () {
        const _id = $(this).data("transactionid");
        $("#barcodeTransaction .valor").html("");
        $("#modalDadosTransacao .cards").hide();
        abreModal("modalDadosTransacao");
        getDetails(_id).then(function (detalhes) {
            $(".load-detalhes").hide();
            $("#modalDadosTransacao .cards").show().css("display", "flex");
            let data = new Date(detalhes.systemTransactionDate).toLocaleDateString("pt-BR");
            let hora = new Date(detalhes.systemTransactionDate).toLocaleTimeString("pt-BR");
            let dataHora = data + " - " + hora;

            var cashbackPayment = detalhes.paymentForms.filter(function (payment) {
                return payment.paymentMethodTarget === "CASHBACK";
            });

            var cardPayment = detalhes.paymentForms.filter(function (payment) {
                return payment.paymentMethodTarget === "CARD";
            });

            let statusCardPayment = cardPayment[0].status;

            $("#idTransaction .valor").text(detalhes._id);
            $("#valorTransaction .valor").text(detalhes.totalAmount.toLocaleString("pt-BR", {
                minimumFractionDigits: 2,
                style: 'currency',
                currency: 'BRL'
            }));
            $("#statusTransaction .valor").text(statusPayment[statusCardPayment].traducao).removeClass().addClass("valor " + statusCardPayment);
            $("#locatorTransaction .valor").text(detalhes.locator);
            $("#dataTransaction .valor").text(dataHora);

            $("#nomePagador .valor").text(detalhes.person.name);
            $("#emailPagador .valor").text(detalhes.person.email[0]);

            if (detalhes.person.documentNumber.length === 11) {
                $("#cpfPagador .valor").text(detalhes.person.documentNumber).mask("000.000.000-00");
            } else if (detalhes.person.documentNumber.length === 14) {
                $("#cpfPagador .valor").text(detalhes.person.documentNumber).mask("00.000.000/0000-00");
            } else {
                $("#cpfPagador .valor").text(detalhes.person.documentNumber);
            }

            $("#telefonePagador .valor").text(detalhes.person.phoneNumbers[0].number).mask("(00) 00000-0000");

            var barcodeNumbers = [];
            detalhes.barCodes.forEach(barcode => {
                barcode.split(",").forEach(number => {
                    barcodeNumbers.push(number.replace(/[^\d]+/g, ''));
                })
            })

            barcodeNumbers.forEach(barcode => {
                $("#barcodeTransaction .valor").append("<span>" + barcode + "<span/>");
            });

            $("#parcelasPayment .valor").text(cardPayment[0].numInstallments);

            let cashbackUtilizado = 0;

            if (cashbackPayment.length > 0) {
                cashbackUtilizado = cashbackPayment[0].totalAmount;
            }

            $("#cashbackUtilizado .valor").text(cashbackUtilizado.toLocaleString("pt-BR", {
                minimumFractionDigits: 2,
                style: 'currency',
                currency: 'BRL'
            }));

            let cashbackRecebido = 0;

            if (detalhes.accountMemberCashback) {
                cashbackRecebido = detalhes.accountMemberCashback.amountRedeem;
            }

            $("#cashbackRecebido .valor").text(cashbackRecebido.toLocaleString("pt-BR", {
                minimumFractionDigits: 2,
                style: 'currency',
                currency: 'BRL'
            }));

            let valorParcela = cardPayment[0].totalAmount / cardPayment[0].numInstallments;

            $("#parcelaValuePayment .valor").text(valorParcela.toLocaleString("pt-BR", {
                minimumFractionDigits: 2,
                style: 'currency',
                currency: 'BRL'
            }));

        }).catch(function (error) {
            $(".msg").addClass("on");
            $(".msg .text").text(error);
        })
    });

    $("#btnProximaPagina").on("click", function (e) {
        e.preventDefault();
        $(".pagination button").prop("disabled", true);
        var transactionsDetails = JSON.parse(sessionStorage.getItem("transaction"));
        if (transactionsDetails.hasNextPage) {
            montaListaTransacoes(chave, valor, transactionsDetails.nextPage);
        }
    });

    $("#btnPaginaAnterior").on("click", function (e) {
        e.preventDefault();
        $(".pagination button").prop("disabled", true);
        var transactionsDetails = JSON.parse(sessionStorage.getItem("transaction"));
        if (transactionsDetails.hasPrevPage) {
            montaListaTransacoes(chave, valor, transactionsDetails.prevPage);
        }
    });

    $("#btnPrimeiraPagina").on("click", function (e) {
        e.preventDefault();
        $(".pagination button").prop("disabled", true);
        var transactionsDetails = JSON.parse(sessionStorage.getItem("transaction"));
        if (transactionsDetails.hasPrevPage) {
            montaListaTransacoes(chave, valor, 1);
        }
    });

    $("#btnUltimaPagina").on("click", function (e) {
        e.preventDefault();
        $(".pagination button").prop("disabled", true);
        var transactionsDetails = JSON.parse(sessionStorage.getItem("transaction"));
        if (transactionsDetails.hasNextPage) {
            montaListaTransacoes(chave, valor, transactionsDetails.totalPages);
        }
    });

    $("#formPesquisaLivre").on("submit", function (e) {

        resetFiltersForm();

        e.preventDefault();
        $("#btnProximaPagina, #btnUltimaPagina, #btnPrimeiraPagina, #btnPaginaAnterior").prop("disabled", true);
        var input = $("#pesquisaLivre");
        var term = input.val().toUpperCase();
        var key = input.data("key");
        if (term.length < 6) {
            $(".msg").addClass("on");
            $(".msg .text").text("Informe um termo válido");
            return;
        }
        var filter = "&" + key + "=" + term;
        montaListaTransacoes(chave, valor, 1, filter);
    });

    $("#formAplicaFiltros").on("submit", function(e){
        e.preventDefault();

        $("#formPesquisaLivre")[0].reset();
        $("#pesquisaLivre").removeClass("input-active");

        $(".filtros-bar").slideUp(240);

        var dateIni = "dateIni=", dateEnd = "dateEnd=", paymentStatus = "paymentStatus=", data = new Date();
        var dia = data.getDate() < 10 ? "0"+data.getDate() : data.getDate();
        var mes = data.getMonth() < 10 ? "0"+(data.getMonth()+1) : data.getMonth()+1;
        var ano = data.getFullYear();
        var hoje = ano + "-" + mes + "-" + dia;
        var dataComp = new Date();
        var filterData = "";

        if($("#selectPeriod").val() === "personalizado"){
            var period = $("#datasPeriodo").val().split(/[^\d]+/g).reverse();
            var dataFinal = period[0] + "-" + period[1] + "-" + period[2];
            var dataInicial = period[3] + "-" + period[4] + "-" + period[5];
            filterData = "&" + dateEnd + dataFinal + "&" + dateIni + dataInicial;
        }else if($("#selectPeriod").val() === "todo"){
            filterData = "";
        }else{
            var period = $("#selectPeriod").val();
            dataComp.setDate(data.getDate() - Number(period));
            dia = dataComp.getDate() < 10 ? "0"+dataComp.getDate() : dataComp.getDate();
            mes = dataComp.getMonth() < 10 ? "0"+(dataComp.getMonth()+1) : dataComp.getMonth()+1;
            ano = dataComp.getFullYear();
            var hojeMenosPeriod = ano + "-" + mes + "-" + dia;
            filterData = "&" + dateEnd + hoje + "&" + dateIni + hojeMenosPeriod;
            console.log(filterData);
        }

        var statusPagamento = $("#selectStatus").val();
        var filterStatus = "&" + paymentStatus + statusPagamento;

        var filter = filterData + filterStatus;

        montaListaTransacoes(chave, valor, 1, filter);
    });

    $("#resetaFiltros").on("click", function(e){
        e.preventDefault();
        resetFiltersForm();
        montaListaTransacoes(chave, valor, 1);
    });

    $("#selectPeriod").on("change", function () {
        if($(this).val() === "personalizado"){
            $("#datasPeriodo").prop("disabled", false);
            $(".formPeriodo").show();
        }else{
            $("#datasPeriodo").prop("disabled", true);
            $(".formPeriodo").hide();
        }
    });

    $("#selectStatus").on("change", function () {
        $("#aplicaFiltros").prop("disabled", false);
    });

    $("#abreFiltros").on("click", function () {
        $(".filtros-bar").slideToggle(240);
    });

    $("#fechaModalFiltros").on("click", function () {
        $("#modalFiltros").hide();
        // $("body, html, .container, .main").css("overflow", "visible");
    });
});

function montaListaTransacoes(chave, valor, pagina, filters = "") {

    $("#btnProximaPagina, #btnUltimaPagina, #btnPrimeiraPagina, #btnPaginaAnterior").prop("disabled", true);

    var statusPayment = {
        "TODOS": {
            "backoffice": "TODOS",
            "traducao": "Todos"
        },
        "PENDENT": {
            "backoffice": "PENDENT",
            "traducao": "Pendente"
        },
        "PROCESSING_PAYMENT": {
            "backoffice": "PROCESSING_PAYMENT",
            "traducao": "Processando"
        },
        // "IN_REVIEW": {
        //     "backoffice": "IN_REVIEW",
        //     "traducao": "Em revisão"
        // },
        "AUTHORIZED": {
            "backoffice": "AUTHORIZED",
            "traducao": "Autorizado"
        },
        // "PARTIAL_PAID": {
        //     "backoffice": "PARTIAL_PAID",
        //     "traducao": "Parcialmente pago"
        // },
        "PAID": {
            "backoffice": "PAID",
            "traducao": "Pago"
        },
        "DENIED": {
            "backoffice": "DENIED",
            "traducao": "Não autorizado"
        },
        "REFUSED": {
            "backoffice": "REFUSED",
            "traducao": "Rejeitado"
        },
        "REFUNDED": {
            "backoffice": "REFUNDED",
            "traducao": "Reembolsado"
        },
        "CHARGEBACK": {
            "backoffice": "CHARGEBACK",
            "traducao": "Chargeback"
        },
        "UNPROCESSED_PAYMENT": {
            "backoffice": "UNPROCESSED_PAYMENT",
            "traducao": "Não processado"
        },
        // "NOPE": {
        //     "backoffice": "NOPE",
        //     "traducao": "Nope"
        // },
        "VOID": {
            "backoffice": "VOID",
            "traducao": "Recusado"
        }
    };

    getTransactions(chave, valor, pagina, filters).then(function (transacoes) {
        $(".load-historico").hide();
        if (!transacoes.docs) {
            $(".msg").addClass("on");
            $(".msg .text").text(transacoes.message);
            return;
        }
        if (!transacoes.totalDocs) {
            $(".msg").addClass("on");
            $(".msg .text").text("Nenhuma venda encontrada");
            return;
        }

        var item = "";
        var docs = transacoes.docs;

        $(".totalDocs").text(transacoes.totalDocs.toLocaleString("pt-BR"));
        $(".totalPages").text(transacoes.page.toLocaleString("pt-BR") + " de " + transacoes.totalPages.toLocaleString("pt-BR"));
        $(".totalAmount").text(transacoes.totalAmount.toLocaleString("pt-BR", {
            minimumFractionDigits: 2,
            style: 'currency',
            currency: 'BRL'
        }));

        docs.forEach(transacao => {

            let data = new Date(transacao.createdDate).toLocaleDateString("pt-BR");
            let hora = new Date(transacao.createdDate).toLocaleTimeString("pt-BR");
            let dataHora = data + " " + hora;

            item += '<div class="transacao" data-id="' + transacao._id + '">';
            item += '<div class="info locator-transacao"><div class="valor">' + transacao.locator + '</div></div>';
            item += '<div class="info valor-transacao"><div class="valor">' + transacao.totalAmount.toLocaleString("pt-BR", {
                minimumFractionDigits: 2,
                style: 'currency',
                currency: 'BRL'
            }) + '</div></div>';
            item += '<div class="info status-transacao"><div class="valor ' + transacao.status + '">' + statusPayment[transacao.status].traducao + '</div></div>';
            item += '<div class="info data-transacao"><div class="valor">' + dataHora + '</div></div>';
            // item += '<div class="info id-transacao"><div class="valor">' + transacao._id + '</div></div>';
            item += '<div class="icone abre-options"><span class="material-icons-round">more_vert</span></div>';
            item += '<div class="lista options">';
            item += '<ul class="linhas">';
            item += '<li class="abre-modal" data-transactionId="' + transacao._id + '">';
            item += '<p class="icon"><span class="material-icons-round">visibility</span></p>';
            item += '<p class="name">Ver detalhes</p>';
            item += '</li>';
            item += '</ul>';
            item += '</div>';
            item += '</div>';
        });

        if (!transacoes.page === transacoes.totalPages) {
            $("#btnProximaPagina, #btnUltimaPagina").prop("disabled", false);
        }

        if (transacoes.hasPrevPage) {
            $("#btnPrimeiraPagina, #btnPaginaAnterior").prop("disabled", false);
        }

        sessionStorage.setItem("transaction", JSON.stringify(transacoes));

        $('html, body').animate({
            scrollTop: $("#topTransactions").offset().top - 108
        }, 500);

        $(".transactionsList").html(item);
    });
}

function resetFiltersForm(){
    $("#datasPeriodo").prop("disabled", true);

    $(".filtros-bar").slideUp(240);

    $("#selectPeriod").prop('selectedIndex',0).trigger("change");
    $("#selectPeriod").parent().find(".nice-select").find(".list li").removeClass("selected focus");
    $("#selectPeriod").parent().find(".nice-select").find(".list li:first").addClass("selected focus");
    var defaultSelectedPeriod = $("#selectPeriod").parent().find(".nice-select").find(".list li:first").text();
    $("#selectPeriod").parent().find(".nice-select").find(".current").text(defaultSelectedPeriod);

    $("#selectStatus").prop('selectedIndex',0).trigger("change");
    $("#selectStatus").parent().find(".nice-select").find(".list li").removeClass("selected focus");
    $("#selectStatus").parent().find(".nice-select").find(".list li:first").addClass("selected focus");
    var defaultSelectedStatus = $("#selectStatus").parent().find(".nice-select").find(".list li:first").text();
    $("#selectStatus").parent().find(".nice-select").find(".current").text(defaultSelectedStatus);
}