unit ituCadastroBasicoV41;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, ExtCtrls, Buttons, JvGradient, utuFactory,
  StdCtrls, ActnList, JvExControls, JvComponent, JvSpeedButton,
  TypInfo, ComCtrls, ituExceptionDetailsDialog, ituInterfaceFactory, ituVCLUIController,
  utuMessage, utuMessageQueue, XMLIntf, msxmldom, XMLDoc, ituUIController;

Const
  cInserir   = '1';
  cConsultar = '2';
  cAtualizar = '3';
  cExcluir   = '4';

type
  TStatus = (StInsert, StDelete, StUpdate, StSelect, StBrowse);

  TPermissao = set of (AcInsert, AcUpdate, AcDelete);

  TitCadastroBasicoV41 = class(itInterfaceForm)
    pnPrincipal: TPanel;
    pnMenuSuperior: TPanel;
    jvGradientSuperior: TJvGradient;
    pnDivisor: TPanel;
    FlowPanel1: TFlowPanel;
    sbNovo: TJvSpeedButton;
    sbSalvar: TJvSpeedButton;
    sbEditar: TJvSpeedButton;
    sbExcluir: TJvSpeedButton;
    sbSair: TJvSpeedButton;
    procedure sbSairClick(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure FormCreate(Sender: TObject);
    procedure sbEditarClick(Sender: TObject);
    procedure FormShow(Sender: TObject);
    procedure sbSalvarClick(Sender: TObject);
    procedure sbExcluirClick(Sender: TObject);
    procedure sbNovoClick(Sender: TObject);
  private
    { Private declarations }
  protected
    hasSearchBeforeNewObject: boolean;
    procedure SetReadOnly(Control: TWinControl; value: Boolean);
    procedure HabilitaEdicao; virtual;
    procedure DesabilitaEdicao; virtual;
    procedure LimpaCampos(Control: TWinControl);
  public
    { Public declarations }
    permissao: TPermissao;
    status: TStatus;
    procedure VerificaPermissoes();
    procedure CadastrarNovoObjeto; virtual;
  end;

  itCadastroBasicoV4 = class(itInterface)
  protected
//    fNewTarget : boolean;
    fOID       : string;
    procedure SetPermissionsToInteraface(piOperationsNode: utField);
    procedure SendToInterface(piRequest: acRequest); virtual;
    procedure SaveFromInterface(piRequest: acRequest);virtual; abstract;
    procedure SalvaObjeto(piRequest: acRequest);virtual;
    procedure ExcluirObjeto(piRequest: acRequest);virtual;
    procedure EditaObjeto(piRequest: acRequest);virtual;
    procedure ConsultaObjeto(piRequest: acRequest);virtual;
    procedure Delete;
    procedure Edita;
    procedure Inserir;
    procedure Consultar;
    procedure GetTargetObjectsData(piRequest: acRequest);virtual;abstract;
  public
    procedure Save;
  end;

implementation

uses acuObject;

{$R *.dfm}

procedure TitCadastroBasicoV41.HabilitaEdicao;
begin
  SetReadOnly(self,false);
end;

procedure TitCadastroBasicoV41.SetReadOnly(Control: TWinControl; value: Boolean);
var
  I: Integer;
begin
  for I := 0 to Control.ControlCount - 1 do
  begin
    if (Control.Controls[i] <> pnMenuSuperior) then
    begin
      try
        if IsPublishedProp(Control.Controls[i],'ReadOnly') then
          SetPropValue(Control.Controls[i],'ReadOnly', value)
        else if //not(control is TPanel)
                not(Control.Controls[i] is TLabel)
                and not(Control.Controls[i] is TPanel)
                and not(Control.Controls[i] is TGroupBox)
                and not(Control.Controls[i] is TPageControl)
                and not(Control.Controls[i] is TTabSheet) then
          Control.Controls[i].Enabled := not value;
      except
        raise;
      end;
      if (Control.Controls[i] is TWinControl)
         and (TWinControl(Control.Controls[i]).ControlCount > 0) then
             SetReadOnly(TWinControl(Control.Controls[i]),value);
    end;
  end;
end;

procedure TitCadastroBasicoV41.DesabilitaEdicao;
begin
  SetReadOnly(self,true);
end;

procedure TitCadastroBasicoV41.LimpaCampos(Control: TWinControl);
var
  I: Integer;
begin
  for I := 0 to Control.ControlCount - 1 do
  begin
    if (Control.Controls[i] <> pnMenuSuperior) then
    begin
      try
        if IsPublishedProp(Control.Controls[i],'Text') then
          SetPropValue(Control.Controls[i],'Text', '');
        if IsPublishedProp(Control.Controls[i],'ItemIndex') then
          SetPropValue(Control.Controls[i],'ItemIndex', -1);
        if IsPublishedProp(Control.Controls[i],'Checked') then
          SetPropValue(Control.Controls[i],'Checked', false)
      except
        raise;
      end;
      if (Control.Controls[i] is TWinControl)
         and (TWinControl(Control.Controls[i]).ControlCount > 0) then
             LimpaCampos(TWinControl(Control.Controls[i]));
    end;
  end;
end;

procedure TitCadastroBasicoV41.VerificaPermissoes();
begin
  if ((status = stInsert) and (AcInsert in permissao)) then
  begin
    sbNovo.Enabled := False;
    sbEditar.Enabled := False;
    sbExcluir.Enabled := status = stUpdate;
    sbSalvar.Enabled := True;
    HabilitaEdicao;
  end
  else
    if (status = stUpdate) and (AcUpdate in permissao) then
    begin
      sbNovo.Visible := False;
      sbEditar.Visible := true;
      sbExcluir.Visible := False;
      sbSalvar.Visible := true;

      sbEditar.Enabled := False;
      sbSalvar.Enabled := True;
      HabilitaEdicao;
    end
    else
      if (status = stBrowse) then
      begin
        sbNovo.Visible := False;
        sbEditar.Visible := False;
        sbExcluir.Visible := False;
        sbSalvar.Visible := False;
      end
      else
        if(status = StDelete)  then
        begin
          sbNovo.Visible := False;
          sbEditar.Visible := False;
          sbExcluir.Visible := True;
          sbSalvar.Visible := False;

          sbExcluir.Enabled := true;
        end
        else
        begin
          sbNovo.Enabled := true;
          sbEditar.Enabled := true;
          sbExcluir.Enabled := true;
          sbSalvar.Enabled := False;
        end;
end;


procedure TitCadastroBasicoV41.sbEditarClick(Sender: TObject);
begin
  inherited;
  with (self.Controller as itCadastroBasicoV4)  do
  begin
//    fNewTarget := false;
   (self.Controller as itCadastroBasicoV4).Edita;
    SetPermissionsToInteraface(nil);
  end;

end;

procedure TitCadastroBasicoV41.sbExcluirClick(Sender: TObject);
begin
  if MessageDlg('Confirma a exclusão do objeto?', mtConfirmation, [mbYes,mbNo], 0) = mrYes then
  begin
    (self.Controller as itCadastroBasicoV4).Delete;
    status := stDelete;
    VerificaPermissoes;
  end;
end;

procedure TitCadastroBasicoV41.sbNovoClick(Sender: TObject);
begin
  with (self.Controller as itCadastroBasicoV4)  do
  begin
    Inserir;
//    fNewTarget := true;
    fOID       := '';
    SetPermissionsToInteraface(nil);
  end;
end;

procedure TitCadastroBasicoV41.FormShow(Sender: TObject);
begin
  inherited;
//  if SISAC_Util.GetDisplayColors <= 8 then
  jvGradientSuperior.Visible := false;
  if (status <> stInsert) and (status <> StUpdate) then DesabilitaEdicao
  else HabilitaEdicao;
end;

procedure TitCadastroBasicoV41.CadastrarNovoObjeto;
begin
  status := stInsert;
  VerificaPermissoes;
  LimpaCampos(self);
  HabilitaEdicao;
end;

procedure TitCadastroBasicoV41.FormCreate(Sender: TObject);
begin
  status := StBrowse;
  hasSearchBeforeNewObject := False;
end;

procedure TitCadastroBasicoV41.FormClose(Sender: TObject; var Action: TCloseAction);
const
  NOT_SAVED_MSG = 'Existem dados que ainda não foram salvos.' + #13 +
                  'Deseja realmente sair?';
begin
  if ((status = stInsert) or (status = stUpdate)) and
     (MessageDlg(NOT_SAVED_MSG, mtConfirmation, [mbYes, mbNo], 0) = mrNo)
    then Action := caNone
    else Action := caFree;
end;

procedure TitCadastroBasicoV41.sbSairClick(Sender: TObject);
begin
  Close;
end;

procedure TitCadastroBasicoV41.sbSalvarClick(Sender: TObject);
begin
  (self.Controller as itCadastroBasicoV4).Save;
end;

{ itCadastroBasicoV4 }



procedure itCadastroBasicoV4.ConsultaObjeto(piRequest: acRequest);
begin

end;

procedure itCadastroBasicoV4.Consultar;
var lRequest : acRequest;
begin
  lRequest:= self.NewRequest('RM_CONSULTA_OBJETO',ConsultaObjeto);
  lRequest.Message.Fields.AddField('OBJECTID').AsString := fOID;
  lRequest.Post;
end;

procedure itCadastroBasicoV4.Delete;
var lRequest : acRequest;
begin
  lRequest:= self.NewRequest('RM_EXCLUI_OBJETO',ExcluirObjeto);
  lRequest.Message.Fields.AddField('OBJECTID').AsString := fOID;
  lRequest.Post;
end;

procedure itCadastroBasicoV4.Edita;
var lRequest : acRequest;
begin
  Screen.Cursor := crHourGlass;
  if Assigned(self.ContextObject) then
    fOID       := self.ContextObject.ObjectID;

  if trim(fOID) <> ''  then
  begin
//    fNewTarget := false;
    lRequest := self.NewRequest('RM_EDITA_OBJETO',GetTargetObjectsData);
    lRequest.Message.Fields.AddField('OBJECTID').AsString := fOID;
    lRequest.Post;
    with self.InterfaceForm as TitCadastroBasicoV41 do
    begin
      status := stUpdate;
      VerificaPermissoes;
      HabilitaEdicao;
    end;
  end;
end;

procedure itCadastroBasicoV4.EditaObjeto(piRequest: acRequest);
begin
  with self.InterfaceForm as TitCadastroBasicoV41 do
  begin
    status := stUpdate;
    VerificaPermissoes;
    HabilitaEdicao;
  end;
  Screen.Cursor := crDefault;

end;

procedure itCadastroBasicoV4.ExcluirObjeto(piRequest: acRequest);
begin
  ShowMessage('Registro excluído.');
end;


procedure itCadastroBasicoV4.Inserir;
begin
  if not Assigned(Self.ContextObject) then
  begin
    self.NewRequest('RM_INCLUI_OBJETO', GetTargetObjectsData).Post;
//    fNewTarget := true;
  end;
end;

procedure itCadastroBasicoV4.SalvaObjeto(piRequest: acRequest);
begin
  with self.InterfaceForm as TitCadastroBasicoV41 do
  begin
    sbNovo.Enabled := true;
    sbEditar.Enabled := true;
    sbExcluir.Enabled := true;
    sbSalvar.Enabled := false;
    status := StBrowse;
    DesabilitaEdicao;
  end;
end;

procedure itCadastroBasicoV4.Save;
var lMessage: acRequest;
begin
  lMessage := self.NewRequest('RM_SALVA_OBJETO', SalvaObjeto);
  Self.SaveFromInterface(lMessage);
  lMessage.Post;
end;

procedure itCadastroBasicoV4.SendToInterface(piRequest: acRequest);
begin
  if Assigned(Self.ContextObject) then
  begin
    if self.ContextObject.OperationCode = cInserir then
      raise Exception.Create('Operação de inserção(1) não requer objeto de contexto.')
    else
      if self.ContextObject.OperationCode = cAtualizar then
      begin
        self.Edita;
       (self.InterfaceForm as TitCadastroBasicoV41).status := StUpdate;
      end
        else if self.ContextObject.OperationCode = cExcluir then
        begin
          self.Edita;
         (self.InterfaceForm as TitCadastroBasicoV41).status := StDelete;
        end
          else if self.ContextObject.OperationCode = cConsultar then
          begin
            self.Edita;
           (self.InterfaceForm as TitCadastroBasicoV41).status := StBrowse;
          end
          else     //Quando tem contexto do objeto porem nao tem operação, considero
          begin    //"Atualizar" para compatibilizar com a interface antiga
            self.Edita;
           (self.InterfaceForm as TitCadastroBasicoV41).status := StUpdate;
          end;
  end
  else
  begin
//    if self.ContextObject.OperationCode = cInserir then
      self.Inserir;
     (self.InterfaceForm as TitCadastroBasicoV41).status := StInsert;
//    else if self.ContextObject.OperationCode = cAtualizar then
//      raise Exception.Create('Objeto de contexto deve ser informado para operação de atualização(3).')
//    else if self.ContextObject.OperationCode = cExcluir then
//      raise Exception.Create('Objeto de contexto deve ser informado para operação de exclusão(4).')
//    else if self.ContextObject.OperationCode = cConsultar then
//      raise Exception.Create('Objeto de contexto deve ser informado para operação de consulta(2).')
  end;

//  if fNewTarget  then
//     (self.InterfaceForm as TitCadastroBasicoV41).status := StInsert
//  else
//     (self.InterfaceForm as TitCadastroBasicoV41).status := stUpdate;

  self.SetPermissionsToInteraface(nil);
end;

procedure itCadastroBasicoV4.SetPermissionsToInteraface(
  piOperationsNode: utField);
var lTitCadastroBasico: TitCadastroBasicoV41;
//    lOperationNode: utField;
 //   lCode: integer;
 //   lmarc : acEnumerator;
begin
  lTitCadastroBasico := self.InterfaceForm as TitCadastroBasicoV41;

  lTitCadastroBasico.permissao := [acInsert,acUpdate,acDelete];
  {lmarc  := piOperationsNode.GetFieldsEnumerator;
  try
    while not lmarc.EOL  do
    begin
      lOperationNode := utField(lmarc.Current);
      lCode := lOperationNode.AttributeByName('Code').AsInteger;
      case lCode of
        1: lTitCadastroBasico.permissao := lTitCadastroBasico.permissao + [acInsert];
        3: lTitCadastroBasico.permissao := lTitCadastroBasico.permissao + [acUpdate];
        4: lTitCadastroBasico.permissao := lTitCadastroBasico.permissao + [acDelete];
      end;
      lmarc.MoveNext;
    end;
  finally
    lmarc.Free;
  end;:}
  lTitCadastroBasico.VerificaPermissoes;
end;


end.
