unit U_frameGJList;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
  System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics,
  cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit,
  cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxNavigator,
  dxDateRanges, dxScrollbarAnnotations, Data.DB, cxDBData, cxCheckBox,
  cxTextEdit, dxBarBuiltInMenu, Vcl.Menus, cxGridCustomPopupMenu,
  cxGridPopupMenu, Datasnap.DBClient, Data.Win.ADODB, cxGridLevel,
  cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxClasses,
  cxGridCustomView, cxGrid, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.ToolWin,
  Vcl.ExtCtrls, dxSkinsCore, dxSkinsDefaultPainters, cxMemo, cxLabel, cxMaskEdit,
  cxDropDownEdit, cxButtonEdit, cxButtons;

type
  TframeGJList = class(TFrame)
    ADOQueryMain: TADOQuery;
    ADOQueryCmd: TADOQuery;
    ADOQueryTemp: TADOQuery;
    CDS_HZ: TClientDataSet;
    DS_HZ: TDataSource;
    cxGridPopupMenu2: TcxGridPopupMenu;
    PopupMenu1: TPopupMenu;
    N1: TMenuItem;
    N2: TMenuItem;
    Panel_GJ: TPanel;
    LabelGJ: TLabel;
    cxLabel240: TcxLabel;
    gj_speed: TcxTextEdit;
    cxLabel278: TcxLabel;
    gj_number: TcxTextEdit;
    TbGJReplace2: TcxButton;
    TbGJClear2: TcxButton;
    cxLabel234: TcxLabel;
    cxLabel236: TcxLabel;
    cxLabel237: TcxLabel;
    cxLabel238: TcxLabel;
    cxLabel247: TcxLabel;
    cxLabel249: TcxLabel;
    cxLabel250: TcxLabel;
    cxLabel251: TcxLabel;
    cxLabel252: TcxLabel;
    cxLabel253: TcxLabel;
    cxLabel273: TcxLabel;
    gj_temperature1: TcxTextEdit;
    gj_temperature10: TcxTextEdit;
    gj_temperature11: TcxTextEdit;
    gj_temperature2: TcxTextEdit;
    gj_temperature3: TcxTextEdit;
    gj_temperature4: TcxTextEdit;
    gj_temperature5: TcxTextEdit;
    gj_temperature6: TcxTextEdit;
    gj_temperature7: TcxTextEdit;
    gj_temperature8: TcxTextEdit;
    gj_temperature9: TcxTextEdit;
    cxGrid8: TcxGrid;
    TvGJ: TcxGridDBTableView;
    cxGridDBColumn24: TcxGridDBColumn;
    cxGridDBColumn27: TcxGridDBColumn;
    TvGJserialno: TcxGridDBColumn;
    cxGridLevel7: TcxGridLevel;
    cxLabel9: TcxLabel;
    TbGJAdd: TcxButton;
    TbGJDel: TcxButton;
    gj_Precautions: TcxMemo;
    cxLabel10: TcxLabel;
    gj_leftGap: TcxTextEdit;
    cxLabel11: TcxLabel;
    gj_rightGap: TcxTextEdit;
    CDS_gj: TClientDataSet;
    DS_gj: TDataSource;
    TvGJgj_spel: TcxGridDBColumn;
    TvGJgj_unit: TcxGridDBColumn;
    TvGJBPIID: TcxGridDBColumn;
    procedure TBRafreshClick(Sender: TObject);

    procedure ToolButton5Click(Sender: TObject);
    procedure ToolButton3Click(Sender: TObject);
    procedure TbGJReplace2Click(Sender: TObject);
    procedure TbGJClear2Click(Sender: TObject);
    procedure TbGJAddClick(Sender: TObject);
    procedure TbGJDelClick(Sender: TObject);
    procedure cxGridDBColumn24PropertiesButtonClick(Sender: TObject;
      AButtonIndex: Integer);
    procedure cxGridDBColumn27PropertiesEditValueChanged(Sender: TObject);

  private
    procedure FillAllTextEditsWithValue(AParent: TWinControl; const AHint, AValue: string; AExclude: TcxTextEdit = nil);
    procedure ClearAllTextEditsByHint(AParent: TWinControl; const AHint: string; AExclude: TcxTextEdit = nil);
    function FindLastEditedTextEdit(AParent: TWinControl; const AHint: string): string;
    { Private declarations }
  public
    procedure InitGrid();
    function SaveData(mPSID: string): Boolean;
    { Public declarations }
  end;

implementation

uses
  U_DataLink, U_RTFun, U_LabelPrint,U_ProductInfoSel;
{$R *.dfm}

procedure TframeGJList.InitGrid();
begin
//  POSNO.SetFocus;
//  try
//    ADOQueryMain.DisableControls;
//    with ADOQueryMain do
//    begin
//      Close;
//      SQL.Clear;
//      sql.Add(' select A.* from  BS_Position A order by POSNO ');
//      Open;
//    end;
//    SCreateCDS(ADOQueryMain, CDS_HZ);
//    SInitCDSData(ADOQueryMain, CDS_HZ);
//  finally
//    ADOQueryMain.EnableControls;
//    ToolButton2.Click;
//  end;
end;

procedure TframeGJList.TbGJAddClick(Sender: TObject);
begin
  with CDS_GJ do
  begin
    Append;
    CDS_GJ.FieldByName('serialno').Value := CDS_GJ.RecordCount + 1;
    Post;
  end;
end;

procedure TframeGJList.TbGJClear2Click(Sender: TObject);
begin
  ClearAllTextEditsByHint(panel_gj, '刮胶温控');
end;

procedure TframeGJList.TbGJDelClick(Sender: TObject);
var
  i: Integer;
begin
  if not CDS_GJ.IsEmpty then
  begin

    if Application.MessageBox('确定要删除数据吗？', '提示', 32 + 4) = IDYES then
    begin
      if Trim(CDS_GJ.fieldbyname('BCPID').AsString) <> '' then
      begin
        with ADOQueryCmd do
        begin
          Close;
          sql.Clear;
          sql.Add('delete BS_Cloth_GY_Sub where BCPID=' + quotedStr(Trim(CDS_GJ.fieldbyname('BCPID').AsString)));
          ExecSQL;
        end;
      end;
      CDS_GJ.Delete;
    end
    else
      exit;

    i := 0;
    CDS_GJ.First;
    while not CDS_GJ.Eof do
    begin
      i := i + 1;
      CDS_GJ.Edit;
      CDS_GJ.fieldByName('serialno').value := i;
      CDS_GJ.Post;
      CDS_GJ.Next;
    end;
  end
  else
  begin
    Application.MessageBox('无可删除数据!', '提示', 0);
    Exit;
  end;
end;

procedure TframeGJList.TbGJReplace2Click(Sender: TObject);
begin
  FillAllTextEditsWithValue(panel_gj, '刮胶温控', FindLastEditedTextEdit(panel_gj, '刮胶温控'));
end;

procedure TframeGJList.TBRafreshClick(Sender: TObject);
begin
  InitGrid();
end;

procedure TframeGJList.ToolButton3Click(Sender: TObject);
var
  RTValues: TArray<string>;
begin

  if CDS_HZ.IsEmpty then
    Exit;
  if CDS_HZ.Locate('SSel', True, []) = False then
  begin
    Application.MessageBox('请先选择数据！', '提示', 0);
    Exit;
  end;
  RTValues := SelCDSKey(CDS_HZ, ['POSID']);

  try
    frmLabelPrint := TfrmLabelPrint.Create(Application);
    with frmLabelPrint do
    begin
      FLMType := 'Position';
      FFiltration1 := RTValues[0];
      if ShowModal = 1 then
      begin
//        Self.InitGrid();
      end;
    end;
  finally
    frmLabelPrint.Free;
  end;
end;

procedure TframeGJList.ToolButton5Click(Sender: TObject);
begin
  if CDS_HZ.IsEmpty then
    Exit;

  if CDS_HZ.Locate('SSel', True, []) = False then
  begin
    Application.MessageBox('请先选择数据！', '提示', 0);
    Exit;
  end;

  if Application.MessageBox('确定要删除数据吗？', '提示', 32 + 4) <> IDYES then
    Exit;

  with CDS_HZ do
  begin
    while not Eof do
    begin
      if CDS_HZ.Locate('SSel', True, []) = True then
      begin
        with ADOQueryCmd do
        begin
          Close;
          sql.Clear;
          sql.Add('delete BS_Position where POSID=' + QuotedStr(CDS_HZ.FieldByName('POSID').AsString));
          ExecSQL;
        end;
      end;

      CDS_HZ.Edit;
      CDS_HZ.FieldByName('SSel').Value := False;
      CDS_HZ.Post;
      Next;
    end;
  end;
  InitGrid();
end;

function TframeGJList.SaveData(mPSID: string): Boolean;
var
  MaxProcessID, MaxBCPID, MaxPSID, MaxDTMID, mDTMID, DTMPSlist: string;
  maxsubid1, maxsubid2, maxsubid3, maxsubid4, maxsubid5, maxsubid6, mmaxgx: string;
begin
  try



////////////////       保存主表      //////////////////////
    with ADOQueryCmd do
    begin
      Close;
      SQL.Clear;
      sql.Add('select * from Bs_Cloth_GY_Main where PSID=''' + Trim(mPSID) + '''');
      Open;
    end;
    with ADOQueryCmd do
    begin
      if Trim(mPSID) = '' then
      begin
        Append;
      end
      else
      begin
        Edit;
      end;
      FieldByName('PSID').Value := Trim(mPSID);

      RTSetsavedata(ADOQueryCmd, 'Bs_Cloth_GY_Main', panel_gj, 2);
      ADOQueryCmd.Post;

          //////////////////       保存刮胶子表          //////////////////////
      with CDS_gj do
      begin
        First;
        while not Eof do
        begin

          if Trim(CDS_gj.fieldbyname('BCPID').AsString) = '' then
          begin
            if GetLSNo(ADOQueryTemp, maxsubid5, 'GJ', 'Bs_Cloth_GY_Sub', 5, 1) = False then
            begin

              Application.MessageBox('取配比子流水号失败！', '提示', 0);
              Exit;
            end;
          end
          else
          begin
            maxsubid5 := Trim(CDS_gj.fieldbyname('BCPID').AsString);
          end;
          with ADOQueryCmd do
          begin
            Close;
            SQL.Clear;
            sql.Add('select * from Bs_Cloth_GY_Sub where ');
            sql.Add('  BCPID=''' + Trim(maxsubid5) + '''');
            Open;
          end;
          with ADOQueryCmd do
          begin
            if Trim(CDS_gj.fieldbyname('BCPID').AsString) = '' then
            begin
              Append;

            end
            else
            begin
              Edit;

            end;
            FieldByName('GYType').Value := '刮胶';
            FieldByName('PSID').Value := Trim(mPSID);
            FieldByName('BCPID').Value := Trim(maxsubid5);
            RTSetSaveDataCDS(ADOQueryCmd, TvGJ, CDS_gj, 'Bs_Cloth_GY_Sub', 0);
            Post;
          end;

          Next;
        end;
      end;
////////////////       保存刮胶子表结束          //////////////////////

    end;

////////////////       保存主表结束          //////////////////////


//    FPSID := maxId;
    Result := True;
  except
    Result := False;

    Application.MessageBox('保存失败!', '提示', 0);
  end;
end;

procedure TframeGJList.cxGridDBColumn24PropertiesButtonClick(Sender: TObject;
  AButtonIndex: Integer);
begin
  try
    frmProductInfoSel := TfrmProductInfoSel.Create(Application);
    with frmProductInfoSel do
    begin
      FSTKName := '助剂';
      if ShowModal = 1 then
      begin
        with Self.CDS_GJ do
        begin
          Edit;
          FieldByName('gj_Name').Value := frmProductInfoSel.CDS_1.fieldbyname('P_Name').value;
          FieldByName('gj_spel').Value := frmProductInfoSel.CDS_1.fieldbyname('P_Type').value;
          FieldByName('gj_unit').Value := frmProductInfoSel.CDS_1.fieldbyname('QtyUnit').value;
          FieldByName('BPIID').Value := frmProductInfoSel.CDS_1.fieldbyname('BPIID').value;
        end;
      end;
    end;
  finally
    frmProductInfoSel.Free;
  end;
end;

procedure TframeGJList.cxGridDBColumn27PropertiesEditValueChanged(
  Sender: TObject);
var
  s: string;
  fValue: Double;
begin
  s := TcxTextEdit(Sender).EditingText;

  if (s <> '') and (s[Length(s)] <> '%') then
  begin
    try
      // 尝试将字符串转换为浮点数
      fValue := StrToFloat(s);
      // 格式化为两位小数并添加百分号
      TvGJ.Controller.FocusedColumn.EditValue := FormatFloat('0.00', fValue) + '%';
    except
      on E: EConvertError do
      begin
        // 如果转换失败，保持原样并添加百分号
        TvGJ.Controller.FocusedColumn.EditValue := s + '%';
      end;
    end;
  end;
end;

procedure TframeGJList.FillAllTextEditsWithValue(AParent: TWinControl; const AHint, AValue: string; AExclude: TcxTextEdit = nil);  // 可选：排除特定控件
var
  i: Integer;
  AControl: TControl;
  ATextEdit: TcxTextEdit;
begin
  for i := 0 to AParent.ControlCount - 1 do
  begin
    AControl := AParent.Controls[i];
    if (AControl is TcxTextEdit) and ((AControl as TcxTextEdit).Text = '') then
    begin
      ATextEdit := AControl as TcxTextEdit;
      if (ATextEdit.Hint = AHint) and (ATextEdit <> AExclude) then
        ATextEdit.Text := AValue;
    end;
  end;
end;

procedure TframeGJList.ClearAllTextEditsByHint(AParent: TWinControl; const AHint: string; AExclude: TcxTextEdit = nil);
var
  i: Integer;
  AControl: TControl;
begin
  for i := 0 to AParent.ControlCount - 1 do
  begin
    AControl := AParent.Controls[i];
    // 检查是否是 TcxTextEdit，并且 Hint 匹配，且不是排除的控件
    if (AControl is TcxTextEdit) and (TcxTextEdit(AControl).Hint = AHint) and (TcxTextEdit(AControl) <> AExclude) then
    begin
      TcxTextEdit(AControl).Text := ''; // 直接清空
    end;
  end;
end;

function TframeGJList.FindLastEditedTextEdit(AParent: TWinControl; const AHint: string): string;
var
  i, j: Integer;
  AControl: TControl;
  SortedControls: TList;
  TempControl: TControl;
begin
  Result := '';

  // 如果没有子控件，直接返回空
  if AParent.ControlCount = 0 then
    Exit;

  // 使用 TList 存储控件（兼容旧版 Delphi）
  SortedControls := TList.Create;
  try
    // 将所有子控件添加到列表
    for i := 0 to AParent.ControlCount - 1 do
      SortedControls.Add(AParent.Controls[i]);

    // 手动排序：按 Top（Y坐标）和 Left（X坐标）升序排列
    for i := 0 to SortedControls.Count - 1 do
    begin
      for j := i + 1 to SortedControls.Count - 1 do
      begin
        // 比较两个控件的 Top 和 Left
        if (TControl(SortedControls[i]).Top > TControl(SortedControls[j]).Top) or ((TControl(SortedControls[i]).Top = TControl(SortedControls[j]).Top) and (TControl(SortedControls[i]).Left > TControl(SortedControls[j]).Left)) then
        begin
          // 交换位置
          TempControl := TControl(SortedControls[i]);
          SortedControls[i] := SortedControls[j];
          SortedControls[j] := TempControl;
        end;
      end;
    end;
    // 遍历排序后的控件
    for i := 0 to SortedControls.Count - 1 do
    begin
      AControl := TControl(SortedControls[i]);
      if (AControl is TcxTextEdit) and (TcxTextEdit(AControl).Hint = AHint) and (TcxTextEdit(AControl).Text <> '') then
      begin
        Result := TcxTextEdit(AControl).Text; // 最后一个符合条件的会被保留
      end;
    end;
  finally
    SortedControls.Free;
  end;
end;

end.

