unit U_MachRollMain;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
  System.Classes, Vcl.Graphics, mmsystem, Diagnostics, Vcl.Controls, Vcl.Forms,
  Vcl.Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters,
  cxClasses, dxLayoutContainer, dxLayoutControl, dxLayoutcxEditAdapters,
  cxContainer, cxEdit, Vcl.StdCtrls, cxTextEdit, Vcl.ExtCtrls,
  dxLayoutControlAdapters, U_BaseList, Data.DB, Data.Win.ADODB, Vcl.Buttons,
  Vcl.ComCtrls, Vcl.ToolWin, cxImage, cxDBEdit, cxStyles, cxCustomData, cxFilter,
  cxData, cxDataStorage, cxNavigator, dxDateRanges, dxScrollbarAnnotations,
  cxDBData, dxBarBuiltInMenu, cxPC, cxGridLevel, cxGridCustomTableView,
  cxGridTableView, cxGridDBTableView, cxGridCustomView, cxGrid, cxMemo,
  cxRichEdit, U_frameBads, Datasnap.DBClient, RM_Common, RM_Class, RM_GridReport,
  cxCheckBox, cxMaskEdit, cxDropDownEdit, Vcl.Menus, cxButtonEdit, RM_Dataset,
  cxGeometry, dxFramedControl, dxPanel, U_KeyBoard, cxGroupBox,
  cxGridCustomPopupMenu, cxGridPopupMenu, MovePanel, RM_RichEdit, cxProgressBar,
  cxCurrencyEdit, Xml.XMLDoc, Xml.xmldom, Xml.XMLIntf, cxDateUtils,
  System.DateUtils;

type
  TfrmMachRollMain = class(TfrmBaseList)
    dxLayoutControl_packGroup_Root: TdxLayoutGroup;
    dxLayoutControl_pack: TdxLayoutControl;
    Piece: TcxTextEdit;
    Qty: TcxTextEdit;
    FtyPCId: TcxTextEdit;
    Color: TcxTextEdit;
    ColorNo: TcxTextEdit;
    CodeName: TcxTextEdit;
    OrderNo: TcxTextEdit;
    edtScan: TcxTextEdit;
    Button_set: TButton;
    BCIOID: TcxTextEdit;
    dxLayoutGroup_scan: TdxLayoutGroup;
    dxLayoutItem1: TdxLayoutItem;
    dxLayoutItem2: TdxLayoutItem;
    dxLayoutItem3: TdxLayoutItem;
    dxLayoutGroup_plan: TdxLayoutGroup;
    dxLayoutItem4: TdxLayoutItem;
    dxLayoutItem5: TdxLayoutItem;
    dxLayoutItem6: TdxLayoutItem;
    dxLayoutGroup_plan_1: TdxLayoutGroup;
    dxLayoutGroup_plan_2: TdxLayoutGroup;
    dxLayoutItem7: TdxLayoutItem;
    dxLayoutItem8: TdxLayoutItem;
    dxLayoutItem9: TdxLayoutItem;
    dxLayoutItem10: TdxLayoutItem;
    dxLayoutItem11: TdxLayoutItem;
    dxLayoutEmptySpaceItem1: TdxLayoutEmptySpaceItem;
    InputLen: TcxTextEdit;
    BTPrint: TButton;
    Button_bad: TButton;
    btnRK: TButton;
    Edit_pieceOrder: TcxTextEdit;
    Edit_fixLen: TcxTextEdit;
    Tare: TcxTextEdit;
    Coefficient: TcxTextEdit;
    InputWeight: TcxTextEdit;
    BatchNO: TcxTextEdit;
    PieceNo: TcxTextEdit;
    OutPutWeight: TcxTextEdit;
    edtPacketNo: TcxTextEdit;
    dxLayoutGroup_do: TdxLayoutGroup;
    dxLayoutItem13: TdxLayoutItem;
    dxLayoutItem_roll: TdxLayoutItem;
    dxLayoutGroup_do1: TdxLayoutGroup;
    dxLayoutGroup_do2: TdxLayoutGroup;
    dxLayoutItem15: TdxLayoutItem;
    dxLayoutItem16: TdxLayoutItem;
    dxLayoutItem_outweight: TdxLayoutItem;
    lblLenUnit: TdxLayoutLabeledItem;
    dxLayoutItem18: TdxLayoutItem;
    dxLayoutLabeledItem2: TdxLayoutLabeledItem;
    dxLayoutItem_packno: TdxLayoutItem;
    dxLayoutItem_rk: TdxLayoutItem;
    dxLayoutItem21: TdxLayoutItem;
    dxLayoutEmptySpaceItem3: TdxLayoutEmptySpaceItem;
    dxLayoutAutoCreatedGroup1: TdxLayoutAutoCreatedGroup;
    dxLayoutAutoCreatedGroup3: TdxLayoutAutoCreatedGroup;
    dxLayoutAutoCreatedGroup5: TdxLayoutAutoCreatedGroup;
    dxLayoutGroup1: TdxLayoutGroup;
    dxLayoutItem_pieceorder: TdxLayoutItem;
    dxLayoutItem_fixlen: TdxLayoutItem;
    dxLayoutEmptySpaceItem5: TdxLayoutEmptySpaceItem;
    dxLayoutItem24: TdxLayoutItem;
    dxLayoutGroup2: TdxLayoutGroup;
    cxDBImage1: TcxDBImage;
    Panel_right: TPanel;
    cxGrid3: TcxGrid;
    Tv3: TcxGridDBTableView;
    v3PieceNo: TcxGridDBColumn;
    Tv3Yardage: TcxGridDBColumn;
    Tv3Meter: TcxGridDBColumn;
    v3NetWeight: TcxGridDBColumn;
    v3GrossWeight: TcxGridDBColumn;
    Tv3Grade: TcxGridDBColumn;
    tv3CIID: TcxGridDBColumn;
    Tv3BatchNO: TcxGridDBColumn;
    Tv3PacketNo: TcxGridDBColumn;
    cxGridLevel2: TcxGridLevel;
    cxPageControl1: TcxPageControl;
    cxTabSheet1: TcxTabSheet;
    cxGrid2: TcxGrid;
    Tv2: TcxGridDBTableView;
    tv2CDType: TcxGridDBColumn;
    tv2CDWZ: TcxGridDBColumn;
    v2Column2: TcxGridDBColumn;
    Tv2CDQty: TcxGridDBColumn;
    Tv2CDReason: TcxGridDBColumn;
    v2Column1: TcxGridDBColumn;
    v2Column3: TcxGridDBColumn;
    v2Column4: TcxGridDBColumn;
    cxGridLevel1: TcxGridLevel;
    sheetLook: TcxTabSheet;
    cxGrid1: TcxGrid;
    TV1: TcxGridDBTableView;
    cxGridDBColumn2: TcxGridDBColumn;
    cxGridDBColumn3: TcxGridDBColumn;
    cxGridDBColumn4: TcxGridDBColumn;
    cxGridDBColumn5: TcxGridDBColumn;
    cxGridDBColumn6: TcxGridDBColumn;
    cxGridDBColumn7: TcxGridDBColumn;
    cxGridDBColumn8: TcxGridDBColumn;
    cxGridDBColumn9: TcxGridDBColumn;
    cxGridLevel3: TcxGridLevel;
    ToolBar2: TToolBar;
    ToolButton3: TToolButton;
    Trolldel: TToolButton;
    Tedit: TToolButton;
    ToolButton4: TToolButton;
    ToolButton7: TToolButton;
    ToolButton8: TToolButton;
    dxLayoutItem_zhfield: TdxLayoutItem;
    AOrdDefNote1: TcxRichEdit;
    dxLayoutItem_pic: TdxLayoutItem;
    dxLayoutAutoCreatedGroup2: TdxLayoutAutoCreatedGroup;
    cds_params: TClientDataSet;
    cds_paramsdabao: TStringField;
    cds_paramspackRolls: TIntegerField;
    cds_paramsrollNoMake: TStringField;
    cds_paramsMinWeight: TIntegerField;
    cds_paramsMaxWeight: TIntegerField;
    cds_paramslblLenUnit: TStringField;
    cds_paramsMinLen: TIntegerField;
    cds_paramsmaxLen: TIntegerField;
    cds_paramsweightRule: TIntegerField;
    cds_paramschen: TStringField;
    cds_paramsmabiao: TStringField;
    cds_paramsmbunit: TStringField;
    cds_paramsmplace: TIntegerField;
    cds_paramsyplace: TIntegerField;
    cds_paramskgplace: TIntegerField;
    cds_paramslabNumber: TIntegerField;
    CDS_2: TClientDataSet;
    DS_2: TDataSource;
    cds_1: TClientDataSet;
    cds_3: TClientDataSet;
    ds_3: TDataSource;
    ds_1: TDataSource;
    ADOQueryMain: TADOQuery;
    cds_paramsoutPage: TStringField;
    ADOQueryPrint: TADOQuery;
    RM1: TRMGridReport;
    grade: TcxComboBox;
    dxLayoutItem_grade: TdxLayoutItem;
    dxLayoutItem17: TdxLayoutItem;
    btnUnRk: TButton;
    Btn_rlBill: TButton;
    dxLayoutItem_unrk: TdxLayoutItem;
    dxLayoutItem_rkd: TdxLayoutItem;
    Tv3FtyPCId: TcxGridDBColumn;
    cds_paramsEndPieceNo: TIntegerField;
    cds_paramsBeginPieceNo: TIntegerField;
    cds_paramsFixedLength: TIntegerField;
    cds_paramspacknoMake: TStringField;
    cds_paramspieceOrder: TBooleanField;
    lblRuleConversion: TcxComboBox;
    dxLayoutItem14: TdxLayoutItem;
    dxLayoutAutoCreatedGroup4: TdxLayoutAutoCreatedGroup;
    cds_paramsLabVolume: TStringField;
    cds_paramsLabPackage: TStringField;
    dxLayoutItem_packnote: TdxLayoutItem;
    packnote: TcxMemo;
    RMDB_1: TRMDBDataSet;
    TprintPack: TToolButton;
    Tlog: TToolButton;
    dxPanel_mid: TdxPanel;
    cxGroupBox_keys: TcxGroupBox;
    FrameKeyBoard1: TFrameKeyBoard;
    frameBads1: TframeBads;
    dxLayoutItem_Pattern: TdxLayoutItem;
    C_Pattern: TcxTextEdit;
    Tv2SubtractQty: TcxGridDBColumn;
    TV1SubtractQty: TcxGridDBColumn;
    Tv3SubtractQty: TcxGridDBColumn;
    RuleYardstick: TcxTextEdit;
    dxLayoutItem_RuleYardstick: TdxLayoutItem;
    cds_paramsAddwetPresent: TFloatField;
    cds_paramsAddLenPresent: TFloatField;
    C_StyleNo: TcxTextEdit;
    dxLayoutItem_StyleNo: TdxLayoutItem;
    Tv3AddwetPresent: TcxGridDBColumn;
    Tv3AddLenPresent: TcxGridDBColumn;
    cxGridPopupMenu1: TcxGridPopupMenu;
    MovePanel1: TMovePanel;
    ADOQueryImage: TADOQuery;
    DS_IMAGE: TDataSource;
    cds_paramspackPrintPreview: TBooleanField;
    RMRichObject1: TRMRichObject;
    cds_paramspacklabNumber: TIntegerField;
    cds_paramspackPostAction: TStringField;
    packPostBtn: TButton;
    dxLayoutItem_packpost: TdxLayoutItem;
    customStrField1: TcxTextEdit;
    dxLayoutItem_customStrField1: TdxLayoutItem;
    dxLayoutItem_customStrField2: TdxLayoutItem;
    customStrField2: TcxTextEdit;
    dxLayoutItem_width: TdxLayoutItem;
    dxLayoutItem_gram: TdxLayoutItem;
    C_Width: TcxTextEdit;
    C_GramWeight: TcxTextEdit;
    dxLayoutItem_addlen: TdxLayoutItem;
    dxLayoutItem_addwet: TdxLayoutItem;
    Tv3addlen: TcxGridDBColumn;
    Tv3addWet: TcxGridDBColumn;
    addLen: TcxTextEdit;
    addWet: TcxTextEdit;
    bt_printmd: TButton;
    dxLayoutItem_btprintmd: TdxLayoutItem;
    TgridLiSet: TToolButton;
    dxLayoutItem_presentLen: TdxLayoutItem;
    dxLayoutItem_presentWeight: TdxLayoutItem;
    presentLen: TcxTextEdit;
    presentWeight: TcxTextEdit;
    unitPieces: TcxTextEdit;
    dxLayoutItem_unitPieces: TdxLayoutItem;
    Tv3unitPieces: TcxGridDBColumn;
    custName: TcxTextEdit;
    dxLayoutItem_custname: TdxLayoutItem;
    customStrField3: TcxComboBox;
    dxLayoutItem_customStrField3: TdxLayoutItem;
    c_ecolor: TcxTextEdit;
    dxLayoutItem_ecolor: TdxLayoutItem;
    Panel_msg: TPanel;
    edit_roll_auto: TcxTextEdit;
    dxLayoutItem_edit_roll_auto: TdxLayoutItem;
    customStrField4: TcxButtonEdit;
    dxLayoutItem_customStrField4: TdxLayoutItem;
    customStrField8: TcxButtonEdit;
    dxLayoutItem_customStrField8: TdxLayoutItem;
    customStrField7: TcxButtonEdit;
    dxLayoutItem_customStrField7: TdxLayoutItem;
    customStrField6: TcxButtonEdit;
    dxLayoutItem_customStrField6: TdxLayoutItem;
    customStrField5: TcxButtonEdit;
    dxLayoutItem_customStrField5: TdxLayoutItem;
    ToolButton1: TToolButton;
    Tv3Column1: TcxGridDBColumn;
    Tv3Column2: TcxGridDBColumn;
    cds_paramsaixunpage: TStringField;
    Tv3Column3: TcxGridDBColumn;
    cds_paramsBegintxm: TStringField;
    cds_paramsendtxm: TStringField;
    TXM: TcxTextEdit;
    dxLayoutItem12: TdxLayoutItem;
    ToolButton2: TToolButton;
    Panel1: TPanel;
    FtyPCIDSX: TcxTextEdit;
    Label1: TLabel;
    procedure FormCreate(Sender: TObject);
    procedure FormShow(Sender: TObject);
    procedure Button_badClick(Sender: TObject);
    procedure frameBads1cxButton3Click(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure FormDestroy(Sender: TObject);
    procedure edtScanDblClick(Sender: TObject);
    procedure edtScanKeyPress(Sender: TObject; var Key: Char);
    procedure frameBads1cxCheckBox_readLenPropertiesChange(Sender: TObject);
    procedure ToolButton8Click(Sender: TObject);
    procedure SpeedButton1Click(Sender: TObject);
    procedure SpeedButton_backClick(Sender: TObject);
    procedure edtScanEnter(Sender: TObject);
    procedure Edit_fixLenClick(Sender: TObject);
    procedure BTPrintClick(Sender: TObject);
    procedure ToolButton7Click(Sender: TObject);
    procedure ToolButton4Click(Sender: TObject);
    procedure TrolldelClick(Sender: TObject);
    procedure ToolButton3Click(Sender: TObject);
    procedure TeditClick(Sender: TObject);
    procedure cxButton2Click(Sender: TObject);
    procedure Tv3CustomDrawCell(Sender: TcxCustomGridTableView; ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean);
    procedure Tv3FocusedRecordChanged(Sender: TcxCustomGridTableView; APrevFocusedRecord, AFocusedRecord: TcxCustomGridRecord; ANewItemRecordFocusingChanged: Boolean);
    procedure Button_setClick(Sender: TObject);
    procedure InputLenKeyPress(Sender: TObject; var Key: Char);
    procedure InputLenPropertiesChange(Sender: TObject);
    procedure btnRKClick(Sender: TObject);
    procedure btnUnRkClick(Sender: TObject);
    procedure Btn_rlBillClick(Sender: TObject);
    procedure Edit_pieceOrderClick(Sender: TObject);
    procedure TprintPackClick(Sender: TObject);
    procedure TlogClick(Sender: TObject);
    procedure FrameKeyBoard1SpeedButton_backClick(Sender: TObject);
    procedure FrameKeyBoard1SpeedButton1Click(Sender: TObject);
    procedure FrameKeyBoard1SpeedButton_ycClick(Sender: TObject);
    procedure dxLayoutItem1CaptionClick(Sender: TObject);
    procedure Tv2DblClick(Sender: TObject);
    procedure lblRuleConversionPropertiesChange(Sender: TObject);
    procedure packPostBtnClick(Sender: TObject);
    procedure frameBads1CIFBegDblClick(Sender: TObject);
    procedure frameBads1cxCheck_lenPropertiesChange(Sender: TObject);
    procedure bt_printmdClick(Sender: TObject);
    procedure dxLayoutControl_packDblClick(Sender: TObject);
    procedure edit_roll_autoClick(Sender: TObject);
    procedure customStrField5DblClick(Sender: TObject);
    procedure customStrField5PropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
    procedure ToolButton1Click(Sender: TObject);
    procedure ToolButton2Click(Sender: TObject);
    procedure FormKeyPress(Sender: TObject; var Key: Char);
    procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
    procedure FtyPCIDSXKeyPress(Sender: TObject; var Key: Char);
  private
    FCIID, FOperationStatus, FCIFName, FWorkshop: string;
    FBCIOID, FOrderNo, FMainId, FSubId, FPCId, FConNo, FConMId, fBuyConNo, FConSId: string;
    FBatchNO, FLenUnit, FC_Code, FC_Name, FC_EName, FC_Spec, FC_Width, FC_GramWeight: string;
    FC_Color, FC_EColor, FC_ColorNo, FC_StyleNo, FC_Composition, FC_Pattern, FC_CustPattern, FC_ColorDepth: string;
    Faddwet, faddlen, FPackbag: double;
    FFtyPCId, FGangNo, FRulePieceNo, FRulePackNo, FCDUnit: string;
    FPieceNo: Integer;
    fIsPack: string;
    fCanAutoPost: boolean;
    fIsCommopen: Boolean;
    FPacketCIID: string;
    fLabPackage, fLabVolume: string;
    FPacketCount: Integer;
    fAddwetVirtual: double;
    fAddLenVirtual: double;
    fOldCheng: string;
    fOldMaBiao: string;
    fTareType: string;
    funitPiecesStr: string; //拼匹
    fstopwatch: TStopwatch;
    fLastPieceNo, fLastTXM: string;
    preEnterName: string;
    procedure setFocusCtrol(controlName: string);
    procedure CIFEndChange(Sender: TObject);
    function CheckData(CKType: string): Boolean;
    procedure QuantityConversion();
    procedure ClearGlobal();
    procedure InitPlan(MSubID: string);
    procedure SetUnit(MUnit: string);
    procedure SetDdetails();
    procedure SetINIFile();
    procedure GetINIFile();
    procedure InitCDGrid(MCIID: string);
    procedure InitCDGridCX(MCIID: string);
    procedure InitJYGrid();
    procedure OpenCom(DllName: string);
    procedure CloseCom(DllName: string);
    procedure ClearCom(DllName: string);
    function SaveData(): Boolean;
    procedure PrtData(MCIID: string; againPring: Boolean = false);
    procedure PrtaixunData(MCIID: string; againPring: Boolean = false);
    procedure PrintBao(PPacketId: string; againPring: Boolean = false);
    procedure InitJTM(MCIID: string);
    procedure BadSpeedButtonClick(Sender: TObject);
    procedure setFormCtrol();
    procedure PrtMD(MInNo: string);
    procedure On1201(var Message: Tmessage); message 1201; // 电子称
    procedure On1301(var Message: Tmessage); message 1301; // 码表
    procedure initEditPiece();
    procedure GetPacketNo();
    procedure getPlanImage(MSubID: string);
    function deletePack(packId: string): boolean;
    function checkPicecNo(): boolean;
    function getCurPieceNO(mCcid: string): string;
    procedure threadLoadform();
    function getCurMaxPieceNo(): integer;
    procedure AppIdleSetFocus(Sender: TObject; var Done: Boolean);
    procedure AutoCloseMessage(const Msg: string; CloseTime: Integer = 2000);
    procedure TimerCloseForm(Sender: TObject);
    type


  public
    fmanage, canshu1: string;
    fFlileFlag: string;
    FNetpoundxs, FGrosspoundxs: Double;
  end;

var
  frmMachRollMain: TfrmMachRollMain;
  newh, newh1: hwnd;

implementation

uses
  U_DataLink, U_ControlData, U_ParamSet, U_RTFun, U_globalVar, U_DjdDjClList_CX,
  U_FormLayOutDesign, U_ZDYHelp, U_iniParam, U_ProductListHelp, U_SysLogList,
  U_MdPrint;
{$R *.dfm}
  /// ///////////////////////////////

function getConfigValue(DllName: string; ConfigName: string; ADOQueryTmp: TADOQuery; defalutValue: Variant): Variant;
begin
  Result := null;
  with ADOQueryTmp do
  begin
    close;
    sql.Clear;
    sql.Add('select item_value,data_type from sy_module_param_set where dll_name=''' + Trim(DllName) + ''' and  config_name=''' + Trim(ConfigName) + '''');
    Open;
    if RecordCount > 0 then
    begin
      if (Trim(fieldByName('data_type').AsString) = '数字') or (Trim(fieldByName('data_type').AsString) = 'number') then
      begin
        Result := StrToFloatDef(Trim(fieldByName('item_value').AsString), 0);
      end
      else if (Trim(fieldByName('data_type').AsString) = '布尔') or (Trim(fieldByName('data_type').AsString) = 'bool') then
      begin
        Result := false;
        if lowercase(Trim(fieldByName('item_value').AsString)) = 'true' then
        begin
          Result := true;
        end;

      end
      else if (Trim(fieldByName('data_type').AsString) = '整数') or (Trim(fieldByName('data_type').AsString) = 'int') then
      begin
        Result := StrToIntDef(Trim(fieldByName('item_value').AsString), 0);
      end
      else
      begin
        Result := Trim(fieldByName('item_value').AsString);
      end;
    end
    else
      Result := defalutValue;
  end;
end;

procedure TfrmMachRollMain.Btn_rlBillClick(Sender: TObject);
begin
  if cds_3.IsEmpty then
    exit;
  if Application.MessageBox('确定要重新打印吗？', '提示', 32 + 4) <> IDYES then
    exit;
  try
    with ADOQueryBaseTemp do
    begin
      Close;
      SQL.Clear;
      SQL.Add(' select * from Trade_Cloth_IO A where IOFlag=''入库''  ');
      SQL.Add(' and A.StkId=''' + trim(cds_3.fieldbyName('CIID').AsString) + '''');
      Open;
    end;

    PrtMD(ADOQueryBaseTemp.fieldbyName('IONo').AsString);

  except
    Application.MessageBox('重新打印失败!', '提示信息', MB_ICONERROR);
  end;

end;

procedure TfrmMachRollMain.BTPrintClick(Sender: TObject);
var
  fPrintFile, MPacketId, FSTXM: string;
  mvalue: double;
  i: Integer;
begin

  try
    fCanAutoPost := false;
    BTPrint.Enabled := false;

    edtScan.SetFocus;
    if trim(OrderNo.Text) = '' then
      exit;
    if trim(grade.Text) = '' then
    begin
      Application.MessageBox('等级不能为空!', '提示', 0);
      exit;
    end;
    if (trim(cds_params.fieldbyName('Begintxm').AsString) <> '') or (trim(cds_params.fieldbyName('endtxm').AsString) <> '') then
    begin
      if (strtointdef(trim(TXM.Text), 0) <= strtointdef(trim(cds_params.fieldbyName('endtxm').AsString), 0)) and (strtointdef(trim(TXM.Text), 0) >= strtointdef(trim(cds_params.fieldbyName('begintxm').AsString), 0)) then
      begin

      end
      else
      begin
        Application.MessageBox('条形码不在范围!', '提示', 0);
        exit;
      end;
    end;
      /////////////////条形码重复判断
    with ADOQueryBaseCmd do
    begin
      Close;
      sql.Clear;
      sql.Add('select Mainid,TXM from Trade_Cloth_Inspect X where X.mainID=' + quotedstr(Trim(FMainId)));
      sql.add('and isnull(TXM,'''')<>'''' ');
      sql.Add(' Group by Mainid,TXM having count(*)>1');
      Open;
    end;
    if not ADOQueryBaseCmd.IsEmpty then
    begin
      FSTXM := Trim(ADOQueryBaseCmd.fieldbyname('TXM').AsString);
      Application.MessageBox(Pchar('条形码: ' + Trim(FSTXM) + ' 重复，请核对处理数据!'), '提示', 0);
      Exit;
    end;
//    if not mustInCheck(application, dxLayoutControl_bzplan, PWideChar('*')) then
//      exit;
    if (pos('*', dxLayoutItem13.Caption) > 0) and (trim(BatchNO.Text) = '') then
    begin
      Application.MessageBox('本厂缸号不能为空！', '提示', 0);
      exit;
    end;
    if (pos('*', dxLayoutItem15.Caption) > 0) and (trim(InputLen.Text) = '') then
    begin
      Application.MessageBox('长度不能为空！', '提示', 0);
      exit;
    end;
    if (pos('*', dxLayoutItem4.Caption) > 0) and (trim(FtyPCId.Text) = '') then
    begin
      Application.MessageBox('染厂缸号不能为空！', '提示', 0);
      exit;
    end;
    if CheckData('提交') = false then
      exit;

    if FCDUnit <> lblLenUnit.CaptionOptions.Hint then
    begin
      Application.MessageBox('单位与计划单设置不符!', '提示', 0);
      exit;
    end;
    QuantityConversion();

    if SaveData() then
    begin
      InputLen.Text := '';
      funitPiecesStr := '';
      unitPieces.Text := '';
      customStrField1.text := '';
      C_Width.text := FC_Width;
      C_GramWeight.text := FC_GramWeight;

      if gPresentclear then
      begin
        presentLen.Text := '';
        presentWeight.Text := '';
      end;
//      if (cds_params.fieldbyName('rollnoMake').AsString = '手动') and  (trim(Edit_pieceOrder.Text) <> '√') then
//      begin
//        pieceNo.Text:=intTostr(getCurMaxPieceNo());
//      end;
      if BTPrint.Caption = '修改提交' then
      begin
        BTPrint.Caption := '提  交';
        cxgrid3.Enabled := true;
        pieceNo.Text := fLastPieceNo;
        TXM.Text := fLastTXM;
        cds_params.edit;
        cds_params.fieldbyName('chen').value := fOldCheng;
        cds_params.fieldbyName('mabiao').value := fOldMaBiao;
        cds_params.Post;
        edtPacketNo.Enabled := true;
        Panel_msg.Visible := true;
        if fileexists(ExtractFilePath(Application.ExeName) + '修改成功.wav') then
          playSound(pwidechar('修改成功.wav'), 0, SND_FILENAME or SND_ASYNC);
      end
      else
      begin
        if fileexists(ExtractFilePath(Application.ExeName) + '正确.wav') then
          playSound(pwidechar('正确.wav'), 0, SND_FILENAME or SND_ASYNC);
      end;

      InputWeight.Text := '';
      // Edit_fixLen.Text := '';
      if (trim(Edit_pieceOrder.Text) = '√') and (strtointdef(trim(PieceNo.Text), 0) > 1) then
      begin
        PieceNo.Text := inttostr(strtointdef(PieceNo.Text, 0) - 1); // 自减卷号
      end
      else if (trim(cds_params.fieldbyName('beginPieceNo').AsString) <> '') then
      begin
        if strtointdef(trim(PieceNo.Text), 0) < strtointdef(trim(cds_params.fieldbyName('endPieceNo').AsString), 0) then
        begin
          PieceNo.Text := inttostr(strtointdef(trim(PieceNo.Text), 0) + 1); //
        end
        else
          PieceNo.Text := getCurPieceNO(FCIID); //
      end
      else if (trim(cds_params.fieldbyName('rollnoMake').AsString) = '自动') then         // (strtointdef(PieceNo.Text, 0) > 0)
      begin
        PieceNo.Text := inttostr(strtointdef(trim(PieceNo.Text), 0) + 1); //
      end
      else
      begin
        if dxLayoutItem_roll.ActuallyVisible then
        begin
          PieceNo.Text := getCurPieceNO(FCIID); //
        end
        else
          PieceNo.Text := '';
      end;
      OutPutWeight.Text := '';
      // PieceNo.Text := inttostr(strtointdef(PieceNo.Text, 0) + 1);  //自增卷号
      if (trim(cds_params.fieldbyName('Begintxm').AsString) <> '') or (trim(cds_params.fieldbyName('endtxm').AsString) <> '') then
      begin
        if (strtointdef(trim(TXM.Text), 0) <= strtointdef(trim(cds_params.fieldbyName('endtxm').AsString), 0)) and (strtointdef(trim(TXM.Text), 0) >= strtointdef(trim(cds_params.fieldbyName('begintxm').AsString), 0)) then
        begin
          TXM.Text := inttostr(strtointdef(trim(TXM.Text), 0) + 1); //
        end;
      end;
      if trim(cds_params.fieldbyName('outPage').AsString) = '√' then
      begin
        PrtData(FCIID);
      end;
      if trim(cds_params.fieldbyName('aixunpage').AsString) = '√' then
      begin
        PrtaixunData(FCIID);
      end;
      if (trim(cds_params.fieldbyName('dabao').AsString) = '√') then
      begin
        FPacketCount := FPacketCount + 1;
        FPacketCIID := FPacketCIID + ',' + FCIID;
        if (trim(cds_params.fieldbyName('packPostAction').AsString) = '自动') and (FPacketCount = cds_params.fieldbyName('packRolls').AsInteger) then
        begin
          if GetLSNo(ADOQueryBaseTemp, MPacketId, 'BI', 'Trade_Cloth_Inspect', 4, 1) = false then
          begin
            Application.MessageBox('取包条码最大号失败！', '提示', 0);
            exit;
          end;
          GetPacketNo();
          try
            ADOQueryBaseCmd.Connection.BeginTrans;
            with ADOQueryBaseCmd do
            begin
              Close;
              SQL.Clear;
              SQL.Add('Update Trade_Cloth_Inspect Set PacketTime=GETDATE() , PacketNo=' + trim(edtPacketNo.Text) + ',PacketId=' + QuotedStr(trim(MPacketId)) + ',PacketCode=' + QuotedStr(trim(DCode)) + ',PacketName=' + QuotedStr(trim(DName)));
              SQL.Add('WHERE EXISTS(select X.RTValue from [dbo].[F_Tool_SplitString](' + QuotedStr(FPacketCIID) + ','','') X where Trade_Cloth_Inspect.CIID=X.RTValue )  ');
              SQL.Add('Update Trade_Cloth_Stock Set PacketTime=GETDATE() , PacketNo=' + trim(edtPacketNo.Text) + ',PacketId=' + QuotedStr(trim(MPacketId)) + ',PacketCode=' + QuotedStr(trim(DCode)) + ',PacketName=' + QuotedStr(trim(DName)));
              SQL.Add('WHERE EXISTS(select X.RTValue from [dbo].[F_Tool_SplitString](' + QuotedStr(FPacketCIID) + ','','') X where Trade_Cloth_Stock.STKID=X.RTValue )  ');
              ExecSQL;
            end;
            if (cds_params.fieldbyName('packlabnumber').AsInteger > 0) then
              PrintBao(MPacketId);
            edtPacketNo.Text := inttostr(strtoint(edtPacketNo.Text) + 1);
            FPacketCIID := '';
            FPacketCount := 0;
            ADOQueryBaseCmd.Connection.CommitTrans;
          except
            ADOQueryBaseCmd.Connection.RollbackTrans;
            Application.MessageBox('打包失败！', '提示信息', 0);
          end;

        end;

      end;

    end;
    InputLen.SetFocus;
    setFocusCtrol(InputLen.Name);
    if gEnterAutoPost then
    begin
      if preEnterName = 'InputLen' then
        InputLen.SetFocus;
      if preEnterName = 'InputWeight' then
        InputWeight.SetFocus;
    end;
    FOperationStatus := '缸条码';
    InitJYGrid();
    InitCDGrid('');
    FCIID := '';
    //清除码表

    if fIsCommopen and gAutoPostClear then
    begin

     // CloseCom(DZCDYDllName);
      ClearCom(MBDYDllName);

    end;

  finally
    BTPrint.Enabled := true;

    InputLen.SetFocus;
  end;
end;

procedure TfrmMachRollMain.bt_printmdClick(Sender: TObject);
var
  WSql: string;
begin
  if cds_3.IsEmpty then
    Exit;

  WSql := '';
  cds_3.DisableControls;
  with cds_3 do
  begin
    First;
    while not Eof do
    begin

      if WSql <> '' then
      begin
        WSql := WSql + ',' + Trim(cds_3.fieldbyname('CIID').AsString);
      end
      else
      begin
        WSql := Trim(cds_3.fieldbyname('CIID').AsString);
      end;

      Next;
    end;
  end;

  cds_3.EnableControls;
  try
    frmMdPrint := TfrmMdPrint.Create(Application);
    with frmMdPrint do
    begin
      FLMType := '入库码单';
      FFiltration1 := WSql;
      FFiltration2 := WSql;
      if ShowModal = 1 then
      begin
//        Self.InitGrid();
      end;
    end;
  finally
    frmMdPrint.Free;
  end;
end;

procedure TfrmMachRollMain.Button_badClick(Sender: TObject);
begin
  inherited;
  cxPageControl1.ActivePageIndex := 0;
  dxPanel_mid.Visible := not dxPanel_mid.Visible;
  cxGroupBox_keys.Left := Panel_right.Left + 15;
end;

procedure TfrmMachRollMain.Button_setClick(Sender: TObject);
begin
  if trim(BCIOID.Text) = '' then
  begin
    exit;
  end;
  frmParamSet := TfrmParamSet.create(Self);
  with frmParamSet do
  begin
    cds_params.Data := Self.cds_params.Data;
    if ShowModal = 1 then
    begin
      Self.cds_params.Data := cds_params.Data;
      setFormCtrol();
    end;
    free;
  end;
  SetINIFile();
  if trim(fmanage) <> '高权限' then
  begin
   // if (trim(DZCDYDllName) <> '') and not fIsCommopen then
    //  OpenCom(DZCDYDllName);
    if (trim(MBDYDllName) <> '') and not fIsCommopen then
      OpenCom(MBDYDllName);

    // edtScan.SetFocus;

  end;
end;

procedure TfrmMachRollMain.btnRKClick(Sender: TObject);
var
  MINo, MStkIds: string;
begin
  if cds_3.IsEmpty then
    exit;
  if Application.MessageBox('您确定要将打卷记录入库吗?', '提示信息', 1) = 2 then
  begin
    exit;
  end;
  btnRK.Enabled := false;
  // 刷出未入库的卷信息，执行入库操作
  with ADOQueryMain do
  begin
    Close;
    SQL.Clear;
    SQL.Add('select A.*');
    SQL.Add('from Trade_Cloth_Inspect A where BCIOID=''' + trim(FBCIOID) + '''');
    SQL.Add('and CIIOFlag=''未入库''');
    SQL.Add('order by filltime desc');
    Open;
  end;
  SCreateCDS(ADOQueryMain, cds_3);
  SInitCDSData(ADOQueryMain, cds_3);

  with cds_3 do
  begin
    DisableControls;
    First;
    while not eof do
    begin
      MStkIds := MStkIds + trim(cds_3.fieldbyName('CIID').AsString) + ',';
      next;
    end;
    EnableControls;
  end;
  MStkIds := copy(MStkIds, 1, Length(MStkIds) - 1);

  if GetLSNo(ADOQueryBaseCmd, MINo, '9', 'Trade_Cloth_IO', 4, 1) = false then
  begin
    Application.MessageBox('取入库单号失败!', '提示', 0);
    exit;
  end;

  ADOQueryBaseCmd.Connection.BeginTrans;
  try

    with ADOQueryBaseCmd do
    begin
      Close;
      SQL.Clear;
      SQL.Add('exec P_Trade_Cloth_In ');
      SQL.Add('@StkIds=' + QuotedStr(trim(MStkIds)));
      SQL.Add(',@IOTime=' + QuotedStr(FormatDateTime('yyyy-MM-dd', SGetServerDate(ADOQueryBaseTemp))));
      SQL.Add(',@IOType=' + QuotedStr('检验入库'));
      SQL.Add(',@IONO=' + QuotedStr(MINo));
      SQL.Add(',@FillId=' + QuotedStr(DCode));
      SQL.Add(',@Filler=' + QuotedStr(DName));
      Open;
    end;
    if ADOQueryBaseCmd.fieldbyName('intReturn').AsInteger = -1 then
    begin
      raise Exception.create(pchar(trim(ADOQueryBaseCmd.fieldbyName('ShowMsg').AsString)));
    end;
    ADOQueryBaseCmd.Connection.CommitTrans;
    Application.MessageBox('数据入库成功！', '提示信息');

    btnRK.Enabled := true;
  except
    btnRK.Enabled := true;
    ADOQueryBaseCmd.Connection.RollbackTrans;
    Application.MessageBox(pchar(Exception(ExceptObject).Message), '提示信息', 0);
  end;
  // 入库完后刷出全部卷信息
  InitJYGrid();

end;

procedure TfrmMachRollMain.btnUnRkClick(Sender: TObject);
var
  MStkIds: string;
begin
  if cds_3.IsEmpty then
    exit;
  if Application.MessageBox('您确定要将打卷记录撤销入库吗?', '提示信息', 1) = 2 then
  begin
    exit;
  end;
  btnUnRk.Enabled := false;
  with cds_3 do
  begin
    DisableControls;
    First;
    while not eof do
    begin
      MStkIds := MStkIds + trim(cds_3.fieldbyName('CIID').AsString) + ',';
      next;
    end;
    EnableControls;
  end;
  MStkIds := copy(MStkIds, 1, Length(MStkIds) - 1);

  try
    ADOQueryBaseCmd.Connection.BeginTrans;
    with ADOQueryBaseCmd do
    begin
      Close;
      SQL.Clear;
      SQL.Add('exec P_Trade_Cloth_ReIn ');
      SQL.Add('@StkIds=' + QuotedStr(trim(MStkIds)));
      SQL.Add(',@IOIDS='''' ');
      Open;
    end;
    if ADOQueryBaseCmd.fieldbyName('intReturn').AsInteger = -1 then
    begin
      raise Exception.create(pchar(trim(ADOQueryBaseCmd.fieldbyName('ShowMsg').AsString)));
    end;
    Application.MessageBox('撤销入库成功！', '提示信息');
    ADOQueryBaseCmd.Connection.CommitTrans;
    btnUnRk.Enabled := true;
  except
    ADOQueryBaseCmd.Connection.RollbackTrans;
    btnUnRk.Enabled := true;
    Application.MessageBox(pchar(Exception(ExceptObject).Message), '提示信息', 0);

  end;

end;

procedure TfrmMachRollMain.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  inherited;
  if fIsCommopen then
  begin
    CloseCom(DZCDYDllName);
    CloseCom(MBDYDllName);
  end;
  Action := caFree;
end;

procedure TfrmMachRollMain.FormCreate(Sender: TObject);
begin
//  fstopwatch := TStopwatch.StartNew;
  inherited;
  canshu1 := Trim(Self.fParameters1);
  Panel_right.Align := alClient;
  fIsCommopen := false;
  cds_params.Close;
  cds_params.CreateDataSet;

  frameBads1.CIFBeg.OnEnter := edtScanEnter;
  frameBads1.CIFEnd.OnEnter := edtScanEnter;
  frameBads1.CIFNumber.OnEnter := edtScanEnter;
  frameBads1.SubtractQty.OnEnter := edtScanEnter;
  frameBads1.CIFQty.OnEnter := edtScanEnter;

end;

procedure TfrmMachRollMain.FormDestroy(Sender: TObject);
begin
  inherited;
  frmMachRollMain := nil;
end;

procedure TfrmMachRollMain.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
  if Key = VK_RETURN then  // VK_RETURN 是回车键的虚拟键码
  begin
    ShowMessage('qq');
    Key := 0;  // 阻止进一步处理
  end;
end;

procedure TfrmMachRollMain.FormKeyPress(Sender: TObject; var Key: Char);
begin
  ShowMessage('Key pressed: ' + IntToStr(Ord(Key)));
  if Key = #13 then
  begin
    ShowMessage('qq');
  end;

end;

procedure TfrmMachRollMain.FormShow(Sender: TObject);
var
  i: Integer;
begin

//  KeyPreview := True;  // 确保表单可以预览按键
  try
    //  loadProcess.Visible:=true;
    //  loadProcess.Refresh;
    Coefficient.Properties.ReadOnly := gZhxsReadonly;
    tare.Properties.ReadOnly := gTareReadonly;

    getSystemIni();
    gGridNativeSet := true;
    if gIsCanDesign then
    begin
      cxGridPopupMenu1.Grid := cxGrid3;
    end;
    TgridLiSet.Visible := gIsCanDesign;
 //
    try
      dxLayoutControl_pack.BeginUpdate;

      cds_params.Edit;
      cds_params.fieldByName('rollnoMake').Value := '手动';
      cds_params.fieldByName('weightRule').Value := 1;
      cds_params.fieldByName('aixunpage').Value := '';
      cds_params.Post;

      setFormCtrol();
    finally
      dxLayoutControl_pack.EndUpdate();
    end;

  //
    frameBads1.fBadBtnSize := gBcSpeedSize;
    frameBads1.InitBadPanel;
    with frameBads1.cxScrollBox1 do
    begin
      for i := 0 to ControlCount - 1 do
      begin
        if Controls[i] is TSpeedButton then
        begin
          TSpeedButton(Controls[i]).OnClick := BadSpeedButtonClick;
        end;
      end;
    end;
  //
    threadLoadform();
 // application.ProcessMessages;
    InitDevCombobox(ADOQueryBaseTemp, grade, 'CPGRADE');


 // InitCDGrid(FCIID);

    if IsINIFile() then
      ReadINIFile()
    else
      WriteINIFile;
    GetINIFile();

    if trim(fmanage) <> '高权限' then
    begin
      if trim(DZCDYDllName) <> '' then
        OpenCom(DZCDYDllName);
      if trim(MBDYDllName) <> '' then
        OpenCom(MBDYDllName);

    // edtScan.SetFocus;

    end;
    if trim(fCanInputFs) = '1' then
    begin
      cxGroupBox_keys.ClientHeight := round(cxGrid3.ClientHeight * 0.6);
      frameKeyBoard1.SpeedButton10.Visible := true;
    end
    else
    begin
      cxGroupBox_keys.ClientHeight := round(cxGrid3.ClientHeight * 0.55);
      frameKeyBoard1.SpeedButton10.Visible := false;
    end;
  finally
//  // 在应用程序空闲时设置焦点（确保所有初始化完成）
//  Application.OnIdle := AppIdleSetFocus;
   // loadProcess.Visible:=false;
  end;

  if canshu1 = '低权限' then
  begin
    Trolldel.visible := false;
    Tedit.visible := false;
  end;


  //////
  if dxLayoutItem_customStrField3.ActuallyVisible then
    InitDevCombobox(ADOQueryBaseTemp, customStrField3, 'DOROLLZDY3');

end;

procedure TfrmMachRollMain.AppIdleSetFocus(Sender: TObject; var Done: Boolean);
begin
  // 确保只执行一次
  Application.OnIdle := nil;

  // 将焦点设置到本窗体
  if Self.CanFocus then
  begin
    Self.SetFocus;
//     可选：输出调试信息

    AutoCloseMessage('操作成功！', 1000); // 1秒后自动关闭

//     ShowMessage('焦点已设置到窗体: ' + Self.Name);

  end;

  Done := True; // 保持默认处理流程
end;

procedure TfrmMachRollMain.AutoCloseMessage(const Msg: string; CloseTime: Integer = 2000);
var
  Form: TForm;
  Label1: TLabel;
  Timer: TTimer;
begin
  Form := TForm.Create(nil);
  try
    Form.BorderStyle := bsDialog;
    Form.Caption := '提示';
    Form.Position := poScreenCenter;
    Form.Width := 300;
    Form.Height := 120;

    Label1 := TLabel.Create(Form);
    Label1.Parent := Form;
    Label1.Caption := Msg + #13#10 + IntToStr(CloseTime div 1000) + '秒后自动关闭...';
    Label1.Align := alClient;
    Label1.Alignment := taCenter;
    Label1.Layout := tlCenter;
    Label1.WordWrap := True;

    Timer := TTimer.Create(Form);
    Timer.Interval := CloseTime;
    Timer.OnTimer := TimerCloseForm;  // 使用独立的方法

    // 需要存储 Form 引用以便在事件中访问
    Tag := Integer(Form);  // 使用 Tag 存储引用

    Form.ShowModal;
  finally
    Form.Free;
  end;
end;

// 独立的计时器事件处理方法
procedure TfrmMachRollMain.TimerCloseForm(Sender: TObject);
var
  Form: TForm;
begin
  // 从 Sender 获取 Timer
  TTimer(Sender).Enabled := False;

  // 获取关联的 Form
  Form := TForm(TTimer(Sender).Owner);
  if Assigned(Form) then
    Form.ModalResult := mrOk;
end;

procedure TfrmMachRollMain.frameBads1CIFBegDblClick(Sender: TObject);
begin
  inherited;
  if strTofloatDef(trim(frameBads1.CIFBeg.text), 0) = 0 then
    frameBads1.CIFBeg.text := inputLen.Text;
end;

procedure TfrmMachRollMain.frameBads1cxButton3Click(Sender: TObject);
begin
  inherited;
  frameBads1.Visible := false;

end;

procedure TfrmMachRollMain.frameBads1cxCheckBox_readLenPropertiesChange(Sender: TObject);
begin
  inherited;
  frameBads1.CIFBeg.Text := '';
//  if trim(TcxTextEdit(Sender).Text) = '' then
//  begin
//    frameBads1.CIFBeg.Text := '';
//  end
//  else
//  begin
//    frameBads1.CIFBeg.Text := '';
//  end;
end;

procedure TfrmMachRollMain.frameBads1cxCheck_lenPropertiesChange(Sender: TObject);
begin
  inherited;
  if frameBads1.cxCheck_len.Checked and (trim(InputLen.Text) <> '') then
  begin
    frameBads1.CIFBeg.Text := trim(InputLen.Text);
    frameBads1.CIFEnd.SetFocus;
  end
  else
  begin
    frameBads1.CIFBeg.Text := ''
  end;
end;

procedure TfrmMachRollMain.FrameKeyBoard1SpeedButton1Click(Sender: TObject);
var
  fsj: string;
  mComponent: TComponent;
  mkey: Char;
begin
  fsj := trim(TSpeedButton(Sender).Hint);
  if trim(fsj) = '' then
    exit;
  mComponent := FindComponent(trim(TSpeedButton(Sender).Hint));
  if mComponent = nil then
    mComponent := frameBads1.FindComponent(trim(TSpeedButton(Sender).Hint));
  if mComponent = nil then
    exit;
  if TcxTextEdit(mComponent).Name = 'KuangHao' then
    exit;
  if (TcxTextEdit(mComponent).Name = 'edtScan') and (trim(TSpeedButton(Sender).Caption) = '回车') then
  begin
    mkey := #13;
    edtScanKeyPress(edtScan, mkey);
    exit;
  end;
  fsj := trim(TcxTextEdit(mComponent).Text);
  if mComponent is TcxCurrencyEdit then
  begin
    TcxCurrencyEdit(mComponent).text := fsj + trim(TSpeedButton(Sender).Caption);
    TcxCurrencyEdit(mComponent).SelectAll;
  end
  else
  begin
    if TcxTextEdit(mComponent).Properties.ReadOnly then
      exit;

    TcxTextEdit(mComponent).Text := fsj + trim(TSpeedButton(Sender).Caption);
    TcxTextEdit(mComponent).SelectAll;
  end;

end;

procedure TfrmMachRollMain.FrameKeyBoard1SpeedButton_backClick(Sender: TObject);
var
  fsj: string;
  mComponent: TComponent;
begin
  mComponent := FindComponent(trim(TSpeedButton(Sender).Hint));
  if mComponent = nil then
    mComponent := frameBads1.FindComponent(trim(TSpeedButton(Sender).Hint));
  if mComponent = nil then
    exit;
  fsj := trim(TcxTextEdit(mComponent).Text);
  if trim(fsj) = '' then
    exit;
  if TcxTextEdit(mComponent).Properties.ReadOnly then
    exit;

  if TcxTextEdit(mComponent).SelText <> '' then
    TcxTextEdit(mComponent).Text := ''
  else
  begin
    TcxTextEdit(mComponent).Text := copy(fsj, 1, Length(fsj) - 1);
   // TcxTextEdit(mComponent).SelectAll;
  end;

end;

procedure TfrmMachRollMain.FrameKeyBoard1SpeedButton_ycClick(Sender: TObject);
begin
  inherited;
  cxGroupBox_keys.Visible := false;
end;

procedure TfrmMachRollMain.FtyPCIDSXKeyPress(Sender: TObject; var Key: Char);
begin
  if Key = #13 then
  begin
    InitJYGrid();
  end;
end;

function TfrmMachRollMain.CheckData(CKType: string): Boolean;
var
  mvalue: double;
  mCurPieceNo: Integer;
  FCD: string;
begin
  Result := false;
  mCurPieceNo := strtointdef(trim(Pieceno.Text), 0);
  try
    if trim(FBCIOID) = '' then
      raise Exception.create('请扫描流程卡！');

    if (trim(CKType) = '提交') then
    begin
      if (cds_params.fieldbyName('BeginPieceNo').AsString <> '') and (cds_params.fieldbyName('EndPieceNo').AsString <> '') and (cds_params.fieldbyName('rollnoMake').AsString = '手动') then
      begin
        if (cds_params.fieldbyName('BeginPieceNo').AsInteger >= cds_params.fieldbyName('endPieceNo').AsInteger) then
        begin
          if (mCurPieceNo < 0) or not ((mCurPieceNo <= cds_params.fieldbyName('BeginPieceNo').AsInteger) and (mCurPieceNo >= cds_params.fieldbyName('endPieceNo').AsInteger)) then
          begin
            Application.MessageBox('手动卷号不在设置的范围内!', '提示信息', 0);
            Exit;
          end;
        end;
        if (cds_params.fieldbyName('BeginPieceNo').AsInteger < cds_params.fieldbyName('endPieceNo').AsInteger) then
        begin
          if (mCurPieceNo < 0) or not ((mCurPieceNo >= cds_params.fieldbyName('BeginPieceNo').AsInteger) and (mCurPieceNo <= cds_params.fieldbyName('endPieceNo').AsInteger)) then
          begin
            Application.MessageBox('手动卷号不在设置的范围内!', '提示信息', 0);
            Exit;
          end;
        end;
      end;

      if trim(cds_params.fieldbyName('dabao').AsString) = '√' then
      begin
        if strtointdef(edtPacketNo.Text, 0) = 0 then
          raise Exception.create('包号不能为空!');
        if cds_params.fieldbyName('packRolls').AsInteger = 0 then
          raise Exception.create('每包卷数还未设置!');

      end;

      if (strtointdef(PieceNo.Text, 0) = 0) and (trim(cds_params.fieldbyName('rollNoMake').AsString) = '手动') then
        raise Exception.create('卷号不能为空!');

      if trim(lblLenUnit.CaptionOptions.Hint) = '' then
        raise Exception.create('长度单位不能为空!');

      if trim(InputWeight.Text) <> '' then
      begin
        if TryStrToFloat(InputWeight.Text, mvalue) = false then
          raise Exception.create('重量录入错误!');
        if strtofloatdef(trim(InputWeight.Text), 0) < cds_params.fieldbyName('minWeight').AsInteger then
          raise Exception.create('重量不能小于' + cds_params.fieldbyName('minWeight').AsString + '!');
        if strtofloatdef(trim(InputWeight.Text), 0) > cds_params.fieldbyName('maxWeight').AsInteger then
          raise Exception.create('重量不能大于' + cds_params.fieldbyName('maxWeight').AsString + '!');
      end;

      if trim(InputLen.Text) <> '' then
      begin
        FCD := trim(InputLen.Text);
        if TryStrToFloat(InputLen.Text, mvalue) = false then
          raise Exception.create('长度录入错误!');
        if strtofloatdef(trim(InputLen.Text), 0) < cds_params.fieldbyName('minLen').AsInteger then
          raise Exception.create('当前长度' + FCD + '长度不能小于' + cds_params.fieldbyName('minLen').AsString + '米!');
        if strtofloatdef(trim(InputLen.Text), 0) > cds_params.fieldbyName('maxLen').AsInteger then
          raise Exception.create('当前长度' + FCD + '长度不能大于' + cds_params.fieldbyName('maxLen').AsString + '米!');
      end;

      if (strtofloatdef(trim(InputLen.Text), 0) = 0) and (strtofloatdef(trim(InputWeight.Text), 0) = 0) and (strtofloatdef(trim(Edit_fixLen.Text), 0) = 0) then
        raise Exception.create('长度和重量不能都为0!!');
    end;
    Result := true;
  except
    Application.MessageBox(pchar(Exception(ExceptObject).Message), '提示信息', 0);
  end;
end;

procedure TfrmMachRollMain.ClearGlobal();
begin
  FBCIOID := '';
  FOrderNo := '';
  FConNo := '';
  FConMId := '';
  FConSId := '';
  FMainId := '';
  FSubId := '';
  FPCId := '';
  FC_CustPattern := '';
  FC_ColorDepth := '';
  FFtyPCId := '';
  FGangNo := '';
  FC_Code := '';
  FC_Name := '';
  FBatchNO := '';
  FC_Spec := '';
  FC_Color := '';
  FC_ColorNo := '';
  FC_EColor := '';
  FC_StyleNo := '';
  FC_Composition := '';
  FC_Width := '';
  FC_GramWeight := '';
  FC_Pattern := '';
  FCIID := '';
  FWorkshop := '';
  InputLen.Text := '';
  Coefficient.Text := '';
  AOrdDefNote1.Text := '';
  Tare.Text := '';
  InputWeight.Text := '';
  FLenUnit := '';
  BatchNO.Text := '';
  Faddwet := 0;
  faddlen := 0;
  FPackbag := 0;
  FPacketCIID := '';
  FPacketCount := 0;

end;

procedure TfrmMachRollMain.QuantityConversion();
var
  Maddwet: double;
  maddLen: double;
begin
  // if trim(OrderNo.Text)='' then exit;
  Maddwet := strTofloatDef(trim(addwet.text), 0); // Faddwet;
  maddLen := strTofloatDef(trim(addlen.text), 0); // faddlen;
  if cds_params.fieldbyName('weightRule').AsInteger = 0 then
  // InputWeight  毛重         OutPutWeight   净重
  begin
    if lblRuleConversion.Text <> '无需转换' then
    begin
      if lblRuleConversion.Text = '长度转公斤' then
      begin
        InputWeight.Text := floattostr((strtofloatdef(trim(InputLen.Text), 0) + maddLen) * strtofloatdef(trim(Coefficient.Text), 0) + strtofloatdef(trim(Tare.Text), 0));
      end;
      if lblRuleConversion.Text = '毛重转长度' then
      begin
        InputLen.Text := floattostr(RoundFloat((strtofloatdef(trim(InputWeight.Text), 0) + Maddwet), cds_params.fieldbyName('kgPlace').AsInteger) * strtofloatdef(trim(Coefficient.Text), 0));
      end;
      if lblRuleConversion.Text = '净重转长度' then
      begin
        InputLen.Text := floattostr((RoundFloat((strtofloatdef(trim(InputWeight.Text), 0) + Maddwet), cds_params.fieldbyName('kgPlace').AsInteger) - strtofloatdef(trim(Tare.Text), 0)) * strtofloatdef(trim(Coefficient.Text), 0));
      end;
    end;
    if strtofloatdef(trim(InputWeight.Text), 0) > 0 then
    begin
      OutPutWeight.Text := floattostr((strtofloatdef(trim(InputWeight.Text), 0) - strtofloatdef(trim(Tare.Text), 0))); // 净重
    end;
  end;

  if cds_params.fieldbyName('weightRule').AsInteger = 1 then
  // InputWeight  净重         OutPutWeight   毛重
  begin
    if lblRuleConversion.Text <> '无需转换' then
    begin
      if lblRuleConversion.Text = '长度转公斤' then
      begin
        InputWeight.Text := floattostr((strtofloatdef(trim(InputLen.Text), 0) + maddLen) * strtofloatdef(trim(Coefficient.Text), 0));
      end;
      if lblRuleConversion.Text = '毛重转长度' then
      begin
        InputLen.Text := floattostr(RoundFloat(((strtofloatdef(trim(InputWeight.Text), 0) + Maddwet) + strtofloatdef(trim(Tare.Text), 0)), cds_params.fieldbyName('kgPlace').AsInteger) * strtofloatdef(trim(Coefficient.Text), 0));
      end;
      if lblRuleConversion.Text = '净重转长度' then
      begin
        InputLen.Text := floattostr((RoundFloat(strtofloatdef(trim(InputWeight.Text), 0) + Maddwet, cds_params.fieldbyName('kgPlace').AsInteger)) * strtofloatdef(trim(Coefficient.Text), 0));
      end;
    end;
    if strtofloatdef(trim(InputWeight.Text), 0) > 0 then
    begin
      OutPutWeight.Text := floattostr((strtofloatdef(trim(InputWeight.Text), 0) + strtofloatdef(trim(Tare.Text), 0))); // 毛重
    end;
  end;

end;

procedure TfrmMachRollMain.InitPlan(MSubID: string);
begin
  fCanAutoPost := false;
  with ADOQueryBaseTemp do
  begin
    Close;
    SQL.Clear;
    SQL.Add('EXEC P_Trade_Insp_Get_plan @SubID=''' + trim(MSubID) + '''');
    Open;

    if not IsEmpty then
    begin
      getPlanImage(trim(MSubID));
      // InitImage(Trim(ADOTmp.fieldbyname('YFTPName').AsString));
      // InitImageHX(Trim(ADOTmp.fieldbyname('HXSID').AsString));
      FBCIOID := trim(MSubID);
      FLenUnit := trim(ADOQueryBaseTemp.fieldbyName('ruleLenUnit').AsString);
      if FLenUnit = '' then
      begin
        FLenUnit := 'M';
      end;
      fLabPackage := trim(ADOQueryBaseTemp.fieldbyName('LabPackage').AsString);
      fLabVolume := trim(ADOQueryBaseTemp.fieldbyName('LabVolume').AsString);
      if (FLenUnit = '') then
      begin
        ShowMessage('计划单包装规则还未设置长度单位!');
      end;

      SetUnit(FLenUnit);
      // 计划单打卷设置的长度单位 ，没填的话赋值和界面一样
      // if Trim(ADOTmp.fieldbyname('CDUnit').AsString) = '' then
      FCDUnit := lblLenUnit.CaptionOptions.Hint;
      // else
      // FCDUnit := Trim(ADOTmp.fieldbyname('ordUnit').AsString);

      FConMId := trim(fieldbyName('ConMId').AsString);
      FConSId := trim(fieldbyName('ConSId').AsString);
      FConNo := trim(fieldbyName('ConNo').AsString);
      FOrderNo := trim(fieldbyName('OrderNo').AsString);
      fBuyConNo := trim(fieldbyName('BuyConNo').AsString);
      FMainId := trim(fieldbyName('MainId').AsString);
      FSubId := trim(fieldbyName('SubId').AsString);
      FC_StyleNo := trim(fieldbyName('C_StyleNo').AsString);
      FC_Composition := trim(fieldbyName('C_Composition').AsString);
      FC_Code := trim(fieldbyName('C_Code').AsString);
      FC_Name := trim(fieldbyName('C_Name').AsString);
      FC_EName := trim(fieldbyName('C_EName').AsString);
      // FBatchNO := Trim(ADOTmp.fieldbyname('BatchNO').AsString);
      FC_Spec := trim(fieldbyName('C_Spec').AsString);
      FC_Color := trim(fieldbyName('C_Color').AsString);
      FC_ColorNo := trim(fieldbyName('C_ColorNo').AsString);
      FC_EColor := trim(fieldbyName('C_EColor').AsString);
      FC_Width := trim(fieldbyName('C_Width').AsString);
      FC_GramWeight := trim(fieldbyName('C_GramWeight').AsString);
      C_width.Text := FC_Width;
      C_GramWeight.Text := FC_GramWeight;
      FC_Pattern := trim(fieldbyName('C_Pattern').AsString);
      C_Pattern.Text := trim(fieldbyName('C_Pattern').AsString);
      FFtyPCId := trim(fieldbyName('FtyPCId').AsString);
      FRulePieceNo := trim(fieldbyName('RulePieceNo').AsString);
      FRulePackNo := trim(fieldbyName('RulePackNo').AsString);

      if FRulePieceNo = '' then
        FRulePieceNo := '按缸号生成';
      if FRulePackNo = '' then
        FRulePackNo := '按订单生成';
         //包装袋
      FPackbag := fieldbyName('Packbag').AsFloat;
      //加重
      Faddwet := fieldbyName('RuleAddwet').AsFloat;
      //加长
      faddlen := fieldbyName('RuleAddLen').AsFloat;
      addwet.text := floatTostr(Faddwet);
      addLen.text := floatTostr(fAddLen);

      fAddwetVirtual := fieldbyName('RuleAddwetVirtual').AsFloat;
      fAddLenVirtual := fieldbyName('RuleAddLenVirtual').AsFloat;
      // 卷号生成规则
      if (FRulePieceNo = '手动') or (FRulePieceNo = '手动生成') then
      begin
        cds_params.edit;
        cds_params.fieldbyName('rollNoMake').value := '手动';
        cds_params.Post;
        dxLayoutItem_roll.Visible := true;
        PieceNo.Text := '';
      end;
      // 包号生成规则
      if (trim(fieldbyName('RulePackNo').AsString) = '手动') or (trim(fieldbyName('RulePackNo').AsString) = '手动生成') then
      begin
        cds_params.edit;
        cds_params.fieldbyName('packNoMake').value := '手动';
        cds_params.Post;
        dxLayoutItem_packno.Visible := true;
        edtPacketNo.Text := '';
      end;
      // 每包卷数
      cds_params.edit;
      cds_params.fieldbyName('packRolls').value := fieldbyName('packRolls').AsInteger;
      cds_params.fieldbyName('packlabnumber').value := fieldbyName('packlabnumber').AsInteger;
      cds_params.fieldbyName('packPostAction').value := trim(fieldbyName('packPostAction').AsString);
      if (fieldbyName('packRolls').AsInteger > 0) and (trim(fieldbyName('RulePackNo').AsString) <> '') then
      begin
        cds_params.fieldbyName('dabao').value := '√';
      end
      else
      begin
        cds_params.fieldbyName('dabao').value := '';
      end;
      //标签出纸
      if (fields.FindField('labelOutPage') <> nil) then
      begin
        if (fieldbyName('labelOutPage').AsBoolean or fieldbyName('labelOutPage').IsNull) then
        begin
          cds_params.fieldbyName('OutPage').value := '√';

        end
        else
        begin
          cds_params.fieldbyName('OutPage').value := '';
        end;
      end
      else
        cds_params.fieldbyName('outPage').value := '√';
//      cds_params.fieldbyName('aixunpage').value := '√';
      if fieldbyName('DecimalY').Value <> null then
        cds_params.fieldbyName('Yplace').value := fieldbyName('DecimalY').AsInteger;
      if fieldbyName('DecimalM').Value <> null then
        cds_params.fieldbyName('MPlace').value := fieldbyName('DecimalM').AsInteger;
      if fieldbyName('DecimalKg').Value <> null then
        cds_params.fieldbyName('kgPlace').value := fieldbyName('DecimalKg').AsInteger;
      cds_params.Post;
      //
      BatchNO.Text := trim(fieldbyName('batchNo').AsString);

      if (fields.FindField('mcxs') <> nil) and (ADOQueryBaseTemp.FieldByName('zhxs').AsFloat > 0) then
        Coefficient.Text := trim(ADOQueryBaseTemp.fieldbyName('zhxs').AsString)
      else
        Coefficient.Text := trim(fieldbyName('Coefficient').AsString);
      FGrosspoundxs := fieldbyName('Grosspoundxs').asfloat;
      FNetpoundxs := fieldbyName('Netpoundxs').AsFloat;
      custName.Text := trim(fieldbyName('custName').AsString);
     // 转换系数类型
      lblRuleConversion.ItemIndex := lblRuleConversion.Properties.Items.IndexOf(fieldbyName('RuleConversion').AsString);
      OrderNo.Text := FOrderNo;
      CodeName.Text := FC_Name;
      ColorNo.Text := FC_ColorNo;
      Color.Text := FC_Color;
      c_eColor.Text := FC_EColor;
      FtyPCId.Text := FFtyPCId;
      BCIOID.Text := FBCIOID;
      Piece.Text := trim(fieldbyName('ordPiece').AsString);
      Qty.Text := trim(fieldbyName('ordQty').AsString) + trim(fieldbyName('ordUnit').AsString);
      // 皮重
      Tare.Text := trim(fieldbyName('RuleLaterTare').AsString);

      fTareType := '';
      //码尺系数
      if (fields.FindField('mcxs') <> nil) and (fieldbyName('mcxs').AsFloat > 0) then
        RuleYardstick.Text := trim(fieldbyName('mcxs').AsString)
      else if fieldbyName('RuleYardstick').AsInteger > 0 then
        RuleYardstick.Text := trim(fieldbyName('RuleYardstick').AsString)
      else
        RuleYardstick.Text := '100';

      packnote.Lines.Clear;
      packnote.Lines.Add('包装要求：');
      packnote.Lines.Add(trim(fieldbyName('packnote').AsString));
      packnote.Lines.Add('备注：');
      packnote.Lines.Add(trim(fieldbyName('ordnote').AsString));
       // 定长     dxLayoutItem_pieceorder
      if fieldbyName('FixedLength').AsInteger > 0 then
      begin
        dxLayoutItem_fixlen.Visible := true;
        // Edit_fixLen.Text := '√';
        Edit_fixLen.Text := trim(fieldbyName('FixedLength').AsString);
      end
      else
      begin
        dxLayoutItem_fixlen.Visible := false;
        Edit_fixLen.Text := '';
      end;
      InputLen.SetFocus;
      setFocusCtrol(InputLen.Name);
      SetDdetails();
    end
    else
    begin
     // ClearGlobal();
      application.MessageBox('输入的条码错误,请检查!', '警告信息');
    end;
  end;
  GetPacketNo();
  InitJYGrid();
  InitCDGrid(FCIID);
  edtScan.Text := '';
  // 显示包
  setFormCtrol();
end;

procedure TfrmMachRollMain.InputLenKeyPress(Sender: TObject; var Key: Char);
begin
  if Key = #13 then
  begin
//    if gEnterAutoPost and ((TComponent(Sender).Name = 'InputLen') or (TComponent(Sender).Name = 'InputWeight')) then
//    begin
//      preEnterName := TComponent(Sender).Name;
//      BTPrint.Click;
//    end
//    else
//    begin
//      Key := #0;
//      SelectNext(ActiveControl as TWinControl, true, true);
//    end;
     BTPrint.Click;
  end;

end;

procedure TfrmMachRollMain.InputLenPropertiesChange(Sender: TObject);
begin

  // if StrToIntDef(trim(InputWeight.Text), 0) = 0 then
  // begin
  // exit;
  // end;
  QuantityConversion();
  if gAutoPost and (trim(cds_params.fieldbyName('mabiao').AsString) = '1') then
  begin
    if StrToFloatdef(trim(InputLen.Text), 0) > 5 then
    begin
      fCanAutoPost := true;
    end;
  end;
end;

procedure TfrmMachRollMain.lblRuleConversionPropertiesChange(Sender: TObject);
begin
  inherited;
  if lblRuleConversion.Text = '无需转换' then
  begin
    OutPutWeight.Text := '';
    InputLen.Text := '';
    InputWeight.Text := '';
  end;
  QuantityConversion();
end;

procedure TfrmMachRollMain.SetUnit(MUnit: string);
begin
  // lblLenUnit.Caption := MUnit;
  lblLenUnit.CaptionOptions.Hint := MUnit;
  lblLenUnit.CaptionOptions.Text := '[B][SIZE=16]' + MUnit + '[/SIZE][/B]';
  // lblLenUnit1.Caption := MUnit;
  frameBads1.lblLenUnit1.Caption := MUnit;
end;

procedure TfrmMachRollMain.SpeedButton1Click(Sender: TObject);
var
  fsj: string;
  mComponent: TComponent;
begin
  fsj := trim(TSpeedButton(Sender).Hint);
  if trim(fsj) = '' then
    exit;
  mComponent := FindComponent(trim(TSpeedButton(Sender).Hint));
  if mComponent = nil then
    mComponent := frameBads1.FindComponent(trim(TSpeedButton(Sender).Hint));
  if mComponent = nil then
    exit;
  if TcxTextEdit(mComponent).Name = 'KuangHao' then
    exit;
  fsj := trim(TcxTextEdit(mComponent).Text);
  TcxTextEdit(mComponent).Text := fsj + trim(TSpeedButton(Sender).Caption);
  TcxTextEdit(mComponent).SelectAll;

end;

procedure TfrmMachRollMain.SpeedButton_backClick(Sender: TObject);
var
  fsj: string;
  mComponent: TComponent;
begin
  mComponent := FindComponent(trim(TSpeedButton(Sender).Hint));
  if mComponent = nil then
    mComponent := frameBads1.FindComponent(trim(TSpeedButton(Sender).Hint));
  if mComponent = nil then
    exit;
  fsj := trim(TcxTextEdit(mComponent).Text);
  if trim(fsj) = '' then
    exit;
  TcxTextEdit(mComponent).Text := copy(fsj, 1, Length(fsj) - 1);
  TcxTextEdit(mComponent).SelectAll;

end;

procedure TfrmMachRollMain.ToolButton1Click(Sender: TObject);
begin
  var WSql: string;
  begin
    WSql := '';
    cds_3.DisableControls;
    with cds_3 do
    begin
      with ADOQueryBaseTemp do
      begin
        close;
        sql.clear;
        sql.add('select stuff((select'',''+  ciid  from Trade_Cloth_Inspect  where  BCIOID=''' + Trim(FSubId) + '''  for xml path('''')),1,1,'''' ) as DYCIID    ');
        open;
      end;
      WSql := Trim(ADOQueryBaseTemp.FieldByName('DYCIID').AsString);
    end;

    cds_3.EnableControls;
    try
      frmMdPrint := TfrmMdPrint.Create(Application);
      with frmMdPrint do
      begin
        FLMType := '入库码单';
        FFiltration1 := WSql;
        FFiltration2 := WSql;
        if ShowModal = 1 then
        begin
          if gPrintMdAutoOut then
//            autoOut(WSql);
//        Self.InitGrid();



        end;
      end;
    finally
      frmMdPrint.Free;
    end;

  end;
end;

procedure TfrmMachRollMain.ToolButton2Click(Sender: TObject);
begin
  inherited;
  frmDjdDjClList_CX := TfrmDjdDjClList_CX.create(Self);
  with frmDjdDjClList_CX do
  begin
    FOrderNo := self.FOrderNo;
    if ShowModal = 1 then
    begin

    end;
    free;
  end;

end;

procedure TfrmMachRollMain.ToolButton3Click(Sender: TObject);
begin
  if cds_3.IsEmpty then
    exit;
//  PrtData(cds_3.fieldbyName('CIID').AsString);
  if trim(cds_params.fieldbyName('outPage').AsString) = '√' then
  begin
    PrtData(cds_3.fieldbyName('CIID').AsString);
  end;
  if trim(cds_params.fieldbyName('aixunpage').AsString) = '√' then
  begin
    PrtaixunData(cds_3.fieldbyName('CIID').AsString);
  end;
end;

procedure TfrmMachRollMain.ToolButton4Click(Sender: TObject);
begin
  try
    frmZDYHelp := TfrmZDYHelp.create(Application);
    with frmZDYHelp do
    begin
      ToolButton1.Visible := false;
      DConString := Self.ADOQueryBaseCmd.Connection.ConnectionString;
      flag := 'WFBCD';
      flagname := '疵点';
      fnote := true;
      V1Note.Caption := '英文名称';
      if ShowModal = 1 then
      begin
        Self.frameBads1.InitBadPanel();
      end;
    end;
  finally
    frmZDYHelp.free;
  end;

end;

procedure TfrmMachRollMain.TrolldelClick(Sender: TObject);
var
  mCiid: string;
begin
  if cds_3.IsEmpty then
    exit;
  if BTPrint.Caption = '修改提交' then
  begin
    Application.MessageBox('修改提交时,禁止再次操作！', '提示信息');
    exit;
  end;
  if dxLayoutItem_rk.Visible then
  begin
    if (Trim(cds_3.FieldByName('ciioflag').AsString) <> '未入库') then
    begin
      Application.MessageBox('已入库禁止删除！', '提示信息');
      exit;
    end;
  end
  else
  begin
    if (Trim(cds_3.FieldByName('ciioflag').AsString) <> '已入库') then
    begin
      Application.MessageBox('已出库禁止删除！', '提示信息');
      exit;
    end;
  end;
  if Trim(cds_3.FieldByName('packetid').AsString) <> '' then
  begin
    if Application.MessageBox(pchar('确定要删除选择的整个包【' + Trim(cds_3.FieldByName('packetNo').AsString) + '】的卷数据吗？'), '提示', 32 + 4) <> IDYES then
      exit;
    deletePack(Trim(cds_3.FieldByName('packetid').AsString));
    exit;
  end
  else
  begin
    if Application.MessageBox('确定要删除选择的卷数据吗？', '提示', 32 + 4) <> IDYES then
      exit;
  end;
  ADOQueryBaseCmd.Connection.BeginTrans;
  try
    mCiid := trim(cds_3.fieldbyName('CIID').AsString);
    with ADOQueryBaseCmd do
    begin
      Close;
      SQL.Clear;
      SQL.Add('insert into Trade_Need_Up(UType,UOperation,UDataId,uoperator) values(''检验'',''检验删除'',' + QuotedStr(mCiid) + ',' + QuotedStr(DName) + ')  ');
      ExecSQL;
    end;
    with ADOQueryBaseCmd do
    begin
      Close;
      SQL.Clear;
      SQL.Add('exec P_Trade_Insp_Del ');
      SQL.Add('@CIIDS=' + QuotedStr(mCiid));
      SQL.Add(',@DCode=' + QuotedStr(DCode));
      SQL.Add(',@DName=' + QuotedStr(DName));
      Open;
    end;
    if ADOQueryBaseCmd.fieldbyName('intReturn').AsInteger = -1 then
    begin
      raise Exception.create(pchar(trim(ADOQueryBaseCmd.fieldbyName('ShowMsg').AsString)));
    end;
    ADOQueryBaseCmd.Connection.CommitTrans;
    if (FPacketCount > 0) and (ansipos(mCiid, FPacketCIID) > 0) then
    begin
      FPacketCount := FPacketCount - 1;
      FPacketCIID := FPacketCIID.Replace(mCiid, '');
      if FPacketCIID = ',' then
        FPacketCIID := '';

    end
    else
    begin
      with ADOQueryMain do
      begin
        Close;
        SQL.Clear;
        SQL.Add('select COUNT(*) AS TotalRows,');
        sql.add('STUFF((SELECT '','' + CIID FROM Trade_Cloth_Inspect WHERE BCIOID=''' + trim(FBCIOID) + ''' AND ISNULL(PacketId,'''') = '''' FOR XML PATH('''')), 1, 1, '''') AS CIID_List ');
        SQL.Add('from Trade_Cloth_Inspect A where BCIOID=''' + trim(FBCIOID) + '''  AND ISNULL(PacketId, '''') = ''''');
//        ShowMessage(sql.Text);
        Open;
      end;
      if (ADOQueryMain.fieldbyName('TotalRows').AsInteger < cds_params.fieldbyName('packRolls').AsInteger) then
      begin
        FPacketCount := ADOQueryMain.fieldbyName('TotalRows').AsInteger;
        FPacketCIID := ADOQueryMain.fieldbyName('CIID_List').AsString;
      end;
    end;

    cds_3.Delete;
    Application.MessageBox('删除成功！', '提示信息');
  except
    ADOQueryBaseCmd.Connection.RollbackTrans;
    Application.MessageBox(pchar(Exception(ExceptObject).Message), '提示信息', 0);
  end;

end;

procedure TfrmMachRollMain.Tv2DblClick(Sender: TObject);
begin
  inherited;
  if Application.MessageBox('确定要删除当前病疵记录吗？', '警告信息', 1) = 2 then
    exit;
  CDS_2.Delete;
end;

procedure TfrmMachRollMain.Tv3CustomDrawCell(Sender: TcxCustomGridTableView; ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean);
begin
  if AViewInfo.GridRecord.Values[TcxGridDBTableView(Sender).GetColumnByFieldName('Grade').Index] = '次品' then
    ACanvas.Brush.Color := clRed;
end;

procedure TfrmMachRollMain.Tv3FocusedRecordChanged(Sender: TcxCustomGridTableView; APrevFocusedRecord, AFocusedRecord: TcxCustomGridRecord; ANewItemRecordFocusingChanged: Boolean);
begin
  inherited;

  InitCDGridCX(cds_3.fieldbyName('CIID').AsString);
end;

procedure TfrmMachRollMain.TeditClick(Sender: TObject);
begin
  if cds_3.IsEmpty then
    exit;
  Panel_msg.Visible := not Panel_msg.Visible;
  cxgrid3.Enabled := not cxgrid3.Enabled;
  InitJTM(cds_3.fieldbyName('CIID').AsString);

  initEditPiece();
end;

procedure TfrmMachRollMain.TlogClick(Sender: TObject);
begin
  frmSysLogList := TfrmSysLogList.create(Self);
  with frmSysLogList do
  begin
    fModel := Self.Caption;
    FMainId := trim(Self.FMainId);
    ShowModal;
    free;
  end;

end;

procedure TfrmMachRollMain.ToolButton7Click(Sender: TObject);
begin
  WriteCxGrid(trim(Self.Caption) + 'Tv1', TV1, gDllFileCaption);
  WriteCxGrid(trim(Self.Caption) + 'Tv2', Tv2, gDllFileCaption);
  WriteCxGrid(trim(Self.Caption) + 'Tv3', Tv3, gDllFileCaption);
  if gIsCanDesign then
  begin
    saveLayOut(application, dxLayoutControl_pack, ADOQueryBaseCmd, PWideChar(fDllFileName + '|' + Self.Name + '|' + dxLayoutControl_pack.Name + '.ini'));
    saveLayOut(application, frameBads1.dxLayoutControl1, ADOQueryBaseCmd, PWideChar(fDllFileName + '|' + Self.Name + '|' + frameBads1.dxLayoutControl1.Name + '.ini'));
  end;
end;

procedure TfrmMachRollMain.ToolButton8Click(Sender: TObject);
begin
  inherited;
  Close;
end;

procedure TfrmMachRollMain.TprintPackClick(Sender: TObject);
begin
  if cds_3.IsEmpty or (trim(cds_3.fieldbyName('PacketId').AsString) = '') then
    exit;
  PrintBao(trim(cds_3.fieldbyName('PacketId').AsString));
end;

procedure TfrmMachRollMain.setFocusCtrol(controlName: string);
var
  i: Integer;
begin
//  with FrameKeyBoard1.dxPanel1 do
//  begin
//    for i := 0 to ControlCount - 1 do
//    begin
//      if Controls[i] is TSpeedButton then
//      begin
//        TSpeedButton(Controls[i]).Hint := trim(controlName);
//        if (trim(controlName) = 'edtScan') and (TSpeedButton(Controls[i]).Name = 'SpeedButton_dot') then
//        begin
//          TSpeedButton(Controls[i]).Caption := '回车';
//        end
//        else if (TSpeedButton(Controls[i]).Name = 'SpeedButton_dot') then
//        begin
//          TSpeedButton(Controls[i]).Caption := '.';
//        end;
//      end;
//    end;
//  end;
//  cxGroupBox_keys.Left := Panel_right.Left + 5;
//  cxGroupBox_keys.Visible := true;
end;

procedure TfrmMachRollMain.CIFEndChange(Sender: TObject);
var
  mvalue: double;
begin
  if trim(frameBads1.CIFBeg.Text) <> '' then
  begin
    if TryStrToFloat(frameBads1.CIFBeg.Text, mvalue) = false then
    begin
      Application.MessageBox('非法数字!', '提示', 0);
      exit;
    end;
  end
  else
  begin
    exit;
  end;
  if trim(frameBads1.CIFEnd.Text) <> '' then
  begin
    if TryStrToFloat(frameBads1.CIFEnd.Text, mvalue) = false then
    begin
      Application.MessageBox('非法数字!', '提示', 0);
      exit;
    end;
  end
  else
  begin
    exit;
  end;
  frameBads1.CIFQty.Text := floattostr(StrToFloat(frameBads1.CIFEnd.Text) - StrToFloat(frameBads1.CIFBeg.Text));
end;

procedure TfrmMachRollMain.SetDdetails();
begin
  AOrdDefNote1.Text := '';
  if fBuyConNo <> '' then
    AOrdDefNote1.Text := AOrdDefNote1.Text + '客户单号:' + fBuyConNo + #13;
  AOrdDefNote1.Text := AOrdDefNote1.Text + '卡号:' + FBCIOID + #13;
  if FC_EName <> '' then
    AOrdDefNote1.Text := AOrdDefNote1.Text + '品名:' + FC_Name + '(' + FC_EName + ')' + #13
  else
    AOrdDefNote1.Text := AOrdDefNote1.Text + '品名:' + FC_Name + #13;
  AOrdDefNote1.Text := AOrdDefNote1.Text + '门幅:' + FC_Width + ' 克重:' + FC_GramWeight + #13;
  // AOrdDefNote1.Text := AOrdDefNote1.Text + '克重:' + FC_GramWeight + #13;
  // AOrdDefNote1.Text := AOrdDefNote1.Text + '颜色:' + FC_Color + ' 色号:' + FC_ColorNo + #13;
  // AOrdDefNote1.Text := AOrdDefNote1.Text + '色号:' + FC_ColorNo + #13;
  if FC_StyleNo <> '' then
    AOrdDefNote1.Text := AOrdDefNote1.Text + '款号:' + FC_StyleNo + #13;
//  if abs(Faddwet) > 0 then
//  begin
//    AOrdDefNote1.Text := AOrdDefNote1.Text + '花型:' + FC_Pattern + ' 加重:' +
//      floattostr(Faddwet) + #13;
//  end
//  else if abs(faddlen) > 0 then
//  begin
//    AOrdDefNote1.Text := AOrdDefNote1.Text + '花型:' + FC_Pattern + ' 加长:' +
//      floattostr(faddlen) + #13;
//  end
  if FC_Pattern <> '' then
  begin
    if FC_Pattern <> '' then
      AOrdDefNote1.Text := AOrdDefNote1.Text + '花型:' + FC_Pattern + #13;
  end;

  if FRulePieceNo <> '' then
    AOrdDefNote1.Text := AOrdDefNote1.Text + '卷号规则:' + FRulePieceNo + #13;

  //if gMachOperators<>'' then
   //   AOrdDefNote1.Text := AOrdDefNote1.Text + '机台人员:' + gMachOperators + #13;

end;

procedure TfrmMachRollMain.SetINIFile();
begin
  IsDZCDYDll := trim(cds_params.fieldbyName('chen').AsString);
  IsMBDYDll := trim(cds_params.fieldbyName('mabiao').AsString);
  IsMBDYDllUnit := trim(cds_params.fieldbyName('mbunit').AsString);

  LabQty := trim(cds_params.fieldbyName('labNumber').AsString);
  FMinLen := trim(cds_params.fieldbyName('minLen').AsString);
  FMaxLen := trim(cds_params.fieldbyName('maxLen').AsString);
  FMinWeight := trim(cds_params.fieldbyName('minweight').AsString);
  FMaxWeight := trim(cds_params.fieldbyName('maxweight').AsString);

  FMPlace := trim(cds_params.fieldbyName('mplace').AsString);
  FYPlace := trim(cds_params.fieldbyName('yplace').AsString);
  FKgPlace := trim(cds_params.fieldbyName('kgplace').AsString);

  WriteINIFile();

end;

//
procedure TfrmMachRollMain.setFormCtrol();
begin
  if cds_params.fieldbyName('dabao').AsString = '√' then
  begin
    dxLayoutItem_packno.Visible := true;
    Tv3PacketNo.Visible := true;
    //
    if (trim(cds_params.fieldbyName('packPostAction').AsString) <> '自动') then
    begin
      dxLayoutItem_packpost.Visible := true;
    end
    else
      dxLayoutItem_packpost.Visible := false;
    //
    if cds_3.IsEmpty then
      edtPacketNo.Text := '1'
    else
      GetPacketNo();
  end
  else
  begin
    dxLayoutItem_packno.Visible := false;
    Tv3PacketNo.Visible := false;
    dxLayoutItem_packpost.Visible := false;
    edtPacketNo.Text := '';
  end;
  //
  if cds_params.fieldbyName('weightRule').AsInteger = 0 then
    dxLayoutItem_outweight.Caption := '[COLOR=Red][SIZE=18]净重[/COLOR][/SIZE]'
  else
    dxLayoutItem_outweight.Caption := '[COLOR=Red][SIZE=18]毛重[/COLOR][/SIZE]';

  if cds_params.fieldbyName('rollnoMake').AsString = '手动' then
  begin
    // PieceNo.Enabled:=true;
    PieceNo.Properties.ReadOnly := false;
    dxLayoutItem_roll.Visible := True;
    edit_roll_auto.Text := '';
    if cds_params.fieldbyName('BeginPieceNo').AsInteger > 0 then
    begin
      PieceNo.Text := cds_params.fieldbyName('BeginPieceNo').AsString;
    end;
    // 倒序
    if (cds_params.fieldbyName('EndPieceNo').AsInteger > 0) and (cds_params.fieldbyName('BeginPieceNo').AsInteger > cds_params.fieldbyName('EndPieceNo').AsInteger) then
    begin
      dxLayoutItem_pieceorder.Visible := true;
      Edit_pieceOrder.Text := '√';
    end
    else
    begin
      dxLayoutItem_pieceorder.Visible := false;
      Edit_pieceOrder.Text := '';
    end;

  end
  else
  begin
    PieceNo.Properties.ReadOnly := true;
    edit_roll_auto.Text := '√';
    dxLayoutItem_roll.Visible := true;
//    PieceNo.Text := cds_params.fieldbyName('BeginPieceNo').AsString;
    // PieceNo.Enabled:=False;
  end;

  FrameKeyBoard1.SpeedButton_zdykey1.Caption := gZdyKey1;
  // FrameKeyBoard1.SpeedButton_zdykey2.Caption := gZdyKey2;
  FrameKeyBoard1.SpeedButton_zdykey2.Caption := gZdyKey2;

  //赠送
  presentlen.text := trim(cds_params.fieldbyName('AddLenPresent').AsString);
  presentWeight.text := trim(cds_params.fieldbyName('AddwetPresent').AsString);
end;

procedure TfrmMachRollMain.GetINIFile();
begin
  with cds_params do
  begin
    if IsEmpty then
      Append
    else
      edit;
    fieldbyName('chen').value := IsDZCDYDll;
    fieldbyName('mabiao').value := IsMBDYDll;
    fieldbyName('mbunit').value := IsMBDYDllUnit;

    fieldbyName('MinLen').value := strtointdef(FMinLen, 0);
    fieldbyName('MaxLen').value := strtointdef(FMaxLen, 100);
    fieldbyName('MinWeight').value := strtointdef(FMinWeight, 0);
    fieldbyName('MaxWeight').value := strtointdef(FMaxWeight, 50);

    fieldbyName('MPlace').value := strtointdef(FMPlace, 1);
    fieldbyName('YPlace').value := strtointdef(FYPlace, 1);
    fieldbyName('KgPlace').value := strtointdef(FKgPlace, 1);

    fieldbyName('labNumber').value := strtointdef(trim(LabQty), 1);
    Post;
  end;

end;

procedure TfrmMachRollMain.InitCDGrid(MCIID: string);
begin
  cxPageControl1.ActivePageIndex := 0;
  try
    tv2.BeginUpdate();
    CDS_2.DisableControls;
    with ADOQueryBaseTemp do
    begin
      Close;
      SQL.Clear;
      SQL.Add('select * from Trade_Cloth_Inspect_Flaw where CIID=' + QuotedStr(trim(MCIID)));
      Open;
    end;
    SCreateCDS(ADOQueryBaseTemp, CDS_2);
    SInitCDSData(ADOQueryBaseTemp, CDS_2);
  finally
    CDS_2.EnableControls;
    tv2.EndUpdate;
  end;
end;

procedure TfrmMachRollMain.InitCDGridCX(MCIID: string);
begin
  cxPageControl1.ActivePageIndex := 1;
  try
    tv1.BeginUpdate();
    with ADOQueryBaseTemp do
    begin
      Close;
      SQL.Clear;
      SQL.Add('select * from Trade_Cloth_Inspect_Flaw where CIID=' + QuotedStr(trim(MCIID)));
      Open;
    end;
    SCreateCDS(ADOQueryBaseTemp, cds_1);
    SInitCDSData(ADOQueryBaseTemp, cds_1);
  finally
    tv1.EndUpdate;
  end;
end;

procedure TfrmMachRollMain.InitJYGrid();
var
  MNetWeight, MJYLen: double;
begin
  try
    TV3.BeginUpdate();
    cds_3.DisableControls;
    with ADOQueryMain do
    begin
      Close;
      SQL.Clear;
      SQL.Add('select A.*');
      SQL.Add('from Trade_Cloth_Inspect A where BCIOID=''' + trim(FBCIOID) + '''');
      if FtyPCIDSX.text <> '' then
      begin
        SQL.Add(' and BatchNO = ''' + FtyPCIDSX.Text + '''');
      end;
      SQL.Add('order by filltime desc');
      Open;
    end;
    SCreateCDS(ADOQueryMain, cds_3);
    SInitCDSData(ADOQueryMain, cds_3);
//    if not cds_3.IsEmpty then
//    begin
//      cds_3.First;
//      PieceNo.Text := trim(cds_3.FieldByName('PieceNo').AsString); //
//    end
//    else
//      PieceNo.Text := '';

  finally
    cds_3.EnableControls;
    tv3.EndUpdate;
  end;

end;

procedure TfrmMachRollMain.OpenCom(DllName: string);
type
  TMyFunc = function(fhandle: hwnd; sCommName: PAnsiChar; IntTime: Integer; IsMessage: Integer): hwnd; stdcall;
var
  Tf: TMyFunc;
  Tp: TFarProc;
  Th: Thandle;
begin
  Th := LoadLibrary(pchar(trim(DllName)));
  if Th > 0 then
  begin
    try
      Tp := GetProcAddress(Th, 'CommOpen');
      if Tp <> nil then
      begin
        Tf := TMyFunc(Tp);
        newh := Tf(Self.Handle, 'Comm1', 500, 1);
        if newh < 1 then
        begin
          Application.MessageBox(pchar('打开串口失败！'), '提示');
        end
        else
          fIsCommopen := true;
      end
      else
      begin
        fIsCommopen := false;
      end;
    finally
      // FreeLibrary(Th);
    end;
  end
  else
  begin
    fIsCommopen := false;
    Application.MessageBox(pchar('找不到 ' + trim(DllName) + ' 文件！'), '提示');
  end;
end;

procedure TfrmMachRollMain.packPostBtnClick(Sender: TObject);
var
  MPacketId: string;
begin
  if (trim(cds_params.fieldbyName('dabao').AsString) <> '√') then
    exit;
  try
    packPostBtn.Enabled := false;
    if FPacketCount = 0 then
    begin
      Application.MessageBox('还未有需要打包的卷！', '提示', 0);
      exit;
    end;
    if FPacketCount > 0 then
    begin
      if GetLSNo(ADOQueryBaseTemp, MPacketId, 'BI', 'Trade_Cloth_Inspect', 4, 1) = false then
      begin
        Application.MessageBox('取包条码最大号失败！', '提示', 0);
        exit;
      end;

      try
        ADOQueryBaseCmd.Connection.BeginTrans;
        with ADOQueryBaseCmd do
        begin
          Close;
          SQL.Clear;
          SQL.Add('Update Trade_Cloth_Inspect Set PacketTime=GETDATE() , PacketNo=' + trim(edtPacketNo.Text) + ',PacketId=' + QuotedStr(trim(MPacketId)) + ',PacketCode=' + QuotedStr(trim(DCode)) + ',PacketName=' + QuotedStr(trim(DName)));
          SQL.Add('WHERE EXISTS(select X.RTValue from [dbo].[F_Tool_SplitString](' + QuotedStr(FPacketCIID) + ','','') X where Trade_Cloth_Inspect.CIID=X.RTValue )  ');
          SQL.Add('Update Trade_Cloth_Stock Set PacketTime=GETDATE() , PacketNo=' + trim(edtPacketNo.Text) + ',PacketId=' + QuotedStr(trim(MPacketId)) + ',PacketCode=' + QuotedStr(trim(DCode)) + ',PacketName=' + QuotedStr(trim(DName)));
          SQL.Add('WHERE EXISTS(select X.RTValue from [dbo].[F_Tool_SplitString](' + QuotedStr(FPacketCIID) + ','','') X where Trade_Cloth_Stock.STKID=X.RTValue )  ');
          ExecSQL;
        end;
        if (cds_params.fieldbyName('packlabnumber').AsInteger > 0) then
          PrintBao(MPacketId);
        edtPacketNo.Text := inttostr(strtoint(edtPacketNo.Text) + 1);
        FPacketCIID := '';
        FPacketCount := 0;
        ADOQueryBaseCmd.Connection.CommitTrans;
            //
        if fileexists(ExtractFilePath(Application.ExeName) + '正确.wav') then
          playSound(pwidechar('正确.wav'), 0, SND_FILENAME or SND_ASYNC);
      except
        ADOQueryBaseCmd.Connection.RollbackTrans;
        Application.MessageBox('打包失败！', '提示信息', 0);
      end;

    end;

  finally
    InitJYGrid();
    packPostBtn.Enabled := true;
  end;

end;

procedure TfrmMachRollMain.CloseCom(DllName: string);
type
  TMyFunc = function(sCommName: PAnsiChar): hwnd; stdcall;
var
  Tf1: TMyFunc;
  Tp1: TFarProc;
  Th1: Thandle;
begin
  Th1 := LoadLibrary(pchar(trim(DllName)));
  if Th1 > 0 then
  begin
    try
      Tp1 := GetProcAddress(Th1, 'CommClose');
      if Tp1 <> nil then
      begin
        Tf1 := TMyFunc(Tp1);
        newh1 := Tf1('Comm1');
      end
      else
      begin

      end;
    finally
      // FreeLibrary(Th1);
    end;
  end
  else
  begin
    Application.MessageBox(pchar('找不到 ' + trim(DllName) + ' 文件！'), '提示');
  end;
end;

////////////////////////////////////////////////////
procedure TfrmMachRollMain.ClearCom(DllName: string);
type
  TMyFunc = function(sCommName: PAnsiChar): hwnd; stdcall;
var
  Tf1: TMyFunc;
  Tp1: TFarProc;
  Th1: Thandle;
begin
  Th1 := LoadLibrary(pchar(trim(DllName)));
  if Th1 > 0 then
  begin
    try
      Tp1 := GetProcAddress(Th1, 'CommClear');
      if Tp1 <> nil then
      begin
        Tf1 := TMyFunc(Tp1);
        newh1 := Tf1('Comm1');
      end
      else
      begin

      end;
    finally
      // FreeLibrary(Th1);
    end;
  end
  else
  begin
    Application.MessageBox(pchar('找不到 ' + trim(DllName) + ' 文件！'), '提示');
  end;
end;

procedure TfrmMachRollMain.customStrField5DblClick(Sender: TObject);
begin
  inherited;
  TcxButtonEdit(Sender).Text := '';
  TcxButtonEdit(Sender).Properties.LookupItems.Text := '';
end;

procedure TfrmMachRollMain.customStrField5PropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
var
  fsj: string;
  FWZ: Integer;
begin
  fsj := trim(TcxButtonEdit(Sender).Hint);
  FWZ := Pos('/', fsj);
  try
    frmZDYHelp := TfrmZDYHelp.Create(Application);
    with frmZDYHelp do
    begin
      flag := Copy(fsj, 1, FWZ - 1);
      flagname := Copy(fsj, FWZ + 1, Length(fsj) - FWZ);

      if ShowModal = 1 then
      begin
        TcxButtonEdit(Sender).Text := trim(ClientDataSet1.fieldbyname('ZDYName').AsString);
      end;
    end;
  finally
    frmZDYHelp.Free;
  end;

end;

procedure TfrmMachRollMain.cxButton2Click(Sender: TObject);
begin
  inherited;
  if FCIFName = '' then
  begin
    frameBads1.dxPanel1.Visible := false;
    exit;
  end;

  with CDS_2 do
  begin
    Append;
    if frameBads1.RadioGroup1.ItemIndex = 5 then
      FieldByName('CIFName').Value := '连续性' + Trim(FCIFName)
    else if frameBads1.RadioGroup1.ItemIndex = 4 then
      FieldByName('CIFName').Value := '整匹' + Trim(FCIFName)
    else
      fieldbyName('CIFName').value := trim(FCIFName);

    fieldbyName('CIFbeg').value := trim(frameBads1.CIFBeg.Text);
    fieldbyName('CIFEnd').value := trim(frameBads1.CIFEnd.Text);
    fieldbyName('CIFNumber').value := strtointdef(trim(frameBads1.CIFNumber.Text), 0);

    fieldbyName('CIFPoints').value := 0;

    if frameBads1.RadioGroup1.ItemIndex > -1 then
    begin
      if frameBads1.RadioGroup1.ItemIndex < 3 then
      begin
        fieldbyName('CIFPoints').value := frameBads1.RadioGroup1.ItemIndex + 1;
      end
      else
      begin
        fieldbyName('CIFPoints').value := 4;
      end;
    end;
    fieldbyName('CIFQty').value := strtofloatdef(trim(frameBads1.CIFQty.Text), 0);
    fieldbyName('SubtractQty').value := strtofloatdef(trim(frameBads1.SubtractQty.Text), 0);
    fieldbyName('IsSubtract').value := frameBads1.IsSubtract.Checked;

    Post;
  end;
  frameBads1.CIFBeg.Text := '';
  frameBads1.CIFEnd.Text := '';
  frameBads1.CIFQty.Text := '';
  frameBads1.dxPanel1.Visible := false;
  cxPageControl1.ActivePageIndex := 0;
end;

procedure TfrmMachRollMain.dxLayoutControl_packDblClick(Sender: TObject);
begin
  if gIsCanDesign then
    layoutDesign(TdxLayoutControl(Sender), ADOQueryBaseCmd, PWideChar(dcode));
end;

procedure TfrmMachRollMain.dxLayoutItem1CaptionClick(Sender: TObject);
var
  mkey: Char;
begin
  inherited;
  frmProductListHelp := TfrmProductListHelp.create(Self);
  with frmProductListHelp do
  begin
    fType := '10';
    if ShowModal = 1 then
    begin
      edtScan.Text := trim(order_main.fieldbyName('Subid').AsString);
      mkey := #13;
      edtScanKeyPress(edtScan, mkey);
    end;
    free;
  end;
//  cds_params.Edit;
//  cds_params.fieldByName('rollnoMake').Value := '手动';
//  cds_params.fieldByName('weightRule').Value := 1;
//  cds_params.fieldByName('aixunpage').Value := '';
//  cds_params.Post;
end;

procedure TfrmMachRollMain.Edit_fixLenClick(Sender: TObject);
begin
  inherited;
  // if trim(Edit_fixLen.Text) = '' then
  // begin
  // Edit_fixLen.Text := '√';
  // end
  // else
  // begin
  // Edit_fixLen.Text := '';
  // end;
end;

procedure TfrmMachRollMain.Edit_pieceOrderClick(Sender: TObject);
begin
  inherited;
  if trim(Edit_pieceOrder.Text) = '' then
  begin
    Edit_pieceOrder.Text := '√';
  end
  else
  begin
    Edit_pieceOrder.Text := '';
  end;
end;

procedure TfrmMachRollMain.edit_roll_autoClick(Sender: TObject);
begin
  if trim(edit_roll_auto.Text) = '' then
  begin
    edit_roll_auto.Text := '√';
    PieceNo.Properties.ReadOnly := true;
    cds_params.Edit;
    cds_params.fieldByName('rollnoMake').Value := '自动';
    cds_params.Post;
  end
  else
  begin
    edit_roll_auto.Text := '';
    PieceNo.Properties.ReadOnly := false;
    cds_params.Edit;
    cds_params.fieldByName('rollnoMake').Value := '手动';
    cds_params.Post;
    if PieceNo.Visible then
      PieceNo.SetFocus;
  end;

end;

procedure TfrmMachRollMain.edtScanDblClick(Sender: TObject);
begin
  inherited;
  edtScan.Text := '';
end;

procedure TfrmMachRollMain.edtScanEnter(Sender: TObject);
begin
  inherited;
  setFocusCtrol(TWinControl(Sender).Name);
end;

procedure TfrmMachRollMain.edtScanKeyPress(Sender: TObject; var Key: Char);
begin
  inherited;
  if Key = #13 then
  begin
    if trim(edtScan.Text) = '' then
      exit;
    if trim(edtScan.Text) = FBCIOID then
      exit;
    ClearGlobal();
    FOperationStatus := '缸条码';
    // InitLCK(edtScan.Text);
    InitPlan(edtScan.Text);
    frameBads1cxCheckBox_readLenPropertiesChange(frameBads1.IsSubtract);
    // 是否读长度勾选
    if trim(OrderNo.Text) <> '' then
      InputLen.SetFocus;
    cxGroupBox_keys.Visible := false;
    if (trim(cds_params.fieldbyName('dabao').AsString) = '√') then
    begin
      with ADOQueryMain do
      begin
        Close;
        SQL.Clear;
        SQL.Add('select COUNT(*) AS TotalRows,');
        sql.add('STUFF((SELECT '','' + CIID FROM Trade_Cloth_Inspect WHERE BCIOID=''' + trim(FBCIOID) + ''' AND ISNULL(PacketId,'''') = '''' FOR XML PATH('''')), 1, 1, '''') AS CIID_List ');
        SQL.Add('from Trade_Cloth_Inspect A where BCIOID=''' + trim(FBCIOID) + '''  AND ISNULL(PacketId, '''') = ''''');
//        ShowMessage(sql.Text);
        Open;
      end;
      if (ADOQueryMain.fieldbyName('TotalRows').AsInteger < cds_params.fieldbyName('packRolls').AsInteger) then
      begin
        FPacketCount := ADOQueryMain.fieldbyName('TotalRows').AsInteger;
        FPacketCIID := ADOQueryMain.fieldbyName('CIID_List').AsString;
      end
      else
      begin
        Application.MessageBox('有超过每包匹数的卷数没有打包，请核对信息！', '提示信息');
        exit;
      end;

    end;
  end;

end;

//

function TfrmMachRollMain.SaveData(): Boolean;
var
  maxno, MCIID, BZID, strsql: string;
  MInputLen, MMeter, MYardage: double;
  MInputWeight, MGrossWeight, MNetWeight, MTare, Maddwet, maddLen: double;
  mYardStick: double;
  mPresentLen, mpresentWeight: double;
  mPresentLen0, mpresentWeight0: double;
  mDetailMs: string;
begin
  Result := false;

  Maddwet := strTofloatDef(trim(addwet.text), 0); // Faddwet;
  maddLen := strTofloatDef(trim(addlen.text), 0); // faddlen;
  mYardStick := strtofloatdef(trim(RuleYardstick.Text), 100);
  mPresentLen := strTofloatDef(trim(presentlen.text), 0);
  mpresentWeight := strTofloatDef(trim(presentWeight.text), 0);
  mPresentLen0 := strTofloatDef(trim(presentlen.text), 0);
  mpresentWeight0 := strTofloatDef(trim(presentWeight.text), 0);
  if (strtoFloatdef(Trim(unitPieces.Text), 0) > 0) and (strtoFloatdef(trim(InputLen.Text), 0) > 0) then
  begin
    if strtoFloatdef(trim(InputLen.Text), 0) > strtoFloatdef(Trim(unitPieces.Text), 0) then
      funitPiecesStr := Trim(unitPieces.Text) + '+' + floatTostr((strtoFloatdef(trim(InputLen.Text), 0)) - strtoFloatdef(Trim(unitPieces.Text), 0));
  end;
  //0:不变；1：减去赠送
  if gPresentNumFlag = 1 then
  begin
    mPresentLen := -1 * mPresentLen;
    mpresentWeight := -1 * mpresentWeight;
  end
  else
  begin
    mPresentLen := 0;
    mpresentWeight := 0;
  end;

  if FOperationStatus = '卷条码' then
  begin
    MCIID := FCIID;
  end
  else
  begin
    MCIID := '';
  end;
  try
    ADOQueryBaseCmd.Connection.BeginTrans;
    /// 保存主表
    with ADOQueryBaseCmd do
    begin
      Close;
      SQL.Clear;
      SQL.Add('select * from Trade_Cloth_Inspect where CIID=''' + trim(MCIID) + '''');
      Open;
    end;
    with ADOQueryBaseCmd do
    begin
      if trim(MCIID) = '' then
      begin
        if not GetLSNo(ADOQueryBaseTemp, maxno, trim(SCXFlag), 'Trade_Cloth_Inspect', 4, 1) then
          raise Exception.create('获取条码失败！');
        Append;
        fieldbyName('Filler').value := trim(DName);
        fieldbyName('CIID').value := trim(maxno);
      end
      else
      begin
        maxno := trim(MCIID);
        edit;
        fieldbyName('Editer').value := trim(DName);
        fieldbyName('EditTime').value := SGetServerDateTime(ADOQueryBaseTemp);
      end;
      // 系数
      fieldbyName('Coefficient').value := strtofloatdef(trim(Coefficient.Text), 0); // 系数
      /// //////////////////////           保存重量         /////////////////////////
      if cds_params.fieldbyName('weightRule').AsInteger = 0 then
      // InputWeight  毛重         OutPutWeight   净重
      begin
        MTare := strtofloatdef(trim(Tare.Text), 0); // 皮重
        MInputWeight := strtofloatdef(trim(InputWeight.Text), 0); //输入为 毛重
        MGrossWeight := MInputWeight + Maddwet + mpresentWeight + FPackbag; // 毛重 + 加重  +包装袋
        MNetWeight := MInputWeight + Maddwet - MTare + mpresentWeight; // 净重 + 加重
        fieldbyName('InputWeight').value := MInputWeight;

        // 净重
        if MInputWeight > 0 then
        begin
          fieldbyName('NetWeight').value := RoundFloat(MNetWeight, cds_params.fieldbyName('KgPlace').AsInteger);
          fieldbyName('GrossWeight').value := RoundFloat(MGrossWeight, cds_params.fieldbyName('KgPlace').AsInteger);     // 毛重
          fieldbyName('Netpound').value := RoundFloat((MNetWeight * FNetpoundxs), cds_params.fieldbyName('KgPlace').AsInteger);
          fieldbyName('Grosspound').value := RoundFloat(((MNetWeight * FNetpoundxs) + FGrosspoundxs), cds_params.fieldbyName('KgPlace').AsInteger);
        end
        else
        begin
          fieldbyName('NetWeight').value := 0;
          fieldbyName('GrossWeight').value := 0;
          fieldbyName('Netpound').value := 0;
          fieldbyName('Grosspound').value := 0;
        end;
        fieldbyName('Tare').value := MTare;
        fieldbyName('addwet').value := Maddwet;

      end;

      if cds_params.fieldbyName('weightRule').AsInteger = 1 then
      // InputWeight  净重         OutPutWeight   毛重
      begin
        MTare := strtofloatdef(trim(Tare.Text), 0); // 皮重
        MInputWeight := strtofloatdef(trim(InputWeight.Text), 0); // 净重
        MGrossWeight := MInputWeight + MTare + Maddwet + mpresentWeight + FPackbag; // 毛重  +包装袋的
        MNetWeight := MInputWeight + Maddwet + mpresentWeight; // 净重 +加重
        fieldbyName('InputWeight').value := MInputWeight;

        if MInputWeight > 0 then
        begin
          fieldbyName('NetWeight').value := RoundFloat(MNetWeight, cds_params.fieldbyName('KgPlace').AsInteger);
          fieldbyName('GrossWeight').value := RoundFloat(MGrossWeight, cds_params.fieldbyName('KgPlace').AsInteger);
          fieldbyName('Netpound').value := RoundFloat((MNetWeight * FNetpoundxs), cds_params.fieldbyName('KgPlace').AsInteger);
          fieldbyName('Grosspound').value := RoundFloat(((MNetWeight * FNetpoundxs) + FGrosspoundxs), cds_params.fieldbyName('KgPlace').AsInteger);
        end
        else
        begin
          fieldbyName('NetWeight').value := 0;
          fieldbyName('GrossWeight').value := 0;
          fieldbyName('Netpound').value := 0;
          fieldbyName('Grosspound').value := 0;
        end;
        // 皮重
        fieldbyName('Tare').value := MTare;
        fieldbyName('addwet').value := Maddwet;
      end;
      /// //////////////////////           保存重量         /////////////////////////
      /// //////////////////////           保存长度         /////////////////////////
      /// = '√'
      if strtofloatdef(trim(Edit_fixLen.Text), 0) > 0 then
        MInputLen := strtofloatdef(trim(Edit_fixLen.Text), 0)
      else
        MInputLen := RoundFloat(strtofloatdef(trim(InputLen.Text), 0), 4);
      // 换算后数量+mAddLen
      if (uppercase(lblLenUnit.CaptionOptions.Hint) = 'M') or (lblLenUnit.CaptionOptions.Hint = '米') then
      begin
        MMeter := RoundFloat((MInputLen + maddLen + mPresentLen) / (mYardStick / 100), cds_params.fieldbyName('MPlace').AsInteger);
        MYardage := RoundFloat(MMeter / 0.9144, cds_params.fieldbyName('YPlace').AsInteger);
      end
      else
      begin
        MYardage := RoundFloat((MInputLen + maddLen + mPresentLen) / (mYardStick / 100), cds_params.fieldbyName('YPlace').AsInteger);
        MMeter := RoundFloat(MYardage * 0.9144, cds_params.fieldbyName('MPlace').AsInteger);
      end;

      ADOQueryBaseCmd.fieldbyName('InputLen').value := RoundFloat(strtofloatdef(trim(InputLen.Text), 0), 2);
      fieldbyName('Meter').value := MMeter;
      fieldbyName('Yardage').value := MYardage;
      fieldbyName('LenUnit').value := trim(lblLenUnit.CaptionOptions.Hint);
      fieldbyName('AddLen').value := maddLen;
      fieldbyName('YardStick').value := mYardStick;

      /// //////////////////////           保存长度         /////////////////////////
      // if Trim(Edit_zp.Text) <> '' then
      // begin
      fieldbyName('Grade').value := trim(grade.Text);
      // end;
      // if Trim(Edit_cp.Text) <> '' then
      // begin
      // FieldByName('Grade').Value := '次品';
      // end;
      if FOperationStatus <> '卷条码' then
      begin
        fieldbyName('PieceNo').value := 0;
      end;

      // 手动卷号
      if (FRulePieceNo = '手动生成') or (FRulePieceNo = '手动') or (cds_params.fieldbyName('rollnoMake').AsString = '手动') then
      begin
        fieldbyName('PieceNo').value := strtoint(trim(PieceNo.Text));
      end;
      fieldbyName('TXM').value := trim(TXM.Text);

      fieldbyName('status').value := '0';
      fieldbyName('OrderNo').value := trim(FOrderNo);
      fieldbyName('MainId').value := trim(FMainId);
      fieldbyName('SubId').value := trim(FSubId);
      fieldbyName('ConNo').value := trim(FConNo);
      fieldbyName('ConMId').value := trim(FConMId);
      fieldbyName('ConSId').value := trim(FConSId);
      fieldbyName('BCIOID').value := trim(FBCIOID);
      fieldbyName('Workshop').value := trim(FWorkshop);
      if dxLayoutItem_rk.Visible then
        fieldbyName('CIIOFlag').value := '未入库'
      else
        fieldbyName('CIIOFlag').value := '已入库';
      fieldbyName('C_Code').value := FC_Code;
      fieldbyName('C_Name').value := FC_Name;
      fieldbyName('C_EName').value := FC_EName;
      fieldbyName('BatchNO').value := BatchNO.Text;
      fieldbyName('FtyPCId').value := FtyPCId.Text; // 原缸号
      fieldbyName('C_Spec').value := FC_Spec;
      fieldbyName('C_Color').value := FC_Color;
      fieldbyName('C_EColor').value := FC_EColor;
      fieldbyName('C_ColorNo').value := FC_ColorNo;
      fieldbyName('C_StyleNo').value := FC_StyleNo;
      fieldbyName('C_Composition').value := FC_Composition;
      if dxLayoutItem_width.ActuallyVisible then
        fieldbyName('C_Width').value := trim(C_width.Text)
      else
        fieldbyName('C_Width').value := FC_Width;

      if dxLayoutItem_gram.ActuallyVisible then
        fieldbyName('C_GramWeight').value := trim(C_GramWeight.Text)
      else
        fieldbyName('C_GramWeight').value := FC_GramWeight;

      fieldbyName('C_Pattern').value := FC_Pattern;
      fieldbyName('C_CustPattern').value := FC_CustPattern;
      fieldbyName('C_ColorDepth').value := FC_ColorDepth;
      fieldbyName('CIMachNo').value := trim(SCXFlag);

      // 虚加重量

      fieldbyName('AddwetVirtual').value := fAddwetVirtual;
      fieldbyName('AddLenVirtual').value := fAddLenVirtual;

      fieldbyName('AddwetPresent').value := abs(mpresentWeight0);
       // cds_params.fieldbyName('AddwetPresent').AsFloat;
      fieldbyName('AddLenPresent').value := abs(mPresentLen0);
      //  cds_params.fieldbyName('AddLenPresent').AsFloat;
      //自定义输入1
      fieldbyName('customStrField1').value := trim(customStrField1.Text);
      fieldbyName('customStrField2').value := trim(customStrField2.Text);
      fieldbyName('customStrField3').value := trim(customStrField3.Text);
      fieldbyName('customStrField4').value := trim(customStrField4.Text);
      fieldbyName('customStrField5').value := trim(customStrField5.Text);
      fieldbyName('customStrField6').value := trim(customStrField6.Text);
      fieldbyName('customStrField7').value := trim(customStrField7.Text);
      fieldbyName('customStrField8').value := trim(customStrField8.Text);


      //拼匹

      if fields.FindField('unitPieces') <> nil then
        fieldbyName('unitPieces').value := funitPiecesStr;
      //机台操作员
      if fields.FindField('operators') <> nil then
        fieldbyName('operators').value := gMachOperators;

      Post;
    end;

    MCIID := trim(maxno);
    FCIID := trim(maxno);

    /// ///////////////       保存疵点信息       //////////////////
    with CDS_2 do
    begin
      First;
      while not eof do
      begin
        if trim(CDS_2.fieldbyName('CIFID').AsString) = '' then
        begin
          if not GetLSNo(ADOQueryBaseTemp, maxno, 'JC', 'Trade_Cloth_Inspect_Flaw', 5, 1) then
            raise Exception.create('获取疵点失败！');
        end
        else
        begin
          maxno := trim(CDS_2.fieldbyName('CIFID').AsString);
        end;
        with ADOQueryBaseCmd do
        begin
          Close;
          SQL.Clear;
          SQL.Add('select * from Trade_Cloth_Inspect_Flaw  ');
          SQL.Add(' where CIFID=''' + trim(maxno) + '''');
          Open;
        end;
        with ADOQueryBaseCmd do
        begin
          if trim(CDS_2.fieldbyName('CIFID').AsString) = '' then
            Append
          else
            edit;
          RTSetSaveDataCDS(ADOQueryBaseCmd, Tv2, CDS_2, 'Trade_Cloth_Inspect_Flaw', 0);
          fieldbyName('CIID').value := trim(MCIID);
          fieldbyName('CIFID').value := trim(maxno);
          Post;
        end;
        CDS_2.edit;
        CDS_2.fieldbyName('CIID').value := trim(MCIID);
        CDS_2.fieldbyName('CIFID').value := trim(maxno);
        next;
      end;
    end;
    /// ///////////////       保存疵点信息       //////////////////
    ///
    /// ///////////////       更新卷号疵点信息       //////////////////
    with ADOQueryBaseCmd do
    begin
      Close;
      SQL.Clear;
      SQL.Add('exec P_Trade_Insp_Up_pack @CIID=''' + trim(MCIID) + '''');
      if FOperationStatus = '缸条码' then
        SQL.Add(',@InspType=' + QuotedStr('待检布出库'))
      else
        SQL.Add(',@InspType=' + QuotedStr('单卷修改'));
      if (cds_params.fieldbyName('rollnoMake').AsString = '手动') then
      begin
        SQL.Add(',@RulePieceNo=' + QuotedStr('手动生成')); // 卷号生成规则
      end
      else
      begin
        SQL.Add(',@RulePieceNo=' + QuotedStr(FRulePieceNo)); // 卷号生成规则
      end;
      ExecSQL;
    end;

    //判断是否有重复
    if not checkPicecNo() then
    begin

      exit;
    end;

    /// ///////////////       更新卷号疵点信息       //////////////////
    ///
    /// ///////////////       更新开卡       //////////////////
    with ADOQueryBaseCmd do
    begin
      Close;
      SQL.Clear;

      if BTPrint.Caption = '提  交' then
      begin
        SQL.Add('insert into Trade_Need_Up(UOperation,UType,UDataId,uoperator) values(''机台检验'',''检验'',' + QuotedStr(maxno) + ',' + QuotedStr(DName) + ')  ');
      end
      else
      begin
        if cds_3.FieldByName('inputLen').AsFloat <> strToFloatDef(trim(inputLen.Text), 0) then
          mDetailMs := '长度' + cds_3.FieldByName('inputLen').AsString + '->' + inputLen.Text;
        if cds_3.FieldByName('inputWeight').AsFloat <> strToFloatDef(trim(inputWeight.Text), 0) then
          mDetailMs := mDetailMs + '  重量' + cds_3.FieldByName('inputWeight').AsString + '->' + inputWeight.Text;
        SQL.Add('insert into Trade_Need_Up(UOperation,UType,UDataId,uoperator,UDetails) values(''检验数据修改'',''检验'',' + QuotedStr(maxno) + ',' + QuotedStr(DName) + ',' + QuotedStr(mDetailMs) + ' )  ');
      end;

      ExecSQL;
    end;
    /// ///////////////       更新开卡       //////////////////
    ///
    ADOQueryBaseCmd.Connection.CommitTrans;
    /// ///////////////       出入库及库存       //////////////////
    with ADOQueryBaseCmd do
    begin
      Close;
      SQL.Clear;
      SQL.Add('exec P_Trade_Insp_In_Stk @CIID=''' + trim(MCIID) + '''');
      ExecSQL;
    end;
    // Open;
    // end;
    // if ADOCmd.FieldByName('intReturn').AsInteger = -1 then
    // begin
    // application.MessageBox(PChar(trim(ADOCmd.FieldByName('ShowMsg').AsString)), '提示信息', 0);
    // Result := False;
    // end
    // else
    // begin
    // Result := True;
    // end;
    /// ///////////////       出入库及库存       //////////////////

    Result := true;
  except
    ADOQueryBaseCmd.Connection.RollbackTrans;
    Application.MessageBox(pchar(Exception(ExceptObject).Message), '提示信息', 0);

  end;
end;

//
procedure TfrmMachRollMain.PrtData(MCIID: string; againPring: Boolean = false);
var
  fPrintFile, gCpCodeAuto: string;
  Txt, fImagePath, Txt2, fImagePath2: string;
  Moudle: Thandle;
  Makebar: TMakebar;
  Mixtext: TMixtext;
begin
  with ADOQueryPrint do
  begin
    Close;
    SQL.Clear;
    SQL.Add(' EXEC P_Trade_Print_Lab ');
    SQL.Add(' @CIID=''' + trim(MCIID) + '''');
    Open;
  end;
  if ADOQueryPrint.IsEmpty then
  begin
    Application.MessageBox('标签内容未找到！', '提示信息', MB_ICONERROR);
    exit;
  end;

  if trim(ADOQueryPrint.fieldbyName('SLabVolume').AsString) <> '' then
    fLabVolume := trim(ADOQueryPrint.fieldbyName('SLabVolume').AsString)
  else
    fLabVolume := trim(ADOQueryPrint.fieldbyName('LabVolume').AsString);
  gCpCodeAuto := getConfigValue('djdMachineInsp.dll', 'LabVolume_Default', ADOQueryBaseTemp, true);
  if fLabVolume = '' then
    fLabVolume := trim(gCpCodeAuto);
//    trim(gDefaultLableFile);

  if fLabVolume = '' then
  begin
    Application.MessageBox('订单还未设置标签！', '提示信息', MB_ICONERROR);
    exit;
  end;

  ExportFtErpFile(fLabVolume + '.rmf', ADOQueryBaseTemp);
  fPrintFile := ExtractFilePath(Application.ExeName) + 'Report\' + fLabVolume + '.rmf';

  if FileExists(fPrintFile) then
  begin
    RM1.LoadFromFile(fPrintFile);
   // if trim(ADOQueryPrint.fieldbyName('LabVolume').AsString) <> '次品标签' then
    RM1.DefaultCopies := cds_params.fieldbyName('labNumber').AsInteger;
   // else
   //   RM1.DefaultCopies := 1;
    RM1.PrintReport;

    //
    if againPring then
    begin
      with ADOQueryBaseCmd do
      begin
        Close;
        SQL.Clear;
        SQL.Add('insert into Trade_Need_Up(UType,UOperation,UDataId,uoperator) values(''检验'',''重打卷标签'',' + QuotedStr(trim(cds_3.fieldbyName('CIID').AsString)) + ',' + QuotedStr(DName) + ')  ');
        ExecSQL;
      end;
    end;

  end
  else
  begin
    Application.MessageBox(pchar('没有找' + fPrintFile), '提示', 0);
  end;
end;

procedure TfrmMachRollMain.PrtaixunData(MCIID: string; againPring: Boolean = false);
var
  xml: TXmlDocument;
  xmlNode: IxmlNode;
begin
  with ADOQueryPrint do
  begin
    Close;
    SQL.Clear;
    SQL.Add(' EXEC P_Trade_Print_Lab ');
    SQL.Add(' @CIID=''' + trim(MCIID) + '''');
    Open;
  end;
  xml := TXmlDocument.Create(nil);
  try
    xml.Active := True;
//    xml.Version := '1.0';
//    xml.Encoding := 'UTF-8';
    xml.DocumentElement := xml.CreateElement('Barcode', '');
/////////////////////////////XML模板/////////////////////////////////////////////
    xmlNode := xml.DocumentElement.AddChild('TemplateNumber');
    xmlNode.ChildNodes.Add(xml.CreateNode('214', ntText));   //模板编号

    xmlNode := xml.DocumentElement.AddChild('BarcodeTitle');
    xmlNode.ChildNodes.Add(xml.CreateNode(Trim(ADOQueryPrint.FieldByName('CustName').AsString), ntText)); //抬头

    xmlNode := xml.DocumentElement.AddChild('ProductName');
    xmlNode.ChildNodes.Add(xml.CreateNode(Trim(ADOQueryPrint.FieldByName('C_color').AsString), ntText));  //品名

    xmlNode := xml.DocumentElement.AddChild('ColorCode');
    xmlNode.ChildNodes.Add(xml.CreateNode(Trim(ADOQueryPrint.FieldByName('C_color').AsString), ntText));  //颜色

    xmlNode := xml.DocumentElement.AddChild('ColorNumber');
    xmlNode.ChildNodes.Add(xml.CreateNode(Trim(ADOQueryPrint.FieldByName('C_ColorNo').AsString), ntText));  //色号

    xmlNode := xml.DocumentElement.AddChild('BatchNO');
    xmlNode.ChildNodes.Add(xml.CreateNode(Trim(ADOQueryPrint.FieldByName('BatchNO').AsString), ntText));  //批号

    xmlNode := xml.DocumentElement.AddChild('Quantity');
    xmlNode.ChildNodes.Add(xml.CreateNode(Trim(ADOQueryPrint.FieldByName('Meter').AsString), ntText));  //数量

    xmlNode := xml.DocumentElement.AddChild('ProductUnit');
    xmlNode.ChildNodes.Add(xml.CreateNode('米', ntText));  //单位

    xmlNode := xml.DocumentElement.AddChild('VolumeNumber');
    xmlNode.ChildNodes.Add(xml.CreateNode(Trim(ADOQueryPrint.FieldByName('PieceNo').AsString), ntText));  //卷号

    xmlNode := xml.DocumentElement.AddChild('Breadth');
    xmlNode.ChildNodes.Add(xml.CreateNode(Trim(ADOQueryPrint.FieldByName('C_Width').AsString), ntText));  //幅宽

    xmlNode := xml.DocumentElement.AddChild('Grammage');
    xmlNode.ChildNodes.Add(xml.CreateNode(Trim(ADOQueryPrint.FieldByName('C_GramWeight').AsString), ntText));  //克重

    xmlNode := xml.DocumentElement.AddChild('Composition');
    xmlNode.ChildNodes.Add(xml.CreateNode('成分', ntText));  //成分

    xmlNode := xml.DocumentElement.AddChild('DateMark');
    xmlNode.ChildNodes.Add(xml.CreateNode(Trim(ADOQueryPrint.FieldByName('Filltime').AsString), ntText));  //时间

    xmlNode := xml.DocumentElement.AddChild('OrderNumber');
    xmlNode.ChildNodes.Add(xml.CreateNode(Trim(ADOQueryPrint.FieldByName('OrderNo').AsString), ntText));  //订单号

    xmlNode := xml.DocumentElement.AddChild('FirstRemark');
    xmlNode.ChildNodes.Add(xml.CreateNode('备注!', ntText));  //备注

    xmlNode := xml.DocumentElement.AddChild('Remark');
    xmlNode.ChildNodes.Add(xml.CreateNode('', ntText));  //行备注

    xml.SaveToFile('D:\aixun\' + inttostr(DateTimeToUnix(Now)) + '.xml');
//    showmessage('D:\aixun\' + inttostr(DateTimeToUnix(Now)) + '.xml');
  finally
    xmlNode := nil;
    xml.Free;
  end;
end;

//
procedure TfrmMachRollMain.PrintBao(PPacketId: string; againPring: Boolean = false);
var
  fPrintFile: string;
  Txt, fImagePath: string;
  Moudle: Thandle;
  Makebar: TMakebar;
  Mixtext: TMixtext;
begin
  with ADOQueryPrint do
  begin
    Close;
    SQL.Clear;
    SQL.Add('exec P_Trade_Insp_Prt_PackLab ' + QuotedStr(PPacketId));
    Open;
  end;

  if trim(ADOQueryPrint.fieldbyName('SLabPackage').AsString) <> '' then
    fLabPackage := trim(ADOQueryPrint.fieldbyName('SLabPackage').AsString)
  else
    fLabPackage := ADOQueryPrint.fieldbyName('LabPackage').AsString;

  if fLabPackage = '' then
    fLabPackage := trim(gDefaultPackLableFile);

  ExportFtErpFile(trim(fLabPackage) + '.rmf', ADOQueryBaseTemp);
  fPrintFile := ExtractFilePath(Application.ExeName) + 'Report\' + trim(fLabPackage) + '.rmf';
  if not FileExists(fPrintFile) then
  begin
    Application.MessageBox(pchar('没有找包标签' + fPrintFile), '提示', 0);
    exit;
  end;
  if FileExists(fPrintFile) then
  begin
    RM1.LoadFromFile(fPrintFile);
    RM1.DefaultCopies := cds_params.fieldbyName('packlabnumber').AsInteger;
    if cds_params.fieldByName('packPrintPreview').AsBoolean then
      RM1.ShowReport
    else
      RM1.PrintReport;
  end;

  if againPring then
  begin
    with ADOQueryBaseCmd do
    begin
      Close;
      SQL.Clear;
      SQL.Add('insert into Trade_Need_Up(UType,UOperation,UDataId,uoperator) values(''检验'',''重打包标签'',' + QuotedStr(trim(cds_3.fieldbyName('CIID').AsString)) + ',' + QuotedStr(DName) + ')  ');
      ExecSQL;
    end;
  end;

  if FileExists(fImagePath) then
    DeleteFile(fImagePath);

end;

procedure TfrmMachRollMain.InitJTM(MCIID: string);
begin
  with ADOQueryBaseTemp do
  begin
    Close;
    SQL.Clear;
    SQL.Add('select * from Trade_Cloth_IO where StkId=''' + trim(MCIID) + ''' and IOFlag=''入库''');
    Open;

    if not IsEmpty then
    begin
      Application.MessageBox('已产生入库数据不能操作!', '提示', 0);
      exit;
    end;
  end;
  //
  with ADOQueryBaseTemp do
  begin
    Close;
    SQL.Clear;
    SQL.Add('select * from Trade_Cloth_IO where StkId=''' + trim(MCIID) + ''' and IOFlag=''出库''');
    Open;
  end;
  if not ADOQueryBaseTemp.IsEmpty then
  begin
    Application.MessageBox('已产生出库数据不能操作!', '提示', 0);
    exit;
  end;
  with ADOQueryBaseTemp do
  begin
    Close;
    SQL.Clear;
    SQL.Add('select * from Trade_Cloth_Inspect where CIID=''' + trim(MCIID) + '''');
    Open;
  end;
  if not ADOQueryBaseTemp.IsEmpty then
  begin
    FOperationStatus := '卷条码';
    FCIID := MCIID;
    InitCDGrid(MCIID);
  end;

end;

//

procedure TfrmMachRollMain.BadSpeedButtonClick(Sender: TObject);
var
  i: Integer;
begin
  inherited;
  if CheckData('疵点') = false then
    exit;
  frameBads1.dxPanel1.Visible := true;
  FCIFName := trim(TSpeedButton(Sender).Hint);

  frameBads1.lblCIFName.Caption := trim(TSpeedButton(Sender).Hint);
  frameBads1.CIFNumber.text := '1';
  frameBads1.CIFNumber.SetFocus;

  frameBads1cxCheckBox_readLenPropertiesChange(frameBads1.IsSubtract);

  if gAutoCheckBadNum then
  begin
    frameBads1.cxCheck_len.Checked := true;
    if frameBads1.cxCheck_len.Checked and (trim(InputLen.Text) <> '') then
    begin
      frameBads1.CIFBeg.Text := trim(InputLen.Text);
      frameBads1.CIFEnd.SetFocus;
    end;
  end;

end;

procedure TfrmMachRollMain.On1301(var Message: Tmessage);
var
  i1, i2: Integer;
  unitname: string;
  fdata: double;
begin
  i1 := Message.WParam;
  i2 := Message.LParam;
  if (trim(cds_params.fieldbyName('mabiao').AsString) = '1') then
  begin
    //自动提交
    if gAutoPost and fCanAutoPost then
    begin
      if i1 = 0 then
      begin
        BTPrint.Click;
        exit;
      end;
    end;
    //米数转码数
    if gMbLenMiToMa then
    begin
      if ((lblLenUnit.CaptionOptions.Hint = 'Y') or (lblLenUnit.CaptionOptions.Hint = '码')) then    //  (i2 <> 0) and
      begin
        i1 := round(i1 / 0.9144);
      end;
    end;
    ////////////////////
//    InputLen.Text := format('%.2f', [i1 / 100000]);

    if trim(cds_params.fieldbyName('mbunit').AsString) = '1' then
    begin
      if i2 = 0 then
      begin
        SetUnit('M');
      end
      else
      begin
        SetUnit('Y');
      end;
    end;
    if trim(lblLenUnit.Caption) = 'M' then
    begin
      InputLen.Text := format('%.' + trim(cds_params.fieldbyName('YPlace').asstring) + 'f', [i1 / 100000]);
    end
    else
    begin
      InputLen.Text := format('%.' + trim(cds_params.fieldbyName('MPlace').asstring) + 'f', [i1 / 100000]);
    end;

  end;
end;

procedure TfrmMachRollMain.On1201(var Message: Tmessage);
var
  i1, i2: Integer;
  unitname: string;
  fdata: double;
begin
  i1 := Message.WParam;
  i2 := Message.LParam;

  if trim(cds_params.fieldbyName('chen').AsString) = '1' then
  begin
    InputWeight.Text := format('%.2f', [i1 / 100000]);
  end;

end;

procedure TfrmMachRollMain.PrtMD(MInNo: string);
var
  fPrintFile, FLBName: string;
begin
  with ADOQueryPrint do
  begin
    Close;
    SQL.Clear;
    SQL.Add(' EXEC P_Trade_Cloth_In_Prt11 ');
    SQL.Add(' @Filtration=''' + trim(MInNo) + '''');
    Open;
  end;

  FLBName := '机台检验入库单';

  ExportFtErpFile(FLBName + '.rmf', ADOQueryBaseTemp);
  fPrintFile := ExtractFilePath(Application.ExeName) + 'Report\' + FLBName + '.rmf';

  if FileExists(fPrintFile) then
  begin
    RM1.LoadFromFile(fPrintFile);
    RM1.DefaultCopies := cds_params.fieldbyName('labNumber').AsInteger;
    RM1.PrintReport;
  end
  else
  begin
    Application.MessageBox(pchar('没有找' + fPrintFile), '提示', 0);
  end;
end;

/// ////////////
procedure TfrmMachRollMain.initEditPiece();
begin
  if BTPrint.Caption = '提  交' then
  begin
    fOldCheng := trim(cds_params.fieldbyName('chen').AsString);
    fOldmabiao := trim(cds_params.fieldbyName('mabiao').AsString);
    BTPrint.Caption := '修改提交';
    with cds_3 do
    begin
      InputLen.Text := fieldbyName('InputLen').AsString;
      SetUnit(FLenUnit);
      fLastPieceNo := trim(PieceNo.Text);
      fLastTXM := trim(TXM.Text);
      PieceNo.Text := fieldbyName('PieceNo').AsString;
      TXM.Text := fieldbyName('TXM').AsString;
      InputWeight.Text := fieldbyName('InputWeight').AsString;
      Tare.Text := fieldbyName('Tare').AsString;
      grade.ItemIndex := grade.Properties.Items.IndexOf(trim(fieldbyName('grade').AsString));
      // Coefficient.Text:=fieldByName('Coefficient').AsString;
    end;

    edtPacketNo.Enabled := False;
  end
  else
  begin
    BTPrint.Caption := '提  交';
    InputLen.Text := '';
    InputWeight.Text := '';
    OutPutWeight.Text := '';
    edtPacketNo.Enabled := true;
    grade.ItemIndex := 0;
    cds_params.edit;
    cds_params.fieldbyName('chen').value := fOldCheng;
    cds_params.fieldbyName('mabiao').value := fOldmabiao;
    cds_params.Post;
  end;

end;

procedure TfrmMachRollMain.GetPacketNo();
var
  mMaxPacketNo: string;
begin
  try
    with ADOQueryBaseTemp do
    begin
      Close;
      SQL.Clear;
      SQL.Add('select max(cast(isnull(PacketNo,''0'') as int)  )+1  as MaxPacketNo from Trade_Cloth_Inspect ');
      SQL.Add('where  OrderNo=' + QuotedStr(trim(OrderNo.Text)));
      if FRulePackNo = '按颜色生成' then
      begin
        sql.Add(' and  c_color=' + quotedstr(Trim(FC_Color)) + ' and isnull(C_ColorNo,'''')=' + quotedstr(Trim(FC_ColorNo)));

      end;
      if FRulePackNo = '按缸号生成' then
      begin
        sql.Add(' and  c_color=' + quotedstr(Trim(FC_Color)) + ' and isnull(BatchNO,'''')=' + quotedstr(Trim(BatchNO.Text)) + ' and isnull(FtyPCId,'''')=' + quotedstr(Trim(FtyPCId.Text)) + ' and isnull(C_ColorNo,'''')=' + quotedstr(Trim(FC_ColorNo)));
      end;
      Open;
    end;
    mMaxPacketNo := trim(ADOQueryBaseTemp.fieldbyName('MaxPacketNo').AsString);
    if mMaxPacketNo = '' then
      mMaxPacketNo := '1';

    edtPacketNo.Text := mMaxPacketNo;
  except

  end;

end;

procedure TfrmMachRollMain.getPlanImage(MSubID: string);
begin
  with ADOQueryImage do
  begin
    close;
    sql.Clear;
    sql.Add('select top 1 * from TP_File A');
    sql.Add('where  WBID=' + quotedstr(MSubID));
    open;
  end;
end;

/////////////////////////////////////
function TfrmMachRollMain.deletePack(packId: string): boolean;
var
  ccids: string;
  packNo: integer;
begin
  try
    ccids := '';
    packNo := strtointdef(Trim(cds_3.FieldByName('packetNo').AsString), 0);
    ADOQueryBaseCmd.Connection.BeginTrans;
    cds_3.First;
    while not cds_3.eof do
    begin
      if Trim(cds_3.FieldByName('packetid').AsString) = packId then
      begin
        ccids := ccids + ',' + Trim(cds_3.FieldByName('CIID').AsString);
      end;
      with ADOQueryBaseCmd do
      begin
        Close;
        SQL.Clear;
        SQL.Add('insert into Trade_Need_Up(UType,UOperation,UDataId,uoperator) values(''检验'',''检验删除'',' + QuotedStr(Trim(cds_3.FieldByName('CIID').AsString)) + ',' + QuotedStr(DName) + ')  ');
        ExecSQL;
      end;
      cds_3.Next;
    end;

    with ADOQueryBaseCmd do
    begin
      Close;
      SQL.Clear;
      SQL.Add('exec P_Trade_Insp_Del ');
      SQL.Add('@CIIDS=' + QuotedStr(ccids));
      SQL.Add(',@DCode=' + QuotedStr(DCode));
      SQL.Add(',@DName=' + QuotedStr(DName));
      Open;
    end;
    if ADOQueryBaseCmd.fieldbyName('intReturn').AsInteger = -1 then
    begin
      raise Exception.create(pchar(trim(ADOQueryBaseCmd.fieldbyName('ShowMsg').AsString)));
    end;
    ADOQueryBaseCmd.Connection.CommitTrans;
    if inttostr(packNo + 1) = trim(edtPacketNo.Text) then
    begin
      edtPacketNo.Text := inttostr(packNo);
    end;

    InitJYGrid();
    Application.MessageBox('删除成功！', '提示信息');
  except
    ADOQueryBaseCmd.Connection.RollbackTrans;
    Application.MessageBox(pchar(Exception(ExceptObject).Message), '提示信息', 0);
  end;
end;

//////////////////////////////////////////////////////
///
function TfrmMachRollMain.checkPicecNo(): boolean;
var
  pieceNo: string;
begin
  result := false;
  if FRulePieceNo = '' then
  begin
    ADOQueryBaseCmd.Connection.RollbackTrans;
    showMessage('计划单中未设置卷号生成规则!');
    exit;
  end;
  try
      //////////////////卷号重复判断
    with ADOQueryBaseCmd do
    begin
      Close;
      sql.Clear;
      if FRulePieceNo = '按订单生成' then
      begin
        sql.Add('select Mainid,pieceNo from Trade_Cloth_Inspect X where X.mainID=' + quotedstr(Trim(FMainId)));
        sql.Add(' Group by Mainid,pieceNo having count(*)>1');
      end
      else if FRulePieceNo = '按缸号生成' then
      begin
        sql.Add('select mainId,C_color,batchNo,pieceNo from Trade_Cloth_Inspect X ');
        sql.Add('where X.mainID=''' + Trim(FMainId) + ''' and X.c_color=' + quotedstr(Trim(FC_Color)) + ' and X.C_name=' + quotedstr(Trim(FC_name)) + 'and isnull(X.BatchNO,'''')=' + quotedstr(Trim(BatchNO.Text)) + ' and isnull(X.FtyPCId,'''')=' + quotedstr(Trim(FtyPCId.Text)) + ' and isnull(X.C_ColorNo,'''')=' + quotedstr(Trim(FC_ColorNo)));
        sql.Add(' Group by mainId,C_color,C_name,BatchNO,pieceNo having count(*)>1');
      end
      else if FRulePieceNo = '按花型颜色缸号生成' then
      begin
        sql.Add('select mainId,C_Pattern,C_color,batchNo,pieceNo from Trade_Cloth_Inspect X ');
        sql.Add('where X.mainID=''' + Trim(FMainId) + ''' and X.c_color=' + quotedstr(Trim(FC_Color)) + ' and isnull(X.BatchNO,'''')=' + quotedstr(Trim(BatchNO.Text)) + ' and isnull(X.FtyPCId,'''')=' + quotedstr(Trim(FtyPCId.Text)) + ' and isnull(X.C_Pattern,'''')=' + quotedstr(Trim(FC_Pattern)));
        sql.Add(' Group by mainId,C_Pattern,C_color,BatchNO,pieceNo having count(*)>1');
      end
      else if FRulePieceNo = '按颜色生成' then
      begin
        sql.Add('select mainId,C_color,pieceNo from Trade_Cloth_Inspect X ');
        sql.Add('where X.mainID=''' + Trim(FMainId) + ''' and X.c_color=' + quotedstr(Trim(FC_Color)) + ' and isnull(X.C_ColorNo,'''')=' + quotedstr(Trim(FC_ColorNo)));
        sql.Add(' Group by mainId,C_color,pieceNo having count(*)>1');
      end
      else if FRulePieceNo = '按花型号生成' then
      begin
        sql.Add('select X.mainId,X.C_StyleNo,X.C_Name,S.BuyConNo,X.C_color,X.C_colorNo,X.batchNo,X.c_pattern,X.pieceNo from Trade_Cloth_Inspect X left join Trade_Plan_Sub S on X.SubId=S.SubId ');
        sql.Add(' where isnull(X.mainID,'''')=''' + Trim(FMainId) + ''' and isnull(X.c_pattern,'''')=' + quotedstr(Trim(FC_pattern)));
        sql.Add(' and isnull(X.C_StyleNo,'''')=''' + Trim(FC_StyleNo) + ''' and isnull(S.BuyConNo,'''')=' + quotedstr(Trim(fBuyConNo)));
        sql.Add(' and isnull(X.C_color,'''')=''' + Trim(FC_color) + ''' and isnull(X.C_colorNo,'''')=' + quotedstr(Trim(FC_colorNo)));
        sql.Add(' and isnull(X.C_Name,'''')=''' + Trim(FC_Name) + ''' and isnull(X.batchNo,'''')=' + quotedstr(Trim(FbatchNo)));
        sql.Add(' Group by X.mainId,X.C_StyleNo,X.C_Name,S.BuyConNo,X.C_color,X.C_colorNo,X.batchNo,X.c_pattern,X.pieceNo having count(*)>1');
//          ShowMessage(sql.text);
      end
      else
      begin
        sql.Add('select mainId from Trade_Cloth_Inspect X ');
        sql.Add('where 1=2 ');
      end;
      Open;
    end;
    if not ADOQueryBaseCmd.IsEmpty then
    begin
      ADOQueryBaseCmd.Connection.RollbackTrans;
      pieceNo := Trim(ADOQueryBaseCmd.fieldbyname('pieceNo').AsString);
      if fileexists(ExtractFilePath(Application.ExeName) + '卷号重复.wav') then
        PlaySound('卷号重复.wav', 0, SND_FILENAME or SND_ASYNC);
      Application.MessageBox(Pchar('卷号: ' + Trim(pieceNo) + ' 重复，请核对处理数据!'), '提示', 0);
      Exit;
    end;
   //
    result := true;
  except
    ADOQueryBaseCmd.Connection.RollbackTrans;
    Application.MessageBox(Pchar('判断卷号是否有重复时发生错误!'), '提示', 0);
  end;

end;

/////////////////////////////////////////////////////////////////
///
function TfrmMachRollMain.getCurPieceNO(mCcid: string): string;
begin
  result := '';
  try
    with ADOQueryBaseTemp do
    begin
      close;
      sql.Clear;
      sql.Add('select PieceNo from Trade_Cloth_Inspect  where CIID=' + quotedstr(mCcid));
      open;
      if ADOQueryBaseTemp.fieldByName('PieceNo').AsInteger > 0 then
        result := intTostr(ADOQueryBaseTemp.fieldByName('PieceNo').AsInteger + 1);
    end;
  except
    application.MessageBox('获取当前卷号时发生错误!', '提示信息', 0);
  end;
end;

////////////////////////////////////////////////
procedure TfrmMachRollMain.threadLoadform();
var
  thread: TThread;
begin
  readLayOut(dxLayoutControl_pack, ADOQueryBaseTemp, PWideChar(fDllFileName + '|' + self.name + '|' + dxLayoutControl_pack.Name + '.ini'));
  readLayOut(frameBads1.dxLayoutControl1, ADOQueryBaseTemp, PWideChar(fDllFileName + '|' + self.name + '|' + frameBads1.dxLayoutControl1.Name + '.ini'));

  thread := TThread.CreateAnonymousThread(
    procedure
    begin
      TThread.Synchronize(nil,
        procedure
        begin
          ReadCxGrid(trim(Self.Caption) + 'Tv1', TV1, gDllFileCaption);
          ReadCxGrid(trim(Self.Caption) + 'Tv2', Tv2, gDllFileCaption);
          ReadCxGrid(trim(Self.Caption) + 'Tv3', Tv3, gDllFileCaption);
         //  readLayOut(dxLayoutControl_pack,ADOQueryBaseTemp,PWideChar( fDllFileName+'|'+self.name+'|'+dxLayoutControl_pack.Name+'.ini'));
          InitCDGrid(FCIID);
        end)
    end);

  thread.FreeOnTerminate := True;
  thread.Start;

end;

///////////////////////////////////////////////////////////////////////////
///
function TfrmMachRollMain.getCurMaxPieceNo(): integer;
var
  maxPieceNo: integer;
begin
  maxPieceNo := 1;
  try
    cds_3.DisableControls;
    with cds_3 do
    begin
      first;
      while not eof do
      begin
        if maxPieceNo >= fieldByName('PieceNo').AsInteger then
        begin
          next;
          continue;
        end
        else
        begin
          maxPieceNo := fieldByName('PieceNo').AsInteger;
        end;
        next;
      end;

    end;
  finally
    cds_3.EnableControls;
  end;
  result := maxPieceNo;
end;

end.

