// eslint-disable-next-line no-unused-vars
class AcessoMetas {
  constructor(tipo, descricao, dtInicio, dtFinal, id, idValor) {
    this.tipo = tipo;
    this.descricao = descricao;
    this.dt_Inicio = dtInicio;
    this.dt_Final = dtFinal;
    this.id = id;
    this.idValor = idValor;

    this.url = '/sisplan/metas/v1/metas?';
  }

  limparFiltros() {
    $('#btnLimpaMetas').trigger('click');
  }

  retornaBotaoOpcoes(data) {
    return `
      <div style="text-align:start;">
        <button class="btn btn-info btn-sm dropdown-toggle btnVerificaOpcoes" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
          ${data}
        </button>
        <div class="dropdown-menu">
          <button class="dropdown-item" type="button" title="Editar" id="btnEditar">Editar</button>
          <button class="dropdown-item" type="button" title="Excluir" id="btnExcluir">Excluir</button>
        </div>
      </div>
    `
  };

  async buscar() {
    $.LoadingOverlay('show');
    try {
      let sWhere = [];
      sWhere = $('#txtMetas').val() != '' ? ` AND METAVENDA.ID IN (${await formataListas($('#txtMetas').val().toString())})` : '';

      const dadosSelect = {
        tabela: `METAVENDA`,
        camposSelect: ["ID", "DESCRICAO", "TIPO", "EMP_ID", "DT_INICIO", "DT_FINAL"],
        orderby: ["ID"],
        where: [`1=1 ${sWhere}`],
      };
      const json = await retornaJsonPesquisaPadrao(JSON.stringify(dadosSelect));

      if (!json) {
        return;
      }

      if (json.length === 0) {
        msgAlerta('Nenhum registro encontrado!');
        return;
      }

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

      this.consulta = json;
      this.columns = [];

      const keys = Object.keys(this.consulta[0]);
      keys.forEach((k) => {
        this.columns.push({
          title: k,
          data: k,
        });
      });

      const botaoDinamico = {
        targets: [0],
        funcao: (data, type, row) => { return this.retornaBotaoOpcoes(data); }
      }

      criaDataTablePadrao('#tabelaMetas', true, false, false, false, false, false, false, this.consulta, this.columns, [], [4, 5], [], [], botaoDinamico);

      $('#tabelaMetas').on('click', 'tr', async function () {
        const data = $('#tabelaMetas').DataTable().row($(this)).data();

        if ($(this).hasClass('selected')) {
          return;
        } else {
          $('#tabelaMetas').DataTable().$('tr.selected').removeClass('selected');
          $(this).addClass('selected');
        }

        $('#tabelaMetas').on('dblclick', 'tr', async function () {
          const data = $('#tabelaMetas').DataTable().row($(this)).data();
          window.location.href = `metas/${data.ID}`;
        });

        $('#tabelaMetas').on('click', '#btnEditar', async function () {
          const data = $('#tabelaMetas').DataTable().row($(this).parents('tr')).data();
          window.location.href = `metas/${data.ID}`;
        });
        $('#tabelaMetas').on('click', '#btnExcluir', async function () {

          msgAlerta('Deseja realmente excluir a meta?', async () => {
            const data = $('#tabelaMetas').DataTable().row($(this).parents('tr')).data();
            const acesso = new AcessoMetas(data.TIPO, data.DESCRICAO, data.DT_INICIO, data.DT_FINAL, data.ID);

            await acesso.deletarMeta()
          })

        });

        new AcessoMetas(data.TIPO, data.DESCRICAO, data.DT_INICIO, data.DT_FINAL, data.ID).retornaValoresMetas();
        $('#tabelaMetas').DataTable().columns.adjust().draw(false);
      });

      $($('#tabelaMetas tr')[1]).trigger('click')
      $('#modal-filtros').modal('hide');

    } finally {
      $.LoadingOverlay('hide');
    }
  }

  async deletarMeta() {
    const response = await requisicao('DELETE', this.url, `ID=${this.id}`, '', 15000);
    if (!response) return;

    if (response.status !== 200) {
      const json = await response.json();
      msgErro(json.mensagem);
      return;
    }

    this.buscar();
    criaMensagemSucesso('Meta deletada com sucesso!');
  }


  async retornaValoresMetas() {
    const dadosSelect = {
      tabela: 'METAVALORES',
      camposSelect: ["ID", "OPERACAO", "VALOR"],
      where: [`ID_META = ${this.id}`],
      orderby: ['ID'],
    };
    const json = await retornaJsonPesquisaPadrao(JSON.stringify(dadosSelect));

    if (!json) {
      return;
    }

    if ($.fn.DataTable.isDataTable('#tabelaValoresMetas')) {
      $('#tabelaValoresMetas').DataTable().destroy();
      $('#tabelaValoresMetas').empty();
    };
    const dataSetCols = []
    const keys = Object.keys(json[0]);
    keys.forEach((k) => {
      dataSetCols.push({
        title: k,
        data: k,
      });
    });

    criaDataTablePadrao('#tabelaValoresMetas', false, false, false, false, false, false, false, json, dataSetCols, [], [], [], [2]);

    $('#tabelaValoresMetas').on('click', 'tr', async function () {
      const data = $('#tabelaValoresMetas').DataTable().row($(this)).data();
      const dataMeta = $('#tabelaMetas').DataTable().row($($('#tabelaMetas tr.selected')[0])).data();


      if ($(this).hasClass('selected')) {
        return;
      } else {
        $('#tabelaValoresMetas').DataTable().$('tr.selected').removeClass('selected');
        $(this).addClass('selected');
      }

      new AcessoMetas(dataMeta.TIPO, dataMeta.DESCRICAO, dataMeta.DT_INICIO, dataMeta.DT_FINAL, dataMeta.ID, data.ID).retornaItensValoresMetas();
    });

    $($('#tabelaValoresMetas tr')[1]).trigger('click')
  }
  async buscarValoresMetas() {
    const response = await requisicao('GET', '/sisplan/metas/v1/opcoes?', `ID=${this.idValor}&TIPO=${this.tipo}`, '', 150000);

    if (!response) {
      return;
    }

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

    return jsonStr;
  }


  async retornaItensValoresMetas() {

    const json = await this.buscarValoresMetas()

    if ($.fn.DataTable.isDataTable('#tabelaItensValoresMetas')) {
      $('#tabelaItensValoresMetas').DataTable().destroy();
      $('#tabelaItensValoresMetas').empty();
    };
    const dataSetCols = []
    const keys = Object.keys(json[0]);
    keys.forEach((k) => {
      dataSetCols.push({
        title: k,
        data: k,
      });
    });

    criaDataTablePadrao('#tabelaItensValoresMetas', true, true, false, true, false, false, false, json, dataSetCols, [], [], [], [3]);
  }

}