unit UEstoqueReajusteM;

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
  TFEstoqueReajusteM = 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;
    ListBoxItem1: TListBoxItem;
    Layout2: TLayout;
    Edit2: TEdit;
    Button9: TButton;
    Panel3: TPanel;
    ListBoxItem4: TListBoxItem;
    Edit4: TEdit;
    ListBoxItem5: TListBoxItem;
    ComboBox1: TComboBox;
    BindSourceDB1: TBindSourceDB;
    LinkControlToFieldDATA_REAJUSTE: TLinkControlToField;
    BindingsList1: TBindingsList;
    LinkControlToField1: TLinkControlToField;
    LinkListControlToField1: TLinkListControlToField;
    LinkFillControlToField1: TLinkFillControlToField;
    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 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, UEstoqueReajusteD;

// pega a ListBox
function TFEstoqueReajusteM.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 TFEstoqueReajusteM.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 TFEstoqueReajusteM.Button3Click(Sender: TObject);
var
 vError : String;
begin
  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 := TFEstoqueReajusteD.Create(Panel3);

  // consultar produtos
  FDataModule.RESTDWClientSQLGeneric.Active := False;
  FDataModule.RESTDWClientSQLGeneric.SQL.Clear;
  FDataModule.RESTDWClientSQLGeneric.SQL.Add('select * from produto');
  FDataModule.RESTDWClientSQLGeneric.Active := True;

  FDataModule.RESTDWClientSQLGeneric.First;
  while not FDataModule.RESTDWClientSQLGeneric.Eof do
  begin

    (FrameAtual as TFEstoqueReajusteD).RESTDWClientSQL1.Active := True;

    (FrameAtual as TFEstoqueReajusteD).RESTDWClientSQL1.Append;
    (FrameAtual as TFEstoqueReajusteD).RESTDWClientSQL1.FieldByName('ID_ESTOQUE_REAJUSTE_CABECALHO').AsString := IDSelecionado;
    (FrameAtual as TFEstoqueReajusteD).RESTDWClientSQL1.FieldByName('ID_PRODUTO').AsString := FDataModule.RESTDWClientSQLGeneric.FieldByName('ID').AsString;
    (FrameAtual as TFEstoqueReajusteD).RESTDWClientSQL1.FieldByName('VALOR_ORIGINAL').AsString := FDataModule.RESTDWClientSQLGeneric.FieldByName('VALOR_VENDA').AsString;
    if ComboBox1.ItemIndex = 0 then
    begin
      (FrameAtual as TFEstoqueReajusteD).RESTDWClientSQL1.FieldByName('VALOR_REAJUSTE').AsFloat :=
                (FDataModule.RESTDWClientSQLGeneric.FieldByName('VALOR_VENDA').AsFloat * StrToFloat(Edit4.Text) / 100) + FDataModule.RESTDWClientSQLGeneric.FieldByName('VALOR_VENDA').AsFloat;
    end
    else
    begin
      (FrameAtual as TFEstoqueReajusteD).RESTDWClientSQL1.FieldByName('VALOR_REAJUSTE').AsFloat :=
                FDataModule.RESTDWClientSQLGeneric.FieldByName('VALOR_VENDA').AsFloat - (FDataModule.RESTDWClientSQLGeneric.FieldByName('VALOR_VENDA').AsFloat * StrToFloat(Edit4.Text) / 100);
    end;
    (FrameAtual as TFEstoqueReajusteD).RESTDWClientSQL1.Post;
    If Not (FrameAtual as TFEstoqueReajusteD).RESTDWClientSQL1.ApplyUpdates(vError) Then
      MessageDlg(vError, TMsgDlgType.mtError, [TMsgDlgBtn.mbOK], 0);

    FDataModule.RESTDWClientSQLGeneric.next;
  end;

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


  Panel1.Visible := False;
end;

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

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

procedure TFEstoqueReajusteM.Button6Click(Sender: TObject);
begin
  RESTDWClientSQL1.Active := False;
  RESTDWClientSQL1.SQL.Clear;
  RESTDWClientSQL1.SQL.Add('select * from estoque_reajuste_cabecalho');
  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 TFEstoqueReajusteM.Button7Click(Sender: TObject);
var
 vError : String;
begin
  FDataModule.RESTDWClientSQLGeneric.Active := False;
  FDataModule.RESTDWClientSQLGeneric.SQL.Clear;
  FDataModule.RESTDWClientSQLGeneric.SQL.Add('select * from estoque_reajuste_detalhe where ID_ESTOQUE_REAJUSTE_CABECALHO = ' + IDSelecionado);
  FDataModule.RESTDWClientSQLGeneric.Active := True;

  if FDataModule.RESTDWClientSQLGeneric.RecordCount > 0 then
    ShowMessage('Impossível excluir. Reajuste do estoque 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 TFEstoqueReajusteM.Button9Click(Sender: TObject);
begin
  Application.CreateForm(TFPegaColaborador, FPegaColaborador);
  FPegaColaborador.ShowModal;
  Edit2.Text := FPegaColaborador.Selecionado;
end;

procedure TFEstoqueReajusteM.ListView1ItemClick(const Sender: TObject; const AItem: TListViewItem);
begin
  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 TFEstoqueReajusteM.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.
