unit U_DyePlanCardInput;

interface

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

type
  TfrmDyePlanCardInput = class(TfrmBaseInput)
    CDS_1: TClientDataSet;
    DS_1: TDataSource;
    ADO_Car: TADOQuery;
    ADOQueryCmd: TADOQuery;
    ADOQueryTmp: TADOQuery;
    GPM_1: TcxGridPopupMenu;
    Panel3: TPanel;
    Panel5: TPanel;
    Panel4: TPanel;
    cxGrid1: TcxGrid;
    TV1: TcxGridDBTableView;
    V1SSel: TcxGridDBColumn;
    V1Column1: TcxGridDBColumn;
    V1Column5: TcxGridDBColumn;
    TV1Column1: TcxGridDBColumn;
    TV1Column5: TcxGridDBColumn;
    TV1Column6: TcxGridDBColumn;
    TV1Column7: TcxGridDBColumn;
    V1Column2: TcxGridDBColumn;
    V1Column3: TcxGridDBColumn;
    TV1Column4: TcxGridDBColumn;
    TV1Column3: TcxGridDBColumn;
    V1Column6: TcxGridDBColumn;
    V1Column4: TcxGridDBColumn;
    TV1Column2: TcxGridDBColumn;
    cxGrid1Level1: TcxGridLevel;
    ToolBar1: TToolBar;
    ToolButton4: TToolButton;
    ADOQueryMain: TADOQuery;
    DS_2: TDataSource;
    CDS_2: TClientDataSet;
    PM_2: TPopupMenu;
    N1: TMenuItem;
    N2: TMenuItem;
    PM_1: TPopupMenu;
    MenuItem1: TMenuItem;
    MenuItem2: TMenuItem;
    GPM_2: TcxGridPopupMenu;
    TV1Column10: TcxGridDBColumn;
    ToolButton5: TToolButton;
    ToolButton1: TToolButton;
    ToolButton2: TToolButton;
    ToolButton3: TToolButton;
    cxPageControl1: TcxPageControl;
    cxTabSheet3: TcxTabSheet;
    cxTabSheet4: TcxTabSheet;
    Panel6: TPanel;
    Label20: TLabel;
    GPM_3: TcxGridPopupMenu;
    CDS_3: TClientDataSet;
    DS_3: TDataSource;
    TbAbnormalKaiKa: TButton;
    TV1Column12: TcxGridDBColumn;
    TV1Column13: TcxGridDBColumn;
    TV1Column14: TcxGridDBColumn;
    TV1Column15: TcxGridDBColumn;
    TV1Column16: TcxGridDBColumn;
    TV1Column17: TcxGridDBColumn;
    Label13: TLabel;
    Label14: TLabel;
    Label18: TLabel;
    Label19: TLabel;
    PCPiece1: TEdit;
    PCQty1: TEdit;
    PCPiece2: TEdit;
    PCQty2: TEdit;
    TV1Column18: TcxGridDBColumn;
    TV1Column19: TcxGridDBColumn;
    ADO_Order: TADOQuery;
    CDS_Color: TClientDataSet;
    pnlkpkk: TPanel;
    Label1: TLabel;
    Label7: TLabel;
    Label15: TLabel;
    Label16: TLabel;
    Label17: TLabel;
    PCTime: TDateTimePicker;
    carnum: TcxCurrencyEdit;
    PCPiece: TcxCurrencyEdit;
    PCType: TComboBox;
    PCQty: TEdit;
    Button2: TButton;
    pnlOrder: TPanel;
    cxGrid2: TcxGrid;
    TV2: TcxGridDBTableView;
    cxGridDBColumn5: TcxGridDBColumn;
    v2Column6: TcxGridDBColumn;
    cxGridDBColumn6: TcxGridDBColumn;
    Tv1OrderNo: TcxGridDBColumn;
    v2Column1: TcxGridDBColumn;
    cxGridDBColumn2: TcxGridDBColumn;
    cxGridDBColumn1: TcxGridDBColumn;
    v1Column8: TcxGridDBColumn;
    cxGridDBColumn3: TcxGridDBColumn;
    cxGridDBColumn4: TcxGridDBColumn;
    cxGrid2Level1: TcxGridLevel;
    Label23: TLabel;
    OrderNo: TBtnEditA;
    Label4: TLabel;
    Label9: TLabel;
    Label11: TLabel;
    Label10: TLabel;
    C_Width: TEdit;
    C_GramWeight: TEdit;
    C_COLORNO: TEdit;
    Label24: TLabel;
    OrdQty: TEdit;
    OrdUnit: TEdit;
    TV1Column20: TcxGridDBColumn;
    TV1Column21: TcxGridDBColumn;
    Label2: TLabel;
    OrdPiece: TEdit;
    Label3: TLabel;
    DTMPSlist: TBtnEditA;
    Label5: TLabel;
    C_Name: TEdit;
    ADO_PB: TADOQuery;
    TV2Column1: TcxGridDBColumn;
    Label6: TLabel;
    DTMID: TEdit;
    avgCard: TButton;
    Label8: TLabel;
    CINote: TEdit;
    TV1KaZu: TcxGridDBColumn;
    TV2C_description: TcxGridDBColumn;
    C_description: TEdit;
    Label12: TLabel;
    TV1C_description: TcxGridDBColumn;
    TV1CINote: TcxGridDBColumn;
    C_COLOR: TEdit;
    AbnormalKaZu: TBtnEditA;
    cxGrid3: TcxGrid;
    Tv3: TcxGridDBTableView;
    cxGridDBColumn7: TcxGridDBColumn;
    cxGridDBColumn8: TcxGridDBColumn;
    cxGridDBColumn9: TcxGridDBColumn;
    cxGridDBColumn10: TcxGridDBColumn;
    cxGridDBColumn11: TcxGridDBColumn;
    cxGridDBColumn12: TcxGridDBColumn;
    cxGridDBColumn13: TcxGridDBColumn;
    cxGridDBColumn14: TcxGridDBColumn;
    cxGridDBColumn15: TcxGridDBColumn;
    cxGridDBColumn16: TcxGridDBColumn;
    cxGridDBColumn17: TcxGridDBColumn;
    cxGridDBColumn18: TcxGridDBColumn;
    cxGridLevel1: TcxGridLevel;
    Label21: TLabel;
    carNum1: TEdit;
    Label22: TLabel;
    carNum2: TEdit;
    Label25: TLabel;
    Label26: TLabel;
    Label27: TLabel;
    Label28: TLabel;
    KaZuQty: TEdit;
    KaZuPiece: TEdit;
    PM_3: TPopupMenu;
    N3: TMenuItem;
    N4: TMenuItem;
    q1: TMenuItem;
    N5: TMenuItem;
    N6: TMenuItem;
    Label29: TLabel;
    OrderNo1: TEdit;
    Tv3C_GramWeight: TcxGridDBColumn;
    Tv3C_COLOR: TcxGridDBColumn;
    Tv3C_COLORNO: TcxGridDBColumn;
    Label30: TLabel;
    PCType1: TComboBox;
    Label31: TLabel;
    DTMPSlist1: TBtnEditA;
    Tv3CustName: TcxGridDBColumn;
    Tv3CINote: TcxGridDBColumn;
    DTMID1: TEdit;
    Label32: TLabel;
    Tv3note: TcxGridDBColumn;
    TV2note: TcxGridDBColumn;
    TbKaiKa: TButton;
    DTMPSlist2: TBtnEditA;
    Label33: TLabel;
    Label34: TLabel;
    DTMID2: TEdit;
    Label35: TLabel;
    F_Name: TEdit;
    Label36: TLabel;
    F_Name1: TEdit;
    procedure FormDestroy(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure FormCreate(Sender: TObject);
    procedure FormShow(Sender: TObject);
    procedure ToolButton4Click(Sender: TObject);
    procedure N1Click(Sender: TObject);
    procedure N2Click(Sender: TObject);
    procedure MenuItem1Click(Sender: TObject);
    procedure MenuItem2Click(Sender: TObject);
    procedure ToolButton5Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure ToolButton1Click(Sender: TObject);
    procedure ToolButton3Click(Sender: TObject);
    procedure ToolButton2Click(Sender: TObject);
//    procedure PCIDKeyPress(Sender: TObject; var Key: Char);
    procedure TbAbnormalKaiKaClick(Sender: TObject);
    procedure TV3DblClick(Sender: TObject);
    procedure OrderNoBtnClick(Sender: TObject);
    procedure C_COLORChange(Sender: TObject);
//    procedure TV3Column1PropertiesEditValueChanged(Sender: TObject);
    procedure DTMPSlistBtnClick(Sender: TObject);
    procedure TV2DblClick(Sender: TObject);
    procedure OrderNoKeyPress(Sender: TObject; var Key: Char);
    procedure avgCardClick(Sender: TObject);
    procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
    procedure AbnormalKaZuBtnClick(Sender: TObject);
    procedure N3Click(Sender: TObject);
    procedure N4Click(Sender: TObject);
    procedure N6Click(Sender: TObject);
    procedure q1Click(Sender: TObject);
    procedure N5Click(Sender: TObject);
    procedure DTMPSlist1BtnClick(Sender: TObject);
    procedure PCPiece1Change(Sender: TObject);
    procedure PCQty1Change(Sender: TObject);
    procedure TbKaiKaClick(Sender: TObject);
    procedure PCTypeChange(Sender: TObject);
    procedure PCType1Change(Sender: TObject);
  private
    FC_Code: string;
    FDTMID1, FDTMPSlist1: string;
    FRollNum: integer;
    FGC_BatchNo, FGC_Piece, FGC_STKID, FGC_Position: string;
    FFromCoNo, FFromCoName, FSaleser, FC_Name, fbzunit: string;
    procedure InitCard();
    procedure InitOrder();
    procedure InitGreyClothStk();
    procedure InitGreyClothStk1();
//    procedure InitRepairCard(PPCID: string);
    { Private declarations }
    procedure ShowDistributionResult(cardCount: Integer; pieceArray, qtyArray: array of Double);
    procedure CalculateDistribution(totalValue: Double; cardCount: Integer; var resultArray: array of Double);
  public
    FWorkshop, FPCIDS, FMainID: string;



    { Public declarations }
  end;

var
  frmDyePlanCardInput: TfrmDyePlanCardInput;

implementation

uses
  U_DataLink, U_ZDYHelp, U_RTFun, U_DyePlanForCardSel, U_DyeProcessSel,
  U_DyeTechnicsSel, U_DyePlanCardSel, U_DyeGreyClothStkSel, U_DyeCardGlideEdit,
  U_CraftSel, U_Dye_AbnormalCardSel;
{$R *.dfm}

procedure TfrmDyePlanCardInput.InitOrder();
var
  fsj: string;
begin
  with Ado_Order do
  begin
    close;
    sql.Clear;
    sql.Add('select A.*');
    sql.Add('from Dye_Plan_Main A ');
//    sql.Add('inner join Dye_Plan_Sub B on A.MainID=B.mainID ');

    sql.Add('where A.MainID=''' + trim(FMainID) + ''' ');
//    ShowMessage(sql.Text);
    open;
  end;
  SCreateCDS(Ado_Order, CDS_Color);
  SInitCDSData(Ado_Order, CDS_Color);

  if not Ado_Order.IsEmpty then
  begin
//    fsj := 'select distinct(C_Color) name from Dye_Plan_sub  where mainid= ' + QuotedStr(Trim(FMainID));
//    SInitComBoxBySql(ADOQueryTmp, C_COLOR, False, fsj);
//    SCSHData(Ado_Order, pnlOrder, 2);
    OrderNo.Text := Trim(Ado_Order.FieldByName('OrderNo').AsString);
    FC_Name := Trim(Ado_Order.FieldByName('C_Name').AsString);
    FFromCoNo := Trim(Ado_Order.FieldByName('CustNo').AsString);
    FFromCoName := Trim(Ado_Order.FieldByName('CustName').AsString);
    FGC_BatchNo := Trim(Ado_Order.FieldByName('GC_BatchNo').AsString);
    FGC_Piece := Trim(Ado_Order.FieldByName('GC_Piece').AsString);
    FGC_STKID := Trim(Ado_Order.FieldByName('GC_STKID').AsString);
    FGC_Position := Trim(Ado_Order.FieldByName('GC_Position').AsString);
//    fbzunit := Trim(Ado_Order.FieldByName('bzunit').AsString);
//    FRollNum :=Trim(Ado_Order.FieldByName('').AsString);
  end;
end;

//procedure TfrmDyePlanCardInput.InitRepairCard(PPCID: string);
//begin
//
//  with ADOQueryTmp do
//  begin
//    close;
//    sql.Clear;
//    sql.Add('select A.*');
//    sql.Add(',GlideList=[dbo].[F_Dye_Card_GlideList](A.PCID) ');
//    sql.Add(',MvPiece=PSC_StkPiece,MvQty=PSC_StkQty ');
//    sql.Add('from Dye_Plan_Card A ');
//    if TRIM(PPCID) = '' then
//      sql.Add('where 1=2 ')
//    else
//      sql.Add('where PCID= ' + Quotedstr(trim(PPCID)));
//
//    open;
//  end;
//  if TRIM(PPCID) = '' then
//  begin
//    SCreateCDS(ADOQueryTmp, CDS_3);
//  end
//  else
//  begin
//    SInitCDSData(ADOQueryTmp, CDS_3);
//  end;
//
//end;

procedure TfrmDyePlanCardInput.InitGreyClothStk();
begin
  try
    ADO_PB.DisableControls;
    with ADO_PB do
    begin
      Filtered := False;
      Close;
      sql.Clear;
      sql.Add(' select A.OrderNo ,A.QtyUnit,A.ioType,IOTime =  min(A.IOTime)');
      SQL.Add(' ,SUM(A.StkQty) as StkQty, SUM(A.StkPiece) as StkPiece ,A.note');
      sql.add(' ,B.custNo,B.CustName,B.MainID');
      SQL.Add(' ,C.C_Name,C.C_Code,C.C_Width,C.C_GramWeight,C.C_COLOR,C.C_COLORNO ');
      SQL.Add(' ,A.F_Name,C.F_Width,C.Material,C.CINote,b.C_description,C.DTMID ');
      sql.Add(' from BS_Cloth_IO A left join Dye_Plan_Main B on A.OrderNo= B.OrderNo ');
      SQL.Add(' left join BS_Cloth_Info C on C.C_Name=B.C_Name');
      SQL.Add(' where isnull(A.STKName,'''')=''染色坯布'' and A.IOFlag=''入库''   ');
//      SQL.Add(' and EXISTS(select * from [dbo].[F_Tool_SplitString](' + quotedstr(FGC_STKID) + ','','' ) X where X.RTValue=A.StkId AND ISNULL(RTValue,'''')<>'''')  ');
      sql.Add(' and not exists(select * from BS_Cloth_io X where X.StkQty=0 and X.StkPiece=0 and X.BCIOID = A.BCIOID) ');
      if trim(OrderNo.Text) <> '' then
      begin
        SQL.Add(' and A.OrderNo= ' + QuotedStr(trim(OrderNo.Text)));
      end;
      SQL.Add(' group by A.OrderNo,A.QtyUnit,A.ioType,A.note,B.custNo,B.CustName,B.MainID');
      SQL.Add(' ,C.C_Name,C.C_Code,C.C_Width,C.C_GramWeight,C.C_COLOR,C.C_COLORNO');
      SQL.Add(' ,A.F_Name,C.F_Width,C.Material,C.CINote,B.C_description,C.DTMID ');
//      ShowMessage(sql.Text);
      Open;
    end;
    SCreateCDS(ADO_PB, CDS_2);
    SInitCDSData(ADO_PB, CDS_2);

//    if (ADO_PB.FieldByName('DTMID').AsString = '') or (ADO_PB.FieldByName('DTMID').AsString = null) then
//    begin
//      Application.MessageBox('未设置默认工序！', '提示信息', MB_OK);
//    end;
//    DTMID1.Text := ADO_PB.FieldByName('DTMID').AsString;
//    with ADOQueryCmd do
//    begin
//      Close;
//      sql.Clear;
//      SQL.Add(' select * from Dye_Technics_Main where DTMID = ' + QuotedStr(Trim(DTMID1.Text)));
//      Open;
//    end;
//    DTMPSlist1.Text := ADOQueryCmd.FieldByName('DTMPSlist').AsString;

    with ADO_PB do
    begin
      Filtered := False;
      Close;
      sql.Clear;
      sql.Add(' select A.* ');
      sql.Add(' from BS_Cloth_IO A where isnull(STKName,'''')=''染色坯布'' ');
      SQL.Add(' and A.IOFlag=''入库''   ');
//      SQL.Add(' and EXISTS(select * from [dbo].[F_Tool_SplitString](' + quotedstr(FGC_STKID) + ','','' ) X where X.RTValue=A.StkId AND ISNULL(RTValue,'''')<>'''')  ');
      SQL.Add(' and A.OrderNo= ' + QuotedStr(trim(OrderNo.Text)));
      SQL.Add(' and A.F_Name= ' + QuotedStr(trim(F_Name.Text)));
//      ShowMessage(sql.Text);
      Open;
    end;
    FGC_STKID := '';
    ADO_PB.First;
    while not ADO_PB.Eof do
    begin
      if (FGC_STKID <> '') and (FGC_STKID <> null) then
      begin
        FGC_STKID := ADO_PB.FieldByName('StkID').AsString + ',' + FGC_STKID;
      end
      else
      begin
        FGC_STKID := ADO_PB.FieldByName('StkID').AsString;
      end;

      ADO_PB.Next;
    end;

  finally
    ADO_PB.EnableControls;
  end;


//  try
//    ADO_PB.DisableControls;
//    with ADO_PB do
//    begin
//      Filtered := False;
//      Close;
//      sql.Clear;
//      sql.Add(' select A.OrderNo, A.C_Name, max(A.F_Name) as F_Name , max(A.QtyUnit) as QtyUnit , max(A.Material) as Material,SUM(A.StkQty) as StkQty, SUM(A.StkPiece) as StkPiece ');
//      sql.Add(' ,IOTime =  min(A.IOTime) ,IOType = max(A.ioType) ,C_Width =  max(A.C_Width) ,F_Width = max(A.F_Width),C_description = max(B.C_description)');
//      sql.Add(' from BS_Cloth_IO A left join Dye_Plan_Main B on A.OrderNo= B.OrderNo ');
//      SQL.Add(' where isnull(A.STKName,'''')=''染色坯布'' and A.IOFlag=''入库''   ');
////      SQL.Add(' and EXISTS(select * from [dbo].[F_Tool_SplitString](' + quotedstr(FGC_STKID) + ','','' ) X where X.RTValue=A.StkId AND ISNULL(RTValue,'''')<>'''')  ');
//      if trim(OrderNo.Text) <> '' then
//      begin
//        SQL.Add(' and A.OrderNo= ' + QuotedStr(trim(OrderNo.Text)));
//      end;
//      SQL.Add(' group by A.OrderNo, A.C_Name');
////      ShowMessage(sql.Text);
//      Open;
//    end;
//    SCreateCDS(ADO_PB, CDS_2);
//    SInitCDSData(ADO_PB, CDS_2);
//
//    with ADO_PB do
//    begin
//      Filtered := False;
//      Close;
//      sql.Clear;
//      sql.Add(' select A.* ');
//      sql.Add(' from BS_Cloth_IO A where isnull(STKName,'''')=''染色坯布'' ');
//      SQL.Add(' and A.IOFlag=''入库''   ');
////      SQL.Add(' and EXISTS(select * from [dbo].[F_Tool_SplitString](' + quotedstr(FGC_STKID) + ','','' ) X where X.RTValue=A.StkId AND ISNULL(RTValue,'''')<>'''')  ');
//      SQL.Add(' and A.OrderNo= ' + QuotedStr(trim(OrderNo.Text)));
////      ShowMessage(sql.Text);
//      Open;
//    end;
//    ADO_PB.First;
//    while not ADO_PB.Eof do
//    begin
//      if (FGC_STKID <> '') and (FGC_STKID <> null) then
//      begin
//        FGC_STKID := ADO_PB.FieldByName('StkID').AsString + ',' + FGC_STKID;
//      end
//      else
//      begin
//        FGC_STKID := ADO_PB.FieldByName('StkID').AsString;
//      end;
//
//      ADO_PB.Next;
//    end;
//  finally
//    ADO_PB.EnableControls;
//  end;

end;

procedure TfrmDyePlanCardInput.InitGreyClothStk1();
begin
  try
    ADO_PB.DisableControls;
    with ADO_PB do
    begin
      Filtered := False;
      Close;
      sql.Clear;
      sql.Add(' select A.OrderNo ,A.QtyUnit,A.ioType,IOTime =  min(A.IOTime)');
      SQL.Add(' ,SUM(A.StkQty) as StkQty, SUM(A.StkPiece) as StkPiece ,A.note');
      sql.add(' ,B.custNo,B.CustName,B.MainID');
      SQL.Add(' ,C.C_Name,C.C_Code,C.C_Width,C.C_GramWeight,C.C_COLOR,C.C_COLORNO ');
      SQL.Add(' ,A.F_Name,C.F_Width,C.Material,C.CINote,b.C_description,C.DTMID ');
      sql.Add(' from BS_Cloth_IO A left join Dye_Plan_Main B on A.OrderNo= B.OrderNo ');
      SQL.Add(' left join BS_Cloth_Info C on C.C_Name=B.C_Name');
      SQL.Add(' where isnull(A.STKName,'''')=''染色坯布'' and A.IOFlag=''入库''   ');
//      SQL.Add(' and EXISTS(select * from [dbo].[F_Tool_SplitString](' + quotedstr(FGC_STKID) + ','','' ) X where X.RTValue=A.StkId AND ISNULL(RTValue,'''')<>'''')  ');
      if trim(OrderNo1.Text) <> '' then
      begin
        SQL.Add(' and A.OrderNo= ' + QuotedStr(trim(OrderNo1.Text)));
        SQL.Add(' and A.F_Name= ' + QuotedStr(trim(F_Name1.Text)));
      end;
      SQL.Add(' group by A.OrderNo,A.QtyUnit,A.ioType,A.note,B.custNo,B.CustName,B.MainID');
      SQL.Add(' ,C.C_Name,C.C_Code,C.C_Width,C.C_GramWeight,C.C_COLOR,C.C_COLORNO');
      SQL.Add(' ,C.F_Name,C.F_Width,C.Material,C.CINote,B.C_description,C.DTMID ');
//      ShowMessage(sql.Text);
      Open;
    end;
    SCreateCDS(ADO_PB, CDS_3);
    SInitCDSData(ADO_PB, CDS_3);

    if (ADO_PB.FieldByName('DTMID').AsString = '') or (ADO_PB.FieldByName('DTMID').AsString = null) then
    begin
      Application.MessageBox('未设置默认工序！', '提示信息', MB_OK);
    end;
    FDTMID1 := ADO_PB.FieldByName('DTMID').AsString;

    if PCType1.text = '正常卡+正常卡' then
    begin
      DTMID1.Text := ADO_PB.FieldByName('DTMID').AsString;
      DTMID2.Text := ADO_PB.FieldByName('DTMID').AsString;
    end
    else if PCType1.text = '正常卡+内回修' then
    begin
      DTMID1.Text := ADO_PB.FieldByName('DTMID').AsString;
      DTMID2.Text := 'GY260407009';
    end
    else if PCType1.text = '内回修+内回修' then
    begin
      DTMID1.Text := 'GY260407009';
      DTMID2.Text := 'GY260407009';
    end;

    with ADOQueryCmd do
    begin
      Close;
      sql.Clear;
      SQL.Add(' select * from Dye_Technics_Main where DTMID = ' + QuotedStr(Trim(DTMID1.Text)));
      Open;
    end;
    FDTMPSlist1 := ADOQueryCmd.FieldByName('DTMPSlist').AsString;
    if PCType1.text = '正常卡+正常卡' then
    begin
      DTMPSlist1.Text := ADOQueryCmd.FieldByName('DTMPSlist').AsString;
      DTMPSlist2.Text := ADOQueryCmd.FieldByName('DTMPSlist').AsString;
    end
    else if PCType1.text = '正常卡+内回修' then
    begin
      DTMPSlist1.Text := ADOQueryCmd.FieldByName('DTMPSlist').AsString;
      DTMPSlist2.Text := '1.定型回修';
    end
    else if PCType1.text = '内回修+内回修' then
    begin
      DTMPSlist1.Text := '1.定型回修';
      DTMPSlist2.Text := '1.定型回修';
    end;

    with ADO_PB do
    begin
      Filtered := False;
      Close;
      sql.Clear;
      sql.Add(' select A.* ');
      sql.Add(' from BS_Cloth_IO A where isnull(STKName,'''')=''染色坯布'' ');
      SQL.Add(' and A.IOFlag=''入库''   ');
//      SQL.Add(' and EXISTS(select * from [dbo].[F_Tool_SplitString](' + quotedstr(FGC_STKID) + ','','' ) X where X.RTValue=A.StkId AND ISNULL(RTValue,'''')<>'''')  ');
      SQL.Add(' and A.OrderNo= ' + QuotedStr(trim(OrderNo1.Text)));
      SQL.Add(' and A.F_Name= ' + QuotedStr(trim(F_Name1.Text)));
//      ShowMessage(sql.Text);
      Open;
    end;
    FGC_STKID := '';
    ADO_PB.First;
    while not ADO_PB.Eof do
    begin
      if (FGC_STKID <> '') and (FGC_STKID <> null) then
      begin
        FGC_STKID := ADO_PB.FieldByName('StkID').AsString + ',' + FGC_STKID;
      end
      else
      begin
        FGC_STKID := ADO_PB.FieldByName('StkID').AsString;
      end;

      ADO_PB.Next;
    end;

  finally
    ADO_PB.EnableControls;
  end;
end;

procedure TfrmDyePlanCardInput.MenuItem1Click(Sender: TObject);
var
  topIndex: Integer;
begin
  topIndex := tv1.Controller.TopRowIndex;
  SelOKNo(CDS_1, True);
  tv1.Controller.TopRowIndex := topIndex;
end;

procedure TfrmDyePlanCardInput.MenuItem2Click(Sender: TObject);
var
  topIndex: Integer;
begin
  topIndex := tv1.Controller.TopRowIndex;
  SelOKNo(CDS_1, False);
  tv1.Controller.TopRowIndex := topIndex;
end;

procedure TfrmDyePlanCardInput.N1Click(Sender: TObject);
var
  topIndex: Integer;
begin
  topIndex := tv1.Controller.TopRowIndex;
  SelOKNo(CDS_2, True);
  tv1.Controller.TopRowIndex := topIndex;
end;

procedure TfrmDyePlanCardInput.N2Click(Sender: TObject);
var
  topIndex: Integer;
begin
  topIndex := tv1.Controller.TopRowIndex;
  SelOKNo(CDS_2, false);
  tv1.Controller.TopRowIndex := topIndex;
end;

procedure TfrmDyePlanCardInput.N3Click(Sender: TObject);
begin
  Clipboard.SetTextBuf(PChar(Trim(CDS_2.fieldbyname(TV2.Controller.FocusedColumn.DataBinding.FilterFieldName).AsString)));

end;

procedure TfrmDyePlanCardInput.N4Click(Sender: TObject);
begin
  Clipboard.SetTextBuf(PChar(Trim(CDS_1.fieldbyname(TV1.Controller.FocusedColumn.DataBinding.FilterFieldName).AsString)));
end;

procedure TfrmDyePlanCardInput.N5Click(Sender: TObject);
var
  topIndex: Integer;
begin
  topIndex := tv1.Controller.TopRowIndex;
  SelOKNo(CDS_3, false);
  tv1.Controller.TopRowIndex := topIndex;
end;

procedure TfrmDyePlanCardInput.N6Click(Sender: TObject);
begin
  Clipboard.SetTextBuf(PChar(Trim(CDS_3.fieldbyname(TV3.Controller.FocusedColumn.DataBinding.FilterFieldName).AsString)));

end;

procedure TfrmDyePlanCardInput.OrderNoBtnClick(Sender: TObject);
begin

  frmProductOrderListSel := TfrmProductOrderListSel.create(self);
  with frmProductOrderListSel do
  begin
    FWorkshop := self.FWorkshop;
    if ShowModal = 1 then
    begin
      fmainID := Order_Main.fieldbyname('mainID').asstring;
//      fC_Code := Order_Main.fieldbyname('C_Code').asstring;
//      fC_name := Order_Main.fieldbyname('C_name').asstring;


      InitOrder();
      InitGreyClothStk();
      if CDS_2.IsEmpty then
      begin
        Application.MessageBox('无产品库存！', '提示信息', MB_OK);
      end;
      InitCard();
//      initGlide();
    end;
    free;
  end;
end;

procedure TfrmDyePlanCardInput.OrderNoKeyPress(Sender: TObject; var Key: Char);
begin
  if Key = #13 then
  begin

//    with ADOQueryTmp do
//    begin
//      close;
//      sql.Clear;
//      sql.Add('exec P_OrderCR');
//    ShowMessage(sql.Text);
//      execsql;
//    end;

    fmainID := OrderNo.Text;
//      fC_Code := Order_Main.fieldbyname('C_Code').asstring;
//      fC_name := Order_Main.fieldbyname('C_name').asstring;


    InitOrder();
    InitGreyClothStk();
    if CDS_2.IsEmpty then
    begin
      Application.MessageBox('无产品库存！', '提示信息', MB_OK);
    end;
    InitCard();
//      initGlide();
  end;

end;

procedure TfrmDyePlanCardInput.PCPiece1Change(Sender: TObject);
begin
   // 如果是整数运算
  PCPiece2.Text := IntToStr(StrToInt(KaZuPiece.Text) - StrToInt(PCPiece1.Text));
end;

procedure TfrmDyePlanCardInput.PCQty1Change(Sender: TObject);
begin
  PCQty2.Text := IntToStr(StrToInt(KaZuQty.Text) - StrToInt(PCQty1.Text));
end;

procedure TfrmDyePlanCardInput.PCType1Change(Sender: TObject);
begin
  if PCType1.text = '正常卡+正常卡' then
  begin
    DTMID1.Text := FDTMID1;
    DTMID2.Text := FDTMID1;
    DTMPSlist1.Text := FDTMPSlist1;
    DTMPSlist2.Text := FDTMPSlist1;

  end
  else if PCType1.text = '正常卡+内回修' then
  begin
    DTMID1.Text := FDTMID1;
    DTMPSlist1.Text := FDTMPSlist1;
    DTMID2.Text := 'GY260407009';
    DTMPSlist2.Text := '1.定型回修';
  end
  else if PCType1.text = '内回修+内回修' then
  begin
    DTMID1.Text := 'GY260407009';
    DTMPSlist1.Text := '1.定型回修';
    DTMID2.Text := 'GY260407009';
    DTMPSlist2.Text := '1.定型回修';
  end;

end;

procedure TfrmDyePlanCardInput.PCTypeChange(Sender: TObject);
begin
  if PCType.text = '外回修' then
  begin
    Self.DTMPSlist.Text := '1.定型回修';
    Self.DTMID.Text := 'GY260407009';
  end
  else
  begin
    Self.DTMPSlist.Text := '';
    Self.DTMID.Text := '';
  end;

end;

procedure TfrmDyePlanCardInput.q1Click(Sender: TObject);
var
  topIndex: Integer;
begin
  topIndex := tv1.Controller.TopRowIndex;
  SelOKNo(CDS_3, True);
  tv1.Controller.TopRowIndex := topIndex;
end;

//procedure TfrmDyePlanCardInput.PCIDKeyPress(Sender: TObject; var Key: Char);
//begin
//  if Key = #13 then
//  begin
//    if Trim(PCID.Text) = '' then
//      exit;
//    InitRepairCard(PCID.Text);
//    PCID.Text := '';
//  end;
//end;

procedure TfrmDyePlanCardInput.InitCard();
begin

  with Ado_car do
  begin
    close;
    sql.Clear;
    sql.Add('select A.* ');
    sql.Add(',GlideList=[dbo].[F_Dye_Card_GlideList](A.PCID) ');
    sql.Add('from Dye_Plan_Card A ');
    sql.Add('where EXISTS(select X.RTValue from [dbo].[F_Tool_SplitString](' + Quotedstr(trim(FPCIDS)) + ', '';'' ) X where X.RTValue=A.PCID ) ');
//    ShowMessage(sql.Text);
    open;
  end;
  SCreateCDS(Ado_car, CDS_1);
  SInitCDSData(Ado_car, CDS_1);

end;

procedure TfrmDyePlanCardInput.FormDestroy(Sender: TObject);
begin
  inherited;
  frmDyePlanCardInput := nil;
end;

procedure TfrmDyePlanCardInput.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
  if Key = VK_ESCAPE then  // VK_ESCAPE 是 ESC 键的常量
  begin
    Key := 0;  // 清除按键，防止继续传递
    Close;     // 或者 ModalResult := mrCancel;
  end;
end;

procedure TfrmDyePlanCardInput.DTMPSlist1BtnClick(Sender: TObject);
begin
  try
    if OrderNo1.Text = '' then
    begin
      Application.MessageBox('请先选择计划单', '提示信息', MB_OK);
      exit;
    end;
    frmCraftSel := TfrmCraftSel.Create(Application);
    with frmCraftSel do
    begin
      fcode := Self.CDS_3.FieldByName('C_Code').AsString;
      fC_name := Self.CDS_3.FieldByName('C_Name').AsString;
      if ShowModal = 1 then
      begin
        with frmCraftSel.CDS_1 do
        begin
          Self.DTMPSlist1.Text := frmCraftSel.CDS_1.FieldByName('DTMPSlist').Value;
          Self.DTMID1.Text := frmCraftSel.CDS_1.FieldByName('DTMID').Value;

          Self.FDTMID1 := frmCraftSel.CDS_1.FieldByName('DTMID').Value;
          Self.FDTMPSlist1 := frmCraftSel.CDS_1.FieldByName('DTMPSlist').Value;
        end;
      end;
    end;
  finally
    frmCraftSel.Free;
  end;
end;

procedure TfrmDyePlanCardInput.DTMPSlistBtnClick(Sender: TObject);
begin
  try
    if OrderNo.Text = '' then
    begin
      Application.MessageBox('请先选择计划单', '提示信息', MB_OK);
      exit;
    end;
    frmCraftSel := TfrmCraftSel.Create(Application);
    with frmCraftSel do
    begin
      fcode := Self.FC_Code;
      fC_name := Self.fC_name;
      if ShowModal = 1 then
      begin
        with frmCraftSel.CDS_1 do
        begin
          Self.DTMPSlist.Text := frmCraftSel.CDS_1.FieldByName('DTMPSlist').Value;
          Self.DTMID.Text := frmCraftSel.CDS_1.FieldByName('DTMID').Value;
        end;
      end;
    end;
  finally
    frmCraftSel.Free;
  end;
end;

procedure TfrmDyePlanCardInput.AbnormalKaZuBtnClick(Sender: TObject);
begin

  frmDye_AbnormalCardSel := TfrmDye_AbnormalCardSel.create(self);
  with frmDye_AbnormalCardSel do
  begin

    if ShowModal = 1 then
    begin
      AbnormalKaZu.Text := frmDye_AbnormalCardSel.CDS_1.FieldByName('KaZu').AsString;
      KaZuPiece.Text := frmDye_AbnormalCardSel.CDS_1.FieldByName('PCPiece').AsString;
      KaZuQty.Text := frmDye_AbnormalCardSel.CDS_1.FieldByName('PCQty').AsString;
      OrderNo1.Text := frmDye_AbnormalCardSel.CDS_1.FieldByName('OrderNo').AsString;
      F_Name1.Text := frmDye_AbnormalCardSel.CDS_1.FieldByName('F_Name').AsString;
//      fmainID := Order_Main.fieldbyname('mainID').asstring;
//      fC_Code := Order_Main.fieldbyname('C_Code').asstring;
//      fC_name := Order_Main.fieldbyname('C_name').asstring;
//      InitOrder();
      InitGreyClothStk1();
//      if CDS_2.IsEmpty then
//      begin
//        Application.MessageBox('无产品库存！', '提示信息', MB_OK);
//      end;
      InitCard();
//      initGlide();
    end;
    free;
  end;
end;

procedure TfrmDyePlanCardInput.avgCardClick(Sender: TObject);
var
  i, k: integer;
  maxId, KZmaxID: string;
  totalPieces, totalQty: Double;
  pieceArray: array of Double;
  qtyArray: array of Double;
  mQRCode: string;
begin
  // 验证输入
  if trim(C_Name.Text) = '' then
  begin
    application.MessageBox('产品名称不能为空！', '提示信息', MB_ICONERROR);
    exit;
  end;

  if (StrToFloatDef(PCPiece.Text, 0) + StrToFloatDef(PCQty.Text, 0)) = 0 then
  begin
    application.MessageBox('开卡匹数、数量不能都为零！', '提示信息', MB_OK);
    exit;
  end;

  if DTMPSlist.Text = '' then
  begin
    application.MessageBox('产品工序不能为空！', '提示信息', MB_OK);
    exit;
  end;

  if GetLSNo(ADOQueryCmd, KZmaxID, 'KZ', 'Dye_Plan_Card_KZ', 3, 1) = False then
  begin
    Application.MessageBox('取最大号失败!', '提示', 0);
    Exit;
  end;

  // 获取车数
  if strtointdef(trim(carNum.text), 0) <= 1 then
    k := 1
  else
    k := strtointdef(trim(carNum.text), 0);

  // 获取总匹数和总数量
  totalPieces := StrToFloatDef(PCPiece.Text, 0);
  totalQty := StrToFloatDef(PCQty.Text, 0);

  // 预分配数组
  SetLength(pieceArray, k);
  SetLength(qtyArray, k);

  // 计算每张卡的分配值
  CalculateDistribution(totalPieces, k, pieceArray);
  CalculateDistribution(totalQty, k, qtyArray);

  CDS_Color.Locate('C_Color', C_Color.Text, []);
  CDS_1.Last;

  for i := 0 to k - 1 do
  begin
    if GetLSNo(ADOQueryCmd, maxId, 'CZ', 'Dye_Plan_Card', 3, 1) = False then
    begin
      Application.MessageBox('取最大号失败!', '提示', 0);
      Exit;
    end;
    FPCIDS := FPCIDS + maxId + ';';

    mQRCode := FC_Name + '|' + OrderNo.Text + '|0|';
    mQRCode := mQRCode + FormatDateTime('yyyymmddhhnnss', SGetServerDateTime(ADOQueryBaseTemp));
    mQRCode := mQRCode + '|0|';
    mQRCode := mQRCode + OrderNo.Text + '*0|0';

    try
      ADOQueryCmd.Connection.BeginTrans;

      with ADOQueryCmd do
      begin
        Close;
        Sql.Clear;
        Sql.Add('select * from Dye_Plan_Card A where 1=2');
        Open;
        Append;
        FieldByName('OrderNo').Value := OrderNo.Text;
        FieldByName('Mainid').Value := FMainid;
        FieldByName('Filler').Value := trim(DName);
        FieldByName('Workshop').Value := trim(FWorkshop);
        FieldByName('PCType').Value := trim(PCType.Text);
        FieldByName('PCID').Value := trim(maxId);
        FieldByName('KaZu').Value := trim(KZmaxID);
        FieldByName('PCTime').Value := formatdateTime('yyyy-MM-dd', PCTime.DateTime);
        FieldByName('GC_BatchNo').Value := trim(FGC_BatchNo);
        FieldByName('GC_Piece').Value := trim(FGC_Piece);
        FieldByName('GC_STKID').Value := trim(FGC_STKID);
        FieldByName('GC_Position').Value := trim(FGC_Position);
        FieldByName('DTMPSlist').Value := trim(DTMPSlist.Text);
        FieldByName('DTMID').Value := Trim(DTMID.Text);
        FieldByName('C_description').Value := trim(C_description.Text);

        FieldByName('bzunit').Value := trim(Fbzunit);
        FieldByName('CustNo').Value := trim(FFromCoNo);
        FieldByName('CustName').Value := trim(FFromCoName);
        FieldByName('Saleser').Value := trim(FSaleser);
        FieldByName('C_Name').Value := trim(FC_Name);
        FieldByName('C_Code').Value := trim(FC_Code);
        FieldByName('C_GramWeight').Value := trim(C_GramWeight.Text);
        FieldByName('F_Name').Value := trim(F_Name.Text);
        FieldByName('C_Width').Value := trim(C_Width.Text);
        FieldByName('C_Color').Value := trim(C_Color.Text);
        FieldByName('PCUnit').Value := trim(OrdUnit.Text);
        FieldByName('C_ColorNo').Value := trim(C_ColorNo.Text);

        FieldByName('CINote').Value := trim(CINote.Text);

        // 使用预分配的匹数和数量
        FieldByName('PCPiece').Value := pieceArray[i];
        FieldByName('PCQty').Value := qtyArray[i];

        FieldByName('batchno').Value := INTTOSTR(k) + '-' + INTTOSTR(i + 1);

        FieldByName('QRCode').Value := trim(mQRCode);
        FieldByName('PrtCount').Value := 0;

        post;
      end;

      with ADOQueryCmd do
      begin
        Close;
        Sql.Clear;
        //对每个流程卡进行出库
        Sql.Add('exec P_Dye_GreyCloth_Out ');
        Sql.Add('@PCID=' + quotedstr(trim(maxId)));
        Sql.Add(',@Filler=' + quotedstr(trim(DName)));
        Open;
      end;

      if ADOQueryCmd.FieldByName('intReturn').AsInteger = -1 then
      begin
        FGC_STKID := '';
        raise Exception.Create(pchar(trim(ADOQueryCmd.FieldByName('ShowMsg').AsString)));
      end;

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

  end;

  with ADOQueryCmd do
  begin
    Close;
    Sql.Clear;
    //更新总卡号分卡号
    Sql.Add('exec P_Dye_Plan_UpdateOrderNo ');
    Sql.Add('@KaZu=' + quotedstr(Trim(KZmaxID)));
    Open;
  end;

  with ADOQueryCmd do
  begin
    Close;
    Sql.Clear;
    //插入待排产数据
    Sql.Add('exec P_Dye_Cloth_GX @carno=' + QuotedStr(trim(KZmaxID)));
    sql.add(',@dname=' + QuotedStr(trim(dname)));
    SQL.Add(',@C_Name=' + QuotedStr(Trim(C_Name.Text)));
    SQL.Add(',@OrderNo=' + QuotedStr(Trim(OrderNo.Text)));
    SQL.Add(',@DTMID=' + QuotedStr(Trim(DTMID.Text)));
    execsql;
  end;

  with ADOQueryCmd do
  begin
    SQL.Clear;
    //备份开卡工艺数据
    SQL.Add('EXEC P_InsertGxToKaika @PCID = ' + quotedstr(trim(KZmaxID)));
    ExecSQL;
  end;

  InitCard();
  InitGreyClothStk();

  // 显示分配结果信息
  ShowDistributionResult(k, pieceArray, qtyArray);
end;


// 分配计算函数
procedure TfrmDyePlanCardInput.CalculateDistribution(totalValue: Double; cardCount: Integer; var resultArray: array of Double);
var
  i: Integer;
  baseValue, remainder: Double;
  intBaseValue, intRemainder: Integer;
begin
  if cardCount <= 0 then
    Exit;

  // 如果是整数，按整数分配
  if Frac(totalValue) = 0 then
  begin
    intBaseValue := Trunc(totalValue) div cardCount;
    intRemainder := Trunc(totalValue) mod cardCount;

    for i := 0 to cardCount - 1 do
    begin
      if i < intRemainder then
        resultArray[i] := intBaseValue + 1
      else
        resultArray[i] := intBaseValue;
    end;
  end;
end;

// 显示分配结果
procedure TfrmDyePlanCardInput.ShowDistributionResult(cardCount: Integer; pieceArray, qtyArray: array of Double);
var
  i: Integer;
  distributionInfo: string;
begin
  distributionInfo := '成功开立' + IntToStr(cardCount) + '张卡，分配情况：' + #13#10;

  for i := 0 to cardCount - 1 do
  begin
    distributionInfo := distributionInfo + Format('卡%d: %.0f匹, %.2f米' + #13#10, [i + 1, pieceArray[i], qtyArray[i]]);
  end;

  ShowMessage(distributionInfo);
end;

procedure TfrmDyePlanCardInput.TbAbnormalKaiKaClick(Sender: TObject);
var
  i, k, k2: integer;
  maxId, KZmaxID, KZmaxID2: string;
  totalPieces, totalQty: Double;
  totalPieces2, totalQty2: Double;
  pieceArray1, pieceArray2: array of Double;
  qtyArray1, qtyArray2: array of Double;
  mQRCode: string;
  HXmaxNo: string;
begin

  // 验证输入
  if trim(AbnormalKaZu.Text) = '' then
  begin
    application.MessageBox('请先选择异常卡组！', '提示信息', MB_ICONERROR);
    exit;
  end;

  if StrToInt(trim(carNum1.Text)) <= 0 then
  begin
    application.MessageBox('车数需大于0！', '提示信息', MB_ICONERROR);
    exit;
  end;
  if StrToInt(trim(carNum2.Text)) <= 0 then
  begin
    application.MessageBox('车数需大于0！', '提示信息', MB_ICONERROR);
    exit;
  end;
  if StrToInt(trim(PCPiece1.Text)) <= 0 then
  begin
    application.MessageBox('开卡匹数需大于0！', '提示信息', MB_ICONERROR);
    exit;
  end;
  if StrToInt(trim(PCPiece2.Text)) <= 0 then
  begin
    application.MessageBox('开卡匹数需大于0！', '提示信息', MB_ICONERROR);
    exit;
  end;
  if StrToInt(trim(PCQty1.Text)) <= 0 then
  begin
    application.MessageBox('开卡数量需大于0！', '提示信息', MB_ICONERROR);
    exit;
  end;
  if StrToInt(trim(PCQty2.Text)) <= 0 then
  begin
    application.MessageBox('开卡数量需大于0！', '提示信息', MB_ICONERROR);
    exit;
  end;

  if trim(OrderNo1.Text) = '' then
  begin
    application.MessageBox('计划单号不能为空！', '提示信息', MB_ICONERROR);
    exit;
  end;

//  if (StrToFloatDef(PCPiece.Text, 0) + StrToFloatDef(PCQty.Text, 0)) = 0 then
//  begin
//    application.MessageBox('开卡匹数、数量不能都为零！', '提示信息', MB_OK);
//    exit;
//  end;
//
  if (DTMPSlist1.Text = '') or (DTMPSlist2.Text = '') then
  begin
    application.MessageBox('产品工序不能为空！', '提示信息', MB_OK);
    exit;
  end;


  //回修卡特殊设置回修工艺
  if PCType1.text <> '正常卡+正常卡' then
  begin
    with ADOQueryTmp do
    begin
      Close;
      SQL.Clear;
      sql.Add(' select * from Bs_Cloth_Dye_Technics where C_Code = ' + QuotedStr(trim(CDS_3.FieldByName('C_Code').AsString)));
      sql.Add(' and DTMID = ''GY260407009'' ');
      Open;
    end;
    if ADOQueryTmp.IsEmpty then
    begin
      if GetLSNo(ADOQueryCmd, HXmaxNo, 'CG', 'Dye_Plan_Glide', 4, 1) = False then
      begin
        Application.MessageBox('取最大号失败!', '提示', 0);
        Exit;
      end;

      with ADOQueryCmd do
      begin
        Close;
        sql.Clear;
        sql.Add(' INSERT into Bs_Cloth_Dye_Technics(BCIID,TechnicsID,DTMID,C_Name,C_Code,DTMNo,DTMName,DTMPSlist,F_Name) ');
        sql.Add(' VALUES(' + QuotedStr(Trim(CDS_3.FieldByName('C_Code').AsString)));       //BCIID
        SQL.Add(' ,' + QuotedStr(Trim(HXmaxNo)));         // TechnicsID
        SQL.Add(' ,''GY260407009'' ');               // DTMID
        SQL.Add(' ,' + QuotedStr(Trim(CDS_3.FieldByName('C_Name').AsString)));     //C_Name
        SQL.Add(' ,' + QuotedStr(Trim(CDS_3.FieldByName('C_Code').AsString)));   //C_Code
        SQL.Add(' ,''定型回修'' ');              // DTMNo
        SQL.Add(' ,''定型回修'' ');               // DTMName
        SQL.Add(' ,''1.定型回修'' ');               //  DTMPSlist
        SQL.Add(' ,' + QuotedStr(Trim(CDS_3.FieldByName('F_Name').AsString)) + ')');     // F_Name
//        SQL.Add(' ,' + QuotedStr(Trim(CDS_2.FieldByName('F_Code').AsString)) + ')');        // F_Code
        ExecSQL;
      end;
    end;
  end;





  // 获取车数
  if strtointdef(trim(carNum1.text), 0) <= 1 then
    k := 1
  else
    k := strtointdef(trim(carNum1.text), 0);

  if strtointdef(trim(carNum2.text), 0) <= 1 then
    k2 := 1
  else
    k2 := strtointdef(trim(carNum2.text), 0);

  // 获取总匹数和总数量
  totalPieces := StrToFloatDef(PCPiece1.Text, 0);
  totalQty := StrToFloatDef(PCQty1.Text, 0);

  totalPieces2 := StrToFloatDef(PCPiece2.Text, 0);
  totalQty2 := StrToFloatDef(PCQty2.Text, 0);

  // 预分配数组
  SetLength(pieceArray1, k);
  SetLength(qtyArray1, k);

  SetLength(pieceArray2, k2);
  SetLength(qtyArray2, k2);

  // 计算每张卡的分配值
  CalculateDistribution(totalPieces, k, pieceArray1);
  CalculateDistribution(totalQty, k, qtyArray1);

  CalculateDistribution(totalPieces2, k2, pieceArray2);
  CalculateDistribution(totalQty2, k2, qtyArray2);

//  CDS_Color.Locate('C_Color', C_Color.Text, []);
//  CDS_1.Last;

  if GetLSNo(ADOQueryCmd, KZmaxID, 'KZ', 'Dye_Plan_Card_KZ', 3, 1) = False then
  begin
    Application.MessageBox('取最大号失败!', '提示', 0);
    Exit;
  end;

  if GetLSNo(ADOQueryCmd, KZmaxID2, 'KZ', 'Dye_Plan_Card_KZ', 3, 1) = False then
  begin
    Application.MessageBox('取最大号失败!', '提示', 0);
    Exit;
  end;

  try
    ADOQueryCmd.Connection.BeginTrans;

    //开卡之前先清空出库数据，更新库存
    with ADOQueryCmd do
    begin
      Close;
      SQL.Clear;
      SQL.Add(' select * from Dye_Plan_Card where KaZu = ' + QuotedStr(Trim(AbnormalKaZu.Text)));
      Open;
    end;
    ADOQueryCmd.First;

    while not ADOQueryCmd.Eof do
    begin
      with ADOQueryBaseCmd do
      begin
        Close;
        Sql.Clear;
          //删除出库记录并且更新库存
        Sql.Add('exec P_Dye_GreyCloth_Out_Del ');
        Sql.Add('@PCID=' + quotedstr(Trim(ADOQueryCmd.fieldbyname('PCID').AsString)));
//        showMessage(sql.Text);
        Open;
      end;
      if ADOQueryBaseCmd.FieldByName('intReturn').AsInteger = -1 then
        raise Exception.Create(pchar(trim(ADOQueryBaseCmd.FieldByName('ShowMsg').AsString)));
      ADOQueryCmd.Next;
    end;

    //设置卡组停工
    with ADOQueryCmd do
    begin
      Close;
      SQL.Clear;
      sql.Add('update  Dye_Plan_Card SET isStop=''1'' ');
      sql.Add(' ,Status = ''10'' ');
      sql.Add('where KaZu=' + quotedstr(trim(AbnormalKaZu.Text)));
      ExecSQL;
    end;

    for i := 0 to k + k2 - 1 do
    begin
      if GetLSNo(ADOQueryCmd, maxId, 'CZ', 'Dye_Plan_Card', 3, 1) = False then
      begin
        Application.MessageBox('取最大号失败!', '提示', 0);
        Exit;
      end;
      FPCIDS := FPCIDS + maxId + ';';

      mQRCode := CDS_3.FieldByName('C_Name').AsString + '|' + OrderNo1.Text + '|0|';
      mQRCode := mQRCode + FormatDateTime('yyyymmddhhnnss', SGetServerDateTime(ADOQueryBaseTemp));
      mQRCode := mQRCode + '|0|';
      mQRCode := mQRCode + OrderNo1.Text + '*0|0';

      with ADOQueryCmd do
      begin
        Close;
        Sql.Clear;
        Sql.Add('select * from Dye_Plan_Card A where 1=2');
        Open;
        Append;
        FieldByName('OrderNo').Value := OrderNo1.Text;
        FieldByName('Mainid').Value := Trim(CDS_3.FieldByName('MainID').AsString);
        FieldByName('Filler').Value := trim(DName);
        FieldByName('Workshop').Value := trim(FWorkshop);

        FieldByName('PCID').Value := trim(maxId);

        if i > k - 1 then
        begin
          FieldByName('KaZu').Value := trim(KZmaxID2);
          FieldByName('DTMPSlist').Value := trim(DTMPSlist2.Text);
          FieldByName('DTMID').Value := Trim(DTMID2.Text);
          if PCType1.Text = '正常卡+正常卡' then
          begin
            FieldByName('PCType').Value := trim('正常卡');
          end
          else if PCType1.Text = '正常卡+内回修' then
          begin
            FieldByName('PCType').Value := trim('内回修');
          end
          else if PCType1.Text = '内回修+内回修' then
          begin
            FieldByName('PCType').Value := trim('内回修');
          end;

        end
        else
        begin
          FieldByName('KaZu').Value := trim(KZmaxID);
          FieldByName('DTMPSlist').Value := trim(DTMPSlist1.Text);
          FieldByName('DTMID').Value := Trim(DTMID1.Text);
          if PCType1.Text = '正常卡+正常卡' then
          begin
            FieldByName('PCType').Value := trim('正常卡');
          end
          else if PCType1.Text = '正常卡+内回修' then
          begin
            FieldByName('PCType').Value := trim('正常卡');
          end
          else if PCType1.Text = '内回修+内回修' then
          begin
            FieldByName('PCType').Value := trim('内回修');
          end;

        end;

//        FieldByName('PCTime').Value := formatdateTime('yyyy-MM-dd', PCTime.DateTime);
        FieldByName('PCTime').Value := SGetServerDateTime(ADOQueryBaseTemp);
//        FieldByName('GC_BatchNo').Value := trim(FGC_BatchNo);
//        FieldByName('GC_Piece').Value := trim(FGC_Piece);
        FieldByName('GC_STKID').Value := trim(FGC_STKID);
//        FieldByName('GC_Position').Value := trim(FGC_Position);

        FieldByName('C_description').Value := Trim(CDS_3.FieldByName('C_description').AsString);

//        FieldByName('bzunit').Value := trim(Fbzunit);
        FieldByName('CustNo').Value := Trim(CDS_3.FieldByName('CustNo').AsString);
        FieldByName('CustName').Value := Trim(CDS_3.FieldByName('CustName').AsString);
//        FieldByName('Saleser').Value := trim(FSaleser);
        FieldByName('C_Name').Value := Trim(CDS_3.FieldByName('C_Name').AsString);
        FieldByName('F_Name').Value := Trim(CDS_3.FieldByName('F_Name').AsString);
        FieldByName('C_Code').Value := Trim(CDS_3.FieldByName('C_Code').AsString);
        FieldByName('C_GramWeight').Value := Trim(CDS_3.FieldByName('C_GramWeight').AsString);
        FieldByName('C_Width').Value := Trim(CDS_3.FieldByName('C_Width').AsString);
        FieldByName('C_Color').Value := Trim(CDS_3.FieldByName('C_Color').AsString);
//        FieldByName('PCUnit').Value := trim(OrdUnit.Text);
        FieldByName('C_ColorNo').Value := Trim(CDS_3.FieldByName('C_ColorNo').AsString);

        FieldByName('CINote').Value := Trim(CDS_3.FieldByName('CINote').AsString);

        // 使用预分配的匹数和数量
        if i > k - 1 then
        begin
          FieldByName('PCPiece').Value := pieceArray2[i - k];
          FieldByName('PCQty').Value := qtyArray2[i - k];
          FieldByName('batchno').Value := INTTOSTR(k2) + '-' + INTTOSTR(i + 1 - k);
        end
        else
        begin
          FieldByName('PCPiece').Value := pieceArray1[i];
          FieldByName('PCQty').Value := qtyArray1[i];
          FieldByName('batchno').Value := INTTOSTR(k) + '-' + INTTOSTR(i + 1);
        end;

        FieldByName('QRCode').Value := trim(mQRCode);
        FieldByName('PrtCount').Value := 0;

        FieldByName('FromPCID').Value := AbnormalKaZu.Text; //来自卡组号

        post;
      end;

      with ADOQueryCmd do
      begin
        Close;
        Sql.Clear;
        //对每个流程卡进行出库
        Sql.Add('exec P_Dye_GreyCloth_Out ');
        Sql.Add('@PCID=' + quotedstr(trim(maxId)));
        Sql.Add(',@Filler=' + quotedstr(trim(DName)));
        Open;
      end;

      if ADOQueryCmd.FieldByName('intReturn').AsInteger = -1 then
      begin
        FGC_STKID := '';
        raise Exception.Create(pchar(trim(ADOQueryCmd.FieldByName('ShowMsg').AsString)));
      end;

    end;

    with ADOQueryCmd do
    begin
      Close;
      Sql.Clear;
    //更新总卡号分卡号
      Sql.Add('exec P_Dye_Plan_UpdateOrderNo ');
//      Sql.Add('@KaZu=' + quotedstr(Trim(KZmaxID2)));
      Sql.Add('@KaZu=' + quotedstr(Trim(KZmaxID)));
      Open;
    end;

    with ADOQueryCmd do
    begin
      Close;
      Sql.Clear;
    //更新总卡号分卡号
      Sql.Add('exec P_Dye_Plan_UpdateOrderNo ');
      Sql.Add('@KaZu=' + quotedstr(Trim(KZmaxID2)));
//      Sql.Add('@KaZu=' + quotedstr(Trim(KZmaxID)));
      Open;
    end;

    with ADOQueryCmd do
    begin
      Close;
      Sql.Clear;
    //插入待排产数据
      Sql.Add('exec P_Dye_Cloth_GX @carno=' + QuotedStr(trim(KZmaxID)));
      sql.add(',@dname=' + QuotedStr(trim(dname)));
      SQL.Add(',@C_Name=' + QuotedStr(Trim(CDS_3.FieldByName('C_Name').AsString)));
      SQL.Add(',@OrderNo=' + QuotedStr(Trim(OrderNo1.Text)));
      SQL.Add(',@DTMID=' + QuotedStr(Trim(DTMID1.Text)));
      execsql;
    end;

    with ADOQueryCmd do
    begin
      Close;
      Sql.Clear;
    //插入待排产数据
      Sql.Add('exec P_Dye_Cloth_GX @carno=' + QuotedStr(trim(KZmaxID2)));
      sql.add(',@dname=' + QuotedStr(trim(dname)));
      SQL.Add(',@C_Name=' + QuotedStr(Trim(CDS_3.FieldByName('C_Name').AsString)));
      SQL.Add(',@OrderNo=' + QuotedStr(Trim(OrderNo1.Text)));
      SQL.Add(',@DTMID=' + QuotedStr(Trim(DTMID2.Text)));
      execsql;
    end;

    with ADOQueryCmd do
    begin
      SQL.Clear;
    //备份开卡工艺数据
      SQL.Add('EXEC P_InsertGxToKaika @PCID = ' + quotedstr(trim(KZmaxID)));
      ExecSQL;
    end;

    with ADOQueryCmd do
    begin
      SQL.Clear;
    //备份开卡工艺数据
      SQL.Add('EXEC P_InsertGxToKaika @PCID = ' + quotedstr(trim(KZmaxID2)));
      ExecSQL;
    end;

    InitCard();
    InitGreyClothStk1();

  // 显示分配结果信息
    ShowDistributionResult(k, pieceArray1, qtyArray1);
    ShowDistributionResult(k2, pieceArray2, qtyArray2);
    ADOQueryCmd.Connection.CommitTrans;
  except
    ADOQueryCmd.Connection.RollbackTrans;
    application.MessageBox(PChar(Exception(ExceptObject).Message), '提示信息', 0);
  end;
end;

procedure TfrmDyePlanCardInput.TbKaiKaClick(Sender: TObject);
var
  HXmaxNo: string;
begin
  //回修卡特殊设置回修工艺
  if PCType.text = '外回修' then
  begin
    with ADOQueryTmp do
    begin
      Close;
      SQL.Clear;
      sql.Add(' select * from Bs_Cloth_Dye_Technics where C_Code = ' + QuotedStr(trim(FC_Code)));
      sql.Add(' and DTMID = ''GY260407009'' ');
      Open;
    end;
    if ADOQueryTmp.IsEmpty then
    begin
      if GetLSNo(ADOQueryCmd, HXmaxNo, 'CG', 'Dye_Plan_Glide', 4, 1) = False then
      begin
        Application.MessageBox('取最大号失败!', '提示', 0);
        Exit;
      end;

      with ADOQueryCmd do
      begin
        Close;
        sql.Clear;
        sql.Add(' INSERT into Bs_Cloth_Dye_Technics(BCIID,TechnicsID,DTMID,C_Name,C_Code,DTMNo,DTMName,DTMPSlist,F_Name) ');
        sql.Add(' VALUES(' + QuotedStr(Trim(FC_Code)));       //BCIID
        SQL.Add(' ,' + QuotedStr(Trim(HXmaxNo)));         // TechnicsID
        SQL.Add(' ,''GY260407009'' ');               // DTMID
        SQL.Add(' ,' + QuotedStr(Trim(C_Name.Text)));     //C_Name
        SQL.Add(' ,' + QuotedStr(Trim(FC_Code)));   //C_Code
        SQL.Add(' ,''定型回修'' ');              // DTMNo
        SQL.Add(' ,''定型回修'' ');               // DTMName
        SQL.Add(' ,''1.定型回修'' ');               //  DTMPSlist
        SQL.Add(' ,' + QuotedStr(Trim(CDS_2.FieldByName('F_Name').AsString)) + ')');     // F_Name
//        SQL.Add(' ,' + QuotedStr(Trim(CDS_2.FieldByName('F_Code').AsString)) + ')');        // F_Code
        ExecSQL;
      end;
    end;
  end;

  if strtointdef(trim(carNum.text), 1) <= 1 then
  begin
    Button2.Click;
  end
  else
  begin
    avgCard.Click;
  end;

end;

//var
//  maxId: string;
//begin
//  PCID.SetFocus;
//  if not GetCard() then
//    Exit;
//
//  if GetLSNo(ADOQueryCmd, maxId, 'CZ', 'Dye_Plan_Card', 3, 1) = False then
//  begin
//    Application.MessageBox('取最大号失败!', '提示', 0);
//    Exit;
//  end;
//  FPCIDS := FPCIDS + maxId + ';';
//  try
//    ADOQueryCmd.Connection.BeginTrans;
//    CDS_3.DisableConstraints;
//
//    with ADOQueryCmd do
//    begin
//      Close;
//      Sql.Clear;
//      Sql.Add('select * from Dye_Plan_Card A where 1=2');
//      Open;
//      Append;
//      FieldByName('Filler').Value := trim(DName);
//      FieldByName('Workshop').Value := trim(FWorkshop);
//      FieldByName('PCType').Value := trim(RePCType.Text);
//      FieldByName('PCID').Value := trim(maxId);
//      FieldByName('PCTime').Value := formatdateTime('yyyy-MM-dd', now());
//      FieldByName('GC_BatchNo').Value := '';
//      FieldByName('GC_Piece').Value := '';
//      FieldByName('GC_STKID').Value := '';
//      FieldByName('GC_Position').Value := '';
//      FieldByName('C_Name').Value := trim(CDS_3.FieldByName('C_Name').AsString);
//      FieldByName('CustNo').Value := trim(CDS_3.FieldByName('CustNo').AsString);
//      FieldByName('CustName').Value := trim(CDS_3.FieldByName('CustName').AsString);
//      FieldByName('MainId').Value := trim(CDS_3.FieldByName('MainId').AsString);
//      FieldByName('SubId').Value := trim(CDS_3.FieldByName('SubId').AsString);
//      FieldByName('C_GramWeight').Value := trim(Re_GramWeight.Text);
//      FieldByName('C_Width').Value := trim(Re_Width.Text);
//      FieldByName('C_Color').Value := trim(Re_Color.Text);
//      FieldByName('PCUnit').Value := trim(ReUnit.Text);
//      FieldByName('C_ColorNo').Value := trim(Re_ColorNo.Text);
//      FieldByName('PCPiece').Value := 0;
//      FieldByName('PCQty').Value := 0;
//      post;
//    end;
//
//    with CDS_3 do
//    begin
//      first;
//      while not Eof do
//      begin
//        with ADOQueryCmd do
//        begin
//          Close;
//          Sql.Clear;
//          Sql.Add('select * from Dye_Plan_Card_Move A where 1=2');
//          Open;
//          Append;
//          FieldByName('Filler').Value := trim(DName);
//          FieldByName('FromID').Value := trim(CDS_3.FieldByName('PCID').AsString);
//          FieldByName('ToID').Value := maxId;
//          FieldByName('MvPiece').Value := CDS_3.FieldByName('MvPiece').AsFloat;
//          FieldByName('MvQty').Value := CDS_3.FieldByName('MvQty').AsFloat;
//          post;
//        end;
//        Next;
//      end;
//    end;
//
//    with ADOQueryCmd do
//    begin
//      Close;
//      Sql.Clear;
//      Sql.Add('exec P_Dye_Card_Move ');
//      Sql.Add('@PCID=' + quotedstr(trim(maxId)));
//      Open;
//    end;
//    if ADOQueryCmd.FieldByName('intReturn').AsInteger = -1 then
//    begin
//      raise Exception.Create(pchar(trim(ADOQueryCmd.FieldByName('ShowMsg').AsString)));
//    end;
//    ADOQueryCmd.Connection.CommitTrans;
//    CDS_3.EnableConstraints;
//  except
//    ADOQueryCmd.Connection.RollbackTrans;
//    CDS_3.EnableConstraints;
//    application.MessageBox(PChar(Exception(ExceptObject).Message), '提示信息', 0);
//  end;
//
//  InitCard();
////  InitRepairCard('');
//end;

procedure TfrmDyePlanCardInput.Button2Click(Sender: TObject);
var
  i, k, fhxInt: integer;
  maxId, maxno, KZmaxID: string;
  mQRCode: string;
begin

  if trim(C_Name.Text) = '' then
  begin
    application.MessageBox('产品名称不能为空！', '提示信息', MB_ICONERROR);
    exit;
  end;
  if (StrToFloatDef(PCPiece.Text, 0) + StrToFloatDef(PCQty.Text, 0)) = 0 then
  begin
    application.MessageBox('开卡匹数、数量不能都为零！', '提示信息', MB_OK);
    exit;
  end;
  if DTMPSlist.Text = '' then
  begin
    application.MessageBox('产品工序不能为空！', '提示信息', MB_OK);
    exit;
  end;

  if GetLSNo(ADOQueryCmd, KZmaxID, 'KZ', 'Dye_Plan_Card_KZ', 3, 1) = False then
  begin
    Application.MessageBox('取最大号失败!', '提示', 0);
    Exit;
  end;

  if strtointdef(trim(carNum.text), 0) <= 1 then
    k := 1
  else
    k := strtointdef(trim(carNum.text), 0);
  CDS_Color.Locate('C_Color', C_Color.Text, []);
  CDS_1.Last;
  for i := 1 to k do
  begin
    if GetLSNo(ADOQueryCmd, maxId, 'CZ', 'Dye_Plan_Card', 3, 1) = False then
    begin
      Application.MessageBox('取最大号失败!', '提示', 0);
      Exit;
    end;
    FPCIDS := FPCIDS + maxId + ';';

//    if not GetLSNo(ADOQueryCmd, maxno, 'PC', 'BS_Cloth_IO', 3, 1) then
//      raise Exception.Create('取染色坯布出库编号失败！');

    mQRCode := FC_Name + '|' + OrderNo.Text + '|0|';
    mQRCode := mQRCode + FormatDateTime('yyyymmddhhnnss', SGetServerDateTime(ADOQueryBaseTemp));
    mQRCode := mQRCode + '|0|';
    mQRCode := mQRCode + OrderNo.Text + '*0|0';

    try
      ADOQueryCmd.Connection.BeginTrans;

      with ADOQueryCmd do
      begin
        Close;
        Sql.Clear;
        Sql.Add('select * from Dye_Plan_Card A where 1=2');
        Open;
        Append;
        FieldByName('OrderNo').Value := OrderNo.Text;
//        FieldByName('SubId').Value := CDS_Color.FieldByName('SubId').Value;
        FieldByName('Mainid').Value := FMainid;
//        FieldByName('BCIOID').Value := maxno;
        FieldByName('Filler').Value := trim(DName);
        FieldByName('Workshop').Value := trim(FWorkshop);
        FieldByName('PCType').Value := trim(PCType.Text);
        FieldByName('PCID').Value := trim(maxId);
        FieldByName('KaZu').Value := trim(KZmaxID);
        FieldByName('PCTime').Value := formatdateTime('yyyy-MM-dd', PCTime.DateTime);
        FieldByName('GC_BatchNo').Value := trim(FGC_BatchNo);
        FieldByName('GC_Piece').Value := trim(FGC_Piece);
        FieldByName('GC_STKID').Value := trim(FGC_STKID);
        FieldByName('GC_Position').Value := trim(FGC_Position);
        FieldByName('DTMPSlist').Value := trim(DTMPSlist.Text);
        FieldByName('DTMID').Value := Trim(DTMID.Text);
        FieldByName('C_description').Value := trim(C_description.Text);
        FieldByName('bzunit').Value := trim(Fbzunit);

        FieldByName('CINote').Value := trim(CINote.Text);
//        FieldByName('STATUS').Value := '9';

        FieldByName('CustNo').Value := trim(FFromCoNo);
        FieldByName('CustName').Value := trim(FFromCoName);
        FieldByName('Saleser').Value := trim(FSaleser);
        FieldByName('C_Name').Value := trim(FC_Name);
        FieldByName('C_Code').Value := trim(FC_Code);
        FieldByName('C_GramWeight').Value := trim(C_GramWeight.Text);
        FieldByName('F_Name').Value := trim(F_Name.Text);
        FieldByName('C_Width').Value := trim(C_Width.Text);
        FieldByName('C_Color').Value := trim(C_Color.Text);
        FieldByName('PCUnit').Value := trim(OrdUnit.Text);
        FieldByName('C_ColorNo').Value := trim(C_ColorNo.Text);
        FieldByName('PCPiece').Value := StrtoIntDef(PCPiece.Text, 0);
        FieldByName('PCQty').Value := StrtoFloatDef(PCQty.Text, 0);
//        ShowMessage(FieldByName('PCQty').Value);
        FieldByName('batchno').Value := INTTOSTR(k) + '-' + INTTOSTR(i);

        FieldByName('QRCode').Value := trim(mQRCode);
        FieldByName('PrtCount').Value := 0;
        post;
      end;

      with ADOQueryCmd do
      begin
        Close;
        Sql.Clear;
        //开卡出库
        Sql.Add('exec P_Dye_GreyCloth_Out ');
        Sql.Add('@PCID=' + quotedstr(trim(maxId)));
        Sql.Add(',@Filler=' + quotedstr(trim(DName)));
//        ShowMessage(sql.Text);
        Open;
      end;
      if ADOQueryCmd.FieldByName('intReturn').AsInteger = -1 then
      begin
        FGC_STKID := '';
        raise Exception.Create(pchar(trim(ADOQueryCmd.FieldByName('ShowMsg').AsString)));
      end;

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

  end;

  with ADOQueryCmd do
  begin
    Close;
    Sql.Clear;
    //更新总卡号分卡号
    Sql.Add('exec P_Dye_Plan_UpdateOrderNo ');
    Sql.Add('@KaZu=' + quotedstr(Trim(KZmaxID)));
    Open;
  end;

  with ADOQueryCmd do
  begin
    Close;
    Sql.Clear;
    //开卡  插入待排产数据
    Sql.Add('exec P_Dye_Cloth_GX @carno=' + QuotedStr(trim(KZmaxID)));
    sql.add(',@dname=' + QuotedStr(trim(dname)));
    SQL.Add(',@C_Name=' + QuotedStr(Trim(C_Name.Text)));
    SQL.Add(',@OrderNo=' + QuotedStr(Trim(OrderNo.Text)));
    SQL.Add(',@DTMID=' + QuotedStr(Trim(DTMID.Text)));
//    showMessage(SQL.Text);
    execsql;
  end;

  with ADOQueryCmd do
  begin
    SQL.Clear;
    //备份开卡工艺数据，以便区分
    SQL.Add('EXEC P_InsertGxToKaika @PCID = ' + quotedstr(trim(KZmaxID)));
    ExecSQL;
  end;

  InitCard();
  InitGreyClothStk();
end;

procedure TfrmDyePlanCardInput.C_COLORChange(Sender: TObject);
begin
  CDS_Color.Locate('C_Color', C_Color.Text, []);
  C_COLOR.Text := CDS_Color.FieldByName('C_COLOR').AsString;
  OrdQty.Text := CDS_Color.FieldByName('C_PlanQty').AsString;
  OrdUnit.Text := CDS_Color.FieldByName('C_Unit').AsString;
  C_COLORNO.Text := CDS_Color.FieldByName('C_COLORNO').AsString;
end;

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

procedure TfrmDyePlanCardInput.FormCreate(Sender: TObject);
begin
  inherited;
  PCTime.Date := DServerDate;
end;

procedure TfrmDyePlanCardInput.FormShow(Sender: TObject);
begin
  inherited;
  ReadCxGrid(self.Caption + 'TV1', Tv1, '生产指示单管理');
  ReadCxGrid(self.Caption + 'TV2', Tv2, '生产指示单管理');
  ReadCxGrid(self.Caption + 'TV3', Tv3, '生产指示单管理');
  InitOrder();
  InitCard();
  InitGreyClothStk();
//  InitRepairCard('');
  KeyPreview := True;
end;

procedure TfrmDyePlanCardInput.ToolButton1Click(Sender: TObject);
var
  MPCIDS: string;
begin
  if CDS_1.Locate('SSel', True, []) = False then
  begin
    Application.MessageBox('没有选择数据!', '提示', 0);
    Exit;
  end;
  with CDS_1 do
  begin
    DisableControls;
    First;
    while not Eof do
    begin
      if Fieldbyname('Ssel').AsBoolean then
      begin
        MPCIDS := MPCIDS + trim(CDS_1.FieldByName('PCID').AsString) + ';';
      end;
      Next;
    end;
    EnableControls;
  end;

  with ADOQueryTmp do
  begin
    close;
    sql.Clear;
    sql.Add('select distinct GX=[dbo].[F_Dye_Card_GlideList](A.RTValue) from [dbo].[F_Tool_SplitString](' + quotedstr(MPCIDS) + ','';'')  A ');
    open;
  end;

  if ADOQueryTmp.RecordCount > 1 then
  begin
    Application.MessageBox('请选择相同工序的卡编辑!', '提示', 0);
    Exit;
  end;

  try
    frmDyeCardGlideEdit := TfrmDyeCardGlideEdit.Create(Application);
    with frmDyeCardGlideEdit do
    begin
      FPCIDS := MPCIDS;
      fname := SELF.CDS_1.FieldByName('c_name').AsString;
      FWorkshop := self.FWorkshop;
      if ShowModal = 1 then
      begin
        InitCard();
      end;
    end;
  finally
    frmDyeCardGlideEdit.Free;
  end;

end;

procedure TfrmDyePlanCardInput.ToolButton2Click(Sender: TObject);
begin
  WriteCxGrid(self.Caption + 'TV1', Tv1, '生产指示单管理');
  WriteCxGrid(self.Caption + 'TV2', Tv2, '生产指示单管理');
  WriteCxGrid(self.Caption + 'TV3', Tv3, '生产指示单管理');

end;

procedure TfrmDyePlanCardInput.ToolButton3Click(Sender: TObject);
begin
  close;
end;

procedure TfrmDyePlanCardInput.ToolButton4Click(Sender: TObject);
begin
  if CDS_1.IsEmpty then
    exit;
  if CDS_1.Locate('SSel', True, []) = False then
  begin
    Application.MessageBox('没有选择数据!', '提示', 0);
    Exit;
  end;
  if Application.MessageBox('确定要删除数据吗？', '提示', 32 + 4) <> IDYES then
    Exit;

  try
    with CDS_1 do
    begin
      DisableControls;
      First;
      while not Eof do
      begin
        if Fieldbyname('Ssel').AsBoolean then
        begin
          try
            ADOQueryCmd.Connection.BeginTrans;

//            with ADOQueryCmd do
//            begin
//              Close;
//              Sql.Clear;
//              Sql.Add('exec P_BS_Cloth_Out_Del ');
//              Sql.Add(' @BCIOIDS=' + quotedstr(Trim(CDS_1.fieldbyname('BCIOID').AsString)));
//              Sql.Add(',@DCode=' + quotedstr(Trim(CDS_1.fieldbyname('C_Code').AsString)));
//              Sql.Add(',@DName=' + quotedstr(Trim(CDS_1.fieldbyname('C_Name').AsString)));
//              Open;
//            end;
//            if ADOQueryCmd.FieldByName('intReturn').AsInteger = -1 then
//              raise Exception.Create(pchar(trim(ADOQueryCmd.FieldByName('ShowMsg').AsString)));

            with ADOQueryCmd do
            begin
              Close;
              Sql.Clear;
              //删除流程卡
              Sql.Add('exec P_Dye_Card_Del ');
              Sql.Add('@PCIDS=' + quotedstr(Trim(CDS_1.fieldbyname('PCID').AsString)));
              Sql.Add(',@DCode=' + quotedstr(Trim(CDS_1.fieldbyname('C_Code').AsString)));
              Sql.Add(',@DName=' + quotedstr(Trim(CDS_1.fieldbyname('C_Name').AsString)));
              Open;
            end;
            if ADOQueryCmd.FieldByName('intReturn').AsInteger = -1 then
              raise Exception.Create(pchar(trim(ADOQueryCmd.FieldByName('ShowMsg').AsString)));

            with ADOQueryTmp do
            begin
              Close;
              SQL.Clear;
              SQL.Add('select * from Dye_Plan_card where KaZu = ' + QuotedStr(Trim(CDS_1.FieldByName('KaZu').AsString)));
              Open;
            end;
            //最后卡组最后一张卡删除，清除卡组数据
            if ADOQueryTmp.IsEmpty then
            begin
              with ADOQueryCmd do
              begin
                Close;
                Sql.Clear;
                Sql.Add('delete from Dye_Plan_glide where PCID = ' + quotedstr(Trim(CDS_1.fieldbyname('KaZu').AsString)));
                ExecSQL;
              end;

              with ADOQueryCmd do
              begin
                Close;
                Sql.Clear;
                //删除存储开卡工艺
                Sql.Add('delete from Bs_Cloth_GY_Main_Kaika where PCID = ' + quotedstr(Trim(CDS_1.fieldbyname('KaZu').AsString)));
                ExecSQL;
              end;

              with ADOQueryCmd do
              begin
                Close;
                Sql.Clear;
                //删除存储开卡工艺
                Sql.Add('delete from Bs_Cloth_GY_Sub_Kaika where PCID = ' + quotedstr(Trim(CDS_1.fieldbyname('KaZu').AsString)));
                ExecSQL;
              end;
            end;
           //取消限制正常卡
//            if (Trim(CDS_1.fieldbyname('PCType').AsString) = '正常卡') then
//            begin
            with ADOQueryCmd do
            begin
              Close;
              Sql.Clear;
                //删除出库记录并且更新库存
              Sql.Add('exec P_Dye_GreyCloth_Out_Del ');
              Sql.Add('@PCID=' + quotedstr(Trim(CDS_1.fieldbyname('PCID').AsString)));
              Open;
            end;

            if ADOQueryCmd.FieldByName('intReturn').AsInteger = -1 then
              raise Exception.Create(pchar(trim(ADOQueryCmd.FieldByName('ShowMsg').AsString)));
//            end;
//            else
//            begin
//              with ADOQueryCmd do
//              begin
//                Close;
//                Sql.Clear;
//                Sql.Add('exec P_Dye_Card_Move_Del ');
//                Sql.Add('@PCID=' + quotedstr(Trim(CDS_1.fieldbyname('PCID').AsString)));
//                Open;
//              end;
//              if ADOQueryCmd.FieldByName('intReturn').AsInteger = -1 then
//                raise Exception.Create(pchar(trim(ADOQueryCmd.FieldByName('ShowMsg').AsString)));
//            end;

            ADOQueryCmd.Connection.CommitTrans;
          except
            ADOQueryCmd.Connection.RollbackTrans;
            raise Exception.Create(PChar(Exception(ExceptObject).Message));
          end;
        end;

        Next;
        EnableControls;
      end;
      with ADOQueryCmd do
      begin
        Close;
        Sql.Clear;
        //更新总卡号分卡号
        Sql.Add('exec P_Dye_Plan_UpdateOrderNo ');
        Sql.Add('@KaZu=' + quotedstr(Trim(CDS_1.fieldbyname('KaZu').AsString)));
        Open;
      end;

      InitCard();
      InitGreyClothStk();
    end;
  except
    CDS_1.EnableControls;
    application.MessageBox(PChar(Exception(ExceptObject).Message), '提示信息', 0);
  end;

end;

procedure TfrmDyePlanCardInput.ToolButton5Click(Sender: TObject);
var
  HasSaved: Boolean; // 记录是否成功保存
begin

  OrderNo.SetFocus;
  HasSaved := False; // 初始化标志

  try
    CDS_1.DisableControls;
    CDS_1.First;
    while not CDS_1.Eof do
    begin
//      if CDS_1.Fieldbyname('Ssel').AsBoolean then
//      begin
      ADOQueryCmd.Connection.BeginTrans;
      try
        with ADOQueryCmd do
        begin
          close;
          sql.Clear;
          sql.Add('select * from Dye_Plan_Card A');
          sql.Add('where PCID=''' + trim(CDS_1.fieldbyname('PCID').AsString) + '''');
          open;
          edit;
          FieldByName('Editer').Value := Trim(DName);
          FieldByName('EditTime').Value := SGetServerDateTime(ADOQueryTmp);
          RTSetSaveDataCDS(ADOQueryCmd, Tv1, CDS_1, 'Dye_Plan_Card', 0);
          post;
        end;

        if (Trim(CDS_1.fieldbyname('PCType').AsString) = '正常卡') or (Trim(CDS_1.fieldbyname('PCType').AsString) = '前道卡') then
        begin
          with ADOQueryCmd do
          begin
            Close;
            Sql.Clear;
            Sql.Add('exec P_Dye_GreyCloth_Out_Del ');
            Sql.Add('@PCID=' + quotedstr(Trim(CDS_1.fieldbyname('PCID').AsString)));
            Open;
          end;
          if ADOQueryCmd.FieldByName('intReturn').AsInteger = -1 then
            raise Exception.Create(pchar(trim(ADOQueryCmd.FieldByName('ShowMsg').AsString)));
          with ADOQueryCmd do
          begin
            Close;
            Sql.Clear;
            Sql.Add('exec P_Dye_GreyCloth_Out ');
            Sql.Add('@PCID=' + quotedstr(Trim(CDS_1.fieldbyname('PCID').AsString)));
            Sql.Add(',@Filler=' + quotedstr(trim(DName)));
            Open;
          end;
          if ADOQueryCmd.FieldByName('intReturn').AsInteger = -1 then
          begin
            raise Exception.Create(pchar(trim(ADOQueryCmd.FieldByName('ShowMsg').AsString)));
          end;
        end
        else
        begin
          with ADOQueryCmd do
          begin
            Close;
            Sql.Clear;
            Sql.Add('exec P_Dye_Card_Move ');
            Sql.Add('@PCID=' + quotedstr(Trim(CDS_1.fieldbyname('PCID').AsString)));
            Open;
          end;
          if ADOQueryCmd.FieldByName('intReturn').AsInteger = -1 then
          begin
            raise Exception.Create(pchar(trim(ADOQueryCmd.FieldByName('ShowMsg').AsString)));
          end;
        end;

        ADOQueryCmd.Connection.CommitTrans;
        HasSaved := True; // 标记有保存操作
      except
        ADOQueryCmd.Connection.RollbackTrans;
        raise Exception.Create(PChar(Exception(ExceptObject).Message));
      end;
//      end;
      CDS_1.Next;
    end;
    CDS_1.EnableControls;

    // 显示保存成功提示
    if HasSaved then
    begin
      Application.MessageBox('保存成功！', '提示信息', MB_OK + MB_ICONINFORMATION);
    end;

    InitCard();
    InitGreyClothStk();
  except
    CDS_1.EnableControls;
    application.MessageBox(PChar(Exception(ExceptObject).Message), '提示信息', MB_OK + MB_ICONERROR);
  end;
end;
//procedure TfrmDyePlanCardInput.ToolButton5Click(Sender: TObject);
//begin
//
//  try
//    CDS_1.DisableControls;
//    CDS_1.First;
//    while not CDS_1.Eof do
//    begin
//      if CDS_1.Fieldbyname('Ssel').AsBoolean then
//      begin
//        ADOQueryCmd.Connection.BeginTrans;
//        try
//          with ADOQueryCmd do
//          begin
//            close;
//            sql.Clear;
//            sql.Add('select * from Dye_Plan_Card A');
//            sql.Add('where PCID=''' + trim(CDS_1.fieldbyname('PCID').AsString) + '''');
//            open;
//            edit;
//            FieldByName('Editer').Value := Trim(DName);
//            FieldByName('EditTime').Value := SGetServerDateTime(ADOQueryTmp);
//            RTSetSaveDataCDS(ADOQueryCmd, Tv1, CDS_1, 'Dye_Plan_Card', 0);
//            post;
//          end;
//
//          if (Trim(CDS_1.fieldbyname('PCType').AsString) = '正常卡') or (Trim(CDS_1.fieldbyname('PCType').AsString) = '前道卡') then
//          begin
//            with ADOQueryCmd do
//            begin
//              Close;
//              Sql.Clear;
//              Sql.Add('exec P_Dye_GreyCloth_Out_Del ');
//              Sql.Add('@PCID=' + quotedstr(Trim(CDS_1.fieldbyname('PCID').AsString)));
//              Open;
//            end;
//            if ADOQueryCmd.FieldByName('intReturn').AsInteger = -1 then
//              raise Exception.Create(pchar(trim(ADOQueryCmd.FieldByName('ShowMsg').AsString)));
//            with ADOQueryCmd do
//            begin
//              Close;
//              Sql.Clear;
//              Sql.Add('exec P_Dye_GreyCloth_Out ');
//              Sql.Add('@PCID=' + quotedstr(Trim(CDS_1.fieldbyname('PCID').AsString)));
//              Sql.Add(',@Filler=' + quotedstr(trim(DName)));
//              Open;
//            end;
//            if ADOQueryCmd.FieldByName('intReturn').AsInteger = -1 then
//            begin
//              raise Exception.Create(pchar(trim(ADOQueryCmd.FieldByName('ShowMsg').AsString)));
//            end;
//          end
//          else
//          begin
//            with ADOQueryCmd do
//            begin
//              Close;
//              Sql.Clear;
//              Sql.Add('exec P_Dye_Card_Move ');
//              Sql.Add('@PCID=' + quotedstr(Trim(CDS_1.fieldbyname('PCID').AsString)));
//              Open;
//            end;
//            if ADOQueryCmd.FieldByName('intReturn').AsInteger = -1 then
//            begin
//              raise Exception.Create(pchar(trim(ADOQueryCmd.FieldByName('ShowMsg').AsString)));
//            end;
//          end;
//
//          ADOQueryCmd.Connection.CommitTrans;
//        except
//          ADOQueryCmd.Connection.RollbackTrans;
//          raise Exception.Create(PChar(Exception(ExceptObject).Message));
//        end;
//      end;
//      CDS_1.Next;
//    end;
//    CDS_1.EnableControls;
//    InitCard();
//    InitGreyClothStk();
//  except
//    CDS_1.EnableControls;
//    application.MessageBox(PChar(Exception(ExceptObject).Message), '提示信息', 0);
//  end;
//
//end;

procedure TfrmDyePlanCardInput.TV2DblClick(Sender: TObject);
begin
  inherited;
//  if OrderNo.Text = '' then
//  begin
//    Exit;
//  end;
  with ADOQueryTmp do
  begin
    Close;
    sql.Clear;
    SQL.Add(' select * from BS_Cloth_info where C_Name = ' + QuotedStr(Trim(CDS_2.FieldByName('C_Name').Value)));
    Open;
  end;

  OrderNo.Text := CDS_2.FieldByName('OrderNo').AsString;
  F_Name.Text := CDS_2.FieldByName('F_Name').AsString;
  C_Width.Text := ADOQueryTmp.FieldByName('C_Width').AsString;

  C_GramWeight.Text := ADOQueryTmp.FieldByName('C_GramWeight').AsString;
  C_Color.Text := ADOQueryTmp.FieldByName('C_Color').AsString;
  C_COLORNO.Text := ADOQueryTmp.FieldByName('C_COLORNO').AsString;
  C_Name.Text := ADOQueryTmp.FieldByName('C_Name').AsString;
  if CDS_2.FieldByName('note').AsString <> '' then
  begin
    CINote.Text := CDS_2.FieldByName('note').AsString + '/' + ADOQueryTmp.FieldByName('CINote').AsString;
  end
  else
  begin
    CINote.Text := ADOQueryTmp.FieldByName('CINote').AsString;
  end;

//  CINote.Text := ADOQueryTmp.FieldByName('CINote').AsString;
  PCType.Text := '正常卡';

  carnum.Text := '1';
  PCPiece.Text := CDS_2.FieldByName('StkPiece').AsString;
  PCQty.Text := CDS_2.FieldByName('STKQty').AsString;

  C_description.Text := CDS_2.FieldByName('C_description').AsString;

  if (ADOQueryTmp.FieldByName('DTMID').AsString = '') or (ADOQueryTmp.FieldByName('DTMID').AsString = null) then
  begin
    Application.MessageBox('未设置默认工序！', '提示信息', MB_OK);
  end;

  DTMID.Text := ADOQueryTmp.FieldByName('DTMID').AsString;
  with ADOQueryCmd do
  begin
    Close;
    sql.Clear;
    SQL.Add(' select * from Dye_Technics_Main where DTMID = ' + QuotedStr(Trim(DTMID.Text)));
    Open;
  end;
  DTMPSlist.Text := ADOQueryCmd.FieldByName('DTMPSlist').AsString;
  FC_Code := ADOQueryTmp.FieldByName('C_Code').AsString;
  FC_Name := ADOQueryTmp.FieldByName('C_Name').AsString;
//  C_Width.Text := ADOQueryTmp.FieldByName('C_Width').Value;
//  C_Width.Text := ADOQueryTmp.FieldByName('C_Width').Value;

  InitGreyClothStk();
end;

//procedure TfrmDyePlanCardInput.TV3Column1PropertiesEditValueChanged(Sender: TObject);
//var
//  mvalue: string;
//begin
//
//  mvalue := TcxTextEdit(Sender).EditingText;
//  with CDS_3 do
//  begin
//    Edit;
//    FieldByName('MvPiece').Value := STRTOFLOATDEF(mvalue, 0);
//    if FieldByName('PSC_StkPiece').AsFloat > 0 then
//      FieldByName('MvQty').Value := STRTOFLOATDEF(mvalue, 0) * (FieldByName('PSC_StkQty').AsFloat / FieldByName('PSC_StkPiece').AsFloat)
//    else
//      FieldByName('MvQty').Value := 0;
//    Post;
//
//  end;
//  Tv3.Controller.EditingController.ShowEdit();
//end;

procedure TfrmDyePlanCardInput.TV3DblClick(Sender: TObject);
begin
//  CDS_3.Delete;

end;

end.

