$(".datepicker").datepicker({
  format: "dd/mm/yyyy",
  endDate: "0d",
  autoclose: true,
  language: "pt-BR",
});

$(".datepicker").mask("00/00/0000");

$.fn.dataTable.moment("DD/MM/YYYY HH:mm:ss");
$("#tabelaLeads").html(
  '<table id="tbLeads" style="width: 100%;" class="table table-striped table-bordered dataTable no-footer cell-border nowrap responsive compact"></table>'
);
$("#tbLeads").dataTable({
  data: [],
  order: [[4, "desc"]],
  columns: [
    { title: "Nome" },
    { title: "Email" },
    { title: "Telefone" },
    { title: "Status" },
    { title: "Data" },
    { title: "Opções" },
    { title: "Qualidade" },
    { title: "Valor Fechado" },
    { title: "Valor Orçado" },
    { title: "ID" },
  ],
  columnDefs: [
    { targets: 5, orderable: false },
    { targets: 9, visible: false },
  ],
  lengthMenu: [
    [25, 50, 100, -1],
    ["25", "50", "100", "todas"],
  ],
  responsive: true,
});

function modal_confirmacao(id) {
  if ($(".dtr-bs-modal").hasClass("in")) {
    $(".dtr-bs-modal").one("hidden.bs.modal", function () {
      modal_confirmacao_2(id);
    });
    $(".dtr-bs-modal").modal("hide");
  } else {
    modal_confirmacao_2(id);
  }
}

function modal_confirmacao_2(id) {
  $(document).ready(function () {
    jQuery.ajax({
      type: "POST",
      url: "action/abrir_modal_contato_restaurar",
      data: { id: id },
      success: function (data) {
        $(".preloader").css({ display: "none" });
        if (data == "-1") {
          window.location.href = "./";
          return;
        }
        if (data.substring(0, 2) == "-2") {
          toastr.clear();
          toastr.error(data.substring(2));
          return;
        }
        $("#modal-confirmacao-conteudo").html(data);
        $("#modal-confirmacao").modal();
      },
      beforeSend: function () {
        $(".preloader").css({ display: "block" });
      },
      complete: function () {
        $(".preloader").css({ display: "none" });
      },
      error: function () {
        $(".preloader").css({ display: "none" });
        toastr.clear();
        toastr.error("Houve um erro ao abrir modal.");
        return;
      },
    });
  });
}

function carregar_dados() {
  $(document).ready(function () {
    var dados = jQuery("#formContatos").serialize();
    jQuery.ajax({
      type: "POST",
      url: "action/atualizar_lixeira",
      data: dados,
      success: function (data) {
        $(".preloader").css({ display: "none" });
        if (data == "-1") {
          window.location.href = "./";
          return;
        }
        if (data.substring(0, 2) == "-2") {
          toastr.clear();
          toastr.error(data.substring(2));
          return;
        }
        var json = JSON.parse(data);
        var table_data = [];
        var quantidade = 0;
        for (var i = 0; i < json.length; i++) {
          var date = Date.parse(json[i].data).toString("dd/MM/yyyy HH:mm:ss");
          var editar =
            "<div class='btn-group'><a href= 'javascript:void(0);' onclick='modal_confirmacao(" +
            json[i].id +
            ")' class='btn btn-default text-green' title='Clique para restaurar o contato.'><i class='fa fa-refresh'></i></a></div>";
          table_data[i] = [
            "",
            json[i].nome,
            json[i].email,
            json[i].telefone,
            json[i].status,
            date,
            editar,
            json[i].qualidade,
            json[i].valorfechado,
            json[i].valororcado,
            json[i].id,
          ];
          quantidade++;
        }
        $(document).ready(function () {
          const colunas = [
            {},
            { title: "Nome" },
            { title: "Email" },
            { title: "Telefone" },
            { title: "Status" },
            { title: "Data" },
            { title: "Opções", className: "table-buttons" },
            { title: "Qualidade" },
            { title: "Valor Fechado" },
            { title: "Valor Orçado" },
          ];
          $.fn.dataTable.moment("DD/MM/YYYY HH:mm:ss");
          $("#tabelaLeads").html(
            '<table id="tbLeads" style="width: 100%;" class="table table-striped table-bordered dataTable no-footer cell-border nowrap responsive compact"></table>'
          );

          if (json.length >= 2) {
            $("#tbLeads").append(
              $('<tfoot style="display: table-header-group;" />').append(
                `<tr>${colunas.map((i) => "<th></th>").join("")}</tr>`
              )
            );
            $("#tbLeads tfoot tr th").each(function (index) {
              if (index !== 6) {
                // numero da coluna das opções
                $(this).html(
                  '<input type="text" style="width: 100%" class="form-control" placeholder="" />'
                );
              }
            });
          }
          $("#tbLeads").dataTable({
            data: table_data,
            order: [[4, "desc"]],
            columns: colunas,
            columnDefs: [
              { targets: 6, orderable: false },
              {
                className: "control",
                orderable: false,
                targets: 0,
                width: "5%",
              },
            ],
            lengthMenu: [
              [25, 50, 100, -1],
              ["25", "50", "100", "todas"],
            ],
            responsive: {
              details: {
                type: "column",
                display: $.fn.dataTable.Responsive.display.modal({
                  header: function (row) {
                    return '<span style="margin-right: 10px"><b>Dados do Contato</b></span>';
                  },
                }),
                renderer: function (api, rowIdx, columns) {
                  text = "";
                  text += columns[5].data + "<br>";
                  for (i = 0; i < columns.length; i++) {
                    column = columns[i];
                    if (i == 5) {
                      continue;
                    }
                    if (i > 0) text += "<br>";
                    text += "<b>" + column.title + ": </b>" + column.data;
                  }
                  return text;
                },
              },
            },
            initComplete: function () {
              // Apply the search
              this.api()
                .columns([4, 7])
                .every(function () {
                  var column = this;
                  var select = $(
                    '<select class="form-control"><option value=""></option></select>'
                  )
                    .appendTo($(column.footer()).empty())
                    .on("change", function () {
                      var val = $.fn.dataTable.util.escapeRegex($(this).val());
                      column
                        .search(val ? "^" + val + "$" : "", true, false)
                        .draw();
                    });
                  column
                    .data()
                    .unique()
                    .sort()
                    .each(function (d, j) {
                      select.append(
                        '<option value="' + d + '">' + d + "</option>"
                      );
                    });
                  var that = this;
                  $("input", this.footer()).on(
                    "keyup change clear",
                    function () {
                      if (that.search() !== this.value) {
                        that.search(this.value).draw();
                      }
                    }
                  );
                });
              this.api()
                .columns([0, 1, 2, 3, 5, 7, 8, 9])
                .every(function () {
                  var that = this;
                  $("input", this.footer()).on(
                    "keyup change clear",
                    function () {
                      if (that.search() !== this.value) {
                        that.search(this.value).draw();
                      }
                    }
                  );
                });
            },
            deferRender: true,
            createdRow: function (row, data, index) {
              $(row).addClass("id" + data[10]);
              var current = $("td", row).eq(4);
              if (current.text() == "Fechado") {
                current.css("color", "#3daf3dff");
              } else if (current.text() == "Perdeu") {
                current.css("color", "#ff0000");
              } else if (current.text() == "Novo") {
                current.css("color", "#4a85f5");
              }
            },
          });
        });
      },
      beforeSend: function () {
        $(".preloader").css({ display: "block" });
      },
      complete: function () {
        $(".preloader").css({ display: "none" });
      },
      error: function () {
        $(".preloader").css({ display: "none" });
        toastr.clear();
        toastr.error("Houve um erro ao atualizar.");
        return;
      },
    });
  });
}

function remover_contato(id) {
  var table = $("#tbLeads").DataTable();
  var tableRow = table.row(".id" + id.toString());
  var rowData = tableRow.data();
  if (rowData == null) {
    return;
  }
  tableRow.remove();
  table.draw(false);
}

function fechar_modal_confirmacao() {
  $("#modal-confirmacao").modal("hide");
}

function atualizar() {
  var valor = $("#data").val();
  if (valor == "CUSTOM_DATE") $(".datadiv").removeClass("hide");
  else {
    $(".datadiv").addClass("hide");
    carregar_dados();
    salvarFiltro(valor, "", "");
  }
}

pegarFiltro(function (filtro, data1, data2) {
  $("#data").val(filtro);
  $("#datainicial").val(data1);
  $("#datafinal").val(data2);
  if (filtro == "CUSTOM_DATE") $(".datadiv").removeClass("hide");
  carregar_dados();
});

$("#data, #switch").change(function () {
  atualizar();
});
$("#datapersonalizada").click(function () {
  salvarFiltro(
    $("#data").val(),
    $("#datainicial").val(),
    $("#datafinal").val()
  );
  carregar_dados();
});
