unit uEditorComision;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, uEditorDBItem, ToolWin, ComCtrls, JvExControls, JvComponent,
  uViewComision, JvNavigationPane, ActnList,
  uEditorBase, StdActns, TB2Dock, TB2Toolbar, TBX, ImgList, PngImageList,
  TB2Item, uEditorItem, DB, uDADataTable, uEditorDBBase, JvFormAutoSize,
  uDAScriptingProvider, uDACDSDataTable, StdCtrls, pngimage, ExtCtrls,
  TBXDkPanels, JvButton, AppEvnts, uCustomView, uViewBase,
  JvAppStorage, JvAppRegistryStorage, JvFormPlacement, JvComponentBase,
  cxCustomData, uBizComisiones,
  uIEditorComision, uComisionesController, JvExComCtrls,
  JvStatusBar, dxLayoutLookAndFeels, uViewGridBase, uViewGrid,
  uViewDetallesGenerico, uViewFacturasComision, dxLayoutControl, cxControls,
  uViewTotales, uDAInterfaces, uViewVendedoresComision;

type
  TfEditorComision = class(TfEditorDBItem, IEditorComision)
    TBXSubmenuItem2: TTBXSubmenuItem;
    TBXItem7: TTBXItem;
    frViewComision1: TfrViewComision;
    frViewFacturasComision1: TfrViewFacturasComision;
    dxLayoutControl1Group_Root: TdxLayoutGroup;
    dxLayoutControl1: TdxLayoutControl;
    dxLayoutControl1Group1: TdxLayoutGroup;
    dxLayoutControl1Item1: TdxLayoutItem;
    frViewTotales1: TfrViewTotales;
    frViewVendedoresComision1: TfrViewVendedoresComision;
    dxLayoutControl1Item2: TdxLayoutItem;
    dxLayoutControl1Group2: TdxLayoutGroup;
    procedure FormShow(Sender: TObject);
    procedure CustomEditorClose(Sender: TObject; var Action: TCloseAction);

    procedure JvFormStorageRestorePlacement(Sender: TObject);
    procedure JvFormStorageSavePlacement(Sender: TObject);
    procedure dsDataTableDataChange(Sender: TObject; Field: TField);
    procedure OnFacturasComisionAfterSummary(ASender: TcxDataSummary);
    procedure OnVendedoresComisionAfterSummary(ASender: TcxDataSummary);
    procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); override;
    procedure OnComisionChanged(Sender: TObject);
    //Importante, es donde deben quitarse eventos para que afecten a la tabla una vez que se cierre el editor

  private
    FImporteTotalFacturas: Variant;
    FImporteTotalVendedores: Variant;
    FTotalVendedores: Variant;

  protected
    FController : IComisionesController;
    FComision: IBizComisiones;
    FViewComision : IViewComision;

    function GetController : IComisionesController;
    procedure SetController (const Value : IComisionesController); virtual;
    function GetComision: IBizComisiones; virtual;
    procedure SetComision(const Value: IBizComisiones); virtual;
    function GetViewComision: IViewComision;
    procedure SetViewComision(const Value: IViewComision);
    property ViewComision: IViewComision read GetViewComision write SetViewComision;

    procedure GuardarInterno; override;
    procedure EliminarInterno; override;
    procedure PrevisualizarInterno; override;
    procedure ImprimirInterno; override;

    procedure PonerTitulos(const ATitulo: string = ''); override;
    function GetModified: Boolean; override;

  public
    property Comision: IBizComisiones read GetComision write SetComision;
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
  end;

implementation

{$R *.dfm}

uses
  uDataTableUtils, uDataModuleUsuarios, uDialogUtils, uCustomEditor,
  uDataModuleBase;

{
******************************* TfEditorComision *******************************
}
function TfEditorComision.GetComision: IBizComisiones;
begin
  Result := FComision;
end;

function TfEditorComision.GetController: IComisionesController;
begin
  Result := FController;
end;

function TfEditorComision.GetModified: Boolean;
var
  bCambiado : Boolean;
begin
  bCambiado := inherited GetModified;
  //Si no hay cambios miramos que no los halla en la lista de recibos
  if not bCambiado then
     bCambiado := frViewFacturasComision1.Modified;
  Result := bCambiado;
end;

function TfEditorComision.GetViewComision: IViewComision;
begin
  Result := FViewComision;
end;

procedure TfEditorComision.GuardarInterno;
var
  bEsNuevo : Boolean;
begin
  inherited;

  ShowHourglassCursor;
  frViewFacturasComision1.OnViewModified := Nil;
  //frViewDetallesFacturaCliente1.SaveGridStatus; // Para guardar estado del grid
  frViewFacturasComision1.cxGrid.ActiveView.BeginUpdate;  // Para que no se mueva el foco
  frViewVendedoresComision1.cxGrid.ActiveView.BeginUpdate;  // Para que no se mueva el foco
  try
    bEsNuevo := FComision.EsNuevo;
    FController.Guardar(FComision);

  finally
    frViewFacturasComision1.cxGrid.ActiveView.EndUpdate;
    frViewVendedoresComision1.cxGrid.ActiveView.EndUpdate;    
//    frViewDetallesFacturaCliente1.RestoreGridStatus;
    HideHourglassCursor;
  end;

  if bEsNuevo then
    ShowInfoMessage('La liquidación de comisiones se ha dado de alta con el código ' + FComision.REFERENCIA);
  Modified := False;
  frViewFacturasComision1.Modified := False;
//  frViewFacturasComision1.OnViewModified := OnFacturasChanged;
end;

procedure TfEditorComision.ImprimirInterno;
begin
  inherited;
  if (Application.MessageBox('¿Desea previsualizar la liquidación de comisiones sin desglosar?', 'Atención', MB_YESNO) = IDYES) then
     FController.Print(FComision, False)
  else
     FController.Print(FComision, True);
end;

procedure TfEditorComision.JvFormStorageRestorePlacement(Sender: TObject);
begin
  inherited;
  //frViewRecibosComision1.RestoreFromRegistry(JvAppRegistryStorage.Root);
end;

procedure TfEditorComision.JvFormStorageSavePlacement(Sender: TObject);
begin
  inherited;
  //frViewRecibosComision1.StoreToRegistry(JvAppRegistryStorage.Root);
end;

procedure TfEditorComision.PonerTitulos(const ATitulo: string);
var
  FTitulo : String;
begin
  FTitulo := ATitulo;
  if (FTitulo = '') and Assigned(Comision) then
  begin
    if Comision.EsNuevo then
      FTitulo := 'Nueva liquidación de comisiones'
    else
      FTitulo := 'Liquidación de comisiones';
  end;

  inherited PonerTitulos(FTitulo);

//  Self.Caption := FTitulo + ' (' + AppFactuGES.EmpresaActiva.NOMBRE + ')';
end;

procedure TfEditorComision.PrevisualizarInterno;
begin
  inherited;
  if (Application.MessageBox('¿Desea previsualizar la liquidación de comisiones sin desglosar?', 'Atención', MB_YESNO) = IDYES) then
     FController.Preview(FComision, False)
  else
     FController.Preview(FComision, True);
end;

procedure TfEditorComision.SetComision(const Value: IBizComisiones);
begin
  FComision := Value;
  if Assigned(FComision) then
  begin
     dsDataTable.DataTable := FComision.DataTable;
     frViewFacturasComision1.Comision := FComision;
     frViewVendedoresComision1.Comision := FComision;
  end
  else
  begin
     dsDataTable.DataTable := Nil;
     frViewFacturasComision1.Comision := Nil;
     frViewVendedoresComision1.Comision := Nil;
  end;

  if Assigned(FViewComision) then
     FViewComision.Comision := FComision;

  frViewTotales1.DADataSource.DataTable := dsDataTable.DataTable;
end;

procedure TfEditorComision.SetController(const Value: IComisionesController);
begin
  FController := Value;
  if Assigned(FController) then
  begin
    frViewFacturasComision1.Controller := FController;
    frViewVendedoresComision1.Controller := FController;    
  end;
end;

procedure TfEditorComision.SetViewComision(const Value: IViewComision);
begin
  FViewComision := Value;

  if Assigned(FViewComision) and Assigned(Comision) then
  begin
    FViewComision.Comision := Comision;
//    FViewComision.Controller := (FController as IComisionesController);
  end;
end;

procedure TfEditorComision.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
  frViewFacturasComision1.cxGridView.DataController.Summary.OnAfterSummary := Nil;
  frViewVendedoresComision1.cxGridView.DataController.Summary.OnAfterSummary := Nil;
  frViewVendedoresComision1.cxGridViewCOMISION.Properties.OnEditValueChanged := Nil;

  inherited;
end;

procedure TfEditorComision.FormShow(Sender: TObject);
begin
  inherited;

  if not Assigned(FViewComision) then
    raise Exception.Create('No hay ninguna vista asignada');

  if not Assigned(Comision) then
    raise Exception.Create('No hay ningún almacén asignado');

  frViewFacturasComision1.cxGridView.DataController.Summary.OnAfterSummary := OnFacturasComisionAfterSummary;
  frViewVendedoresComision1.cxGridView.DataController.Summary.OnAfterSummary := OnVendedoresComisionAfterSummary;
  frViewVendedoresComision1.cxGridViewCOMISION.Properties.OnEditValueChanged := OnComisionChanged;

  Comision.DataTable.Active := True;
end;

procedure TfEditorComision.OnComisionChanged(Sender: TObject);
begin
  inherited;

  FImporteTotalFacturas := frViewFacturasComision1.cxGridView.DataController.Summary.FooterSummaryValues[1];
  //Recalculamos comisiones
  if Assigned(FController)
     and (not VarIsNull(FImporteTotalFacturas))
     and (FImporteTotalFacturas > 0) then
     begin
      if Comision.Vendedores.DataTable.Editing then
         Comision.Vendedores.post; //fallo componente no se enteraría del cambio

      FController.RecalcularComisiones(Comision, FImporteTotalFacturas);
     end;
end;

procedure TfEditorComision.OnFacturasComisionAfterSummary(ASender: TcxDataSummary);
begin
  inherited;

  if (FImporteTotalFacturas <> ASender.FooterSummaryValues[1]) then
  begin
     FImporteTotalFacturas := ASender.FooterSummaryValues[1];

     //Recalculamos comisiones
     if Assigned(FController)
     and (not VarIsNull(FImporteTotalFacturas))
     and (FImporteTotalFacturas > 0) then
        FController.RecalcularComisiones(Comision, FImporteTotalFacturas);
  end;
end;

procedure TfEditorComision.OnVendedoresComisionAfterSummary(ASender: TcxDataSummary);
begin
  inherited;

  if (FTotalVendedores <> ASender.FooterSummaryValues[2]) then
  begin
     FTotalVendedores := ASender.FooterSummaryValues[2];

     //Recalculamos comisiones
     if Assigned(FController)
     and (not VarIsNull(FImporteTotalFacturas))
     and (FImporteTotalFacturas > 0) then
        FController.RecalcularComisiones(Comision, FImporteTotalFacturas);
  end;

  if (FImporteTotalVendedores <> ASender.FooterSummaryValues[1]) then
  begin
    FImporteTotalVendedores := ASender.FooterSummaryValues[1];

    //Asignamos el importe total de las comisiones
    if Assigned(FController) then
       FController.AsignarImporteTotal(Comision, FImporteTotalVendedores);
  end;
end;

destructor TfEditorComision.Destroy;
begin
  // Utilizar mejor OnClose;
  inherited;
end;

procedure TfEditorComision.dsDataTableDataChange(Sender: TObject; Field: TField);
begin
  inherited;
  ActualizarEstadoEditor;
end;

constructor TfEditorComision.Create(AOwner: TComponent);
begin
  inherited;
  FImporteTotalFacturas := -1;
  FImporteTotalVendedores := -1;
  FTotalVendedores := -1;
  pgPaginas.ActivePageIndex := 0;
  FViewComision := frViewComision1;
end;

procedure TfEditorComision.CustomEditorClose(Sender: TObject;
  var Action: TCloseAction);
begin
  inherited;

  dsDataTable.DataTable := NIL;
  FViewComision := NIL;
  FComision := NIL;
end;

procedure TfEditorComision.EliminarInterno;
begin
  if (Application.MessageBox('¿Desea borrar esta liquidación de comisiones?', 'Atención', MB_YESNO) = IDYES) then
  begin
    inherited;
    //Quitamos los eventos antes de eliminar para que no intercedan en la operacion
    frViewFacturasComision1.cxGridView.DataController.Summary.OnAfterSummary := Nil;
    frViewVendedoresComision1.cxGridView.DataController.Summary.OnAfterSummary := Nil;
    frViewVendedoresComision1.cxGridViewCOMISION.Properties.OnEditValueChanged := Nil;

    if not FController.Eliminar(FComision) then
       actRefrescar.Execute;
  end;
end;

end.
