unit U_TradeMarketQtyInPut;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  System.Types, Dialogs, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData,
  cxDataStorage, cxEdit, DB, cxDBData, cxCalendar, cxDropDownEdit, ComCtrls,
  ToolWin, cxGridLevel, cxGridCustomTableView, cxGridTableView,
  cxGridDBTableView, cxClasses, cxControls, cxGridCustomView, cxGrid,
  cxGridCustomPopupMenu, cxGridPopupMenu, ADODB, DBClient, cxButtonEdit,
  cxTextEdit, StdCtrls, ExtCtrls, cxLookAndFeels, cxLookAndFeelPainters,
  cxNavigator, dxDateRanges, dxBarBuiltInMenu, U_BaseInput, System.ImageList,
  Vcl.ImgList, ComObj, dxScrollbarAnnotations, cxContainer, dxCore, cxDateUtils,
  cxMaskEdit, cxImageList, cxCurrencyEdit, Vcl.Menus, Clipbrd, dxSkinsCore,
  dxSkinsDefaultPainters, dxSkinWXI;

type
  TfrmTradeMarketQtyInPut = class(TfrmBaseInput)
    DS_1: TDataSource;
    CDS_1: TClientDataSet;
    ADOQueryCmd: TADOQuery;
    ADOQueryMain: TADOQuery;
    ADOQueryTemp: TADOQuery;
    GPM_1: TcxGridPopupMenu;
    CDS_LM: TClientDataSet;
    pnl1: TPanel;
    tlb1: TToolBar;
    btn4: TToolButton;
    pnl2: TPanel;
    inPiece: TcxCurrencyEdit;
    Label9: TLabel;
    inQty: TcxCurrencyEdit;
    Label13: TLabel;
    TBSave: TToolButton;
    TBClose: TToolButton;
    Label1: TLabel;
    GroupBox1: TGroupBox;
    cxGrid1: TcxGrid;
    Tv1: TcxGridDBTableView;
    cxGridDBColumn8: TcxGridDBColumn;
    cxGridLevel1: TcxGridLevel;
    btnAdd: TToolButton;
    Tv1Column1: TcxGridDBColumn;
    Tv1Column2: TcxGridDBColumn;
    Tv1Column3: TcxGridDBColumn;
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure FormShow(Sender: TObject);
    procedure FromCoNameDblClick(Sender: TObject);
    procedure inQtyKeyPress(Sender: TObject; var Key: Char);
    procedure TBCloseClick(Sender: TObject);
    procedure TBSaveClick(Sender: TObject);
    procedure btnAddClick(Sender: TObject);
    procedure Tv1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
    procedure Tv1DblClick(Sender: TObject);
  private
    { Private declarations }
    function SaveData(): Boolean;
    function SaveData2(): Boolean;
    function Split(const s: string; Separator: char): TStringDynArray;
  public
    { Public declarations }
    PMTMSId, PFTMMID: string;
    canshu4: string;
    FName, FColor, FColorNo: string;
    MTMSId, FTMMID: string;
  end;

var
  frmTradeMarketQtyInPut: TfrmTradeMarketQtyInPut;

implementation

uses
  U_DataLink, U_RTFun, U_RPFun;

{$R *.dfm}

// 分割字符串函数

function TfrmTradeMarketQtyInPut.SaveData2(): Boolean;
var
  MBCIOID, Maxno: string;
begin
  try
    ADOQueryCmd.Connection.BeginTrans;
    CDS_1.DisableControls;
    with CDS_1 do
    begin
      First;
      while not eof do
      begin
        with ADOQueryTemp do
        begin
          Close;
          sql.Clear;
          sql.Add('select * from BS_Cloth_IO where BCIOID=''' + Trim(CDS_1.fieldbyname('BCIOID').AsString) + '''');
          Open;
        end;
        MBCIOID := Trim(ADOQueryTemp.fieldbyname('BCIOID').AsString);
        if Trim(MBCIOID) = '' then
        begin
          if not GetLSNo(ADOQueryCmd, Maxno, 'MC', 'BS_Cloth_IO', 4, 1) then
            raise Exception.Create('取染色坯布出库编号失败！');
        end
        else
        begin
          Maxno := Trim(MBCIOID);
        end;
        with ADOQueryCmd do
        begin
          Close;
          sql.Clear;
          sql.Add('select * from BS_Cloth_IO where BCIOID=''' + Trim(Maxno) + '''');
          Open;
        end;
        with ADOQueryCmd do
        begin
          if Trim(MBCIOID) = '' then
          begin
            Append;
            FieldByName('Fillid').Value := Trim(Dcode);
            FieldByName('Filler').Value := Trim(DName);
            FieldByName('status').value := '0';
          end
          else
          begin
            Edit;
            FieldByName('Editid').Value := Trim(Dcode);
            FieldByName('Editer').Value := Trim(DName);
            FieldByName('EditTime').Value := SGetServerDate(ADOQueryTemp);

          end;
          RTSetSaveDataCDS(ADOQueryCmd, Tv1, CDS_1, 'BS_Cloth_IO', 0);

          Post;
        end;
//        with ADOQueryCmd do
//        begin
//          Close;
//          sql.Clear;
//          sql.Add('Update BS_Cloth_IO Set StkPiece=(select Sum(isnull(Piece,0)*IOQtyFlag) from BS_Cloth_IO A where A.STKID=BS_Cloth_IO.BCIOID)');
////          sql.Add(',STKQty=(select Sum(isnull(Qty,0)*IOQtyFlag) from BS_Cloth_IO A where A.STKID=BS_Cloth_IO.BCIOID )');
//          sql.Add(',StkQty=(select Sum([dbo].[F_UnitConversion](A.QTYUNIT,A.NETWeight ,A.Meter ,A.Yardage )    *IOQtyFlag) from BS_Cloth_IO A where A.STKID=BS_Cloth_IO.BCIOID  )');
//
//          sql.Add('where BCIOID=''' + Trim(CDS_1.fieldbyname('STKID').AsString) + '''');
//          ExecSQL;
//        end;
//        with ADOQueryTemp do
//        begin
//          Close;
//          sql.Clear;
//          sql.Add('select * from BS_Cloth_IO where BCIOID=''' + Trim(CDS_1.fieldbyname('STKID').AsString) + '''');
//          Open;
//        end;
//        if ADOQueryTemp.FieldByName('STKQty').Value < 0 then
//          raise Exception.Create('出库数量大于入库数量不能保存！');

//        with ADOQueryCmd do
//        begin
//          Close;
//          Sql.Clear;
//          Sql.Add('exec P_BS_Cloth_Move ');
//          Sql.Add(' @BCIOID=' + quotedstr(Trim(Maxno)));
//          Open;
//        end;
//        if ADOQueryCmd.FieldByName('intReturn').AsInteger = -1 then
//          raise Exception.Create(pchar(trim(ADOQueryCmd.FieldByName('ShowMsg').AsString)));
        with ADOQueryCmd do
        begin
          Close;
          sql.Clear;
          sql.Add('insert into Finance_Need_Up(UType,UDataId,UOperation,UOperator,UModule,UDetails)       ');
          sql.Add('values(''贸易布坯出库''    ');
          sql.Add(',' + quotedstr(Maxno));
          sql.Add(',''保存''   ');
          sql.Add(',' + quotedstr(DName));
          sql.Add(',' + quotedstr(trim(self.Caption)));
          sql.Add(',' + quotedstr(Maxno));
          sql.Add(')  ');
          ExecSQL;
        end;
        Edit;
        FieldByName('BCIOID').Value := Trim(Maxno);
        Post;
        Next;
      end;
    end;
    CDS_1.EnableControls;
    ADOQueryCmd.Connection.CommitTrans;
    Result := True;
  except
    Result := False;
    ADOQueryCmd.Connection.RollbackTrans;
    application.MessageBox(PChar(Exception(ExceptObject).Message), '提示信息', 0);
  end;

end;

function TfrmTradeMarketQtyInPut.Split(const s: string; Separator: char): TStringDynArray;
var
  i, ItemIndex: Integer;
  len: Integer;
  SeparatorCount: Integer;
  Start: Integer;
begin
  len := Length(s);
  if len = 0 then
  begin
    Result := nil;
    Exit;
  end;

  // 计算分隔符数量
  SeparatorCount := 0;
  for i := 1 to len do
    if s[i] = Separator then
      Inc(SeparatorCount);

  SetLength(Result, SeparatorCount + 1);
  ItemIndex := 0;
  Start := 1;

  // 拆分字符串
  for i := 1 to len do
  begin
    if s[i] = Separator then
    begin
      Result[ItemIndex] := Copy(s, Start, i - Start);
      Inc(ItemIndex);
      Start := i + 1;
    end;
  end;

  Result[ItemIndex] := Copy(s, Start, len - Start + 1);
end;

procedure TfrmTradeMarketQtyInPut.btnAddClick(Sender: TObject);
begin
  if CDS_1.IsEmpty = False then
  begin
    CopyAddRowCDS(CDS_1);
    with CDS_1 do
    begin
      Edit;
      FieldByName('TMSQID').Value := null;

      post;
    end;
  end
  else
  begin
    with CDS_1 do
    begin
      Append;


      //FieldByName('QtyUnit').Value := 'M';
      Post;
    end;
  end;
end;

procedure TfrmTradeMarketQtyInPut.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  inherited;
  Action := caFree;
end;

function TfrmTradeMarketQtyInPut.SaveData(): Boolean;
var
  Maxno, PTMSQID: string;
  // 增加：判断是否跳过当前行
  bSkip: Boolean;
begin
  try
    ADOQueryCmd.Connection.BeginTrans;
    CDS_1.DisableControls;
    with CDS_1 do
    begin
      First;
      while not eof do
      begin
        // ====================== 核心判断：Qty=0 新增时跳过 ======================
        bSkip := False;
        if FieldByName('Qty').AsFloat = 0 then // 数量=0
        begin
          // 判断当前记录是否是新增（Append）状态
          if (CDS_1.State = dsInsert) or (Trim(FieldByName('TMSQID').AsString) = '') then
          begin
            bSkip := True; // 标记跳过
            Next;          // 直接下一条
            Continue;      // 不执行保存
          end;
        end;
        // ======================================================================

        with ADOQueryTemp do
        begin
          Close;
          sql.Clear;
          sql.Add('select * from Trade_Market_Sub_Qty where TMSQID=''' + Trim(CDS_1.fieldbyname('TMSQID').AsString) + '''');
          open;
        end;

        PTMSQID := Trim(ADOQueryTemp.fieldbyname('TMSQID').AsString);
        if Trim(PTMSQID) = '' then
        begin
          if GetLSNo(ADOQueryTemp, Maxno, 'MX', 'Trade_Market_Sub_Qty', 4, 1) = False then
          begin
            Application.MessageBox('取最大号失败!', '提示', 0);
            Exit;
          end;
        end
        else
        begin
          Maxno := Trim(PTMSQID);
        end;

        with ADOQueryCmd do
        begin
          Close;
          sql.Clear;
          SQL.Add('select * from Trade_Market_Sub_Qty where TMSQID=''' + Trim(Maxno) + '''');
          Open;
        end;

        with ADOQueryCmd do
        begin
          if Trim(PTMSQID) = '' then
          begin
            Append;
            FieldByName('FillId').Value := Trim(DCode);
            FieldByName('Filler').Value := Trim(DName);
            FieldByName('TMSQID').Value := Trim(Maxno);
          end
          else
          begin
            Edit;
            FieldByName('EditId').Value := Trim(DCode);
            FieldByName('Editer').Value := Trim(DName);
            FieldByName('EditTime').Value := SGetServerDateTime(ADOQueryTemp);
          end;

          RTSetSaveDataCDS(ADOQueryCmd, Tv1, CDS_1, 'Trade_Market_Sub_Qty', 0);
          FieldByName('TMSQID').AsString := Trim(Maxno);
          FieldByName('TMSId').AsString := CDS_1.FieldByName('TMSId').AsString;
          FieldByName('TMMId').AsString := CDS_1.FieldByName('TMMId').AsString;
          Post;
        end;

        Next;
      end;
    end;

    CDS_1.EnableControls;

    with ADOQueryCmd do
    begin
      close;
      SQL.Clear;
      sql.Add('update Trade_Market_Sub set outqty = (select sum(qty) from Trade_Market_Sub_Qty X where X.TMSID = Trade_Market_Sub.TMSID) where TMSID = ' + QuotedStr(PMTMSId));
      ExecSQL;
    end;

    ADOQueryCmd.Connection.CommitTrans;
    Result := True;

  except
    Result := False;
    ADOQueryCmd.Connection.RollbackTrans;
    application.MessageBox(PChar(Exception(ExceptObject).Message), '提示信息', 0);
  end;
end;

procedure TfrmTradeMarketQtyInPut.FormShow(Sender: TObject);
begin
  inherited;
  ReadCxGrid('大货单', Tv1, '贸易门市管理');
  TBSave.Visible := true;
  with ADOQueryTemp do
  begin
    Close;
    SQL.Clear;
//    sql.Add(' select A.* from Trade_Market_Sub_Qty A');
//    sql.Add('where A.TMSId=''' + Trim(PMTMSId) + '''');
    sql.Add('   select * from Bs_Cloth_IO A inner join Trade_Market_Sub B on A.TMMID=B.TMMId and A.TMSId=B.TMSId');
    sql.Add('where A.TMSId=''' + Trim(MTMSId) + '''');
//    showmessage(sql.text);
    Open;
  end;
  SCreateCDS(ADOQueryTemp, CDS_1);
  SInitCDSData(ADOQueryTemp, CDS_1);

  if canshu4 = '新余' then
  begin
    pnl2.Visible := true;
    btnAdd.Visible := true;

    with ADOQueryTemp do
    begin
      Close;
      SQL.Clear;
      sql.Add(' select A.* from Trade_Market_Sub_Qty A');
      sql.Add('where A.TMSId=''' + Trim(PMTMSId) + '''');
//      sql.Add('   select * from Bs_Cloth_IO A inner join Trade_Market_Sub B on A.TMMID=B.TMMId and A.TMSId=B.TMSId');
//      sql.Add('where A.TMSId=''' + Trim(MTMSId) + '''');
//    showmessage(sql.text);
      Open;
    end;
    SCreateCDS(ADOQueryTemp, CDS_1);
    SInitCDSData(ADOQueryTemp, CDS_1);
  end;

end;

procedure TfrmTradeMarketQtyInPut.FromCoNameDblClick(Sender: TObject);
begin
  TcxButtonEdit(Sender).Text := '';
  TcxButtonEdit(Sender).Properties.LookupItems.Text := '';
end;

procedure TfrmTradeMarketQtyInPut.inQtyKeyPress(Sender: TObject; var Key: Char);
var
  i: Integer;
  MaxNo: string;
begin
  if Key = #13 then
  begin

    with CDS_1 do
    begin
      DisableControls;
      for i := 1 to StrToIntDef(inPiece.Text, 1) do
      begin
        Append;
        FieldByName('Qty').Value := StrTofloatDef(inQty.Text, 0);
        FieldByName('TMSQID').Value := MaxNo;
        FieldByName('TMSId').Value := PMTMSId;
        FieldByName('TMMId').Value := PFTMMId;
        Post;

      end;
      EnableControls;
    end;
    inPiece.Text := '1';
    inQty.Text := '';
  end;
end;

procedure TfrmTradeMarketQtyInPut.TBSaveClick(Sender: TObject);
var
  Maxno: string;
begin
  with cds_1 do
  begin
    while cds_1.Locate('Qty', null, []) do
    begin
      cds_1.Delete
    end;
  end;
  with cds_1 do
  begin
    while cds_1.Locate('Qty', 0, []) do
    begin
      cds_1.Delete
    end;
  end;
//  if CDS_1.Locate('Qty', null, []) = True then
//  begin
//    Application.MessageBox('数量不能为空!', '提示', 0);
//    Exit;
//  end;
//  if CDS_1.Locate('Qty', 0, []) = True then
//  begin
//    Application.MessageBox('数量不能为0!', '提示', 0);
//    Exit;
//  end;
  if canshu4 = '新余' then
  begin
    if SaveData() then
    begin
      Application.MessageBox('保存成功!', '提示', 0);
      ModalResult := 1;

    end;
  end
  else
  begin
    if SaveData2() then
    begin
      Application.MessageBox('保存成功!', '提示', 0);
      ModalResult := 1;

    end;
  end;

end;

procedure TfrmTradeMarketQtyInPut.TBCloseClick(Sender: TObject);
begin
  inherited;
  Close;
end;

procedure TfrmTradeMarketQtyInPut.Tv1DblClick(Sender: TObject);
begin

  with ADOQueryTemp do
  begin
    Close;
    SQL.Clear;
    sql.Add('delete Trade_Market_Sub_Qty   where TMSQID=' + quotedstr(Trim(CDS_1.FieldByName('TMSQID').AsString)));
    ExecSQL;
  end;
  CDS_1.Delete;

end;

procedure TfrmTradeMarketQtyInPut.Tv1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
  if Key = VK_DOWN then
  begin
    btnAdd.Click();

  end;
  // 检测是否按下 Ctrl+V
//  if (Key = Ord('V')) and (Shift = [ssCtrl]) then
//  begin
//    pasteDatatTocxGrid(Tv1);
//
//  end;

end;

end.

