$(document).ready(async function () {
  componenteFiltro('material', true);
  componenteFiltro('deposito', true);
  componenteFiltro('empresa', true);

  $('#btnConsultar').on('click', async function () {
    const materiais = await formataListas($('#txtMaterial').val().toString());
    const depositos = await formataListas($('#txtDeposito').val().toString());
    const empresas = await formataListas($('#txtEmpresa').val().toString());

    if (materiais == '') {
      msgAlerta('Necessário filtrar ao menos um material.');
      return;
    }

    const response = await requisicao('GET', `/sisplan/followup/v1/consulta?`, `MATERIAIS=${materiais}&DEPOSITOS=${depositos}&EMPRESAS=${empresas}`);
    const json = await response.json();

    criaTabelaMetas(json);
  });

  function criaTabelaMetas(json) {
    const dataSetCols = [];
    const keys = Object.keys(json[0]);

    keys.forEach(value => {
      dataSetCols.push({
        title: value.replace('QTDE_', '').replace('MES', '').replace('TOTAL', 'Total'),
        data: value,
      });
    });

    json.forEach((value, idx) => {
      if (value.MES == 'ESTOQUE') {
        value.rowColor = '#fce9d8';
      } else if (value.MES.includes(' - Compra')) {
        value.rowColor = '#bda55d';
      } else if (value.MES.includes(' - OC: ')) {
        value.rowColor = '#c9bb8e';
      } else if (value.MES.includes(' - Venda')) {
        value.rowColor = '#ffa695';
      } else if (value.MES.includes(' - Saldo')) {
        value.rowColor = '#ffa695';
      } else if (value.MES.includes(' - Cobertura')) {
        value.rowColor = '#ffa695';
      } else if (value.MES == '') {
        value.rowColor = '#d3d3d3';
      } else if (value.MES != 'Venda Meta') {
        value.rowColor = '#dce6f0';
      }

      if (value.MES == 'Venda Meta') {
        Object.keys(value).forEach(prop => {

          if (prop.includes('QTDE_')) {
            value[prop] = `<input type="text" class="input-default focus form-control campoMeta" data-codigo="${prop.replace('QTDE_', '')}" value="0">`;
          }

          if (prop.includes('TOTAL')) {
            value[prop] = `<input type="text" class="input-default focus form-control" id="campoTotal" value="0" disabled>`;
          }

        });
      }

      value.MES = '<b>' + value.MES + '</b>';
    });

    if ($.fn.DataTable.isDataTable('#tabelaItens')) {
      $('#tabelaItens').DataTable().destroy();
      $('#tabelaItens').empty();
    }

    $("#tabelaItens").DataTable({
      paging: false,
      filter: false,
      info: false,
      order: false,
      sort: false,
      destroy: true,
      autoWidth: true,
      columns: dataSetCols,
      data: json,
      rowCallback: function (row, data, index) {
        if (data.rowColor) {
          $(row).css('background-color', data.rowColor);
        }
      }
    });

    $('#tabelaItens td, #tabelaItens th').css('border-bottom', 'dashed 1px');
    $('#tabelaItens thead tr th').css('border-bottom', 'none');
    $('#tabelaItens thead tr th').css('font-size', '17px');
    $($('#tabelaItens thead tr th')[0]).css('background-color', 'var(--color-primary)');
    $($('#tabelaItens thead tr th')[0]).css('border-top', 'none');

    $('.campoMeta').maskMoney({
      decimal: '.',
      thousands: '',
      precision: 0,
    });

    funcaoCampoMeta();
  };

  function funcaoCampoMeta() {
    $('.campoMeta').on('blur', function () {
      if ($(this).val() == '') {
        $(this).val('0');
      }
      calculaTotalMeta();
    });
  };

  function calculaTotalMeta() {
    let sum = 0;
    for (let i = 0; i < $('.campoMeta').length; i++) {
      sum += parseFloat(coalesce($($('.campoMeta')[i]).val()));
    }
    $('#campoTotal').val(sum);
    funcaoCampoMeta();
  };
});