unit acInput;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  StdCtrls, ExtCtrls, AcStruc, ExtUtils, IniFiles, acBase, acTblFrm, mteTypes, ComCtrls;

type
  TInputForm = class;
  TFieldPanel = class(TCustomPanel)
  private
    FForm: TInputForm;
    FRawValue: TStaticText;
    FField: TMicexField;
    FGroupIndex: Integer;
    FControl: TWinControl;
    procedure OnChange(Comp: TObject);
    procedure paDblClick(Sender: TObject);
  public
    constructor Create(AOwner: TInputForm; AField: TMicexField; ATop, AHeight: Integer); reintroduce;
    function Prev: TFieldPanel;
    function Next: TFieldPanel;
    function PrevIsSecBoard: Boolean;
  end;

  TPanelList = class(TList)
  private
    function GetPanel(AIndex: Integer): TFieldPanel;
  public
    function Last: TFieldPanel;
    property Panels[AIndex: Integer]: TFieldPanel read GetPanel; default;
  end;

  TInputForm = class(TBaseForm)
    paButtons: TPanel;
    cbRawValues: TCheckBox;
    btnMore: TButton;
    btnLess: TButton;
    btnOk: TButton;
    btnCancel: TButton;
    Bevel: TBevel;
    paRight: TPanel;
    paLeft: TPanel;
    paTop: TPanel;
    procedure ToggleRawValues(Sender: TObject);
    procedure MoreClick(Sender: TObject);
    procedure LessClick(Sender: TObject);
  private
    FFields: TList;
    FPanelList: TPanelList;
    // unhandled stuff
    FDecimals: Integer;
    FGroupCount: Integer;
    FGroupHeight: Integer;
    FSecList: TSecProps;
    FSecCodeList: TFirmProps;
    FFromMsg: PBaseMsgRec;
    procedure OnKeyPress(Sender: TObject; var Key: Char);
    function StrToNumber(const S: string; Fld: TMicexField): string;
    function HasVarBlock: Boolean;
    procedure CreateInputField(FieldPos: Integer; Field: TMicexField; var Params: string);
    procedure AdjustHeight;
    procedure AddGroup(var Params: string; Adjust: Boolean);
    procedure FormatNumbers;
  protected
    procedure UpdateActions; override;
  public
    procedure CreateParams(var Params: TCreateParams); override;
    destructor Destroy; override;
    function GetInputParams(const AId: string; var Params: string): Boolean;
{    property Fields: IFields read FFields;
    property Tsmr: TZTsmr read FTsmr;}
  end;

function GetInputParams(AMsg: TMicexMessage; const ACaption: string; AFields: TList; AIface: TMicexIface;
  out AParams: string; AFromMsg: PBaseMsgRec; ASecList: TSecProps; ASecCodeList: TFirmProps): Boolean;

implementation

uses TypInfo;

{$R *.dfm}

const
  SMALL_WIDTH     = 363;
  FULL_WIDTH      = 520;

resourcestring
  sRawValues      = '"Сырые" значения';
  sRawValueHint   = 'Строка, которая будет отправлена в торговую систему';

type
  THWinControl = class(TWinControl) end;

var
  ShowRawValues: Boolean = False;

function GetLastParam(Msg: TMicexMessage; Iface: TMicexIface): string;
const
  Prefixes: array [Boolean] of string = ('trn_', 'tbl_');
var
  Params: string;
  I: Integer;
begin
  with TIniFile.Create(IniFileName) do
  try
    Params := ReadString('ifc_' + Iface.Name, Prefixes[Msg.IsTable] + Msg.Name, '');
    I := 1;
    Result := '';
    while I <= Length(Params) do
    begin
      if Params[I] = '%' then
      begin
        Inc(I);
        if Params[I] = '%' then Result := Result + '%'
        else
        begin
          Result := Result + Char(StrToIntDef('$' + Copy(Params, I, 2), 32));
          Inc(I);
        end;
      end
      else Result := Result + Params[I];
      Inc(I);
    end;
  finally
    Free;
  end;
end;

function ConvertDateTimeToStr(const DT: TDateTime; FieldType: TTEFieldType): string;
begin
  if FieldType = ftDate then
    Result := FormatDateTime('yyyymmdd', DT)
  else
    Result := FormatDateTime('hhnnss', DT);
end;

function ConvertStrToDateTime(const S: string; FieldType: TTEFieldType): TDateTime;

  function GetNumber(Buf: PChar): Integer;
  begin
    Result := (Byte(Buf^) - Ord('0')) * 10 + Byte((Buf + 1)^) - Ord('0');
  end;

var
  P: PChar;
begin
  Result := -1;
  try
    if FieldType = ftDate then
      if Length(S) >= 8 then
      begin
        P := PChar(S);
        Result := EncodeDate(StrToInt(Copy(S, 1, 4)), GetNumber(P + 4), GetNumber(P + 6));
      end
      else
    else
      if Length(S) >= 6 then
      begin
        P := PChar(S);
        Result := EncodeTime(GetNumber(P), GetNumber(P + 2), GetNumber(P + 4), 0);
      end;
  except
  end;
end;

function ConvertInteger(AValue: string; ASize: Integer; AType: TTEFieldType; Decimals: Integer): string;
var
  PointPos, Index, PointLen: Integer;
begin
  if (AType <> ftFLoatPoint) and (Decimals >= 0) then
  begin
    PointPos := LastDelimiter('.,' + FormatSettings.DecimalSeparator, AValue);
    if PointPos > 0 then PointLen := Length(AValue) - PointPos else PointLen := 0;
    if PointLen < Decimals then
      for Index := 1 to Decimals - PointLen do
        AValue := AValue + '0'
    else
      if PointLen > Decimals then
        for Index := 1 to PointLen - Decimals do
          Delete(AValue, Length(AValue), 1);
  end;

  if AType = ftFloatPoint then
    AValue := StringReplace(StringReplace(AValue, ',', '.', []), FormatSettings.DecimalSeparator, '.', [])
  else begin
    PointPos := LastDelimiter('.,' + FormatSettings.DecimalSeparator, AValue);
    if PointPos > 0 then Delete(AValue, PointPos, 1);
  end;

  if (AValue <> '') and (AValue[1] = '-') then Index := 2 else Index := 1;
  while Length(AValue) < ASize do Insert('0', AValue, Index);
  while Length(AValue) > ASize do Delete(AValue, Index, 1);
  Result := Copy(AValue, 1, ASize);
end;

function ConvertParameter(const AValue: string; AKind: TTEFieldType;
  ASize: Integer; Decimals: Integer): string;
var
  S: string;
begin
  case AKind of
    ftFixed, ftFloat, ftInteger, ftFloatPoint:
      if Trim(AValue) = '' then S := EPadRight(AValue, ASize)
      else
        case AKind of
          ftFixed: S := ConvertInteger(AValue, ASize, AKind, 2);
          ftFloat: S := ConvertInteger(AValue, ASize, AKind, Decimals);
          ftFloatPoint: S := ConvertInteger(AValue, ASize, AKind, -1);
          else S := ConvertInteger(AValue, ASize, AKind, 0);
        end;

    else S := EPadRight(AValue, ASize);
  end;
  SetString(Result, PChar(S), ASize);
end;

function StripField(var S: string; Size: Integer; AType: TTEFieldType): string;
var
  Decimals: Integer;
begin
  Result := Trim(Copy(S, 1, Size));
  if (Result <> '') then
    if (AType in [ftInteger, ftFixed, ftFloat]) then
    begin
      if AType = ftFixed then Decimals := 2 else Decimals := 0;
      Result := EFormatNumber(Result, Decimals);
    end else if AType = ftFloatPoint then
      Result := FormatFloatPoint(Result);
  Delete(S, 1, Size);
end;

function GetFieldHint(Fld: TMicexField): string;
var
  SizeStr: string;
begin
  Result := Copy(GetEnumName(TypeInfo(TTEFieldType),
    Integer(Fld.FieldType)), 3, MaxInt);

  if Fld.Decimals > 0 then FmtStr(SizeStr, '%d.%d', [Fld.Size, Fld.Decimals])
  else SizeStr := IntToStr(Fld.Size);

  if Assigned(Fld.EnumPtr) then
    SizeStr := SizeStr + ' (' + Fld.EnumPtr.Name + ')';

  Result := Result + ': ' + SizeStr + sLineBreak + Fld.Caption;
end;

function GetMinNeededLength(Fields: TList): Integer;
var
  I: Integer;
begin
  Result := 0;
  for I := 0 to Fields.Count - 1 do
    with TMicexField(Fields[I]) do
      if Flags and ffVarBlock = 0 then Inc(Result, Size);
end;

function GetFieldFromMsg(FieldId: string; FromMsg: PBaseMsgRec; AType: TTEFieldType): string;
var
  FieldIndex, Decimals: Integer;
begin
  Result := '';
  if Assigned(FromMsg) then
    with FromMsg^ do
    begin
      if SameText(Msg.Name, 'BCMESSAGES') then
      begin
        if SameText(FieldId, 'USERIDTO') then FieldId := 'FROMUSER';
      end;

      if Msg.OutFields.Find(FieldId, FieldIndex) then
      begin
        Result := Rows.Values[RowNum, FieldIndex];
        if (Result <> '') then
          if (AType in [ftInteger, ftFixed, ftFloat]) then
          begin
            if AType = ftFixed then Decimals := 2 else Decimals := 0;
            Result := EFormatNumber(Result, Decimals);
          end else if AType = ftFloatPoint then
            Result := FormatFloatPoint(Result);
      end
    end;
end;

function GetInputParams(AMsg: TMicexMessage; const ACaption: string; AFields: TList; AIface: TMicexIface;
  out AParams: string; AFromMsg: PBaseMsgRec; ASecList: TSecProps; ASecCodeList: TFirmProps): Boolean;
begin
  if not Assigned(AFields) or (AFields.Count = 0) then
  begin
    AParams := '';
    Result := True;
    Exit;
  end;

  AParams := GetLastParam(AMsg, AIface);
  with TInputForm.Create(Application) do
  try
    FFields := AFields;
    FSecList := ASecList;
    FSecCodeList := ASecCodeList;
    FFromMsg := AFromMsg;
    Caption := ACaption;
    Result := GetInputParams(ACaption, AParams);
  finally
    Free;
  end;
end;

{ TInputForm }

procedure TInputForm.CreateParams(var Params: TCreateParams);
begin
  inherited;
  Params.WndParent := Screen.Forms[0].Handle;
  FDecimals := -1;
end;

destructor TInputForm.Destroy;
begin
  FreeAndNil(FPanelList);
  inherited;
end;

procedure TInputForm.ToggleRawValues(Sender: TObject);
const
  Widths: array [Boolean] of Integer = (SMALL_WIDTH, FULL_WIDTH);
begin
  Width := Widths[(Sender as TCheckBox).Checked];
end;

function TInputForm.StrToNumber(const S: string; Fld: TMicexField): string;
begin
  Result := Trim(S);
  if Result <> '' then
  if (Fld.FieldType in [ftFixed, ftFloat]) and (LastDelimiter('.,' + FormatSettings.DecimalSeparator, S) = 0) then
  begin
    if Fld.Decimals < 0 then Result := EFormatNumber(S, FDecimals)
    else Result := EFormatNumber(S, Fld.Decimals);
  end else
    if Fld.FieldType = ftFloatPoint then
      Result := FormatFloatPoint(S);
end;

procedure TInputForm.OnKeyPress(Sender: TObject; var Key: Char);
var
  Fld: TMicexField;
begin
  Fld := TMicexField((Sender as TComponent).Tag);
  if Fld.FieldType in [ftInteger, ftFixed, ftFloat, ftFloatPoint] then
  begin
    if ((Fld.Decimals <> 0) or (Fld.FieldType = ftFloatPoint)) and (not CharInSet(Key, ['0'..'9', '.', ',', #8, FormatSettings.DecimalSeparator])) then Key := #0;
    if (Fld.Decimals = 0) and (Fld.FieldType <> ftFloatPoint) and (not CharInSet(Key, ['0'..'9', #8])) then Key := #0;
  end;
end;

function TInputForm.HasVarBlock: Boolean;
var
  I: Integer;
begin
  for I := 0 to FFields.Count - 1 do
    if TMicexField(FFields[I]).Flags and ffVarBlock <> 0 then
    begin
      Result := True;
      Exit;
    end;
  Result := False;
end;

procedure TInputForm.AddGroup(var Params: string; Adjust: Boolean);
var
  StartIndex, EndIndex, PanelIndex, I{, PrevHeight}: Integer;
begin
  // find first and last field of repeatable group
  StartIndex := -1;
  EndIndex := -1;
  for I := FFields.Count - 1 downto 0 do
    if TMicexField(FFields[I]).Flags and ffVarBlock <> 0 then
    begin
      if EndIndex < 0 then EndIndex := I;
      StartIndex := I;
    end;

  PanelIndex := FPanelList.Count;
  // find panel before which to insert a new group
  if EndIndex < FFields.Count - 1 then
    for I := FPanelList.Count - 1 downto 0 do
      if FPanelList[I].FField = FFields[EndIndex + 1] then
      begin
        PanelIndex := I;
        Break;
      end;

  Inc(FGroupCount);
  for I := StartIndex to EndIndex do
  begin
    CreateInputField(PanelIndex, FFields[I], Params);
    Inc(PanelIndex);
  end;

//  PrevHeight := Height;
  AdjustHeight;
//  Top := Top - (Height - PrevHeight) div 2;
end;

procedure TInputForm.MoreClick(Sender: TObject);
var
  Params: string;
begin
  Params := '';
  AddGroup(Params, True);
end;

procedure TInputForm.LessClick(Sender: TObject);
var
  I{, PrevHeight}: Integer;
begin
  for I := FPanelList.Count - 1 downto 0 do
    if FPanelList[I].FGroupIndex = FGroupCount then
    begin
      FPanelList[I].Free;
      FPanelList.Delete(I);
    end;

  Dec(FGroupCount);
//  PrevHeight := Height;
  AdjustHeight;
//  Top := Top + (PrevHeight - Height) div 2;
end;

procedure TInputForm.CreateInputField(FieldPos: Integer; Field: TMicexField; var Params: string);
const
  sLabels: array [Boolean] of string = ('%s:', '%s [%d]:');
  sChecks: array [Boolean] of string = ('%s', '%s [%d]');
  sGroups: array [Boolean] of string = (' %s ', ' %s [%d] ');
var
  Value, FullSecCode: string;
  CI, ConstIdx, FieldTop, FieldHeight: Integer;
  FieldPanel: TFieldPanel;
begin
  with Field do
  begin
    if not Assigned(EnumPtr) or (EnumPtr.Kind <> ekGroup) then FieldHeight := 24
    else FieldHeight := (EnumPtr.GetConstCount + 1) shr 1 * 17 + 21;

    if FPanelList.Count = 0 then FieldTop := paTop.Height
    else
      if FieldPos < FPanelList.Count then FieldTop := FPanelList[FieldPos].Top
      else with FPanelList.Last do FieldTop := Top + Height;

    FieldPanel := TFieldPanel.Create(Self, Field, FieldTop, FieldHeight);
    FPanelList.Insert(FieldPos, FieldPanel);

    with TLabel.Create(Self) do
    begin
      if not Assigned(EnumPtr) or (EnumPtr.Kind = ekCombo) then
        Caption := Format(sLabels[Flags and ffVarBlock <> 0], [GetDisplayName(Field, True), FGroupCount]);
      Parent := FieldPanel;
      SetBounds(12, (FieldHeight - Height) div 2, 165, Height);
    end;

    if not Assigned(EnumPtr) then
    begin
      if FieldType in [ftDate, ftTime] then
      begin
        FieldPanel.FControl := TDateTimePicker.Create(Self);
        with TDateTimePicker(FieldPanel.FControl) do
        begin
          Value := GetFieldFromMsg(Field.Name, FFromMsg, FieldType);
          if Value = '' then
            if Params = '' then Value := DefValue
            else Value := StripField(Params, Size, FieldType)
          else StripField(Params, Size, FieldType);

          if FieldType = ftTime then
          begin
            DateMode := dmUpDown;
            Kind := dtkTime;
          end;
          ShowCheckBox := True;
          DateTime := ConvertStrToDateTime(Value, FieldType);
          Tag := IntPtr(Field);
          Hint := GetFieldHint(Field);
          OnChange := FieldPanel.OnChange;
          Parent := FieldPanel;
          SetBounds(181, (FieldHeight - Height) div 2, 165, Height);
          if DateTime = -1 then
          begin
            DateTime := Now;;
            Checked := False;
          end;
        end;
      end
      else
        if Flags and ffSecCode <> 0 then
        begin
          FieldPanel.FControl := TComboBox.Create(Self);
          with TComboBox(FieldPanel.FControl) do
          begin
            Parent := FieldPanel;
            Hint := GetFieldHint(Field);
            Style := csDropDown;
            Tag := IntPtr(Field);
            MaxLength := Size;

            Sorted := True;
            Items.BeginUpdate;
            try
              if FieldPanel.PrevIsSecBoard then
                for CI := 0 to FSecList.Count - 1 do
                  with FSecList[CI]^ do
                    Items.AddObject(Format('%s - %s',
                      [ShortName, Copy(SecCode, 1, 4)]), TObject(FSecList[CI]))
              else
                for CI := 0 to FSecCodeList.Count - 1 do
                  with FSecCodeList[CI]^ do
                    Items.AddObject(ShortName, TObject(FSecCodeList[CI]))
            finally
              Items.EndUpdate;
            end;

            Value := GetFieldFromMsg(Field.Name, FFromMsg, FieldType);
            if Value = '' then
              if Params = '' then Value := DefValue
              else Value := StripField(Params, Size, FieldType)
            else StripField(Params, Size, FieldType);

            Text := Value;
            OnChange := FieldPanel.OnChange;

            FullSecCode := Trim(Value);
            // form SECBOARD + SECCODE
            if FieldPanel.Prev <> nil then
              FullSecCode := EPadRight(THWinControl(FieldPanel.Prev.FControl).Text, 4) + FullSecCode;

            for CI := 0 to Items.Count - 1 do
              if Trim(PSecProp(Items.Objects[CI]).SecCode) = FullSecCode then
              begin
                ItemIndex := CI;
                OnChange(FieldPanel.FControl);
                Break;
              end;

            SetBounds(181, (FieldHeight - Height) div 2, 165, Height);
          end;
        end
        else
        begin
          FieldPanel.FControl := TEdit.Create(Self);
          with TEdit(FieldPanel.FControl) do
          begin
            Value := GetFieldFromMsg(Field.Name, FFromMsg, FieldType);
            if Value = '' then
              if Params = '' then Value := DefValue
              else Value := StripField(Params, Size, FieldType)
            else StripField(Params, Size, FieldType);

            Text := StrToNumber(Value, Field);
            if (FieldType in [ftInteger, ftFixed, ftFloat]) and (FDecimals <> 0) then
              MaxLength := Size + 1
            else
              MaxLength := Size;
            Tag := IntPtr(Field);
            Hint := GetFieldHint(Field);
            OnChange := FieldPanel.OnChange;
            Parent := FieldPanel;
            SetBounds(181, (FieldHeight - Height) div 2, 165, Height);
          end;
        end;
    end
    else    // handle EnumType
    begin
      Value := GetFieldFromMsg(Field.Name, FFromMsg, FieldType);
      if Value = '' then
        if Params = '' then Value := DefValue
        else Value := StripField(Params, Size, FieldType)
      else StripField(Params, Size, FieldType);

      ConstIdx := EnumPtr.GetConstIndex(PChar(Value));
      if ConstIdx < 0 then ConstIdx := 0;

      case EnumPtr.Kind of
        ekCheck:
          begin
            FieldPanel.FControl := TCheckBox.Create(Self);
            with TCheckBox(FieldPanel.FControl) do
            begin
              Caption := Format(sChecks[Field.Flags and ffVarBlock <> 0], [GetDisplayName(Field, True), FGroupCount]);
              Hint := GetFieldHint(Field);
              Tag := IntPtr(Field);
              Checked := Boolean(ConstIdx);
              OnClick := FieldPanel.OnChange;
              Parent := FieldPanel;
              SetBounds(12, (FieldHeight - Height) div 2, 334, Height);
            end;
          end;

        ekGroup:
          begin
            FieldPanel.FControl := TRadioGroup.Create(Self);
            with TRadioGroup(FieldPanel.FControl) do
            begin
              Caption := Format(sGroups[Field.Flags and ffVarBlock <> 0], [GetDisplayName(Field, True), FGroupCount]);
              Hint := GetFieldHint(Field);
              Tag := IntPtr(Field);
              Columns := 2;

              Items.BeginUpdate;
              with EnumPtr do
              begin
                for CI := 0 to GetConstCount - 1 do
                  Items.Add(GetLongName(CI));
              end;

              Parent := FieldPanel;
              SetBounds(12, 2, 334, FieldHeight - 4);
              Items.EndUpdate;
              OnClick := FieldPanel.OnChange;
              ItemIndex := ConstIdx;
            end;
          end;

        ekCombo:
          begin
            FieldPanel.FControl := TComboBox.Create(Self);
            with TComboBox(FieldPanel.FControl) do
            begin
              Parent := FieldPanel;
              Hint := GetFieldHint(Field);
              Style := csDropDownList;
              Tag := IntPtr(Field);
              with EnumPtr do
                for CI := 0 to GetConstCount - 1 do
                  Items.Add(GetLongName(CI));
              ItemIndex := ConstIdx;
              OnChange := FieldPanel.OnChange;
              SetBounds(181, (FieldHeight - Height) div 2, 165, Height);
            end;
          end;
      end;
    end;

    FieldPanel.OnChange(FieldPanel.FControl);
    THWinControl(FieldPanel.FControl).OnKeyPress := Self.OnKeyPress;
  end;
end;

procedure TInputForm.AdjustHeight;
var
  I: Integer;
begin
  if FPanelList.Count > 0 then
     with FPanelList.Last do
       Self.ClientHeight := Top + Height + paButtons.Height + 8
  else Self.ClientHeight := 50;

  // adjust TabOrder of all created panels
  for I := 0 to FPanelList.Count - 1 do
    FPanelList[I].TabOrder := I;
end;

function TInputForm.GetInputParams(const AId: string; var Params: string): Boolean;
var
  I, H, DecNum, ParamsLen, MinNeededLength, TailLength, GroupLength, LastGroupIndex: Integer;
  Comp: TComponent;
  Fld: TMicexField;
  Value, TailParams: string;
begin
  FPanelList := TPanelList.Create;
  Width := FULL_WIDTH;
  Height := Screen.Height;
  ParamsLen := Length(Params);
  GroupLength := 0;

  btnMore.Visible := HasVarBlock;
  btnLess.Visible := btnMore.Visible;

  MinNeededLength := GetMinNeededLength(FFields);
  if (ParamsLen = 0) or (ParamsLen >= MinNeededLength) then FGroupCount := 1
  else FGroupCount := 0;  // not enough parameters even for 1 group of repeatable fields

  TailLength := 0;
  LastGroupIndex := MaxInt;
  H := 0;
  for I := FFields.Count - 1 downto 0 do
    if TMicexField(FFields[I]).Flags and ffVarBlock = 0 then Inc(H, TMicexField(FFields[I]).Size)
    else
    begin
      LastGroupIndex := I;
      TailLength := H;
      Break;
    end;

  TailParams := Copy(Params, Length(Params) - TailLength + 1, TailLength);
  Params := Copy(Params, 1, Length(Params) - TailLength);

  for I := 0 to FFields.Count - 1 do
  begin
    // Skip first USERID field
    if (TMicexField(FFields[I]).Flags and ffVarBlock = 0) or (FGroupCount > 0) then
      if I <= LastGroupIndex then
        CreateInputField(FPanelList.Count, TMicexField(FFields[I]), Params)
      else
        CreateInputField(FPanelList.Count, TMicexField(FFields[I]), TailParams);
    if TMicexField(FFields[I]).Flags and ffVarBlock <> 0 then
    begin
      Inc(FGroupHeight, FPanelList.Last.Height);
      Inc(GroupLength, TMicexField(FFields[I]).Size);
    end;
  end;

  if (GroupLength <> 0) and (Length(Params) >= GroupLength) then
    for I := 0 to Length(Params) div GroupLength - 1 do
      AddGroup(Params, False);
  AdjustHeight;

  cbRawValues.Checked := ShowRawValues;
  ToggleRawValues(cbRawValues);
  Params := '';
  FormatNumbers;

  if ShowModal = mrOk then
  begin
    Result := True;
    for I := 0 to FPanelList.Count - 1 do
    begin
      Comp := FPanelList[I].FControl;
      Fld := FPanelList[I].FField;
      if Comp is TEdit then Value := TEdit(Comp).Text
      else
        if Comp is TDateTimePicker then
        begin
          if TDateTimePicker(Comp).Checked then
            Value := ConvertDateTimeToStr(TDateTimePicker(Comp).DateTime, Fld.FieldType)
          else
            Value := '';
        end
        else
        begin
          if Comp is TComboBox then
          begin
            if Fld.Flags and ffSecCode <> 0 then
              with TComboBox(Comp) do
                if ItemIndex >= 0 then
                  if FPanelList[I].PrevIsSecBoard then
                    Value := Copy(PSecProp(Items.Objects[ItemIndex]).SecCode, 5, 12)
                  else
                    Value := PFirmProp(Items.Objects[ItemIndex]).Code
                else
                  Value := Text
            else
              Value := Fld.EnumPtr.GetConst(TComboBox(Comp).ItemIndex);
          end
          else
          begin
            if Comp is TCheckBox then H := Byte(TCheckBox(Comp).Checked) else
              H := TRadioGroup(Comp).ItemIndex;
            with Fld.EnumPtr do
              Value := GetConst(H);
          end;
        end;

      if Fld.Decimals < 0 then DecNum := FDecimals else DecNum := Fld.Decimals;
      with Fld do Value := ConvertParameter(Value, FieldType, Size, DecNum);
      Params := Params + Value;
    end;
  end
  else Result := False;
  ShowRawValues := cbRawValues.Checked;
end;

procedure TInputForm.UpdateActions;
begin
  inherited;
  btnMore.Enabled := Height + FGroupHeight < Screen.Height;
  btnLess.Enabled := FGroupCount > 0;
end;

procedure TInputForm.FormatNumbers;
var
  I: Integer;
  Panel: TFieldPanel;
begin
  if FDecimals >= 0 then
    for I := 0 to FPanelList.Count - 1 do
    begin
      Panel := FPanelList[I];
      if Panel.FField.FieldType = ftFloat then Panel.OnChange(Panel.FControl);
    end;
end;

{ TFieldPanel }

constructor TFieldPanel.Create(AOwner: TInputForm; AField: TMicexField; ATop, AHeight: Integer);
begin
  inherited Create(AOwner);
  FForm := AOwner;
  FField := AField;
  Height := AHeight;
  Align := alTop;
  Top := ATop;
  Parent := AOwner as TWinControl;
  ParentFont := True;
  BevelOuter := bvNone;
  Caption := '';
  OnDblClick := paDblClick;
  if AField.Flags and ffVarBlock <> 0 then FGroupIndex := AOwner.FGroupCount;

  FRawValue := TStaticText.Create(Self);
  with FRawValue do
  begin
    Font.Name := 'Courier New';
    Caption := 'raw value';
    Hint := sRawValueHint;
    BorderStyle := sbsSunken;
    Parent := Self;
    SetBounds(358, (AHeight - 17) div 2, Self.Width - 362, 17);
  end;
end;

function TFieldPanel.Next: TFieldPanel;
var
  I: Integer;
begin
  with FForm.FPanelList do
  begin
    I := IndexOf(Self) + 1;
    if I < Count then Result := Panels[I] else Result := nil;
  end;
end;

function TFieldPanel.Prev: TFieldPanel;
var
  I: Integer;
begin
  with FForm.FPanelList do
  begin
    I := IndexOf(Self) - 1;
    if I >= 0 then Result := Panels[I] else Result := nil;
  end;
end;

function TFieldPanel.PrevIsSecBoard: Boolean;
begin
  Result := (Prev <> nil) and (Prev.FField.NameType = fntSecBoard);
end;

procedure TFieldPanel.OnChange(Comp: TObject);
var
  Value: string;
  H, {I, }DecNum: Integer;
begin
  if Comp is TEdit then Value := TEdit(Comp).Text
  else
    if Comp is TDateTimePicker then
    begin
      if TDateTimePicker(Comp).Checked then
        Value := ConvertDateTimeToStr(TDateTimePicker(Comp).DateTime, FField.FieldType)
      else
        Value := '';
    end
    else
    begin
      if Comp is TComboBox then
      begin
        if FField.Flags and ffSecCode <> 0 then
          with TComboBox(Comp) do
        begin
          if ItemIndex >= 0 then
          begin
            if PrevIsSecBoard then
              with PSecProp(Items.Objects[ItemIndex])^ do
              begin
                if Prev <> nil then
                begin
                  THWinControl(Prev.FControl).Text := Copy(SecCode, 1, 4);
                end;
                Value := Copy(SecCode, 5, 12);
                FForm.FDecimals := Decimals;
              end
            else begin
              Value := PFirmProp(Items.Objects[ItemIndex]).Code;
              FForm.FDecimals := -1;
            end;
          end
          else
          begin
            Value := Text;
            FForm.FDecimals := -1;
          end;

          FForm.FormatNumbers;
        end
        else
          Value := FField.EnumPtr.GetConst(TComboBox(Comp).ItemIndex);
      end
      else
      begin
        if Comp is TCheckBox then H := Byte(TCheckBox(Comp).Checked) else
          H := TRadioGroup(Comp).ItemIndex;
        with FField.EnumPtr do
          Value := GetConst(H);
      end;
    end;

  if FField.Decimals < 0 then DecNum := FForm.FDecimals else DecNum := FField.Decimals;
  with FField do Value := ConvertParameter(Value, FieldType, Size, DecNum);

  FRawValue.Caption := Value;
end;

procedure TFieldPanel.paDblClick(Sender: TObject);
begin
//  ShowMessageFmt('Font Name="%s", Size=%d', [FRawValue.Font.Name, FRawValue.Font.Size]);
  FRawValue.Font.Style := [fsItalic];
end;

{ TPanelList }

function TPanelList.GetPanel(AIndex: Integer): TFieldPanel;
begin
  Result := Items[AIndex];
end;

function TPanelList.Last: TFieldPanel;
begin
  Result := Items[Count - 1];
end;

end.
