unit frm_SelectCalidadDocumento;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Grids, Vcl.DBGrids,
  Data.DB, FireDAC.Comp.Client, FireDAC.Stan.Param, uAppTheme, frm_BaseSelect;

type
  TfrmSelectCalidadDocumento = class(TfrmBaseSelect)
  private
    FExcludeHitoId: Integer;
  protected
    procedure DoSearch; override;
  public
    constructor Create(AOwner: TComponent); override;
    property ExcludeHitoId: Integer read FExcludeHitoId write FExcludeHitoId;
  end;

var
  frmSelectCalidadDocumento: TfrmSelectCalidadDocumento;

implementation

uses
  dmg_Main;

{$R *.dfm}

constructor TfrmSelectCalidadDocumento.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  FExcludeHitoId := 0;
  MultiSelect := True;
end;

procedure TfrmSelectCalidadDocumento.DoSearch;
var
  LSql: string;
begin
  dmgMain.qryExec.Close;
  LSql :=
    'SELECT d.id, d.codigo_doc, d.nombre_doc, d.periodicidad, ' +
    '       COALESCE(d.departamento_responsable, g.nombre, ''General'') AS departamento_responsable ' +
    'FROM ge_calidad_documentos d ' +
    'LEFT JOIN ge_calidad_grupos g ON d.id_grupo = g.id ' +
    'WHERE d.activo = 1 ';

  if FExcludeHitoId > 0 then
  begin
    LSql := LSql +
      'AND d.id NOT IN (SELECT id_documento FROM ge_calidad_hitos_documentos WHERE id_hito = :hito) ';
  end;

  if Trim(edtSearch.Text) <> '' then
  begin
    LSql := LSql +
      'AND (d.codigo_doc LIKE :search OR d.nombre_doc LIKE :search OR d.departamento_responsable LIKE :search OR d.periodicidad LIKE :search) ';
  end;

  LSql := LSql + 'ORDER BY d.departamento_responsable, d.codigo_doc';

  dmgMain.qryExec.SQL.Text := LSql;

  if FExcludeHitoId > 0 then
    dmgMain.qryExec.ParamByName('hito').AsInteger := FExcludeHitoId;

  if Trim(edtSearch.Text) <> '' then
    dmgMain.qryExec.ParamByName('search').AsString := '%' + Trim(edtSearch.Text) + '%';

  dmgMain.qryExec.Open;

  // Configurar columnas de la rejilla
  dbGridSelect.Columns.Clear;
  with dbGridSelect.Columns.Add do
  begin
    FieldName := 'codigo_doc';
    Title.Caption := 'Código';
    Width := 110;
  end;
  with dbGridSelect.Columns.Add do
  begin
    FieldName := 'nombre_doc';
    Title.Caption := 'Nombre del Documento / Checklist';
    Width := 300;
  end;
  with dbGridSelect.Columns.Add do
  begin
    FieldName := 'periodicidad';
    Title.Caption := 'Periodicidad';
    Width := 130;
  end;
  with dbGridSelect.Columns.Add do
  begin
    FieldName := 'departamento_responsable';
    Title.Caption := 'Departamento';
    Width := 130;
  end;

  if dmgMain.qryExec.FindField('id') <> nil then
    dmgMain.qryExec.FieldByName('id').Visible := False;
end;

end.
