unit U_YMTRKInPut;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  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, dxSkinsCore, dxSkinBlack, dxSkinBlue,
  dxSkinBlueprint, dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom, dxSkinDarkSide,
  dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinFoggy,
  dxSkinGlassOceans, dxSkinHighContrast, dxSkiniMaginary, dxSkinLilian,
  dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMetropolis,
  dxSkinMetropolisDark, dxSkinMoneyTwins, dxSkinOffice2007Black,
  dxSkinOffice2007Blue, dxSkinOffice2007Green, dxSkinOffice2007Pink,
  dxSkinOffice2007Silver, dxSkinOffice2010Black, dxSkinOffice2010Blue,
  dxSkinOffice2010Silver, dxSkinOffice2013DarkGray, dxSkinOffice2013LightGray,
  dxSkinOffice2013White, dxSkinPumpkin, dxSkinSeven, dxSkinSevenClassic,
  dxSkinSharp, dxSkinSharpPlus, dxSkinSilver, dxSkinSpringTime, dxSkinStardust,
  dxSkinSummer2008, dxSkinTheAsphaltWorld, dxSkinsDefaultPainters,
  dxSkinValentine, dxSkinVS2010, dxSkinWhiteprint, dxSkinXmas2008Blue,
  dxSkinscxPCPainter, cxNavigator, cxCurrencyEdit, IdBaseComponent, IdComponent,
  IdTCPConnection, IdTCPClient, IdHTTP;

type
  TfrmYMTRKInPut = class(TForm)
    cxGrid2: TcxGrid;
    Tv1: TcxGridDBTableView;
    v1Column2: TcxGridDBColumn;
    v2Column1: TcxGridDBColumn;
    v1Column9: TcxGridDBColumn;
    v2Column6: TcxGridDBColumn;
    cxGrid2Level1: TcxGridLevel;
    ToolBar1: TToolBar;
    TBAdd: TToolButton;
    TBDel: TToolButton;
    TBSave: TToolButton;
    TBClose: TToolButton;
    v1Column4: TcxGridDBColumn;
    DataSource3: TDataSource;
    CDS_Sub: TClientDataSet;
    ADOQueryCmd: TADOQuery;
    ADOQueryMain: TADOQuery;
    ADOQueryTemp: TADOQuery;
    cxGridPopupMenu2: TcxGridPopupMenu;
    v1Column12: TcxGridDBColumn;
    v1Column14: TcxGridDBColumn;
    v1Column6: TcxGridDBColumn;
    v1Column7: TcxGridDBColumn;
    v1Column8: TcxGridDBColumn;
    v1Column10: TcxGridDBColumn;
    v1Column1: TcxGridDBColumn;
    v1Column3: TcxGridDBColumn;
    v1Column11: TcxGridDBColumn;
    v1Column15: TcxGridDBColumn;
    v1Column17: TcxGridDBColumn;
    v1Column18: TcxGridDBColumn;
    v1Column19: TcxGridDBColumn;
    v1Column20: TcxGridDBColumn;
    v1Column21: TcxGridDBColumn;
    ToolButton2: TToolButton;
    Panel4: TPanel;
    Label14: TLabel;
    Panel10: TPanel;
    Image2: TImage;
    Button1: TButton;
    GroupBox1: TGroupBox;
    CheckBox1: TCheckBox;
    CheckBox2: TCheckBox;
    CheckBox3: TCheckBox;
    CheckBox4: TCheckBox;
    CheckBox5: TCheckBox;
    CheckBox6: TCheckBox;
    CheckBox7: TCheckBox;
    CheckBox8: TCheckBox;
    CheckBox9: TCheckBox;
    Button2: TButton;
    Panel2: TPanel;
    CDS_MX: TClientDataSet;
    DS_MX: TDataSource;
    cxGrid1: TcxGrid;
    TvMX: TcxGridDBTableView;
    TvMXMXID: TcxGridDBColumn;
    TvMXMXQty: TcxGridDBColumn;
    cxGridLevel2: TcxGridLevel;
    Tv1Column1: TcxGridDBColumn;
    Tv1Column3: TcxGridDBColumn;
    TvMXColumn1: TcxGridDBColumn;
    Tv1PriceType: TcxGridDBColumn;
    Tv1IsTax: TcxGridDBColumn;
    Tv1Money: TcxGridDBColumn;
    Tv1Price: TcxGridDBColumn;
    Panel3: TPanel;
    Label17: TLabel;
    AddNum: TEdit;
    BtnQuicklyAdd: TButton;
    ToolBar2: TToolBar;
    TbAddRow: TToolButton;
    TbDeleteRow: TToolButton;
    http: TIdHTTP;
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure TBAddClick(Sender: TObject);
    procedure TBCloseClick(Sender: TObject);
    procedure FormShow(Sender: TObject);
    procedure TBDelClick(Sender: TObject);
    procedure TBSaveClick(Sender: TObject);
    procedure v1Column14PropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
    procedure v2Column1PropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
    procedure v1Column11PropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
    procedure v1Column16PropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
    procedure v1Column18PropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
    procedure Button2Click(Sender: TObject);
    procedure ToolButton2Click(Sender: TObject);
    procedure Image2Click(Sender: TObject);
    procedure Button1Click(Sender: TObject);
    procedure ToolButton3Click(Sender: TObject);
    procedure Tv1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
    procedure cxGridDBColumn8PropertiesEditValueChanged(Sender: TObject);
    procedure ToolButton4Click(Sender: TObject);
    procedure TvMXCustomDrawIndicatorCell(Sender: TcxGridTableView; ACanvas: TcxCanvas; AViewInfo: TcxCustomGridIndicatorItemViewInfo; var ADone: Boolean);
    procedure TvMXKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
    procedure v1Column21PropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
    procedure Tv1PricePropertiesEditValueChanged(Sender: TObject);
    procedure Tv1PriceTypePropertiesEditValueChanged(Sender: TObject);
    procedure BtnQuicklyAddClick(Sender: TObject);
    procedure TbAddRowClick(Sender: TObject);
    procedure TbDeleteRowClick(Sender: TObject);
    procedure AddNumKeyPress(Sender: TObject; var Key: Char);
    procedure FormDestroy(Sender: TObject);
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
    function SaveCKData(): Boolean;
    procedure InitMXGrid(SPID: string);
    procedure InitGrid();
    procedure AddRows();
    function YFData(): Boolean;
    function BatchStockIn(MXIDs: string; UserID: string): Boolean;
  public
    { Public declarations }
    FBCId: string;
    PState, CopyInt: Integer;
    FSelectedSPIDs: TStringList; // 用于保存所有选中的SPID
  end;

var
  frmYMTRKInPut: TfrmYMTRKInPut;

implementation

uses
  U_DataLink, U_RTFun, U_ZDYHelp, U_ZdyAttachGYS, U_MLMangeYHSel, U_ZdyAttachKH,
  U_KuWeiList, superobject;

{$R *.dfm}

function TfrmYMTRKInPut.BatchStockIn(MXIDs: string; UserID: string): Boolean;
var
  IdHttp: TIdHTTP;
  Url, ResponseStr: string;
  ResponseStream: TStringStream;
  vJson1: ISuperObject;
begin
  Result := False;

//   参数验证
  if Trim(MXIDs) = '' then
  begin
    ShowMessage('MXID不能为空');
    Exit;
  end;

  if Trim(UserID) = '' then
  begin
    ShowMessage('用户ID不能为空');
    Exit;
  end;

  IdHttp := TIdHTTP.Create(nil);
  ResponseStream := TStringStream.Create('');
  try
    try
      // GET请求 - 不需要设置ContentType
      // 参数直接放在URL中
      // 接口URL（参数编码在URL中）
      Url := 'http://www.rightsoft.top/YunXiang/api/YMTCK/batchStockIn?' + 'MXID=' + Trim(MXIDs) + '&userid=' + Trim(UserID);
//      ShowMessage(Url);
      // 发送GET请求
      IdHttp.Get(Url, ResponseStream);

      // 获取响应内容
      ResponseStr := ResponseStream.DataString;

      // 解析JSON响应
      vJson1 := SO(ResponseStr);
//      ShowMessage(ResponseStr);
      if (vJson1.O['code'] <> nil) then
      begin
        if (vJson1.O['code'].AsInteger = 10000) then
        begin
          Result := True;
          ShowMessage('批量入库成功！');
        end
        else
        begin
          // 获取错误信息
          if vJson1.O['message'] <> nil then
            ShowMessage('批量入库失败: ' + vJson1.O['message'].AsString)
          else
            ShowMessage('批量入库失败，未知错误');
        end;
      end
      else
      begin
        ShowMessage('接口返回格式错误');
      end;

    except
      on e: Exception do
      begin
        ShowMessage('网络请求异常: ' + e.Message);
      end;
    end;

  finally
    IdHttp.Free;
    ResponseStream.Free;
  end;
end;

function TfrmYMTRKInPut.YFData(): Boolean;
var
  CRID, OrdMainId, YFID, FComTaiTou, FCRID, FFactoryName, FFactoryNo: string;
begin
  Result := False;
  FFactoryName := Trim(CDS_Sub.FieldByName('FactoryName').AsString);
  FFactoryNo := Trim(CDS_Sub.FieldByName('FactoryNo').AsString);
  with ADOQueryTemp do
  begin
    Close;
    SQL.Clear;
    sql.Add('select * from YS_Money_KC where FactoryNo=' + quotedstr(Trim(FFactoryNo)));
    sql.Add(' and KCType=''GYS'' ');
    Open;
  end;
  if ADOQueryTemp.IsEmpty = False then
  begin
    CRID := ADOQueryTemp.fieldbyname('CRID').AsString;
  end
  else
  begin
    with ADOQueryTemp do
    begin
      Close;
      sql.Clear;
      sql.Add('select * from YS_Money_CRID');
      Open;
    end;
    if ADOQueryTemp.IsEmpty = False then
    begin
      with ADOQueryCmd do
      begin
        Close;
        sql.Clear;
        sql.Add('Update YS_Money_CRID set CRID=CRID+1');
        sql.Add('select * from YS_Money_CRID ');
        Open;
      end;
    end
    else
    begin
      with ADOQueryCmd do
      begin
        Close;
        sql.Clear;
        sql.Add('insert into YS_Money_CRID select 0 ');
        sql.Add('select * from YS_Money_CRID ');
        Open;
      end;
    end;

    CRID := ADOQueryCmd.fieldbyname('CRID').AsString;
    with ADOQueryCmd do
    begin
      Close;
      SQL.Clear;
      sql.Add('select * from YS_Money_KC where 1=2');
      Open;
    end;
    with ADOQueryCmd do
    begin
      Append;
      FieldByName('CRID').Value := StrToInt(CRID);
      FieldByName('FactoryName').Value := Trim(FFactoryName);
      FieldByName('FactoryNo').Value := Trim(FFactoryNo);
      FieldByName('ZdyStr1').Value := '应付付';
      FieldByName('KCType').Value := 'GYS';
      Post;
    end;
  end;

  with ADOQueryTemp do
  begin
    Close;
    sql.Clear;
    sql.Add('select * from YS_Money_CR where FactoryNo=' + quotedstr(Trim(FFactoryNo)));
    sql.Add(' and YFTypeId=''' + Trim(CDS_Sub.fieldbyname('SPID').AsString) + '''');
    Open;
  end;
  if ADOQueryTemp.IsEmpty then
  begin
    if GetLSNo(ADOQueryCmd, YFID, 'JG', 'YS_Money_CR', 4, 1) = False then
    begin
      Application.MessageBox('取应付最大号失败!', '提示', 0);
      Exit;
    end;
  end
  else
  begin
    YFID := Trim(ADOQueryTemp.fieldbyname('YFID').AsString);
  end;
  with ADOQueryCmd do
  begin
    Close;
    sql.Clear;
    sql.Add('select * from YS_Money_CR where YFID=''' + Trim(YFID) + '''');
    Open;
  end;

  with ADOQueryCmd do
  begin
    if ADOQueryTemp.IsEmpty then
    begin
      Append;
      FieldByName('SCQty').Value := CDS_Sub.FieldByName('Qty').Asfloat;
      FieldByName('SCPS').Value := CDS_Sub.FieldByName('PiQty').Asfloat;
    end
    else
      Edit;

    FieldByName('YFID').Value := Trim(YFID);
    FieldByName('YFTypeId').Value := Trim(CDS_Sub.fieldbyname('SPID').AsString);
    FieldByName('CRID').Value := StrToInt(CRID);
    FieldByName('YFName').Value := '采购费';
    FieldByName('Filler').Value := Trim(DName);
    FieldByName('CRType').Value := '应付款登记';
    FieldByName('CRFlag').Value := '应付付';
    FieldByName('ChkStatusP').Value := '未审核';
    FieldByName('ChkStatusQ').Value := '未审核';
    FieldByName('QtyFlag').Value := 1;
    FieldByName('FactoryName').Value := Trim(FFactoryName);
    FieldByName('FactoryNo').Value := Trim(FFactoryNo);
    FieldByName('CRTime').Value := CDS_Sub.fieldbyname('CRTime').AsString;
    if CDS_Sub.FieldByName('PriceType').Value = '米' then
    begin
      FieldByName('Qty').Value := CDS_Sub.FieldByName('Qty').Asfloat;
      FieldByName('QtyUnit').Value := 'M';
    end
    else
    begin
      FieldByName('Qty').Value := CDS_Sub.FieldByName('KGQty').Asfloat;
      FieldByName('QtyUnit').Value := 'KG';
    end;
    FieldByName('PS').Value := CDS_Sub.FieldByName('PiQty').Asfloat;
    FieldByName('YFType').Value := '自动生成';
    FieldByName('Price').Value := CDS_Sub.FieldByName('Price').Asfloat;
    FieldByName('Money').Value := CDS_Sub.FieldByName('Money').Asfloat;
    if CDS_Sub.FieldByName('IsTax').Value = '含税' then
    begin
      FieldByName('HanShui').Value := '含税';
    end
    else
    begin
      FieldByName('HanShui').Value := '不含税';
    end;
    FieldByName('CKNO').Value := trim(CDS_Sub.fieldbyname('SPID').AsString);
    FieldByName('SJQty').Value := CDS_Sub.FieldByName('Money').Asfloat;
    FieldByName('MiQty').Value := CDS_Sub.FieldByName('Qty').Asfloat;
    FieldByName('KGQty').Value := CDS_Sub.FieldByName('KGQty').Asfloat;
    FieldByName('JSmoney').Value := CDS_Sub.FieldByName('Money').Asfloat;
    FieldByName('HSmoney').Value := CDS_Sub.FieldByName('Money').Asfloat;
    FieldByName('P_CodeName').Value := CDS_Sub.FieldByName('SPName').Asstring;
    FieldByName('P_MF').Value := CDS_Sub.FieldByName('SPMF').Asstring;
    FieldByName('P_KZ').Value := CDS_Sub.FieldByName('SPKZ').Asstring;
    FieldByName('P_Color').Value := CDS_Sub.FieldByName('SPColor').Asstring;
//    FieldByName('P_ColorNo').Value := Trim(MYColorNo.Text); CDS_Sub.FieldByName('ColorNo').Asstring;
    FieldByName('P_HX').Value := CDS_Sub.FieldByName('SPHX').Asstring;
    FieldByName('BZType').Value := '￥';
    FieldByName('status').Value := '0';
    Post;
  end;
  with ADOQueryCmd do
  begin
    Close;
    sql.Clear;
    sql.Add('Update YS_Money_KC Set KCMoney=(select isnull(Sum(HSMoney*QtyFlag),0) from YS_Money_CR A where A.CRID=YS_Money_KC.CRID)');
    sql.Add(' where CRID=' + CRID);
    ExecSQL;
  end;
  Result := True;
end;

procedure TfrmYMTRKInPut.InitMXGrid(SPID: string);
var
  FilterSPID: string;
begin
  if not Assigned(CDS_MX) then
    Exit;

  try
    CDS_MX.DisableControls;
    try
      // 清除现有过滤器
      CDS_MX.Filtered := False;
      CDS_MX.Filter := '';

      // 从CDS_Sub获取SPID并设置过滤条件

      FilterSPID := SPID;

      if FilterSPID <> '' then
      begin
        CDS_MX.Filter := 'SPID = ''' + FilterSPID + '''';
        CDS_MX.Filtered := True;
      end;

      // 可选：如果没有过滤条件，定位到第一条记录
      if not CDS_MX.Filtered then
        CDS_MX.First;

    finally
      CDS_MX.EnableControls;
    end;
  except
    on E: Exception do
    begin
      // 可以在这里添加错误处理，比如显示消息
      MessageDlg('初始化MXGrid时出错: ' + E.Message, mtError, [mbOK], 0);
    end;
  end;
end;

procedure TfrmYMTRKInPut.AddRows();
var
  i, PiQty: Integer;
  MaxNo, MMXID, SPID: string;
begin
  if CDS_Sub.IsEmpty then
    Exit;
  SPID := Trim(CDS_Sub.fieldbyname('SPID').AsString);
  PiQty := CDS_Sub.fieldbyname('PiQty').AsInteger;

  try
    for i := 1 to PiQty do
    begin
      if GetLSNo(ADOQueryTemp, MaxNo, 'MCM', 'YMT_CK_MX', 3, 1) = False then
      begin
        Application.MessageBox('取最大号失败!', '提示', 0);
        Exit;
      end;

      MMXID := Trim(MaxNo);
      with ADOQueryCmd do
      begin
        Close;
        SQL.Clear;
        sql.Add('insert into  YMT_CK_MX (MXID,SPID,MXQty)');
        sql.Add('values(' + quotedstr(MMXID));
        sql.Add(',' + quotedstr(Trim(SPID)));
        sql.Add(',0');
        sql.Add(')');
        ExecSQL;
      end;
    end;
    InitMXGrid(SPID);
  except
    Application.MessageBox('添加失败!', '提示', 0);
  end;
end;

procedure TfrmYMTRKInPut.InitGrid();
var
  SPIDList: string;
  i: Integer;
begin
  // 如果有多个选中的SPID，构建IN查询条件
  if Assigned(FSelectedSPIDs) and (FSelectedSPIDs.Count > 0) then
  begin
    SPIDList := '';
    for i := 0 to FSelectedSPIDs.Count - 1 do
    begin
      if i > 0 then
        SPIDList := SPIDList + ',';
      SPIDList := SPIDList + QuotedStr(FSelectedSPIDs[i]);
    end;

    with ADOQueryTemp do
    begin
      Close;
      sql.Clear;
      sql.Add(' select A.* ');
      sql.Add(',OrderNO=(select OrderNO from JYOrder_Main JM where JM.MainId=A.ORDMainIdRK)');
      sql.Add(' from YMT_CK_CR A');
      sql.Add(' where SPID IN (' + SPIDList + ')');
      Open;
    end;
  end
  else
  begin
    // 原有的单个SPID查询逻辑
    with ADOQueryTemp do
    begin
      Close;
      sql.Clear;
      sql.Add(' select A.* ');
      sql.Add(',OrderNO=(select OrderNO from JYOrder_Main JM where JM.MainId=A.ORDMainIdRK)');
      sql.Add(' from YMT_CK_CR A');
      sql.Add(' where SPID=''' + Trim(FBCId) + '''');
      Open;
    end;
  end;
  
  // 其余代码保持不变
  SCreateCDS20(ADOQueryTemp, CDS_Sub);
  SInitCDSData20(ADOQueryTemp, CDS_Sub);
  if CDS_Sub.IsEmpty then
    Exit;

  // 注意：这里可能需要修改，因为现在有多个SPID
  // 您需要决定如何处理多个SPID的情况
  InitMXGrid(CDS_Sub.fieldbyname('SPID').AsString);
  
  // 其余代码保持不变
  with ADOQueryTemp do
  begin
    Close;
    sql.Clear;
    sql.Add('select * from YMT_CK_CR where FZSPID=''' + Trim(CDS_Sub.fieldbyname('SPID').AsString) + '''');
    sql.Add(' and CRQtyFlag=-1');
    Open;
  end;

  if not ADOQueryTemp.IsEmpty then
  begin
    // 禁用相关列
    v1Column4.Options.Focusing := False;
    v1Column14.Options.Focusing := False;
    v2Column1.Options.Focusing := False;
    v1Column8.Options.Focusing := False;
    v1Column7.Options.Focusing := False;
    v1Column1.Options.Focusing := False;
    v1Column10.Options.Focusing := False;
    v1Column11.Options.Focusing := False;
    Exit;
  end
  else
  begin
    // 启用相关列
    v1Column4.Options.Focusing := True;
    v1Column14.Options.Focusing := True;
    v2Column1.Options.Focusing := True;
    v1Column8.Options.Focusing := True;
    v1Column7.Options.Focusing := True;
    v1Column1.Options.Focusing := True;
    v1Column10.Options.Focusing := True;
    v1Column11.Options.Focusing := True;
  end;
end;
//procedure TfrmYMTRKInPut.InitGrid();
//begin
//  with ADOQueryTemp do
//  begin
//    Close;
//    sql.Clear;
//    sql.Add(' select A.* ');
//    sql.Add(',OrderNO=(select OrderNO from JYOrder_Main JM where JM.MainId=A.ORDMainIdRK)');
//    sql.Add(' from YMT_CK_CR A');
//    sql.Add(' where SPID=''' + Trim(FBCId) + '''');
//    Open;
//  end;
//  SCreateCDS20(ADOQueryTemp, CDS_Sub);
//  SInitCDSData20(ADOQueryTemp, CDS_Sub);
//  if CDS_Sub.IsEmpty then
//    Exit;
//
//  InitMXGrid(CDS_Sub.fieldbyname('SPID').AsString);
//  with ADOQueryTemp do
//  begin
//    Close;
//    sql.Clear;
//    sql.Add('select * from YMT_CK_CR where FZSPID=''' + Trim(CDS_Sub.fieldbyname('SPID').AsString) + '''');
//    sql.Add(' and CRQtyFlag=-1');
//    Open;
//  end;
//  if not ADOQueryTemp.IsEmpty then
//  begin
//    v1Column4.Options.Focusing := False;
//    v1Column14.Options.Focusing := False;
//    v2Column1.Options.Focusing := False;
//    v1Column8.Options.Focusing := False;
//    v1Column7.Options.Focusing := False;
//    v1Column1.Options.Focusing := False;
//    v1Column10.Options.Focusing := False;
//    v1Column11.Options.Focusing := False;
//    Exit;
//  end
//  else
//  begin
//    v1Column4.Options.Focusing := True;
//    v1Column14.Options.Focusing := True;
//    v2Column1.Options.Focusing := True;
//    v1Column8.Options.Focusing := True;
//    v1Column7.Options.Focusing := True;
//    v1Column1.Options.Focusing := True;
//    v1Column10.Options.Focusing := True;
//    v1Column11.Options.Focusing := True;
//  end;
//end;

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

procedure TfrmYMTRKInPut.TBAddClick(Sender: TObject);
var
  MMaxno: string;
begin
  if GetLSNo(ADOQueryCmd, MMaxno, 'DR', 'YMT_CK_CR', 3, 1) = False then
  begin
    Application.MessageBox('取待检布入库编号失败!', '提示', 0);
    Exit;
  end;
  if CDS_Sub.IsEmpty = False then
  begin
    CopyAddRowCDS(CDS_Sub);
    with CDS_Sub do
    begin
      Edit;
      FieldByName('SPID').Value := Trim(MMaxno);
      post;
    end;
  end
  else
  begin
    with CDS_Sub do
    begin
      Append;
      FieldByName('SPID').Value := Trim(MMaxno);
      FieldByName('CRTime').Value := Trim(FormatDateTime('yyyy-MM-dd', Now));
      FieldByName('QtyUnit').Value := 'M';
      FieldByName('ToFactoryName').Value := '云翔仓库';
      FieldByName('PriceType').Value := '米';
      FieldByName('IsTax').Value := '含税';
      FieldByName('Price').Value := '0';
      FieldByName('Qty').Value := '0';
      FieldByName('KGQty').Value := '0';
      Post;
    end;
  end;
end;

function TfrmYMTRKInPut.SaveCKData(): Boolean;
var
  FCRID, Maxno, MaxMXno, FFSPID, FFMXID: string;
  MXIDs: string; // 用于收集需要批量入库的MXID
begin
  try
    ADOQueryCmd.Connection.BeginTrans;
    CDS_Sub.DisableControls;
    // 初始化MXIDs，每个主表项开始时清空
    MXIDs := '';
    with CDS_Sub do
    begin
      First;
      while not eof do
      begin

        with ADOQueryTemp do
        begin
          Close;
          sql.Clear;
          sql.Add('select * from YMT_CK_CR where SPID=''' + Trim(CDS_Sub.fieldbyname('SPID').AsString) + '''');
          open;
        end;
        FFSPID := Trim(ADOQueryTemp.fieldbyname('SPID').AsString);

        if Trim(FFSPID) = '' then
        begin
          Maxno := Trim(CDS_Sub.fieldbyname('SPID').AsString);
        end
        else
        begin
          Maxno := Trim(FFSPID);
        end;

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

        with ADOQueryCmd do
        begin
          if Trim(FFSPID) = '' then
          begin
            Append;
          end
          else
          begin
            Edit;
          end;
          ////////////////////////////////////////////////////////////////////////////////////////////
          //////////保存主表数据
          FieldByName('SPID').Value := Trim(Maxno);
          FieldByName('FZSPID').Value := Trim(Maxno);
          FieldByName('CKName').Value := '待检布';
          FieldByName('CustomerNo').Value := Trim(CDS_Sub.fieldbyname('CustomerNo').AsString);
          FieldByName('FactoryNo').Value := Trim(CDS_Sub.fieldbyname('FactoryNo').AsString);
          FieldByName('FromFactoryNo').Value := Trim(CDS_Sub.fieldbyname('FromFactoryNo').AsString);
          FieldByName('ToFactoryNo').Value := Trim(CDS_Sub.fieldbyname('ToFactoryNo').AsString);
          FieldByName('ORDMainIdRK').Value := Trim(CDS_Sub.fieldbyname('ORDMainIdRK').AsString);
          FieldByName('ORDSubIdRK').Value := Trim(CDS_Sub.fieldbyname('ORDSubIdRK').AsString);
          FieldByName('CRFlag').Value := '入库';
          FieldByName('CRQtyFlag').Value := 1;

          RTSetSaveDataCDS(ADOQueryCmd, Tv1, CDS_Sub, 'YMT_CK_CR', 2);

          if Trim(FFSPID) = '' then
            FieldByName('Filler').Value := Trim(DName)
          else
          begin
            FieldByName('Editer').Value := Trim(DName);
            FieldByName('EditTime').Value := SGetServerDate(ADOQueryTemp);
          end;

          if Trim(CDS_Sub.fieldbyname('OrderNo').AsString) <> '' then
          begin
            FieldByName('QCOrderNo').Value := Trim(CDS_Sub.fieldbyname('OrderNo').AsString);
          end;
          ////////////////////////////////////////////////////////////////////////////////////////////
          Post;
        end;

        //////////生成应付数据
        YFData();

        with ADOQueryCmd do
        begin
          Close;
          sql.Clear;
          sql.Add('Update YMT_CK_CR Set MXKCQty=(select sum(isnull(Qty,0)*CRQtyFlag) from YMT_CK_CR A where A.FZSPID=YMT_CK_CR.SPID)');
          sql.Add(',MXKCPiQty=(select sum(isnull(PiQty,0)*CRQtyFlag) from YMT_CK_CR A where A.FZSPID=YMT_CK_CR.SPID)');
          sql.Add(' where SPID=''' + Trim(Maxno) + '''');
          ExecSQL;
        end;

        with ADOQueryTemp do
        begin
          Close;
          sql.Clear;
          sql.Add('select * from YMT_CK_CR where SPID=''' + Trim(Maxno) + '''');
          Open;
        end;

        if ADOQueryTemp.FieldByName('MXKCQty').Value < 0 then
        begin
          CDS_Sub.DisableControls;
          ADOQueryCmd.Connection.RollbackTrans;
          Application.MessageBox('入库数小于出库数不能保存!', '提示', 0);
          Exit;
        end;


       ///////////////////////////////////////////////////////////////////////////
       /// 保存子表
        with CDS_MX do
        begin
          DisableControls; // 禁用CDS_MX控件
          try
            CDS_MX.Filter := 'SPID = ''' + Trim(Maxno) + '''';
            First;
            while not Eof do
            begin
              // 查询明细记录是否存在
              with ADOQueryTemp do
              begin
                Close;
                SQL.Clear;
                SQL.Add('select * from YMT_CK_MX where MXID=''' + Trim(CDS_MX.fieldbyname('MXID').AsString) + '''');
                Open;
              end;

              FFMXID := Trim(ADOQueryTemp.fieldbyname('MXID').AsString);

              if Trim(FFMXID) = '' then
                MaxMXno := Trim(CDS_MX.fieldbyname('MXID').AsString)
              else
                MaxMXno := Trim(FFMXID);

              // 准备明细数据
              with ADOQueryCmd do
              begin
                Close;
                SQL.Clear;
                SQL.Add('select * from YMT_CK_MX where MXID=''' + Trim(MaxMXno) + '''');
                Open;

                if Trim(FFMXID) = '' then
                  Append
                else
                  Edit;

                FieldByName('SPID').Value := Trim(CDS_MX.fieldbyname('SPID').AsString);
                FieldByName('MXID').Value := Trim(MaxMXno); // 确保MXID被设置

                RTSetSaveDataCDS(ADOQueryCmd, TvMX, CDS_MX, 'YMT_CK_MX', 0);

                if Trim(FFMXID) = '' then
                  FieldByName('Filler').Value := Trim(DName)
                else
                begin
                  FieldByName('EditUser').Value := Trim(DName);
                  FieldByName('EditTime').Value := SGetServerDate(ADOQueryTemp);
                end;

                Post;
              end;

              // 检查MQty是否大于0，如果是则收集MXID
              if CDS_MX.FieldByName('MQty').AsFloat > 0 then
              begin
                if MXIDs <> '' then
                  MXIDs := MXIDs + ',' + Trim(MaxMXno)
                else
                  MXIDs := Trim(MaxMXno);
              end;

              Next; // 移动到下一条记录，避免死循环
            end;
          finally
            EnableControls; // 恢复CDS_MX控件状态
          end;
        end;

        Edit;
        FieldByName('SPID').Value := Trim(Maxno);
        Post;

        Next;
      end;
    end;
    CDS_Sub.EnableControls;

    ADOQueryCmd.Connection.CommitTrans;
    // 如果有需要批量入库的记录，调用接口
    if MXIDs <> '' then
    begin
      if not BatchStockIn(MXIDs, Trim(DCode)) then
      begin
//             如果接口调用失败，可以选择回滚事务
//        ADOQueryCmd.Connection.RollbackTrans;
        Application.MessageBox('批量入库接口调用失败!', '提示', 0);
        Exit;
      end;
    end;
    Result := True;
  except
    Result := False;

    ADOQueryCmd.Connection.RollbackTrans;
    Application.MessageBox('保存异常!', '提示', 0);
  end;

end;

procedure TfrmYMTRKInPut.TBCloseClick(Sender: TObject);
begin
  WriteCxGrid('待检布入库登记', Tv1, '待检布仓库');
  Close;
end;

procedure TfrmYMTRKInPut.FormShow(Sender: TObject);
var
  fsj: string;
begin
  ReadCxGrid('待检布入库登记', Tv1, '待检布仓库');
  InitGrid();

  with ADOQueryTemp do
  begin
    Close;
    sql.Clear;
    sql.Add('select * from YMT_CK_MX ');
    Open;
  end;
  SCreateCDS20(ADOQueryTemp, CDS_MX);
  SInitCDSData20(ADOQueryTemp, CDS_MX);
  if PState = 0 then
    InitMXGrid(' ')
  else
    InitMXGrid(Trim(CDS_Sub.fieldbyname('SPID').AsString));
end;

procedure TfrmYMTRKInPut.TBDelClick(Sender: TObject);
begin
  if CDS_Sub.IsEmpty then
    Exit;
  if Trim(CDS_Sub.fieldbyname('SPID').AsString) <> '' then
  begin
    if Application.MessageBox('确定要删除数据吗？', '提示', 32 + 4) <> IDYES then
      Exit;
    with ADOQueryTemp do
    begin
      Close;
      sql.Clear;
      sql.Add('select * from YMT_CK_CR where FZSPID=''' + Trim(CDS_Sub.fieldbyname('SPID').AsString) + '''');
      sql.Add(' and CRQtyFlag=-1');
      Open;
    end;
    if ADOQueryTemp.IsEmpty = False then
    begin
      Application.MessageBox('已有出库记录，不能删除!', '提示', 0);
      Exit;
    end;
    try
      ADOQueryCmd.Connection.BeginTrans;
      with ADOQueryCmd do
      begin
        Close;
        sql.Clear;
        sql.Add(' delete YMT_CK_CR where SPID=''' + Trim(CDS_Sub.fieldbyname('SPID').AsString) + '''');
        ExecSQL;
      end;

      ADOQueryCmd.Connection.CommitTrans;
      CDS_Sub.Delete;
    except
      ADOQueryCmd.Connection.RollbackTrans;
      Application.MessageBox('删除异常!', '提示', 0);
    end;

  end
  else
  begin
    CDS_Sub.Delete;
  end;

end;

procedure TfrmYMTRKInPut.TBSaveClick(Sender: TObject);
begin
  if CDS_Sub.IsEmpty then
    Exit;
//  if CDS_Sub.Locate('CRTime', null, []) = True then
//  begin
//    Application.MessageBox('入库时间不能为空!', '提示', 0);
//    Exit;
//  end;

  if CDS_Sub.Locate('CRType', null, []) = True then
  begin
    Application.MessageBox('入库类型不能为空!', '提示', 0);
    Exit;
  end;
  if CDS_Sub.Locate('SPName', null, []) = True then
  begin
    Application.MessageBox('品名不能为空!', '提示', 0);
    Exit;
  end;

//  if CDS_Sub.Locate('OrderNo', null, []) = True then
//  begin
//    Application.MessageBox('订单号不能为空!', '提示', 0);
//    Exit;
//  end;
//  if CDS_Sub.Locate('ToFactoryName', null, []) = True then
//  begin
//    Application.MessageBox('存放工厂不能为空!', '提示', 0);
//    Exit;
//  end;
  if (trim(CDS_Sub.fieldbyname('CRType').AsString) <> '期初入库') and (trim(CDS_Sub.fieldbyname('CRType').AsString) <> '客户退货') then
  begin
    if CDS_Sub.Locate('FactoryName', null, []) = True then
    begin
      Application.MessageBox('供应商不能为空!', '提示', 0);
      Exit;
    end;
  end;


//  if CDS_Sub.Locate('PiQty', null, []) = True then
//  begin
//    Application.MessageBox('匹数不能为空!', '提示', 0);
//    Exit;
//  end;
//  if CDS_Sub.Locate('Qty', null, []) = True then
//  begin
//    Application.MessageBox('数量不能为空!', '提示', 0);
//    Exit;
//  end;
//  if CDS_Sub.Locate('QtyUnit', null, []) = True then
//  begin
//    Application.MessageBox('数量单位不能为空!', '提示', 0);
//    Exit;
//  end;
//  if CDS_Sub.Locate('CRType;FromFactoryName', VarArrayOf(['生产退回', Null]), [loPartialKey]) = True then
//  begin
//    Application.MessageBox('生产退回的数据，来自工厂不能为空!', '提示', 0);
//    Exit;
//  end;
  if SaveCKData() then
  begin
    Application.MessageBox('保存成功!', '提示', 0);
    ModalResult:=1;
    Exit;
  end;
end;

procedure TfrmYMTRKInPut.v1Column14PropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
begin
  try
    frmZdyAttachGYS := TfrmZdyAttachGYS.Create(Application);
    with frmZdyAttachGYS do
    begin
      if ShowModal = 1 then
      begin

        with Self.CDS_Sub do
        begin
          edit;
          FieldByName('FactoryNo').Value := Trim(frmZdyAttachGYS.CDS_HZ.fieldbyname('KHNo').AsString);
          FieldByName('FactoryName').Value := Trim(frmZdyAttachGYS.CDS_HZ.fieldbyname('KHNameJC').AsString);
          FieldByName('FromFactoryNo').Value := Trim(frmZdyAttachGYS.CDS_HZ.fieldbyname('KHNo').AsString);
          FieldByName('FromFactoryName').Value := Trim(frmZdyAttachGYS.CDS_HZ.fieldbyname('KHNameJC').AsString);
          //Post;
        end;
      end;
    end;
  finally
    frmZdyAttachGYS.Free;
  end;

end;

procedure TfrmYMTRKInPut.v2Column1PropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
begin
  try
    frmMLMangeYHSel := TfrmMLMangeYHSel.Create(Application);
    with frmMLMangeYHSel do
    begin
      if ShowModal = 1 then
      begin
        with Self.CDS_Sub do
        begin
          Edit;
          FieldByName('SPcode').Value := Trim(frmMLMangeYHSel.CDS_Main.fieldbyname('MLXXNO').AsString);
          FieldByName('SPName').Value := Trim(frmMLMangeYHSel.CDS_Main.fieldbyname('MLName').AsString);
          FieldByName('GYLXName').Value := Trim(frmMLMangeYHSel.CDS_Main.fieldbyname('GYLXName').AsString);
          FieldByName('SPCF').Value := Trim(frmMLMangeYHSel.CDS_Main.fieldbyname('MLCF').AsString);
          FieldByName('SPMF').Value := Trim(frmMLMangeYHSel.CDS_Main.fieldbyname('MLMF').AsString);
          FieldByName('SPKZ').Value := Trim(frmMLMangeYHSel.CDS_Main.fieldbyname('MLkz').AsString);

        end;
      end;
    end;
  finally
    frmMLMangeYHSel.Free;
  end;
end;

procedure TfrmYMTRKInPut.v1Column11PropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
begin
  try
    frmZdyAttachGYS := TfrmZdyAttachGYS.Create(Application);
    with frmZdyAttachGYS do
    begin
      if ShowModal = 1 then
      begin
        with Self.CDS_Sub do
        begin
          edit;
          FieldByName('ToFactoryNo').Value := Trim(frmZdyAttachGYS.CDS_HZ.fieldbyname('KHNo').AsString);
          FieldByName('ToFactoryName').Value := Trim(frmZdyAttachGYS.CDS_HZ.fieldbyname('KHNameJC').AsString);
          //Post;
        end;
      end;
    end;
  finally
    frmZdyAttachGYS.Free;
  end;
end;

procedure TfrmYMTRKInPut.v1Column16PropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
begin
  try
    frmZdyAttachGYS := TfrmZdyAttachGYS.Create(Application);
    with frmZdyAttachGYS do
    begin
      if ShowModal = 1 then
      begin
        with Self.CDS_Sub do
        begin
          edit;
          FieldByName('FromFactoryNo').Value := Trim(frmZdyAttachGYS.CDS_HZ.fieldbyname('ZdyCode').AsString);
          FieldByName('FromFactoryName').Value := Trim(frmZdyAttachGYS.CDS_HZ.fieldbyname('ZdyName').AsString);
          //Post;
        end;
      end;
    end;
  finally
    frmZdyAttachGYS.Free;
  end;
end;

procedure TfrmYMTRKInPut.v1Column18PropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
begin
  try
    frmKuWeiList := TfrmKuWeiList.Create(Application);
    with frmKuWeiList do
    begin
      if ShowModal = 1 then
      begin
        with Self.CDS_Sub do
        begin
          Edit;
          FieldByName('KuWei').Value := Trim(frmKuWeiList.Order_Main.fieldbyname('KWName').AsString);
        end;
      end;
    end;
  finally
    frmKuWeiList.Free;
  end;
end;

procedure TfrmYMTRKInPut.Button2Click(Sender: TObject);
var
  CRType, FactoryName, RCGangNo, ToFactoryName, KuWei, QtyUnit, Note: string;
  i, PiQty: Integer;
  qty: Double;
begin
  try
    if CDS_Sub.IsEmpty then
      Exit;
    CDS_Sub.DisableControls;
    with CDS_Sub do
    begin
      CRType := Trim(CDS_Sub.fieldbyname('CRType').AsString);
      FactoryName := Trim(CDS_Sub.fieldbyname('FactoryName').AsString);
      RCGangNo := Trim(CDS_Sub.fieldbyname('RCGangNo').AsString);
      ToFactoryName := Trim(CDS_Sub.fieldbyname('ToFactoryName').AsString);
      KuWei := Trim(CDS_Sub.fieldbyname('KuWei').AsString);
      PiQty := CDS_Sub.fieldbyname('PiQty').AsInteger;
      qty := CDS_Sub.fieldbyname('Qty').AsFloat;
      QtyUnit := Trim(CDS_Sub.fieldbyname('QtyUnit').AsString);
      Note := Trim(CDS_Sub.fieldbyname('Note').AsString);
    end;
    with CDS_Sub do
    begin
      First;
      while not eof do
      begin
        Edit;
        if CheckBox1.Checked then
          FieldByName('CRType').Value := CRType;
        if CheckBox2.Checked then
          FieldByName('FactoryName').Value := FactoryName;
        if CheckBox3.Checked then
          FieldByName('RCGangNo').Value := RCGangNo;
        if CheckBox4.Checked then
          FieldByName('ToFactoryName').Value := ToFactoryName;
        if CheckBox5.Checked then
          FieldByName('KuWei').Value := KuWei;
        if CheckBox6.Checked then
          FieldByName('PiQty').Value := PiQty;
        if CheckBox7.Checked then
          FieldByName('Qty').Value := qty;
        if CheckBox8.Checked then
          FieldByName('QtyUnit').Value := QtyUnit;
        if CheckBox9.Checked then
          FieldByName('Note').Value := Note;
        Post;
        Next;
      end;
    end;
    CDS_Sub.EnableControls;
  except
    Application.MessageBox('替换异常!', '提示', 0);
  end;
end;

procedure TfrmYMTRKInPut.ToolButton2Click(Sender: TObject);
begin
  Panel4.Visible := True;
end;

procedure TfrmYMTRKInPut.Image2Click(Sender: TObject);
begin
  Panel4.Visible := False;
end;

procedure TfrmYMTRKInPut.Button1Click(Sender: TObject);
var
  i: Integer;
begin
  for i := 0 to GroupBox1.ControlCount - 1 do
  begin
    if GroupBox1.Controls[i] is TCheckBox then
    begin
      TCheckBox(GroupBox1.Controls[i]).Checked := true;
    end;
  end;
end;

procedure TfrmYMTRKInPut.ToolButton3Click(Sender: TObject);
var
  i, PiQty: Integer;
  MaxNo, MMXID, SPID: string;
begin
  SPID := Trim(CDS_Sub.fieldbyname('SPID').AsString);
  PiQty := StrToInt(Trim(CDS_Sub.fieldbyname('PiQty').AsString));
  if GetLSNo(ADOQueryTemp, MaxNo, 'MCM', 'YMT_CK_MX', 3, 1) = False then
  begin
    Application.MessageBox('取最大号失败!', '提示', 0);
    Exit;
  end;

  try
    ADOQueryCmd.Connection.BeginTrans;
    for i := 0 to PiQty - 1 do
    begin
      MMXID := Trim(MaxNo);
      with ADOQueryCmd do
      begin
        Close;
        SQL.Clear;
        sql.Add('insert into  YMT_CK_MX (MXID,SPID,MXQty)');
        sql.Add('values(' + quotedstr(MMXID));
        sql.Add(',' + quotedstr(Trim(SPID)));
        sql.Add(',0');
        sql.Add(')');
        ExecSQL;
      end;
    end;
    ADOQueryCmd.Connection.CommitTrans;
    InitMXGrid(SPID);
  except
    ADOQueryCmd.Connection.RollbackTrans;
    Application.MessageBox('添加失败!', '提示', 0);
  end;

end;

procedure TfrmYMTRKInPut.Tv1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin

  InitMXGrid(Trim(CDS_Sub.fieldbyname('SPID').AsString));

end;

procedure TfrmYMTRKInPut.cxGridDBColumn8PropertiesEditValueChanged(Sender: TObject);
var
  mvalue, FFieldName: string;
begin

  mvalue := TcxTextEdit(Sender).EditingText;
  FFieldName := Trim(TvMX.Controller.FocusedColumn.DataBinding.FilterFieldName);
  with CDS_MX do
  begin
    Edit;
    FieldByName(FFieldName).Value := mvalue;
    Post;
  end;

  with ADOQueryCmd do
  begin
    Close;
    SQL.Clear;
    sql.Add('update YMT_CK_MX set ' + FFieldName + ' = ' + mvalue);
    sql.Add('  where MXID=' + quotedstr(Trim(CDS_MX.FieldByName('MXID').AsString)));
    ExecSQL;
  end;
  TvMX.Controller.EditingController.ShowEdit();
end;

procedure TfrmYMTRKInPut.ToolButton4Click(Sender: TObject);
begin
  with ADOQueryCmd do
  begin
    Close;
    SQL.Clear;
    sql.Add('delete YMT_CK_MX   where MXID=' + quotedstr(Trim(CDS_MX.FieldByName('MXID').AsString)));
    ExecSQL;
  end;
  CDS_MX.Delete;
end;

procedure TfrmYMTRKInPut.TvMXCustomDrawIndicatorCell(Sender: TcxGridTableView; ACanvas: TcxCanvas; AViewInfo: TcxCustomGridIndicatorItemViewInfo; var ADone: Boolean);
var
  FValue: string;
  FBounds: TRect;
begin
  FBounds := AViewInfo.Bounds;
  if (AViewInfo is TcxGridIndicatorRowItemViewInfo) then
  begin
    ACanvas.FillRect(FBounds);
    ACanvas.DrawComplexFrame(FBounds, clBtnHighlight, clBtnShadow, [bBottom, bLeft, bRight], 1);
    FValue := IntToStr(TcxGridIndicatorRowItemViewInfo(AViewInfo).GridRecord.Index + 1);
    InflateRect(FBounds, -1, -1);    //Platform   specific.   May   not   work   on   Linux.
    ACanvas.Font.Color := clBlack;
    ACanvas.Brush.Style := bsClear;
    ACanvas.DrawText(FValue, FBounds, cxAlignCenter or cxAlignTop);
    ADone := True;
  end;
end;

procedure TfrmYMTRKInPut.TvMXKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
  TvMX.OptionsData.Editing := False;
  if Key = 13 then
    Key := 40;
  TvMX.OptionsData.Editing := True;
end;

procedure TfrmYMTRKInPut.v1Column21PropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
begin
  try
    frmZdyAttachkh := TfrmZdyAttachkh.Create(Application);
    with frmZdyAttachkh do
    begin
      if ShowModal = 1 then
      begin

        with Self.CDS_Sub do
        begin
          edit;
          FieldByName('CustomerNo').Value := Trim(frmZdyAttachkh.CDS_HZ.fieldbyname('KHNo').AsString);
          FieldByName('CustomerNoName').Value := Trim(frmZdyAttachkh.CDS_HZ.fieldbyname('KHNameJC').AsString);
          //Post;
        end;
      end;
    end;
  finally
    frmZdyAttachkh.Free;
  end;

end;

procedure TfrmYMTRKInPut.Tv1PricePropertiesEditValueChanged(Sender: TObject);
var
  mvalue, FFieldName: string;
begin
  mvalue := TcxCurrencyEdit(Sender).EditingText;
  FFieldName := Trim(Tv1.Controller.FocusedColumn.DataBinding.FilterFieldName);
  with CDS_Sub do
  begin
    Edit;
    FieldByName(FFieldName).Value := mvalue;
    Post;
  end;

  with CDS_Sub do
  begin
    Edit;
    if FieldByName('PriceType').Value = '米' then
      FieldByName('Money').Value := FieldByName('Price').Asfloat * FieldByName('Qty').Asfloat
    else
      FieldByName('Money').Value := FieldByName('Price').Asfloat * FieldByName('KGQty').Asfloat;
    Post;
  end;
end;

procedure TfrmYMTRKInPut.Tv1PriceTypePropertiesEditValueChanged(Sender: TObject);
var
  mvalue, FFieldName: string;
begin
  mvalue := TcxComboBox(Sender).EditingText;
  FFieldName := Trim(Tv1.Controller.FocusedColumn.DataBinding.FilterFieldName);
  with CDS_Sub do
  begin
    Edit;
    FieldByName(FFieldName).Value := mvalue;
    Post;
  end;

  with CDS_Sub do
  begin
    Edit;
    if FieldByName('PriceType').Value = '米' then
      FieldByName('Money').Value := FieldByName('Price').Asfloat * FieldByName('Qty').Asfloat
    else
      FieldByName('Money').Value := FieldByName('Price').Asfloat * FieldByName('KGQty').Asfloat;
    Post;
  end;
end;

procedure TfrmYMTRKInPut.BtnQuicklyAddClick(Sender: TObject);
var
  Num, i: Integer;
  MaxNo, MMXID, SPID: string;
begin
  Num := StrToInt(Trim(AddNum.Text));
  SPID := Trim(CDS_Sub.fieldbyname('SPID').AsString);
  if SPID = '' then
    Exit;

  try
    ADOQueryCmd.Connection.BeginTrans;
    for i := 1 to Num do
    begin
      if GetLSNo(ADOQueryTemp, MaxNo, 'MCM', 'YMT_CK_MX', 3, 1) = False then
      begin
        Application.MessageBox('取最大号失败!', '提示', 0);
        Exit;
      end;
      MMXID := Trim(MaxNo);
      with CDS_MX do
      begin
        Append;
        FieldByName('MXID').Value := MMXID;
        FieldByName('SPID').Value := SPID;
        FieldByName('MQty').Value := '0';
        FieldByName('KGQty').Value := '0';
        Post;
      end;
    end;
    ADOQueryCmd.Connection.CommitTrans;
  except
    ADOQueryCmd.Connection.RollbackTrans;
    Application.MessageBox('添加失败!', '提示', 0);
  end;

end;

procedure TfrmYMTRKInPut.TbAddRowClick(Sender: TObject);
var
  MaxNo, MMXID, SPID: string;
begin
  SPID := Trim(CDS_Sub.fieldbyname('SPID').AsString);
  if SPID = '' then
    Exit;
  if GetLSNo(ADOQueryTemp, MaxNo, 'MCM', 'YMT_CK_MX', 3, 1) = False then
  begin
    Application.MessageBox('取最大号失败!', '提示', 0);
    Exit;
  end;

  MMXID := Trim(MaxNo);

  with CDS_MX do
  begin
    if IsEmpty = False then
    begin
      Append;
    end
    else
    begin
      Edit;
    end;
    FieldByName('MXID').Value := MMXID;
    FieldByName('SPID').Value := SPID;
    FieldByName('MQty').Value := '0';
    FieldByName('KGQty').Value := '0';
    Post;
  end;

end;

procedure TfrmYMTRKInPut.TbDeleteRowClick(Sender: TObject);
var
  Bookmark: TBookmark;
begin
  if CDS_MX.IsEmpty then
  begin
    Application.MessageBox('当前没有可删除的记录！', '提示', MB_ICONWARNING);
    Exit;
  end;

  if Trim(CDS_MX.fieldbyname('MXID').AsString) <> '' then
  begin
    with ADOQueryTemp do
    begin
      Close;
      sql.Clear;
      sql.Add('select * from YMT_FHSQ_Sub where MXID=''' + Trim(CDS_MX.fieldbyname('MXID').AsString) + '''');
      Open;
    end;
    if ADOQueryTemp.IsEmpty = False then
    begin
      Application.MessageBox('已有出库申请记录，不能删除!', '提示', 0);
      Exit;
    end;
  end;

  if Application.MessageBox('确定要删除当前行吗？', '确认删除', MB_ICONQUESTION + MB_YESNO) <> IDYES then
    Exit;
    
  // 记录当前行，删除后尝试回到附近位置
  Bookmark := CDS_MX.GetBookmark;
  with ADOQueryCmd do
  begin
    Close;
    SQL.Clear;
    sql.Add('delete YMT_CK_MX   where MXID=' + quotedstr(Trim(CDS_MX.FieldByName('MXID').AsString)));
    ExecSQL;
  end;
  with ADOQueryCmd do
  begin
    Close;
    SQL.Clear;
    sql.Add('delete YMT_CK_CR   where FromMXID=' + quotedstr(Trim(CDS_MX.FieldByName('MXID').AsString)));
    ExecSQL;
  end;
  try
    CDS_MX.Delete;
  finally
    if CDS_MX.BookmarkValid(Bookmark) then
      CDS_MX.GotoBookmark(Bookmark);
    CDS_MX.FreeBookmark(Bookmark);
  end;

end;

procedure TfrmYMTRKInPut.AddNumKeyPress(Sender: TObject; var Key: Char);
begin
  if Key = #13 then
    BtnQuicklyAdd.Click;

end;

procedure TfrmYMTRKInPut.FormDestroy(Sender: TObject);
begin
 if Assigned(FSelectedSPIDs) then
    FSelectedSPIDs.Free;
  inherited;
end;

procedure TfrmYMTRKInPut.FormCreate(Sender: TObject);
begin
FSelectedSPIDs := TStringList.Create;
end;

end.

