unit U_MachRollMain;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
  System.Classes, Vcl.Graphics, mmsystem, 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, dxSkinsCore, dxSkinWXI, frxBarcode,
  frxOLE, frxRich, frxClass, frxDBSet, frxTableObject, frxExportPPTX,
  frxExportXLSX, frxExportBaseDialog, frxExportXLS, Vcl.Mask, cxSplitter,
  Vcl.DBCtrls, dxX509Certificate, dxPDFCore, dxPDFBase, dxPDFText,
  dxPDFRecognizedObject, dxPDFForm, dxPDFFormData, dxPDFDocument, dxPrintUtils,
  dxCustomPreview, dxPDFDocumentViewer, dxPDFViewer;

type
  TfrmMachRollMain = class(TfrmBaseList)
    dxLayoutControl_packGroup_Root: TdxLayoutGroup;
    dxLayoutControl_pack: TdxLayoutControl;
    Piece: TcxTextEdit;
    Qty: 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;
    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;
    查看: 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;
    ffRMDB_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;
    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;
    frxXLSExport1: TfrxXLSExport;
    frxXLSXExport1: TfrxXLSXExport;
    frxPPTXExport1: TfrxPPTXExport;
    frxReportTableObject1: TfrxReportTableObject;
    frxReport1: TfrxReport;
    RMDB_1: TfrxDBDataset;
    frxRichObject1: TfrxRichObject;
    frxOLEObject1: TfrxOLEObject;
    frxBarCodeObject1: TfrxBarCodeObject;
    BAN: TSpeedButton;
    dxLayoutItem20: TdxLayoutItem;
    ADOCmd: TADOQuery;
    ADOQuery1: TADOQuery;
    ADOTemp: TADOQuery;
    PlateNo: TcxTextEdit;
    dxLayoutItem12: TdxLayoutItem;
    Tv3Column1: TcxGridDBColumn;
    ToolButton1: TToolButton;
    ToolButton2: TToolButton;
    Tv3Column2: TcxGridDBColumn;
    dxLayoutItem19: TdxLayoutItem;
    FtyPCId: TcxTextEdit;
    Tv3Column3: TcxGridDBColumn;
    cxSplitter1: TcxSplitter;
    edtChen: TcxTextEdit;
    dxLayoutItem_chen: TdxLayoutItem;
    edtMaBiao: TcxTextEdit;
    dxLayoutItem4: TdxLayoutItem;
    outPage: TcxTextEdit;
    dxLayoutItem22: TdxLayoutItem;
    labNumber: TComboBox;
    dxLayoutItem23: TdxLayoutItem;
    dxLayoutAutoCreatedGroup7: TdxLayoutAutoCreatedGroup;
    dxLayoutAutoCreatedGroup9: TdxLayoutAutoCreatedGroup;
    dxLayoutAutoCreatedGroup8: TdxLayoutAutoCreatedGroup;
    dxLayoutAutoCreatedGroup10: TdxLayoutAutoCreatedGroup;
    C_StyleNo: TcxComboBox;
    dxLayoutItem_StyleNo: TdxLayoutItem;
    cxGroupBox_DJTYpe: TcxGroupBox;
    MovePanel2: TMovePanel;
    dxPDFViewer1: TdxPDFViewer;
    DJTYpe: TComboBox;
    Button1: TButton;
    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 FtyPCIdChange(Sender: TObject);
    procedure BANClick(Sender: TObject);
    procedure ToolButton2Click(Sender: TObject);
    procedure ToolButton1Click(Sender: TObject);
    procedure BatchNOExit(Sender: TObject);
    procedure edtChenClick(Sender: TObject);
    procedure edtMaBiaoClick(Sender: TObject);
    procedure outPageClick(Sender: TObject);
    procedure labNumberChange(Sender: TObject);
    procedure C_StyleNoChange(Sender: TObject);
    procedure C_StyleNoDropDown(Sender: TObject);
    procedure C_StyleNoPropertiesChange(Sender: TObject);
    procedure Button1Click(Sender: TObject);
  private
    FCIID, FOperationStatus, FCIFName, FWorkshop: string;
    FBCIOID, FOrderNo, FMainId, FSubId, FPCId, FConNo, FConMId, fBuyConNo, FConSId, FDJTYpe: 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_EComposition, FC_Pattern, FC_CustPattern, FC_ColorDepth: string;
    Faddwet, faddlen: double;
    FFtyPCId, FGangNo, FRulePieceNo, FRulePackNo, FCDUnit: string;
    FPieceNo: Integer;
    fIsPack: string;
    fIsCommopen: Boolean;
    FPacketCIID: string;
    fLabPackage, fLabVolume: string;
    FPacketCount: Integer;
    fAddwetVirtual: double;
    fAddLenVirtual: double;
    fTareType: string;
    funitPiecesStr: 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);
    function SaveData(): Boolean;
    procedure PrtData(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 GetRulePacketNo();
    procedure CheckRulePacketNo();
    procedure getPlanImage(MSubID: string);
    procedure loadstyleno();
    function deletePack(packId: string): boolean;
    function checkPicecNo(): boolean;
    function getCurPieceNO(mCcid: string): string;
    function InitDevComboboxG(ADOQueryTmp: TADOQuery; combobox: TcxCombobox; mFlag: string; selFlag: Boolean = true): Boolean;
    type

  public
    fmanage: string;
    fFlileFlag, FFsubid, FFactoryname, FSBuyConNo: string;
  end;

var
  frmMachRollMain: TfrmMachRollMain;
  newh, newh1: hwnd;

implementation

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

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 BS_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, MPlateId: string;
  mvalue: double;
  i: Integer;
begin

  try
    BTPrint.Enabled := false;

    edtScan.SetFocus;
    if trim(OrderNo.Text) = '' then
      exit;
    if trim(DJTYpe.Text) = '' then
    begin
      Application.MessageBox('打卷类型不能为空!', '提示', 0);
      exit;
    end;
    if trim(grade.Text) = '' then
    begin
      Application.MessageBox('等级不能为空!', '提示', 0);
      exit;
    end;

    with ADOCmd do
    begin
      Close;
      SQL.Clear;
      SQL.Add(' select * from BS_Cloth_IO A where STKName=''贸易待检布''  ');
      SQL.Add(' and A.FromSubId=''' + trim(Fsubid) + '''');
      Open;
    end;
//    if ADOCmd.IsEmpty then
//    begin
//      Application.MessageBox('该颜色未在待检布仓库，不可以检验该颜色！', '提示信息', MB_ICONERROR);
//      exit;
//    end;
    if ((trim(Coefficient.text) = '') and ((trim(lblRuleConversion.text) = '无需转换') or (trim(lblRuleConversion.text) = ''))) or (trim(C_Width.text) = '') or (trim(C_GramWeight.text) = '') then
    begin
      with ADOCmd do
      begin
        Close;
        SQL.Clear;
        SQL.Add(' select * from Trade_Cloth_Inspect A where A.mainid=''' + trim(Fmainid) + '''   ');
        SQL.Add(' and A.C_Name=''' + trim(CodeName.text) + '''');
        Open;
      end;
      if ADOCmd.IsEmpty then
      begin
        Application.MessageBox('该卷为第一卷,不允许克重门幅系数为空！', '提示信息', MB_ICONERROR);
        exit;
      end;
    end;
//    if (trim(Coefficient.text) <> '') and ((trim(lblRuleConversion.text) = '无需转换') or (trim(lblRuleConversion.text) = '')) then
//    begin
//      Application.MessageBox('系数不是空的时候,不能为无需转换！', '提示信息', MB_ICONERROR);
//      exit;
//    end;
    if (trim(Coefficient.text) = '') and ((trim(lblRuleConversion.text) <> '无需转换') or (trim(lblRuleConversion.text) = '')) then
    begin
      Application.MessageBox('系数不能为空！', '提示信息', MB_ICONERROR);
      exit;
    end;
    if CheckData('提交') = false then
      exit;

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

    if SaveData() then
    begin
      InputLen.Text := '';
      presentLen.Text := '';
      funitPiecesStr := '';
      presentWeight.Text := '';
      if BTPrint.Caption = '修改提交' then
      begin
        BTPrint.Caption := '提  交';
        cds_params.edit;
        cds_params.fieldbyName('chen').value := '1';
        cds_params.fieldbyName('mabiao').value := '1';
        cds_params.Post;
        edtPacketNo.Enabled := 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('outPage').AsString) = '√' then
      begin
        PrtData(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;

          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 Bs_Cloth_IO 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 Bs_Cloth_IO.STKID=X.RTValue )  ');
              ExecSQL;
            end;
            if (cds_params.fieldbyName('packlabnumber').AsInteger > 0) then
              PrintBao(MPacketId);
//            edtPacketNo.Text := inttostr(strtoint(edtPacketNo.Text) + 1);
            GetRulePacketNo();
            FPacketCIID := '';
            FPacketCount := 0;
            ADOQueryBaseCmd.Connection.CommitTrans;
          except
            ADOQueryBaseCmd.Connection.RollbackTrans;
            Application.MessageBox('打包失败！', '提示信息', 0);
          end;

        end;

      end;

    end;
    InputLen.SetFocus;
    setFocusCtrol(InputLen.Name);
    FOperationStatus := '缸条码';
    InitJYGrid();
    InitCDGrid('');
    FCIID := '';
  finally
    BTPrint.Enabled := true;
  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;
  try
    frmLabelPrint := TfrmLabelPrint.Create(Application);
    with frmLabelPrint do
    begin
      FLMType := '入库码单';
      FFiltration1 := WSql;
      if ShowModal = 1 then
      begin
//        Self.InitGrid();
      end;
    end;
  finally
    frmLabelPrint.Free;
  end;
end;

procedure TfrmMachRollMain.Button1Click(Sender: TObject);
begin
  if trim(DJTYpe.text) <> '' then
  begin
    cxGroupBox_DJTYpe.Visible := false;
    FDJTYpe := trim(DJTYpe.text);
  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.BANClick(Sender: TObject);
var
  fPrintFile: string;
  Txt, fImagePath, Txt2, fImagePath2: string;
  Moudle: Thandle;
  Makebar: TMakebar;
  Mixtext: TMixtext;
begin
  with ADOQueryPrint do
  begin
    Close;
    sql.Clear;
    sql.Add('exec P_Print_Ban ''' + trim(fmainId) + ''', ''' + Trim(PlateNo.Text) + ''' ');
    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);
//  if fLabVolume = '' then
//  begin
//    Application.MessageBox('订单还未设置标签！', '提示信息', MB_ICONERROR);
//    exit;
//  end;
  ExportFtErpFile('板标签.rmf', ADOQueryBaseTemp);
  fPrintFile := ExtractFilePath(Application.ExeName) + 'Report\板标签.rmf';

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

  PlateNo.Text := inttostr(strtoint(PlateNo.Text) + 1);

end;

procedure TfrmMachRollMain.BatchNOExit(Sender: TObject);
begin
  if BTPrint.Caption = '提  交' then
  begin
    with ADOQueryBaseCmd do
    begin
      Close;
      sql.Clear;
      if FRulePieceNo = '按订单生成' then
      begin
        sql.Add('select maxRoll=1+isnull(cast(max(PieceNo) as int),0) from Trade_Cloth_Inspect X where X.mainID=' + quotedstr(Trim(FMainId)));
      end
      else if FRulePieceNo = '按缸号生成' then
      begin
        sql.Add('select maxRoll=1+isnull(cast(max(PieceNo) as int),0)from Trade_Cloth_Inspect X ');
        sql.Add('where X.mainID=''' + Trim(FMainId) + ''' and X.subid=''' + Trim(FSubId) + ''' and X.c_color=' + quotedstr(Trim(FC_Color)) + ' and isnull(X.BatchNO,'''')=' + quotedstr(Trim(BatchNO.Text)));

      end
      else if FRulePieceNo = '按颜色生成' then
      begin
        sql.Add('select maxRoll=1+isnull(cast(max(PieceNo) as int),0) from Trade_Cloth_Inspect X ');
        sql.Add('where X.mainID=''' + Trim(FMainId) + ''' and  X.subid=''' + Trim(FSubId) + ''' and X.c_color=' + quotedstr(Trim(FC_Color)));

      end
      else if (FRulePieceNo = '手动') or (FRulePieceNo = '手动生成') then
      begin

      end
      else
      begin
        sql.Add('select maxRoll=1+isnull(cast(max(PieceNo) as int),0) ');
        sql.Add('from Trade_Cloth_Inspect X where X.subID=''' + trim(FSubId) + ''' ');

      end;
      Open;
    end;

    PieceNo.Text := Trim(ADOQueryBaseCmd.fieldbyname('maxRoll').AsString);
  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', 'BS_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_BS_Cloth_In_Insp ');
      SQL.Add(' @CIIDS=' + 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
  inherited;
  fIsCommopen := false;
  cds_params.Close;
  cds_params.CreateDataSet;
  Panel_right.Align := alClient;
  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;

function TfrmMachRollMain.InitDevComboboxG(ADOQueryTmp: TADOQuery; combobox: TcxCombobox; mFlag: string; selFlag: Boolean = true): Boolean;
begin
  Result := false;
  try
    with ADOQueryTmp do
    begin
      close;
      sql.Clear;
      sql.Add('select a.itemText from SY_Dict_Item a');
      sql.Add(' inner join SY_Dict b on b.dictId=a.dictId');
      sql.Add(' where b.dictcode=' + QuotedStr(mFlag));
      sql.Add('and a.valid=1 and b.valid=1');
      sql.Add('order by A.sortorder');
      Open;

      if IsEmpty then
      begin
        application.MessageBox(PWideChar('未定义对应的字段字典数据(' + mFlag + ')'), '', 0);
        Exit;
      end;
      combobox.Properties.BeginUpdate;
      combobox.Properties.Items.Clear;
      first;
      while not eof do
      begin
        combobox.Properties.Items.Add(trim(FieldByName('itemText').AsString));
        next;
      end;
      if selFlag and (combobox.Properties.Items.Count > 0) then
      begin
        combobox.ItemIndex := 0;
      end;

      combobox.Properties.EndUpdate();
    end;

  except

    raise Exception.Create(PWideChar('获取字段字典数据(' + mFlag + ')时，发生错误!'));

  end;
end;

procedure TfrmMachRollMain.FormShow(Sender: TObject);
var
  i: Integer;
begin
//  inherited;
//  gIsCanDesign := IsHasDesignRight(ADOQueryBaseTemp, PWideChar(dCode));
  gGridNativeSet := true;
  if gIsCanDesign then
  begin
    cxGridPopupMenu1.Grid := cxGrid3;
  end;
  TgridLiSet.Visible := gIsCanDesign;
  InitDevComboboxG(ADOQueryBaseTemp, grade, 'CPGRADE');
  ReadCxGrid(trim(Self.Caption) + 'Tv1', TV1, gDllFileCaption);
  ReadCxGrid(trim(Self.Caption) + 'Tv2', Tv2, gDllFileCaption);
  ReadCxGrid(trim(Self.Caption) + 'Tv3', Tv3, gDllFileCaption);
 //  fDllFileName + '|' + Self.Name + '|' + dxLayoutControl_pack.Name+ '.ini'
  readLayOut(dxLayoutControl_pack, ADOQueryBaseTemp, PWideChar(fDllFileName + '|' + self.name + '|' + dxLayoutControl_pack.Name + '.ini'));
  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;
  InitCDGrid(FCIID);

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

  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;
  dxLayoutItem20.Visible := true;
  if not cds_params.IsEmpty then
  begin
    cds_params.Edit;
    with cds_params do
    begin
      cds_params.fieldByName('chen').Value := '1';
      cds_params.fieldByName('mabiao').Value := '1';
      cds_params.fieldByName('outPage').Value := '√';
      cds_params.fieldByName('labNumber').Value := StrToIntDef(labNumber.Text, 1);
    end;
    cds_params.Post;
  end;

end;

procedure TfrmMachRollMain.loadstyleno;
begin
  C_StyleNo.Properties.Items.Clear;
//  ShowMessage(fFsubid);

  with ADOQuery1 do
  begin
    Close;
    SQL.Clear;
    SQL.Add('SELECT c_styleno FROM trade_plan_sub_style WHERE subid = ''' + Trim(FFsubid) + '''');
//    ShowMessage(SQL.Text);
    Open;

    while not Eof do
    begin
      C_StyleNo.Properties.Items.Add(FieldByName('c_styleno').AsString);
      Next;
    end;
  end;
  if C_StyleNo.Text = '' then
  begin
    if C_StyleNo.Properties.Items.Count > 0 then
      C_StyleNo.ItemIndex := 0;
  end;
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
    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;
  TcxTextEdit(mComponent).Text := copy(fsj, 1, Length(fsj) - 1);
  TcxTextEdit(mComponent).SelectAll;

end;

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

procedure TfrmMachRollMain.FtyPCIdChange(Sender: TObject);
begin
//  BatchNO.Text := FtyPCId.Text;
end;

function TfrmMachRollMain.CheckData(CKType: string): Boolean;
var
  mvalue: double;
  mCurPieceNo: Integer;
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').AsInteger > cds_params.fieldbyName('endPieceNo').AsInteger) then
      begin
        if (mCurPieceNo > 0) and 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) and not ((mCurPieceNo >= cds_params.fieldbyName('BeginPieceNo').AsInteger) and (mCurPieceNo <= cds_params.fieldbyName('endPieceNo').AsInteger)) then
        begin
          Application.MessageBox('手动卷号不在设置的范围内!', '提示信息', 0);
          Exit;
        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) and (trim(cds_params.fieldbyName('packNoMake').AsString) = '自动') 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
        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('长度不能小于' + cds_params.fieldbyName('minLen').AsString + '米!');
        if strtofloatdef(trim(InputLen.Text), 0) > cds_params.fieldbyName('maxLen').AsInteger then
          raise Exception.create('长度不能大于' + 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_EComposition := '';
  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;
  FPacketCIID := '';
  FPacketCount := 0;

end;

procedure TfrmMachRollMain.QuantityConversion();
begin
  // if trim(OrderNo.Text)='' then exit;

  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) * strtofloatdef(trim(Coefficient.Text), 0) + strtofloatdef(trim(Tare.Text), 0));
      end;
      if lblRuleConversion.Text = '毛重转长度' then
      begin
        InputLen.Text := floattostr(strtofloatdef(trim(InputWeight.Text), 0) * strtofloatdef(trim(Coefficient.Text), 0));
      end;
      if lblRuleConversion.Text = '净重转长度' then
      begin
        InputLen.Text := floattostr((RoundFloat(strtofloatdef(trim(InputWeight.Text), 0), 1) - 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) * strtofloatdef(trim(Coefficient.Text), 0));
      end;
      if lblRuleConversion.Text = '毛重转长度' then
      begin
        InputLen.Text := floattostr((strtofloatdef(trim(InputWeight.Text), 0) + strtofloatdef(trim(Tare.Text), 0)) * strtofloatdef(trim(Coefficient.Text), 0));
      end;
      if lblRuleConversion.Text = '净重转长度' then
      begin
        InputLen.Text := floattostr(RoundFloat(strtofloatdef(trim(InputWeight.Text), 0), 1) * 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
  with ADOQueryBaseTemp do
  begin
    Close;
    SQL.Clear;
    SQL.Add('EXEC P_Trade_Insp_Get_plan @SubID=''' + trim(MSubID) + '''');
//    showmessage(sql.text);
    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);
      // FPCId := Trim(ADOTmp.fieldbyname('ToPCId').AsString);
      // FC_CustPattern := Trim(ADOTmp.fieldbyname('C_CustPattern').AsString);
      // FC_ColorDepth := Trim(ADOTmp.fieldbyname('C_ColorDepth').AsString);
      FSBuyConNo := Trim(fieldbyname('BuyConNo').AsString);
      FC_StyleNo := trim(fieldbyName('C_StyleNo').AsString);
      FC_EComposition := trim(fieldbyName('C_EComposition').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);
      customStrField1.Text := trim(fieldbyName('PO').AsString);
//      FFtyPCId := trim(fieldbyName('FtyPCId').AsString);
      FRulePieceNo := trim(fieldbyName('RulePieceNo').AsString);
      FRulePackNo := trim(fieldbyName('RulePackNo').AsString);
      //加重
      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 fieldbyName('DecimalY').AsInteger > 0 then
//        cds_params.fieldbyName('Yplace').value := fieldbyName('DecimalY').AsInteger;
//      if fieldbyName('DecimalM').AsInteger > 0 then
//        cds_params.fieldbyName('MPlace').value := fieldbyName('DecimalM').AsInteger;
//      if fieldbyName('DecimalKg').AsInteger > 0 then
//        cds_params.fieldbyName('kgPlace').value := fieldbyName('DecimalKg').AsInteger;
      if ADOQueryBaseTemp.fieldbyName('DecimalY').AsInteger >= 0 then
        cds_params.fieldbyName('Yplace').value := ADOQueryBaseTemp.fieldbyName('DecimalY').AsInteger;
      if ADOQueryBaseTemp.fieldbyName('DecimalM').AsInteger >= 0 then
        cds_params.fieldbyName('MPlace').value := ADOQueryBaseTemp.fieldbyName('DecimalM').AsInteger;
      if ADOQueryBaseTemp.fieldbyName('DecimalKg').AsInteger >= 0 then
        cds_params.fieldbyName('kgPlace').value := ADOQueryBaseTemp.fieldbyName('DecimalKg').AsInteger;

        //
      cds_params.fieldbyName('outPage').value := '√';
      cds_params.fieldbyName('dabao').value := '√';
      cds_params.fieldByName('packlabNumber').Value := '1';
      cds_params.Post;
      //
//      BatchNO.Text := trim(fieldbyName('batchNo').AsString);
//      Coefficient.Text := trim(fieldbyName('Coefficient').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;
      FtyPCId.Text := FFtyPCId;
      BCIOID.Text := FBCIOID;
//      C_StyleNo.Text := FC_StyleNo;

      Piece.Text := trim(fieldbyName('ordPiece').AsString);
      Qty.Text := trim(fieldbyName('ordQty').AsString) + trim(fieldbyName('ordUnit').AsString);
      //
      Tare.Text := trim(fieldbyName('RuleLaterTare').AsString);

      fTareType := '';

      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 StrToFloatDef(fieldbyName('FixedLength').AsString, 0) > 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;

  with ADOQueryBaseTemp do
  begin
    Close;
    SQL.Clear;
    SQL.Add('EXEC P_Trade_Insp_Get_WFKZ @SubID=''' + trim(FSubId) + '''');
//    showmessage(sql.text);
    Open;
    if not IsEmpty then
    begin
      FC_Width := trim(fieldbyName('C_Width').AsString);
      FC_GramWeight := trim(fieldbyName('C_GramWeight').AsString);
      C_width.Text := FC_Width;
      C_GramWeight.Text := FC_GramWeight;
      Coefficient.Text := trim(fieldbyName('Coefficient').AsString);
      lblRuleConversion.Text := trim(fieldbyName('lblRuleConversion').AsString);
    end
    else
    begin
      C_width.Text := '';
      C_GramWeight.Text := '';
      Coefficient.Text := '';
      lblRuleConversion.Text := '';
    end;

  end;
  with ADOQueryBaseCmd do
  begin
    Close;
    SQL.Clear;
    SQL.Add(' select DISTINCT FtyPCId from BS_Cloth_IO A  where A.IOFlag=''出库'' and A.IOType=''投产出库'' ');
    sql.Add(' and isnull(stkName,'''')=''贸易布匹''');
    sql.Add('and tosubid=(select ordsid from Trade_Plan_sub E WHERE E.SUBID=' + QuotedStr(TRIM(FSUBID)));
    SQL.Add(')');
    open;
  end;
//  FtyPCId.Clear;
//  while not ADOQueryBaseCmd.Eof do
//  begin
//    FtyPCId.Items.Add(ADOQueryBaseCmd.FieldByName('FtyPCId').AsString);
//    ADOQueryBaseCmd.Next;
//  end;
//  FtyPCId.ItemIndex := 0;
  InitJYGrid();

  InitCDGrid(FCIID);
  edtScan.Text := '';

  // 显示包
  setFormCtrol();

end;

procedure TfrmMachRollMain.InputLenKeyPress(Sender: TObject; var Key: Char);
begin
  if Key = #13 then
  begin
    Key := #0;
    SelectNext(ActiveControl as TWinControl, true, true);
  end;

end;

procedure TfrmMachRollMain.InputLenPropertiesChange(Sender: TObject);
begin

  // if StrToIntDef(trim(InputWeight.Text), 0) = 0 then
  // begin
  // exit;
  // end;
  QuantityConversion();
end;

procedure TfrmMachRollMain.labNumberChange(Sender: TObject);
begin
  inherited;
  if not cds_params.IsEmpty then
  begin
    cds_params.Edit;
    with cds_params do
    begin
      cds_params.fieldByName('labNumber').Value := StrToIntDef(labNumber.Text, 1);
    end;
    cds_params.Post;
  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);
var
  MPacketId, FCXPacketCIID: string;
begin
  if (trim(cds_params.fieldbyName('dabao').AsString) <> '√') then
    exit;
  try
    packPostBtn.Enabled := false;
    FCXPacketCIID := '';
    with CDS_3 do
    begin
      First;
      while not Eof do
      begin
        if CDS_3.FieldByName('ssel').AsBoolean = True then
        begin
          FCXPacketCIID := FCXPacketCIID + ',' + trim(cds_3.fieldbyName('CIID').AsString);
        end;
        Next;
      end;
      with ADOQueryBaseCmd do
      begin
        close;
        sql.clear;
        sql.add('select top 1  isnull(PacketNo,0) PacketNo   from  Trade_Cloth_Inspect     ');
        SQL.Add('where  EXISTS(select X.RTValue from [dbo].[F_Tool_SplitString](' + QuotedStr(FCXPacketCIID) + ','','') X where Trade_Cloth_Inspect.CIID=X.RTValue )  ');
        sql.add('  order by PacketNo desc');
//        showmessage(SQL.text);
        Open;
      end;
      if ADOQueryBaseCmd.fieldbyName('PacketNo').asfloat > 0 then
      begin
        Application.MessageBox('请先撤销打包之后，再重新打包！', '提示', 0);
        exit;
      end;
//      CheckRulePacketNo();
//          GetRulePacketNo();    判断最大包号

      try
        if FRulePackNo = '按缸号生成' then
        begin
          with ADOQueryBaseTemp do
          begin
            Close;
            SQL.Clear;
            SQL.Add('select  * from Trade_Cloth_Inspect X ');
            sql.Add('where X.mainID=''' + Trim(FMainId) + ''' and X.subid=''' + Trim(FSubId) + ''' and X.PacketNo=''' + Trim(edtPacketNo.text) + ''' and X.c_color=' + quotedstr(Trim(FC_Color)) + ' and isnull(X.BatchNO,'''')=' + quotedstr(Trim(BatchNO.Text)));

            Open;
          end;
        end
        else if FRulePackNo = '按订单生成' then
        begin
          with ADOQueryBaseTemp do
          begin
            Close;
            SQL.Clear;
            SQL.Add('select * from Trade_Cloth_Inspect X ');
            SQL.Add('where X.mainID=''' + Trim(FMainId) + ''' and X.PacketNo=''' + Trim(edtPacketNo.text) + ''' and   OrderNo=' + QuotedStr(trim(OrderNo.Text)));
            Open;
          end;
        end
        else if FRulePackNo = '按颜色生成' then
        begin
          with ADOQueryBaseTemp do
          begin
            Close;
            SQL.Clear;
            SQL.Add('select *  from Trade_Cloth_Inspect X ');
            sql.Add('where X.mainID=''' + Trim(FMainId) + ''' and  X.subid=''' + Trim(FSubId) + ''' and X.PacketNo=''' + Trim(edtPacketNo.text) + ''' and X.c_color=' + quotedstr(Trim(FC_Color)));
            Open;
          end;
        end
        else if FRulePackNo = '按客户款号生成' then
        begin
          with ADOQueryBaseTemp do
          begin
            Close;
            SQL.Clear;
            SQL.Add('select *  from Trade_Cloth_Inspect X ');
            sql.Add('where X.mainID=''' + Trim(FMainId) + '''   and X.PacketNo=''' + Trim(edtPacketNo.text) + ''' and X.C_StyleNo=' + quotedstr(Trim(FC_StyleNo)));
            Open;
          end;
        end
        else
        begin
          with ADOQueryBaseTemp do
          begin
            Close;
            SQL.Clear;
            SQL.Add('select * from Trade_Cloth_Inspect X ');
            SQL.Add('where X.mainID=''' + Trim(FMainId) + ''' and X.PacketNo=''' + Trim(edtPacketNo.text) + ''' and   OrderNo=' + QuotedStr(trim(OrderNo.Text)));
            Open;
          end;
        end;
        if not ADOQueryBaseTemp.IsEmpty then
        begin
          Application.MessageBox('该包号已经存在，请重新输入！', '提示', 0);
          exit;
        end;

      except

      end;

      if GetLSNo(ADOQueryBaseTemp, MPacketId, 'BI', 'Trade_Cloth_Inspect', 4, 1) = false then
      begin
        Application.MessageBox('取包条码最大号失败！', '提示', 0);
        exit;
      end;
    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(FCXPacketCIID) + ','','') 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(FCXPacketCIID) + ','','') X where Trade_Cloth_Stock.CIID=X.RTValue )  ');
//      showmessage(SQL.text);
        ExecSQL;
      end;
      if (cds_params.fieldbyName('packlabnumber').AsInteger > 0) then
        PrintBao(MPacketId);
//      edtPacketNo.Text := inttostr(strtoint(edtPacketNo.Text) + 1);
      GetRulePacketNo();
      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;

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

end;

procedure TfrmMachRollMain.ToolButton2Click(Sender: TObject);
var
  cxPacketCIID: string;
  PDetailPs: string;
begin
  if CDS_3.IsEmpty then
    Exit;
  if CDS_3.Locate('SSel', True, []) = False then
  begin
    Application.MessageBox('没有选择数据!', '提示', 0);
    Exit;
  end;
  if Application.MessageBox('确定要撤销打包吗？', '提示', 32 + 4) <> IDYES then
    Exit;
  with CDS_3 do
  begin
    First;
    while not Eof do
    begin
      if CDS_3.FieldByName('ssel').AsBoolean = True then
      begin
        with ADOCmd do
        begin
          Close;
          sql.Clear;
          SQL.Add('Update Trade_Cloth_Inspect Set PacketTime=null, PacketNo=null,PacketId=null,PacketCode=null,PacketName=null ');
          SQL.Add('WHERE  CIID=' + QuotedStr(trim(cds_3.fieldbyName('CIID').AsString)));
          SQL.Add('Update Trade_Cloth_Stock Set  PacketTime=null, PacketNo=null,PacketId=null,PacketCode=null,PacketName=null ');
          SQL.Add('WHERE  CIID=' + QuotedStr(trim(cds_3.fieldbyName('CIID').AsString)));
          PDetailPs := '卷条码' + cds_3.FieldByName('CIID').AsString + '包条码' + cds_3.FieldByName('PacketId').AsString + '包号' + cds_3.FieldByName('PacketNo').AsString;
          SQL.Add('insert into Trade_Need_Up(UType,UOperation,UDataId,uoperator) values(''检验'',''检验撤销打包'',' + QuotedStr(PDetailPs) + ',' + QuotedStr(DName) + ')  ');
//          showmessage(sql.text);
          execsql;
        end;

      end;
      Next;
    end;
  end;

  InitJYGrid();
end;

procedure TfrmMachRollMain.ToolButton3Click(Sender: TObject);
begin
  if cds_3.IsEmpty then
    exit;
  PrtData(cds_3.fieldbyName('CIID').AsString);

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 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;
    if Application.MessageBox('确定要删除选择的已经打包的卷数据吗？', '提示', 32 + 4) <> IDYES then
      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;

    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;
  if AViewInfo.GridRecord.Values[TcxGridDBTableView(Sender).GetColumnByFieldName('Bstatus').Index] > 0 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;
  if BTPrint.Caption = '提  交' then
  begin
    if Application.MessageBox('确定要修改选择的卷数据吗？', '提示', 32 + 4) <> IDYES then
      exit;
  end;
  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'));
  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
  else
  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();
    GetRulePacketNo();
  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;

    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;

  end
  else
  begin
    PieceNo.Properties.ReadOnly := true;
    // 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
    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;
  end;
end;

procedure TfrmMachRollMain.InitCDGridCX(MCIID: string);
begin
  cxPageControl1.ActivePageIndex := 1;
  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);
end;

procedure TfrmMachRollMain.InitJYGrid();
var
  MNetWeight, MJYLen: double;
begin
  try
    cds_3.DisableControls;
    with ADOQueryMain do
    begin
      Close;
      SQL.Clear;
      SQL.Add('select A.*,Bstatus=(case when isnull(PacketNo,0)>0 then 1 else 0 end)');
      SQL.Add('from Trade_Cloth_Inspect A where BCIOID=''' + trim(FBCIOID) + '''');
      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;
  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;
    with ADOQuery1 do
    begin
      Close;
      SQL.Clear;
      SQL.Add('select isnull(count(*),0) as js from Trade_Cloth_Inspect where  PacketNo=''' + trim(edtPacketNo.Text) + ''' and  mainid=''' + trim(Fmainid) + ''' ');
      open;
    end;
    if ADOQuery1.fieldbyName('JS').AsInteger = 1 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;
      GetRulePacketNo();
      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);
        GetRulePacketNo();
        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.cxButton2Click(Sender: TObject);
begin
  inherited;
  if FCIFName = '' then
  begin
    frameBads1.dxPanel1.Visible := false;
    exit;
  end;

  with CDS_2 do
  begin
    Append;
    // if RadioGroup1.ItemIndex = 5 then
    // FieldByName('CIFName').Value := '连续性' + Trim(FCIFName)
    // else if 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.C_StyleNoChange(Sender: TObject);
var
  FFactoryname: string;
begin

end;

procedure TfrmMachRollMain.C_StyleNoDropDown(Sender: TObject);
begin
  inherited;
//  C_StyleNoChange(Sender);
end;

procedure TfrmMachRollMain.C_StyleNoPropertiesChange(Sender: TObject);
begin
  with ADOQueryBaseTemp do
  begin
    Close;
    SQL.Clear;
    SQL.Add('select factoryname,BuyConNo from trade_plan_sub_style ' + 'where subid = ''' + FFSubId + ''' ' +       // 注意加引号
      'and c_styleno = ''' + Trim(C_StyleNo.Text) + '''');  // 同样加引号
    Open;

    if not ADOQueryBaseTemp.IsEmpty then
    begin
      FFactoryname := ADOQueryBaseTemp.FieldByName('factoryname').AsString;
      FSBuyConNo := ADOQueryBaseTemp.FieldByName('BuyConNo').AsString;
    end
    else
    begin

      FFactoryname := '';  // 没查到时置空
//      FSBuyConNo := '';
    end;
  end;

//   测试输出（可删）
//  ShowMessage('工厂名称: ' + FFactoryname);

end;

procedure TfrmMachRollMain.edtChenClick(Sender: TObject);
begin
  inherited;
  if trim(edtChen.Text) = '' then
  begin
    edtChen.Text := '√';
  end
  else
  begin
    edtChen.Text := '';
  end;
//  if not cds_params.IsEmpty then
//  begin
  cds_params.Edit;
  with cds_params do
  begin
    if Trim(edtChen.Text) = '√' then
      cds_params.fieldByName('chen').Value := '1'
    else
      cds_params.fieldByName('chen').Value := '0';

  end;
  cds_params.Post;
//  end;
end;

procedure TfrmMachRollMain.outPageClick(Sender: TObject);
begin
  inherited;
  if trim(outPage.Text) = '' then
  begin
    outPage.Text := '√';
  end
  else
  begin
    outPage.Text := '';
  end;
//  if not cds_params.IsEmpty then
//  begin
  cds_params.Edit;
  with cds_params do
  begin
    // 出纸
    cds_params.fieldByName('outPage').Value := outPage.Text;
  end;
  cds_params.Post;
//  end;
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;
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.edtMaBiaoClick(Sender: TObject);
begin
  inherited;
  if trim(edtMaBiao.Text) = '' then
  begin
    edtMaBiao.Text := '√';
  end
  else
  begin
    edtMaBiao.Text := '';
  end;
//  if not cds_params.IsEmpty then
//  begin

  with cds_params do
  begin
    cds_params.Edit;
    if Trim(edtMaBiao.Text) = '√' then
      cds_params.fieldByName('mabiao').Value := '1'
    else
      cds_params.fieldByName('mabiao').Value := '0';
    cds_params.Post;
  end;

//  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.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;
    FFsubid := edtScan.Text;

    ClearGlobal();
    FOperationStatus := '缸条码';
    // InitLCK(edtScan.Text);
    InitPlan(edtScan.Text);
    C_StyleNo.Text := FC_StyleNo;
    loadstyleno();
//    C_StyleNo.ItemIndex := 0;
    frameBads1cxCheckBox_readLenPropertiesChange(frameBads1.IsSubtract);
    // 是否读长度勾选
    if trim(OrderNo.Text) <> '' then
      InputLen.SetFocus;
    cxGroupBox_keys.Visible := false;
    DJTYpe.text := '';
    cxGroupBox_DJTYpe.Visible := True;
  end;
end;

//

function TfrmMachRollMain.SaveData(): Boolean;
var
  maxno, MCIID, BZID, strsql, maxPlateid: string;
  MInputLen, MMeter, MYardage: double;
  MInputWeight, MGrossWeight, MNetWeight, MTare, Maddwet, maddLen: double;
  mYardStick: double;
  mPresentLen, mpresentWeight: 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);
  if (strtoIntdef(Trim(unitPieces.Text), 0) > 0) and (strtoIntdef(trim(InputLen.Text), 0) > 0) then
  begin
    if strtoIntdef(trim(InputLen.Text), 0) > strtoIntdef(Trim(unitPieces.Text), 0) then
      funitPiecesStr := intTostr((strtoIntdef(trim(InputLen.Text), 0)) - strtoIntdef(Trim(unitPieces.Text), 0)) + '+' + Trim(unitPieces.Text);
  end;
  //0:不变；1：减去赠送
  if gPresentNumFlag = 1 then
  begin
    mPresentLen := -1 * mPresentLen;
    mpresentWeight := -1 * mpresentWeight;
  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); // 系数
      fieldbyname('Factoryname').Value := FFactoryname;
      fieldbyname('BuyConNo').Value := FSBuyConNo;
      fieldbyname('c_styleno').value := C_StyleNo.Text;
      /// //////////////////////           保存重量         /////////////////////////
      if cds_params.fieldbyName('weightRule').AsInteger = 0 then
      // InputWeight  毛重         OutPutWeight   净重
      begin
        MTare := strtofloatdef(trim(Tare.Text), 0); // 皮重
        MInputWeight := RoundFloat(strtofloatdef(trim(InputWeight.Text), 0), cds_params.fieldbyName('KgPlace').AsInteger); //输入为 毛重
        MGrossWeight := MInputWeight + Maddwet + mpresentWeight; // 毛重 + 加重
//        MNetWeight := MInputWeight + Maddwet - MTare; // 净重 + 加重
//           MGrossWeight := MInputWeight + Maddwet + mpresentWeight; // 毛重 + 加重
        MNetWeight := MInputWeight + Maddwet - MTare + mpresentWeight; // 净重 + 加重
        fieldbyName('InputWeight').value := MInputWeight;

        // 净重
        if MInputWeight > 0 then
        begin
          fieldbyName('NetWeight').value := MNetWeight;
          // 毛重
          fieldbyName('GrossWeight').value := MGrossWeight;
        end
        else
        begin
          fieldbyName('NetWeight').value := 0;
          fieldbyName('GrossWeight').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 := RoundFloat(strtofloatdef(trim(InputWeight.Text), 0), cds_params.fieldbyName('KgPlace').AsInteger); // 净重
        MGrossWeight := MInputWeight + MTare + Maddwet; // 毛重
        MNetWeight := MInputWeight + Maddwet; // 净重 +加重
//          MGrossWeight := MInputWeight + MTare + Maddwet + mpresentWeight; // 毛重
//        MNetWeight := MInputWeight + Maddwet + mpresentWeight; // 净重 +加重
        fieldbyName('InputWeight').value := MInputWeight;

        if MInputWeight > 0 then
        begin
          fieldbyName('NetWeight').value := MNetWeight;
          fieldbyName('GrossWeight').value := MGrossWeight;
        end
        else
        begin
          fieldbyName('NetWeight').value := 0;
          fieldbyName('GrossWeight').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) / (mYardStick / 100), cds_params.fieldbyName('MPlace').AsInteger);
        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) / (mYardStick / 100), cds_params.fieldbyName('YPlace').AsInteger);
        MMeter := RoundFloat(MYardage * 0.9144, cds_params.fieldbyName('MPlace').AsInteger);
      end;

      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('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);
      fieldbyName('CIIOFlag').value := '未入库';
//      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; // 原缸号

      if (StrToIntDef(Plateno.Text, 0) <> 0) and (FieldByName('grade').AsString <> '自留样') then
      begin
        FieldByName('Plateno').AsString := Trim(Plateno.Text);
      end;

      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;
      fieldbyName('C_EComposition').value := FC_EComposition;
      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('DJTYpe').value := trim(FDJTYpe);


      // 虚加重量

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

      fieldbyName('AddwetPresent').value := abs(mpresentWeight);
       // cds_params.fieldbyName('AddwetPresent').AsFloat;
      fieldbyName('AddLenPresent').value := abs(mPresentLen);
      //  cds_params.fieldbyName('AddLenPresent').AsFloat;
      //自定义输入1
      fieldbyName('customStrField1').value := trim(customStrField1.Text);
      fieldbyName('customStrField2').value := trim(customStrField2.Text);
      fieldbyName('lblRuleConversion').value := trim(lblRuleConversion.Text);
      //拼匹
      if FieldList.FieldByName('unitPieces') <> nil then
        fieldbyName('unitPieces').value := funitPiecesStr;
      //机台操作员
      if FieldList.FieldByName('operators') <> nil then
        fieldbyName('operators').value := gMachOperators;

      Post;
    end;
    if PlateNo.Text <> '' then
    begin
      with ADOTemp do
      begin
        Close;
        sql.Clear;
        sql.Add('select * from Trade_Cloth_Inspect where Mainid=''' + FMainId + ''' and isnull(PlateNo,'''')=''' + trim(PlateNo.Text) + '''  ');
        sql.Add(' and CIID<>''' + Trim(maxno) + ''' ');
        Open;
      end;

      if ADOTemp.IsEmpty then
      begin
        if GetLSNo(ADOQuery1, maxPlateid, 'Ban', 'Trade_Cloth_Inspect', 4, 1) = False then
        begin
          ADOCmd.Connection.RollbackTrans;
          Application.MessageBox('生成流水号异常！', '提示', 0);
          exit;
        end;

        with ADOCmd do
        begin
          Close;
          sql.clear;
          sql.add('update Trade_Cloth_Inspect set Plateid=''' + trim(maxPlateid) + ''' where CIID=''' + Trim(maxno) + ''' ');
          ExecSQL;
        end;
      end
      else
      begin
        with ADOCmd do
        begin
          Close;
          sql.clear;
          sql.add('update Trade_Cloth_Inspect set Plateid=''' + trim(ADOTemp.fieldbyname('Plateid').AsString) + ''' where CIID=''' + Trim(maxno) + ''' ');
          ExecSQL;
        end;
      end;
    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) + '''');
//      ShowMessage(sql.Text);
      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: 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) + '''');
//    ShowMessage(SQL.Text);
    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);
  if fLabVolume = '' then
  begin
    Application.MessageBox('订单还未设置标签！', '提示信息', MB_ICONERROR);
    exit;
  end;
  ExportFtErpFile(FLabVolume + '.rmf', ADOQueryBaseTemp);
  fPrintFile := ExtractFilePath(Application.ExeName) + 'Report\' + FLabVolume + '.rmf';
//  ExportFtErpFile(fLabVolume + '.fr3', ADOQueryBaseTemp);
//  fPrintFile := ExtractFilePath(Application.ExeName) + 'Report\' + fLabVolume + '.fr3';
//  if FileExists(fPrintFile) then
//  begin
//
//    frxReport1.LoadFromFile(fPrintFile);
//    frxReport1.PrintOptions.Copies := cds_params.fieldbyName('labNumber').AsInteger;
//    frxReport1.PrintOptions.ShowDialog := false;
//    frxReport1.PrepareReport(True);
//    frxReport1.Print();
//    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;
////    self.Close;
//  end
//  else
//  begin
//    Application.MessageBox(PChar('没有找到' + fPrintFile), '提示', 0);
//  end;


  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.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('LabPackage').AsString) <> '' then
    fLabPackage := trim(ADOQueryPrint.fieldbyName('LabPackage').AsString)
  else
    fLabPackage := ADOQueryPrint.fieldbyName('LabPackage').AsString;

  ExportFtErpFile(fLabPackage + '.rmf', ADOQueryBaseTemp);
  fPrintFile := ExtractFilePath(Application.ExeName) + 'Report\' + fLabPackage + '.rmf';
//  ExportFtErpFile(trim(fLabPackage) + '.fr3', ADOQueryBaseTemp);
//  fPrintFile := ExtractFilePath(Application.ExeName) + 'Report\' + trim(fLabPackage) + '.fr3';
  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 FileExists(fPrintFile) then
//  begin
//
//    frxReport1.LoadFromFile(fPrintFile);
//    frxReport1.PrintOptions.Copies := cds_params.fieldbyName('packlabnumber').AsInteger;
//    if cds_params.fieldByName('packPrintPreview').AsBoolean then
//    begin
//      frxReport1.PrintOptions.ShowDialog := true;
//      frxReport1.ShowReport;
//    end
//    else
//    begin
//      frxReport1.PrintOptions.ShowDialog := false;
//      frxReport1.PrepareReport(true);
//      frxReport1.Print();
//    end;

  end
  else
  begin
    Application.MessageBox(PChar('没有找到' + fPrintFile), '提示', 0);
  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 BS_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 BS_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.SetFocus;

  frameBads1.CIFNumber.text := '1';
//  frameBads1.CIFBeg.text := trim(Self.InputLen.text);
  frameBads1cxCheckBox_readLenPropertiesChange(frameBads1.IsSubtract);

  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;

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
//    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 (SCXFlag = '1') or (SCXFlag = '2') then
    begin
      if frameBads1.lblLenUnit1.Caption = 'M' then
      begin
        InputLen.Text := format('%.' + trim(FMPlace) + 'f', [i1 / 100000]);
      end
      else
        InputLen.Text := format('%.' + trim(FMPlace) + 'f', [i1 / 100000 / 0.9144]);
//      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
    else
    begin
      InputLen.Text := format('%.' + trim(FMPlace) + 'f', [i1 / 100000]);
//      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;
      if i2 = 0 then
      begin
        SetUnit('M');
      end
      else
      begin
        SetUnit('Y');
      end;
    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('%.' + trim(FKgPlace) + 'f', [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
    BTPrint.Caption := '修改提交';
    with cds_3 do
    begin
      InputLen.Text := fieldbyName('InputLen').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 := '1';
    cds_params.fieldbyName('mabiao').value := '1';
    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)));

      Open;
    end;
    mMaxPacketNo := trim(ADOQueryBaseTemp.fieldbyName('MaxPacketNo').AsString);
    if mMaxPacketNo = '' then
      mMaxPacketNo := '1';

    edtPacketNo.Text := mMaxPacketNo;
  except

  end;

end;

procedure TfrmMachRollMain.GetRulePacketNo();
var
  mMaxPacketNo: string;
begin
  try
    if FRulePackNo = '按缸号生成' then
    begin
      with ADOQueryBaseTemp do
      begin
        Close;
        SQL.Clear;
        SQL.Add('select max(cast(isnull(PacketNo,''0'') as int)  )+1  as MaxPacketNo from Trade_Cloth_Inspect X ');
        sql.Add('where X.mainID=''' + Trim(FMainId) + ''' and X.subid=''' + Trim(FSubId) + ''' and X.c_color=' + quotedstr(Trim(FC_Color)) + ' and isnull(X.BatchNO,'''')=' + quotedstr(Trim(BatchNO.Text)));

        Open;
      end;
    end
    else if FRulePackNo = '按订单生成' then
    begin
      with ADOQueryBaseTemp do
      begin
        Close;
        SQL.Clear;
        SQL.Add('select max(cast(isnull(PacketNo,''0'') as int)  )+1  as MaxPacketNo from Trade_Cloth_Inspect X ');
        SQL.Add('where X.mainID=''' + Trim(FMainId) + ''' and   OrderNo=' + QuotedStr(trim(OrderNo.Text)));
        Open;
      end;
    end
    else if FRulePackNo = '按客户款号生成' then
    begin
      with ADOQueryBaseTemp do
      begin
        Close;
        SQL.Clear;
        SQL.Add('select max(cast(isnull(PacketNo,''0'') as int)  )+1  as MaxPacketNo from Trade_Cloth_Inspect X ');
        sql.Add('where X.mainID=''' + Trim(FMainId) + '''  and X.C_StyleNo=' + quotedstr(Trim(FC_StyleNo)));
        Open;
      end;
    end
    else if FRulePackNo = '按颜色生成' then
    begin
      with ADOQueryBaseTemp do
      begin
        Close;
        SQL.Clear;
        SQL.Add('select max(cast(isnull(PacketNo,''0'') as int)  )+1  as MaxPacketNo from Trade_Cloth_Inspect X ');
        sql.Add('where X.mainID=''' + Trim(FMainId) + ''' and  X.subid=''' + Trim(FSubId) + ''' and X.c_color=' + quotedstr(Trim(FC_Color)));
        Open;
      end;
    end
    else
    begin
      with ADOQueryBaseTemp do
      begin
        Close;
        SQL.Clear;
        SQL.Add('select max(cast(isnull(PacketNo,''0'') as int)  )+1  as MaxPacketNo from Trade_Cloth_Inspect X ');
        SQL.Add('where X.mainID=''' + Trim(FMainId) + ''' and   OrderNo=' + QuotedStr(trim(OrderNo.Text)));
        Open;
      end;
    end;

    mMaxPacketNo := trim(ADOQueryBaseTemp.fieldbyName('MaxPacketNo').AsString);
    if mMaxPacketNo = '' then
      mMaxPacketNo := '1';

    edtPacketNo.Text := mMaxPacketNo;
  except

  end;

end;

procedure TfrmMachRollMain.CheckRulePacketNo();
var
  mMaxPacketNo: string;
begin
  try
    if FRulePackNo = '按缸号生成' then
    begin
      with ADOQueryBaseTemp do
      begin
        Close;
        SQL.Clear;
        SQL.Add('select  * from Trade_Cloth_Inspect X ');
        sql.Add('where X.mainID=''' + Trim(FMainId) + ''' and X.subid=''' + Trim(FSubId) + ''' and X.c_color=' + quotedstr(Trim(FC_Color)) + ' and isnull(X.BatchNO,'''')=' + quotedstr(Trim(BatchNO.Text)));

        Open;
      end;
    end
    else if FRulePackNo = '按订单生成' then
    begin
      with ADOQueryBaseTemp do
      begin
        Close;
        SQL.Clear;
        SQL.Add('select * from Trade_Cloth_Inspect X ');
        SQL.Add('where X.mainID=''' + Trim(FMainId) + ''' and   OrderNo=' + QuotedStr(trim(OrderNo.Text)));
        Open;
      end;
    end
    else if FRulePackNo = '按客户款号生成' then
    begin
      with ADOQueryBaseTemp do
      begin
        Close;
        SQL.Clear;
        SQL.Add('select *  from Trade_Cloth_Inspect X ');
        sql.Add('where X.mainID=''' + Trim(FMainId) + ''' and  X.subid=''' + Trim(FSubId) + ''' and X.C_StyleNo=' + quotedstr(Trim(FC_StyleNo)));
        Open;
      end;
    end
    else if FRulePackNo = '按颜色生成' then
    begin
      with ADOQueryBaseTemp do
      begin
        Close;
        SQL.Clear;
        SQL.Add('select *  from Trade_Cloth_Inspect X ');
        sql.Add('where X.mainID=''' + Trim(FMainId) + ''' and  X.subid=''' + Trim(FSubId) + ''' and X.c_color=' + quotedstr(Trim(FC_Color)));
        Open;
      end;
    end
    else
    begin
      with ADOQueryBaseTemp do
      begin
        Close;
        SQL.Clear;
        SQL.Add('select * from Trade_Cloth_Inspect X ');
        SQL.Add('where X.mainID=''' + Trim(FMainId) + ''' and   OrderNo=' + QuotedStr(trim(OrderNo.Text)));
        Open;
      end;
    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.subid=''' + Trim(FSubId) + ''' and X.c_color=' + quotedstr(Trim(FC_Color)) + ' and isnull(X.BatchNO,'''')=' + quotedstr(Trim(BatchNO.Text)));
        sql.Add(' Group by mainId,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.subid=''' + Trim(FSubId) + ''' and X.c_color=' + quotedstr(Trim(FC_Color)));
        sql.Add(' Group by mainId,C_color,pieceNo having count(*)>1');
      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;

end.

