unit UCompraRequisicaoM;

interface

uses
  System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, 
  FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls,
  FMX.ScrollBox, FMX.Memo, FMX.ListBox, FMX.DateTimeCtrls, FMX.Edit,
  FMX.Layouts, FMX.TabControl, FMX.Controls.Presentation, System.Actions,
  FMX.ActnList, FMX.Gestures, Data.Bind.EngExt, Fmx.Bind.DBEngExt, System.Rtti,
  System.Bindings.Outputs, Fmx.Bind.Editors, FMX.ListView.Types,
  FMX.ListView.Appearances, FMX.ListView.Adapters.Base, FMX.ListView,
  Data.Bind.Components, Data.Bind.DBScope, Data.DB, Datasnap.DBClient,
  Fmx.Bind.Navigator, FireDAC.Stan.Intf, FireDAC.Stan.Option,
  FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf,
  FireDAC.DApt.Intf, uDWAbout, uRESTDWPoolerDB, FireDAC.Comp.DataSet,
  FireDAC.Comp.Client, uDWConstsData, FMX.Menus, Data.Bind.Controls;

type
  TFCompraRequisicaoM = class(TFrame)
    VertScrollBox1: TVertScrollBox;
    MainLayout1: TLayout;
    TabControl1: TTabControl;
    TabItem1: TTabItem;
    NameList: TListBox;
    ListBoxItem3: TListBoxItem;
    Edit3: TEdit;
    TabItem5: TTabItem;
    ToolBar1: TToolBar;
    Button2: TButton;
    Label2: TLabel;
    Button1: TButton;
    GestureManager1: TGestureManager;
    ActionList1: TActionList;
    PreviousTabAction: TPreviousTabAction;
    NextTabAction: TNextTabAction;
    TitleAction: TControlAction;
    TabItem3: TTabItem;
    SterlingStyleBook: TStyleBook;
    ListView1: TListView;
    StyleBook1: TStyleBook;
    Button5: TButton;
    Panel1: TPanel;
    Button3: TButton;
    Button4: TButton;
    RESTDWClientSQL1: TRESTDWClientSQL;
    Button6: TButton;
    Panel2: TPanel;
    Button7: TButton;
    ListBoxItem2: TListBoxItem;
    Layout1: TLayout;
    Edit1: TEdit;
    Button8: TButton;
    ListBoxItem1: TListBoxItem;
    Layout2: TLayout;
    Edit2: TEdit;
    Button9: TButton;
    BindSourceDB1: TBindSourceDB;
    LinkControlToFieldDATA_REQUISICAO: TLinkControlToField;
    BindingsList1: TBindingsList;
    LinkListControlToField1: TLinkListControlToField;
    Panel3: TPanel;
    procedure ActionList1Update(Action: TBasicAction; var Handled: Boolean);
    procedure ListView1ItemClick(const Sender: TObject;
      const AItem: TListViewItem);
    procedure Button4Click(Sender: TObject);
    procedure Button3Click(Sender: TObject);
    procedure Button5Click(Sender: TObject);
    procedure Button6Click(Sender: TObject);
    procedure Button7Click(Sender: TObject);
    procedure Button8Click(Sender: TObject);
    procedure Button9Click(Sender: TObject);
  private
    { Private declarations }
    function FindListBox(const AObj: TFmxObject): TListBox;
    function GetIsFilled(const AList: TListBox): Boolean;
  public
    IDSelecionado: String;
  end;

var
  FrameAtual: TFrame;

implementation

{$R *.fmx}

uses UDataModule, UPegaSubGrupo, UPegaUnidade, UPegaTipoRequisicao,
  UPegaColaborador, UCompraRequisicaoD;

// pega a ListBox
function TFCompraRequisicaoM.FindListBox(const AObj: TFmxObject): TListBox;
var
  Obj: TFmxObject;
begin
  Result := nil;
  if AObj.ChildrenCount > 0 then
  begin
    for Obj in AObj.Children do
    begin
      if Obj is TListBox then
        Result := TListBox(Obj)
      else
        Result := FindListBox(Obj);

      if Result <> nil then
        Exit(Result);
    end;
  end;
end;

// verifica se os itens da ListBox estão preenchidos
function TFCompraRequisicaoM.GetIsFilled(const AList: TListBox): Boolean;
var
  I: Integer;
  Item: TListBoxItem;
  Obj: TFmxObject;
begin
  Result := True;
  (*
  for I := 0 to AList.Count - 1 do
  begin
    Item := AList.ItemByIndex(I);
    for Obj in Item.Children do
    begin
      if Obj is TEdit then
        Result := TEdit(Obj).Text <> '';
      if Obj is TDateEdit then
        Result := not TDateEdit(Obj).IsEmpty;
      if Obj is TComboBox then
        Result := TComboBox(Obj).ItemIndex >= 0;

      if not Result then
        Exit(Result);
    end;
    if not Result then
      Exit(Result);
  end;
  *)
end;

procedure TFCompraRequisicaoM.Button3Click(Sender: TObject);
var
 vError : String;
begin
  RESTDWClientSQL1.FieldByName('ID_COMPRA_TIPO_REQUISICAO').AsString := Copy(Edit1.Text, 1, pos('|', Edit1.Text)-1);
  RESTDWClientSQL1.FieldByName('ID_COLABORADOR').AsString := Copy(Edit2.Text, 1, pos('|', Edit2.Text)-1);

  RESTDWClientSQL1.Post;

  If Not RESTDWClientSQL1.ApplyUpdates(vError) Then
    MessageDlg(vError, TMsgDlgType.mtError, [TMsgDlgBtn.mbOK], 0);

  RESTDWClientSQL1.Last;
  IDSelecionado := RESTDWClientSQL1.FieldByName('ID').AsString;
  //

  if Assigned(FrameAtual) then
    FreeAndNil(FrameAtual);
  FrameAtual := TFCompraRequisicaoD.Create(Panel3);

  with FrameAtual do
  begin
    Parent := Panel3;
    Align := FMX.Types.TAlignLayout.Client;
  end;

  Panel1.Visible := False;
end;

procedure TFCompraRequisicaoM.Button4Click(Sender: TObject);
begin
  RESTDWClientSQL1.Cancel;
  TabControl1.SetActiveTabWithTransition(TabItem3, TTabTransition.Slide);
end;

procedure TFCompraRequisicaoM.Button5Click(Sender: TObject);
begin
  RESTDWClientSQL1.Insert;
  TabControl1.SetActiveTabWithTransition(TabItem1, TTabTransition.Slide);
end;

procedure TFCompraRequisicaoM.Button6Click(Sender: TObject);
begin
  RESTDWClientSQL1.Active := False;
  RESTDWClientSQL1.SQL.Clear;
  RESTDWClientSQL1.SQL.Add('select * from compra_requisicao');
  try
    RESTDWClientSQL1.Active := True;
  except
    on E: Exception do
    begin
      raise Exception.Create('Erro ao executar a consulta: ' + sLineBreak + E.Message);
    end;
  end;
end;

procedure TFCompraRequisicaoM.Button7Click(Sender: TObject);
var
 vError : String;
begin
  FDataModule.RESTDWClientSQLGeneric.Active := False;
  FDataModule.RESTDWClientSQLGeneric.SQL.Clear;
  FDataModule.RESTDWClientSQLGeneric.SQL.Add('select * from compra_requisicao_detalhe where ID_COMPRA_REQUISICAO = ' + IDSelecionado);
  FDataModule.RESTDWClientSQLGeneric.Active := True;

  if FDataModule.RESTDWClientSQLGeneric.RecordCount > 0 then
    ShowMessage('Impossível excluir. Requisição possui itens.')
  else
  begin
    RESTDWClientSQL1.Delete;

    If Not RESTDWClientSQL1.ApplyUpdates(vError) Then
      MessageDlg(vError, TMsgDlgType.mtError, [TMsgDlgBtn.mbOK], 0);
    TabControl1.SetActiveTabWithTransition(TabItem3, TTabTransition.Slide);
  end;
end;

procedure TFCompraRequisicaoM.Button8Click(Sender: TObject);
begin
  Application.CreateForm(TFPegaTipoRequisicao, FPegaTipoRequisicao);
  FPegaTipoRequisicao.ShowModal;
  Edit1.Text := FPegaTipoRequisicao.Selecionado;
end;

procedure TFCompraRequisicaoM.Button9Click(Sender: TObject);
begin
  Application.CreateForm(TFPegaColaborador, FPegaColaborador);
  FPegaColaborador.ShowModal;
  Edit2.Text := FPegaColaborador.Selecionado;
end;

procedure TFCompraRequisicaoM.ListView1ItemClick(const Sender: TObject; const AItem: TListViewItem);
begin
  FPegaTipoRequisicao.RESTDWClientSQL1.Active := False;
  FPegaTipoRequisicao.RESTDWClientSQL1.SQL.Clear;
  FPegaTipoRequisicao.RESTDWClientSQL1.SQL.Add('select * from compra_tipo_requisicao where id=' + RESTDWClientSQL1.FieldByName('ID_COMPRA_TIPO_REQUISICAO').AsString);
  try
    FPegaTipoRequisicao.RESTDWClientSQL1.Active := True;
  except
    on E: Exception do
    begin
      raise Exception.Create('Erro ao executar a consulta: ' + sLineBreak + E.Message);
    end;
  end;
  Edit1.Text := FPegaTipoRequisicao.RESTDWClientSQL1.FieldByName('ID').AsString + '|' + FPegaTipoRequisicao.RESTDWClientSQL1.FieldByName('NOME').AsString;

  FPegaColaborador.RESTDWClientSQL1.Active := False;
  FPegaColaborador.RESTDWClientSQL1.SQL.Clear;
  FPegaColaborador.RESTDWClientSQL1.SQL.Add('select * from colaborador where id=' + RESTDWClientSQL1.FieldByName('ID_COLABORADOR').AsString);
  try
    FPegaColaborador.RESTDWClientSQL1.Active := True;
  except
    on E: Exception do
    begin
      raise Exception.Create('Erro ao executar a consulta: ' + sLineBreak + E.Message);
    end;
  end;
  // Dica: crie uma view no banco de dados para pegar o nome do empregado
  Edit2.Text := FPegaColaborador.RESTDWClientSQL1.FieldByName('ID').AsString + '|' + FPegaColaborador.RESTDWClientSQL1.FieldByName('MATRICULA').AsString;

  // Necessário porque o campo de lookup não tem binding e se o usuário alterar apenas ele ocorrerá um erro de edit not in edit or insert mode
  RESTDWClientSQL1.Edit;

  // Remove os detalhes. Pense numa maneira de recarregar os detalhes aqui.
  if Assigned(FrameAtual) then
    FreeAndNil(FrameAtual);
  Panel1.Visible := True;

  IDSelecionado := RESTDWClientSQL1.FieldByName('ID').AsString;

  NextTabAction.Execute;
end;

procedure TFCompraRequisicaoM.ActionList1Update(Action: TBasicAction; var Handled: Boolean);
var
  LTab: TTabItem;
  LList: TListBox;
begin
  LTab := TabControl1.ActiveTab;

  (*
  if Action = NextTabAction then
  begin
    LList := FindListBox(LTab);
    if LList <> nil then
      NextTabAction.Enabled := GetIsFilled(LList);
  end;
  *)

  if Action = TitleAction then
    TitleAction.Text := LTab.Text;

  if LTab.Name = 'TabItem3' then
  begin
    Button1.Visible := False;
    Button6.Visible := True;
    Button5.Visible := True;
  end
  else
  begin
    Button1.Visible := True;
    Button6.Visible := False;
    Button5.Visible := False;
  end;
end;

end.
