unit U_ContractList;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ExtCtrls, ComCtrls, ToolWin, cxStyles, cxCustomData,
  cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, ADODB,
  cxGridCustomPopupMenu, cxGridPopupMenu, cxGridLevel, cxClasses, cxControls,
  cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView,
  cxGrid, DBClient, cxCheckBox, cxCalendar, cxSplitter, RM_Dataset, RM_System,
  RM_Common, RM_Class, RM_GridReport, RM_e_Xls, Menus, cxPC, cxButtonEdit,
  cxTextEdit, cxLookAndFeels, cxLookAndFeelPainters, cxNavigator,
  dxBarBuiltInMenu, ComObj;

type
  FdDy = record
    inc: integer; //客户端套接字句柄
    FDdys: string[32]; //客户端套接字
    FdDysName: string[32]; //客户端套接字
  end;

  TfrmContractList = class(TForm)
    ToolBar1: TToolBar;
    TBRafresh: TToolButton;
    TBFind: TToolButton;
    TBAdd: TToolButton;
    TBEdit: TToolButton;
    TBDel: TToolButton;
    TBPrint: TToolButton;
    TBClose: TToolButton;
    Tv1: TcxGridDBTableView;
    cxGrid1Level1: TcxGridLevel;
    cxGrid1: TcxGrid;
    cxGridPopupMenu1: TcxGridPopupMenu;
    ADOQueryCmd: TADOQuery;
    ADOQueryMain: TADOQuery;
    ADOQueryTemp: TADOQuery;
    DataSource1: TDataSource;
    TBExport: TToolButton;
    v1OrdDate: TcxGridDBColumn;
    v1DeliveryDate: TcxGridDBColumn;
    v1OrdPerson1: TcxGridDBColumn;
    v1ConNo: TcxGridDBColumn;
    v1MPRTSpec: TcxGridDBColumn;
    Order_Main: TClientDataSet;
    RM1: TRMGridReport;
    RMDBDataSet1: TRMDBDataSet;
    RMXLSExport1: TRMXLSExport;
    v1CustomerNoName: TcxGridDBColumn;
    v1PRTOrderQty: TcxGridDBColumn;
    PopupMenu1: TPopupMenu;
    N2: TMenuItem;
    ToolButton1: TToolButton;
    v1OrdDefStr1: TcxGridDBColumn;
    v1Column1: TcxGridDBColumn;
    ToolButton2: TToolButton;
    ADOQueryPrint: TADOQuery;
    CDS_Print: TClientDataSet;
    v1Column4: TcxGridDBColumn;
    PopupMenu2: TPopupMenu;
    N11: TMenuItem;
    N21: TMenuItem;
    N31: TMenuItem;
    Panel1: TPanel;
    Label1: TLabel;
    Label4: TLabel;
    Label5: TLabel;
    Label8: TLabel;
    Label9: TLabel;
    Label12: TLabel;
    Label13: TLabel;
    BegDate: TDateTimePicker;
    EndDate: TDateTimePicker;
    CustomerNoName: TEdit;
    ConPerson1: TEdit;
    MPRTCodeName: TEdit;
    ConNo: TEdit;
    MPRTKZ: TEdit;
    MPRTMF: TEdit;
    v1Column2: TcxGridDBColumn;
    ToolButton4: TToolButton;
    Label2: TLabel;
    v1Column3: TcxGridDBColumn;
    cxTabControl1: TcxTabControl;
    Tchk: TToolButton;
    Tnochk: TToolButton;
    cxSplitter1: TcxSplitter;
    cxGrid2: TcxGrid;
    TV2: TcxGridDBTableView;
    v1Column5: TcxGridDBColumn;
    v1Column6: TcxGridDBColumn;
    v1PRTColor: TcxGridDBColumn;
    cxGridDBColumn1: TcxGridDBColumn;
    cxGridDBColumn2: TcxGridDBColumn;
    v1Column7: TcxGridDBColumn;
    v1Column8: TcxGridDBColumn;
    cxGridDBColumn3: TcxGridDBColumn;
    v1OrderUnit: TcxGridDBColumn;
    v1PRTPrice: TcxGridDBColumn;
    v1PriceUnit: TcxGridDBColumn;
    cxGridDBColumn4: TcxGridDBColumn;
    cxGridDBColumn5: TcxGridDBColumn;
    cxGridLevel1: TcxGridLevel;
    ADOQuerySub: TADOQuery;
    DataSource2: TDataSource;
    KHConNO: TEdit;
    Label3: TLabel;
    TQX: TToolButton;
    TNOQX: TToolButton;
    ToolButton3: TToolButton;
    v1Column9: TcxGridDBColumn;
    Label6: TLabel;
    v1ConMoney: TcxGridDBColumn;
    ThreeColorBase: TcxStyleRepository;
    SHuangSe: TcxStyle;
    SkyBlue: TcxStyle;
    Default: TcxStyle;
    QHuangSe: TcxStyle;
    Red: TcxStyle;
    FontBlue: TcxStyle;
    TextSHuangSe: TcxStyle;
    FonePurple: TcxStyle;
    FoneClMaroon: TcxStyle;
    FoneRed: TcxStyle;
    RowColor: TcxStyle;
    handBlack: TcxStyle;
    cxBlue: TcxStyle;
    cxStyle1: TcxStyle;
    v1Column10: TcxGridDBColumn;
    V2Column1: TcxGridDBColumn;
    V2Column3: TcxGridDBColumn;
    V2Column4: TcxGridDBColumn;
    V2Column2: TcxGridDBColumn;
    V2Column5: TcxGridDBColumn;
    ToolButton5: TToolButton;
    OpenDialog1: TOpenDialog;
    cxGrid3: TcxGrid;
    TV3: TcxGridDBTableView;
    TV3Column2: TcxGridDBColumn;
    TV3Column1: TcxGridDBColumn;
    cxGridDBColumn6: TcxGridDBColumn;
    cxGridDBColumn7: TcxGridDBColumn;
    cxGridDBColumn11: TcxGridDBColumn;
    cxGridDBColumn13: TcxGridDBColumn;
    cxGridLevel2: TcxGridLevel;
    ToolButton6: TToolButton;
    N1: TMenuItem;
    ToolButton7: TToolButton;
    TV2Column1: TcxGridDBColumn;
    ToolButton8: TToolButton;
    Order_sub: TClientDataSet;
    Tv1Column1: TcxGridDBColumn;
    ToolButton9: TToolButton;
    TV3Column3: TcxGridDBColumn;
    TV3Column4: TcxGridDBColumn;
    cxGrid4: TcxGrid;
    TV4: TcxGridDBTableView;
    cxGridDBColumn8: TcxGridDBColumn;
    cxGridDBColumn9: TcxGridDBColumn;
    cxGridDBColumn10: TcxGridDBColumn;
    cxGridDBColumn12: TcxGridDBColumn;
    cxGridDBColumn14: TcxGridDBColumn;
    cxGridDBColumn15: TcxGridDBColumn;
    cxGridDBColumn16: TcxGridDBColumn;
    cxGridDBColumn17: TcxGridDBColumn;
    cxGridLevel3: TcxGridLevel;
    Panel2: TPanel;
    Label7: TLabel;
    Button2: TButton;
    Button3: TButton;
    Edit1: TEdit;
    ToolButton10: TToolButton;
    Cds_Print1: TClientDataSet;
    procedure FormDestroy(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure FormCreate(Sender: TObject);
    procedure TBCloseClick(Sender: TObject);
    procedure TBFindClick(Sender: TObject);
    procedure TBEditClick(Sender: TObject);
    procedure TBDelClick(Sender: TObject);
    procedure TBExportClick(Sender: TObject);
    procedure TBPrintClick(Sender: TObject);
    procedure TBRafreshClick(Sender: TObject);
    procedure TBAddClick(Sender: TObject);
    procedure FormShow(Sender: TObject);
    procedure Tv1CellDblClick(Sender: TcxCustomGridTableView; ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton; AShift: TShiftState; var AHandled: Boolean);
    procedure TBTPClick(Sender: TObject);
    procedure CheckBox1Click(Sender: TObject);
    procedure CheckBox2Click(Sender: TObject);
    procedure Tv1StylesGetContentStyle(Sender: TcxCustomGridTableView; ARecord: TcxCustomGridRecord; AItem: TcxCustomGridTableItem; out AStyle: TcxStyle);
    procedure v1DeliveryDateCustomDrawCell(Sender: TcxCustomGridTableView; ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean);
    procedure N1Click(Sender: TObject);
    procedure N2Click(Sender: TObject);
    procedure ToolButton1Click(Sender: TObject);
    procedure ToolButton2Click(Sender: TObject);
    procedure CustomerNoNameChange(Sender: TObject);
    procedure ConNoKeyPress(Sender: TObject; var Key: Char);
    procedure ToolButton4Click(Sender: TObject);
    procedure cxTabControl1Change(Sender: TObject);
    procedure TchkClick(Sender: TObject);
    procedure TnochkClick(Sender: TObject);
    procedure Tv1FocusedRecordChanged(Sender: TcxCustomGridTableView; APrevFocusedRecord, AFocusedRecord: TcxCustomGridRecord; ANewItemRecordFocusingChanged: Boolean);
    procedure TQXClick(Sender: TObject);
    procedure TNOQXClick(Sender: TObject);
    procedure ToolButton3Click(Sender: TObject);
    procedure Tv1CustomDrawCell(Sender: TcxCustomGridTableView; ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean);
    procedure ToolButton5Click(Sender: TObject);
    procedure ToolButton6Click(Sender: TObject);
    procedure ToolButton7Click(Sender: TObject);
    procedure ToolButton8Click(Sender: TObject);
    procedure ToolButton9Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure Button3Click(Sender: TObject);
    procedure ToolButton10Click(Sender: TObject);
  private
    DQdate: TDateTime;
    fuserName: string;
    procedure InitGrid();
    procedure InitForm();
    function DelData(): Boolean;
    procedure InitGridFH();
    procedure SetStatus();
    procedure InitSub();
    { Private declarations }
  public
    FFInt, FCloth: Integer;

    { Public declarations }
  end;

var
  frmContractList: TfrmContractList;
  dFdDy: array[0..120] of FdDy;

implementation

uses
  U_DataLink, U_ConInPut, U_Fun, U_ZDYHelp, U_FjList_RZ, U_LabelList,
  U_LabelListts;

{$R *.dfm}
procedure TfrmContractList.InitSub();
begin
  ADOQuerySub.Close;
  if Order_Main.IsEmpty then
    exit;
  with ADOQuerySub do
  begin
    close;
    sql.Clear;
    sql.Add('select A.*,IScZ=isnull((select count(MainID) from JYOrder_Sub X where X.Sorddefstr10=A.subID),0) from JYOrderCon_sub A ');
    sql.Add('where mainID =' + quotedstr((Order_Main.fieldbyname('mainID').AsString)));
    open;
  end;
  SCreateCDS20(ADOQuerySub, Order_sub);
  SInitCDSData20(ADOQuerySub, Order_sub);
end;

procedure TfrmContractList.SetStatus();
begin

  tchk.Visible := false;
  tnochk.Visible := false;
  tbedit.Visible := false;
  tbdel.Visible := false;
  Tqx.Visible := false;
  TNoqx.Visible := false;
 { if Trim(DParameters1)<>'高权限'  then
  begin
    case cxTabControl1.TabIndex of
    0:begin
       IF trim(DCode)<>'A2' then
       begin
         tbedit.Visible:=true;
         tbdel.Visible:=true;
       end;
        Tqx.Visible:=true;
      end;
    1:begin
        Tqx.Visible:=true;
      end;
    2:begin
        TNoqx.Visible:=true;
      end;
    3:begin
      end;
    end;
  end
  else
  begin
    case cxTabControl1.TabIndex of
    0:begin
       tchk.Visible:=true;
       tbedit.Visible:=true;
       tbdel.Visible:=true;
       Tqx.Visible:=true;
      end;
    1:begin
       tnochk.Visible:=true;
       Tqx.Visible:=true;
      end;
    2:begin
        TNoqx.Visible:=true;
      end;
    3:begin
      //  TNoqx.Visible:=true;
      end;
    end;
  end; }

  case cxTabControl1.TabIndex of
    0:
      begin
        tchk.Visible := true;
        tbedit.Visible := true;
        tbdel.Visible := true;
       //Tqx.Visible:=true;
      end;
    1:
      begin
        tnochk.Visible := true;
     //  Tqx.Visible:=true;
      end;
    2:
      begin
      //  TNoqx.Visible:=true;
      end;
  end;

end;

procedure TfrmContractList.FormDestroy(Sender: TObject);
begin
  frmContractList := nil;
end;

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

procedure TfrmContractList.FormCreate(Sender: TObject);
begin
  cxgrid1.Align := alClient;
  //BegDate.DateTime:=SGetServerDateTime(ADOQueryTemp)-7;
  //EndDate.DateTime:=SGetServerDateTime(ADOQueryTemp);
  DQdate := SGetServerDate(ADOQueryTemp);
end;

procedure TfrmContractList.TBCloseClick(Sender: TObject);
begin
  Close;
  if FCloth <> 1 then
    WriteCxGrid('订单合同列表', Tv1, '生产指示单管理1')
  else
    WriteCxGrid('订单合同列表选择', Tv1, '生产指示单管理1');
end;

procedure TfrmContractList.InitGrid();
begin
  try
    ADOQueryMain.DisableControls;
    with ADOQueryMain do
    begin
      Filtered := False;
      Close;
      sql.Clear;
      sql.Add('select A.*,A.ConNo ConNoM ');
      SQL.Add(',PRTOrderQty=(select Sum(PRTOrderQty) from JYOrderCon_Sub B where B.MainId=A.MainId)');
      SQL.Add(',ConMoney=(select Sum(PRTOrderQty*PRTPrice) from JYOrderCon_Sub B where B.MainId=A.MainId)');
      SQL.Add(',OrderUnit=(select top 1 OrderUnit from JYOrderCon_Sub B where B.MainId=A.MainId)');
      SQL.Add(',PriceUnit=(select top 1 PriceUnit from JYOrderCon_Sub B where B.MainId=A.MainId)');
      SQL.Add(',PRTPrice=(select top 1 PRTPrice from JYOrderCon_Sub B where B.MainId=A.MainId)');
      sql.Add(',ISSC=cast((case when isnull((select count(WBID) from TP_File X where X.WBID=A.maiNID and X.TFType=''合同''),0)>0 then 1 else 0 end) as bit)');
      sql.Add(' from JYOrderCon_Main A  ');
  //    sql.Add(' left join Contract_Main B on B.conNO=A.conNo ');
      SQL.Add('where  A.OrdDate>=''' + FormatDateTime('yyyy-MM-dd', BegDate.DateTime) + '''');
      SQL.Add('and  A.OrdDate<''' + FormatDateTime('yyyy-MM-dd', enddate.DateTime + 1) + '''');
      sql.Add(' and A.MPRTType=''外销'' ');
      if Trim(DParameters1) <> '高权限' then
      begin
        sql.Add('and A.Filler=''' + Trim(DName) + '''');     
      end;
      if cxTabControl1.TabIndex < 2 then
      begin
        sql.Add(' and  isnull(A.status,''0'')=''' + inttostr(cxTabControl1.TabIndex) + '''');
      end;
//      ShowMessage(SQL.text);
      Open;
    end;
    SCreateCDS20(ADOQueryMain, Order_Main);
    SInitCDSData20(ADOQueryMain, Order_Main);
  finally
    ADOQueryMain.EnableControls;
  end;
end;

procedure TfrmContractList.InitGridFH();
begin
  try
    ADOQueryMain.DisableControls;
    with ADOQueryMain do
    begin
      Filtered := False;
      Close;
      sql.Clear;
      sql.Add('exec Order_QryList :MainId,:WSql');
      Parameters.ParamByName('WSql').Value := ' and FillTime>=''' + Trim(FormatDateTime('yyyy-MM-dd', BegDate.DateTime)) + '''' + ' and FillTime<''' + Trim(FormatDateTime('yyyy-MM-dd', EndDate.DateTime + 1)) + '''';
      Open;
    end;
    SCreateCDS20(ADOQueryMain, Order_Main);
    SInitCDSData20(ADOQueryMain, Order_Main);
  finally
    ADOQueryMain.EnableControls;
  end;
end;

procedure TfrmContractList.InitForm();
begin

  if FCloth <> 1 then
    ReadCxGrid('订单合同列表', Tv1, '生产指示单管理1')
  else
    ReadCxGrid('订单合同列表选择', Tv1, '生产指示单管理1');

//  if FCloth = 1 then
//  begin
//    v1Column4.Visible := True;
// //   v1PRTPrice.Visible:=False;
//   // v1PRTPrice.Hidden:=True;
//  end
//  else
//  begin
//    v1Column4.Visible := False;
//  //  v1PRTPrice.Visible:=True;
//  //  v1PRTPrice.Hidden:=False;
//  end;
  BegDate.DateTime := SGetServerDate10(ADOQueryTemp) - 30;
  EndDate.DateTime := SGetServerDate10(ADOQueryTemp);
  InitGrid();
end;

procedure TfrmContractList.TBFindClick(Sender: TObject);
begin
  if ADOQueryMain.Active = False then
    Exit;
  SDofilter(ADOQueryMain, SGetFilters(Panel1, 1, 2));
  SCreateCDS20(ADOQueryMain, Order_Main);
  SInitCDSData20(ADOQueryMain, Order_Main);
end;

procedure TfrmContractList.TBEditClick(Sender: TObject);
begin
  if Order_Main.IsEmpty then
    Exit;
  if Trim(Order_Main.fieldbyname('Filler').AsString) <> Trim(DName) then
  begin
    Application.MessageBox('不能操作他人的数据!', '提示', 0);
    Exit;
  end;
  with ADOQueryTemp do
  begin
    close;
    sql.Clear;
    sql.Add('select mainID from JYOrder_main A where ConNo=' + quotedstr(trim(Order_Main.fieldbyname('conNO').AsString)));
    open;
  end;

  try
    frmConInPut := TfrmConInPut.Create(Application);
    with frmConInPut do
    begin
      PState := 1;
      FMainId := Trim(Self.Order_Main.fieldbyname('MainId').AsString);

      if not ADOQueryTemp.IsEmpty then
      begin
        frmConInPut.ConNo.Enabled := False;
      end;

      if ShowModal = 1 then
      begin

      end;
    end;
  finally
    frmConInPut.Free;
  end;
end;

procedure TfrmContractList.TBDelClick(Sender: TObject);
begin
  if Order_Main.IsEmpty then
    Exit;
  if Trim(Order_Main.fieldbyname('Filler').AsString) <> Trim(DName) then
  begin
    Application.MessageBox('不能操作他人的数据!', '提示', 0);
    Exit;
  end;
  if Application.MessageBox('确定要删除数据吗？', '提示', 32 + 4) <> IDYES then
    Exit;
  if DelData() then
  begin
    Order_Main.Delete;
  end;
end;

function TfrmContractList.DelData(): Boolean;
begin
  try
    Result := false;
    ADOQueryCmd.Connection.BeginTrans;

    with ADOQueryCmd do
    begin
      Close;
      sql.Clear;
      sql.Add('delete JYOrderCon_Sub where MainId=''' + Trim(Order_Main.fieldbyname('MainId').AsString) + '''');
      sql.Add('delete JYOrderCon_Main where MainId=''' + Trim(Order_Main.fieldbyname('MainId').AsString) + '''');
      sql.Add('insert into SY_SysLog(operor,opertime,Model,acction,opevent,result) values( ');
      sql.Add(' ' + quotedstr(trim(DName)));
      sql.Add(',getdate() ');
      sql.Add(',' + quotedstr(trim(self.Caption)));
      sql.Add(',' + quotedstr(trim('外销合同删除')));
      sql.Add(',' + quotedstr(trim('合同号：' + trim(Order_Main.FieldByName('conNo').AsString))));
      sql.Add(',' + quotedstr(trim('成功')));
      sql.Add(')');
      ExecSQL;
    end;

    ADOQueryCmd.Connection.CommitTrans;
    Result := True;
  except
    ADOQueryCmd.Connection.RollbackTrans;
    Result := False;
    Application.MessageBox('数据删除异常！', '提示', 0);
  end;
end;

procedure TfrmContractList.TBExportClick(Sender: TObject);
begin
  if ADOQueryMain.IsEmpty then
    Exit;
  SelExportData(Tv1, ADOQueryMain, '生产指示单列表');
end;

procedure TfrmContractList.TBPrintClick(Sender: TObject);
var
  fPrintFile: string;
  EngMoney: string;
  fRMXLSExport1: TRMXLSExport;
begin
  if Order_Main.IsEmpty then
    Exit;
  fRMXLSExport1 := TRMXLSExport.Create(self);
  fPrintFile := ExtractFilePath(Application.ExeName) + 'Report\外销合同.rmf';
  with ADOQueryPrint do
  begin
    Close;
    sql.Clear;
    sql.Add('select A.*,B.*,ConMoney=B.PRTOrderQty*B.PRTPrice,COL=''COL:''  ');
    sql.Add(',Case when substring(PriceNote,1,3)=''FOB'' then '' ''+A.FromPlace else '' ''+A.ToPlace end as PriceNote10 ');
    sql.Add(',PrtImage=(select Top 1 FilesOther from TP_File X where X.WBID=B.PRTCode) ');
    sql.Add(' from JYOrderCon_Main A inner join JYOrderCon_Sub B on A.MainId=B.MainId ');
    sql.Add(' where A.MainId=''' + Trim(Order_Main.fieldbyname('MainId').AsString) + '''');
    Open;
  end;
  SCreateCDS20(ADOQueryPrint, CDS_Print);
  SInitCDSData20(ADOQueryPrint, CDS_Print);
  //
  with ADOQueryTemp do
  begin
    close;
    sql.Clear;
    sql.Add('select TolConMoney=Sum(PRTOrderQty*PRTPrice)');
    sql.Add(' from JYOrderCon_Main A inner join JYOrderCon_Sub B on A.MainId=B.MainId ');
    sql.Add(' where A.MainId=''' + Trim(Order_Main.fieldbyname('MainId').AsString) + '''');
    Open;
  end;
  EngMoney := num2cengnum(ADOQueryTemp.fieldbyname('TolConMoney').AsString);
  EngMoney := UpperCase(EngMoney);
  if FileExists(fPrintFile) then
  begin
    RMVariables['EngMoney'] := EngMoney;
   // RM1.PreviewButtons:=[pbZoom,pbLoad,pbSave,pbPrint,pbFind,pbPageSetup,pbExit,pbSaveToXLS,pbExport,pbNavigator];
    //RMVariables['enddate']:=enddate.DateTime;
    //RMVariables['printtime']:=Now;
    //RMVariables['printer']:=Trim(gUserName);
    RM1.LoadFromFile(fPrintFile);
    RM1.ShowReport;
  end
  else
  begin
    Application.MessageBox(PChar('没有找' + ExtractFilePath(Application.ExeName) + 'Report\英文合同.rmf'), '提示', 0);
  end;
  fRMXLSExport1.Free;
end;

procedure TfrmContractList.TBRafreshClick(Sender: TObject);
begin
  if FFInt = 1 then
  begin
    InitGridFH();
  end
  else
    InitGrid();
  TBFind.Click;
end;

procedure TfrmContractList.TBAddClick(Sender: TObject);
var
  maxno: string;
begin
  try
    frmConInPut := TfrmConInPut.Create(Application);
    with frmConInPut do
    begin
      PState := 0;
      FMainId := '';
      if ShowModal = 1 then
      begin

      end;
    end;
  finally
    frmConInPut.Free;
  end;
end;

procedure TfrmContractList.FormShow(Sender: TObject);
begin

  InitForm();
  SetStatus();
end;

procedure TfrmContractList.Tv1CellDblClick(Sender: TcxCustomGridTableView; ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton; AShift: TShiftState; var AHandled: Boolean);
begin
  if ToolButton1.Visible = False then
    Exit;
  ToolButton1.Click;
end;

procedure TfrmContractList.TBTPClick(Sender: TObject);
var
  FQty, FQty1, FMxQty, FPQty, FMxQtyS, FPQtyS: string;
begin
end;

procedure TfrmContractList.CheckBox1Click(Sender: TObject);
begin
  InitGrid();
end;

procedure TfrmContractList.CheckBox2Click(Sender: TObject);
begin
  TBRafresh.Click;
end;

procedure TfrmContractList.Tv1StylesGetContentStyle(Sender: TcxCustomGridTableView; ARecord: TcxCustomGridRecord; AItem: TcxCustomGridTableItem; out AStyle: TcxStyle);
var
  id, id10: Integer;
begin
  {try
    if Tv1.GroupedItemCount=0 then
    begin
      Id:=Tv1.GetColumnByFieldName('DeliveryDate').Index-tv1.GroupedItemCount;
      Id10:=Tv1.GetColumnByFieldName('SubStatus').Index-tv1.GroupedItemCount;
      if Trim(VarToStr(ARecord.Values[id]))='' then Exit;
      if Id<0 then Exit;
      if ARecord.Values[id10]='完成' then exit;
      if (ARecord.Values[id]-DQdate)>=4 then Exit;
      if ((ARecord.Values[id]-DQdate)>=0) and ((ARecord.Values[id]-DQdate)<4) then
        AStyle:=DataLink_.QHuangSe
      else
      if ARecord.Values[id]-DQdate<0 then
      begin
        AStyle:=DataLink_OrderManage.FenHongS;
      end;
    end else
    begin

    end;
  except
  end; }
end;

procedure TfrmContractList.v1DeliveryDateCustomDrawCell(Sender: TcxCustomGridTableView; ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean);
begin
 { Id:=TV1.GetColumnByFieldName('DeliveryDate').Index;//;-TV1.GroupedItemCount;
  Id10:=TV1.GetColumnByFieldName('SubStatus').Index;
  if Id<0 then Exit;
  if AViewInfo.GridRecord.Values[Id10]='完成' then Exit;
  if AViewInfo.GridRecord.Values[Id]-SGetServerDate(ADOQueryTemp)>=4 then Exit;
  if ((AViewInfo.GridRecord.Values[id]-SGetServerDate10(ADOQueryTemp))>=0) and ((AViewInfo.GridRecord.Values[id]-SGetServerDate(ADOQueryTemp))<4) then
    ACanvas.Brush.Color:=clYellow
  else
  if (AViewInfo.GridRecord.Values[id])-(SGetServerDate10(ADOQueryTemp)<0) then
  begin
    ACanvas.Brush.Color:=clRed;
  end;
  begin
    ACanvas.Brush.Color:=clRed;
  end else
  if AViewInfo.GridRecord.Values[Id]='Purple' then
  begin
    ACanvas.Brush.Color:=clPurple;
  end else
  if AViewInfo.GridRecord.Values[Id]='Olive' then
  begin
    ACanvas.Brush.Color:=clOlive;
  end else
  if AViewInfo.GridRecord.Values[Id]='Teal' then
  begin
    ACanvas.Brush.Color:=clTeal;
  end else
  if AViewInfo.GridRecord.Values[Id]='Background' then
  begin
    ACanvas.Brush.Color:=clBackground;
  end;   }
end;

procedure TfrmContractList.N1Click(Sender: TObject);
//var
//  fPrintFile: string;
//  Porderno: string;
begin
  SelOKNo(Order_Main, False);
//  if Order_Main.IsEmpty then
//    Exit;
//  fPrintFile := ExtractFilePath(Application.ExeName) + 'Report\生产指示单10.rmf';
//  SDofilter(ADOQueryMain, ' OrderNoM=''' + Trim(Order_Main.fieldbyname('OrderNoM').AsString) + '''');
//  SCreateCDS20(ADOQueryMain, Order_Main);
//  SInitCDSData20(ADOQueryMain, Order_Main);
//  Porderno := Trim(Order_Main.fieldbyname('OrderNoM').AsString);
//  if FileExists(fPrintFile) then
//  begin
//    //RMVariables['begindate']:=begindate.DateTime;
//    //RMVariables['enddate']:=enddate.DateTime;
//    //RMVariables['printtime']:=Now;
//    //RMVariables['printer']:=Trim(gUserName);
//    RM1.LoadFromFile(fPrintFile);
//    RM1.ShowReport;
//  end
//  else
//  begin
//    Application.MessageBox(PChar('没有找' + ExtractFilePath(Application.ExeName) + 'Report\生产指示单10.rmf'), '提示', 0);
//  end;
//  SDofilter(ADOQueryMain, '');
//  SCreateCDS20(ADOQueryMain, Order_Main);
//  SInitCDSData20(ADOQueryMain, Order_Main);
//  Order_Main.Locate('ordernoM', Porderno, []);
end;

procedure TfrmContractList.N2Click(Sender: TObject);
//var
//  fPrintFile: string;
//  Porderno: string;
begin
  SelOKNo(Order_Main, True);
//  if Order_Main.IsEmpty then
//    Exit;
//  fPrintFile := ExtractFilePath(Application.ExeName) + 'Report\生产指示单.rmf';
//  SDofilter(ADOQueryMain, ' OrderNoM=''' + Trim(Order_Main.fieldbyname('OrderNoM').AsString) + '''');
//  SCreateCDS20(ADOQueryMain, Order_Main);
//  SInitCDSData20(ADOQueryMain, Order_Main);
//  Porderno := Trim(Order_Main.fieldbyname('OrderNoM').AsString);
//  if FileExists(fPrintFile) then
//  begin
//    //RMVariables['begindate']:=begindate.DateTime;
//    //RMVariables['enddate']:=enddate.DateTime;
//    //RMVariables['printtime']:=Now;
//    //RMVariables['printer']:=Trim(gUserName);
//    RM1.LoadFromFile(fPrintFile);
//    RM1.ShowReport;
//  end
//  else
//  begin
//    Application.MessageBox(PChar('没有找' + ExtractFilePath(Application.ExeName) + 'Report\生产指示单.rmf'), '提示', 0);
//  end;
//  SDofilter(ADOQueryMain, '');
//  SCreateCDS20(ADOQueryMain, Order_Main);
//  SInitCDSData20(ADOQueryMain, Order_Main);
//  Order_Main.Locate('ordernoM', Porderno, []);
end;

procedure TfrmContractList.ToolButton1Click(Sender: TObject);
begin
  if Order_Main.IsEmpty then
    Exit;
  try
    frmConInPut := TfrmConInPut.Create(Application);
    with frmConInPut do
    begin
      PState := 1;
      FMainId := Trim(Self.Order_Main.fieldbyname('MainId').AsString);
      ToolBar2.Visible := False;
      TBSave.Visible := False;
      ScrollBox1.Enabled := False;
      Tv1.OptionsSelection.CellSelect := False;
      if ShowModal = 1 then
      begin

      end;
    end;
  finally
    frmConInPut.Free;
  end;
end;

procedure TfrmContractList.ToolButton2Click(Sender: TObject);
begin
  if Order_Main.IsEmpty then
    Exit;
  try
    frmConInPut := TfrmConInPut.Create(Application);
    with frmConInPut do
    begin
      PState := 1;
      CopyInt := 99;
      FMainId := Trim(Self.Order_Main.fieldbyname('MainId').AsString);
      if ShowModal = 1 then
      begin

      end;
    end;
  finally
    frmConInPut.Free;
  end;
end;

procedure TfrmContractList.CustomerNoNameChange(Sender: TObject);
begin
  if ADOQueryMain.Active = False then
    Exit;
  SDofilter(ADOQueryMain, SGetFilters(Panel1, 1, 2));
  SCreateCDS20(ADOQueryMain, Order_Main);
  SInitCDSData20(ADOQueryMain, Order_Main);
end;

procedure TfrmContractList.ConNoKeyPress(Sender: TObject; var Key: Char);
begin
  if Key = #13 then
  begin
    if Length(Tedit(Sender).Text) < 1 then
      Exit;
    try
      ADOQueryMain.DisableControls;
      with ADOQueryMain do
      begin
        Filtered := False;
        Close;
        SQL.Clear;
        sql.Add('select A.*,A.ConNo ConNoM ');
        SQL.Add(',PRTOrderQty=(select Sum(PRTOrderQty) from JYOrderCon_Sub B where B.MainId=A.MainId)');
        SQL.Add(',ConMoney=(select Sum(PRTOrderQty*PRTPrice) from JYOrderCon_Sub B where B.MainId=A.MainId)');
        SQL.Add(',OrderUnit=(select top 1 OrderUnit from JYOrderCon_Sub B where B.MainId=A.MainId)');
        SQL.Add(',PriceUnit=(select top 1 PriceUnit from JYOrderCon_Sub B where B.MainId=A.MainId)');
        SQL.Add(',PRTPrice=(select top 1 PRTPrice from JYOrderCon_Sub B where B.MainId=A.MainId)');
        SQL.Add(',case when isnull((select top 1 X.conNO from Contract_Main X where X.conNo=A.conNO) ,'''')='''' then ''否'' else ''是'' end as IScg  ');
        sql.Add(',ISSC=cast((case when isnull((select count(WBID) from TP_File X where X.WBID=A.maiNID and X.TFType=''合同''),0)>0 then 1 else 0 end) as bit)');
        sql.Add(' from JYOrderCon_Main A  ');
        SQL.Add('where  OrdDate>=''' + '1899-01-01' + '''');
        SQL.Add('and  OrdDate<''' + '2050-01-01' + '''');
        sql.Add(' and MPRTType=''外销'' ');
        if Trim(DParameters1) <> '高权限' then
        begin
          sql.Add('and A.Filler=''' + Trim(DName) + '''');
        end;
        sql.Add(' and ' + Tedit(Sender).Name + ' like ' + quotedstr(trim('%' + trim(Tedit(Sender).Text) + '%')));
      //  sql.Add(' and ConNo like '''+'%'+Trim(ConNoM.Text)+'%'+'''');
        Open;
      end;
      SCreateCDS20(ADOQueryMain, Order_Main);
      SInitCDSData20(ADOQueryMain, Order_Main);
    finally
      ADOQueryMain.EnableControls;
    end;
  end;
end;

procedure TfrmContractList.ToolButton4Click(Sender: TObject);
begin
  try
    frmZDYHelp := TfrmZDYHelp.Create(Application);
    with frmZDYHelp do
    begin
      flag := 'MPRTNameType';
      flagname := '产品类别定义';
      V1HelpType.Visible := True;
      V1HelpType.Caption := '缩写名';
      fnote := True;
      V1Name.Caption := '中文';
      V1Note.Caption := '英文';
      if ShowModal = 1 then
      begin

      end;
    end;
  finally
    frmZDYHelp.Free;
  end;
end;

procedure TfrmContractList.cxTabControl1Change(Sender: TObject);
begin
  SetStatus();
  TBRafresh.Click;
end;

procedure TfrmContractList.TchkClick(Sender: TObject);
begin
  if Order_Main.IsEmpty then
    exit;
  try
    with ADOQueryCmd do
    begin
      close;
      sql.Clear;
      sql.Add('update  JYOrdercon_Main SET status=''1'' ');
      sql.Add('where mainID=' + quotedstr(trim(Order_Main.fieldbyname('mainID').AsString)));
      sql.Add('insert into SY_SysLog(operor,opertime,Model,acction,opevent,result) values( ');
      sql.Add(' ' + quotedstr(trim(DName)));
      sql.Add(',getdate() ');
      sql.Add(',' + quotedstr(trim(self.Caption)));
      sql.Add(',' + quotedstr(trim('外销合同审核')));
      sql.Add(',' + quotedstr(trim('合同号：' + trim(Order_Main.FieldByName('conNo').AsString))));
      sql.Add(',' + quotedstr(trim('成功')));
      sql.Add(')');
      execsql;
    end;
    application.MessageBox('操作合同完成成功！', '提示信息');
    TBRafresh.Click;
  except
    application.MessageBox('操作合同完成失败！', '提示信息', 0);
  end;
end;

procedure TfrmContractList.TnochkClick(Sender: TObject);
begin
  if Order_Main.IsEmpty then
    exit;
  try
    with ADOQueryCmd do
    begin
      close;
      sql.Clear;
      sql.Add('update  JYOrdercon_Main SET status=''0'' ');
      sql.Add('where mainID=' + quotedstr(trim(Order_Main.fieldbyname('mainID').AsString)));
      sql.Add('insert into SY_SysLog(operor,opertime,Model,acction,opevent,result) values( ');
      sql.Add(' ' + quotedstr(trim(DName)));
      sql.Add(',getdate() ');
      sql.Add(',' + quotedstr(trim(self.Caption)));
      sql.Add(',' + quotedstr(trim('外销合同撤销审核')));
      sql.Add(',' + quotedstr(trim('合同号：' + trim(Order_Main.FieldByName('conNo').AsString))));
      sql.Add(',' + quotedstr(trim('成功')));
      sql.Add(')');
      execsql;
    end;
    application.MessageBox('撤销合同完成成功！', '提示信息');
    TBRafresh.Click;
  except
    application.MessageBox('撤销合同完成失败！', '提示信息', 0);
  end;
end;

procedure TfrmContractList.Tv1FocusedRecordChanged(Sender: TcxCustomGridTableView; APrevFocusedRecord, AFocusedRecord: TcxCustomGridRecord; ANewItemRecordFocusingChanged: Boolean);
begin
  InitSub();
end;

procedure TfrmContractList.TQXClick(Sender: TObject);
begin
  if Order_Main.IsEmpty then
    exit;
  try
    with ADOQueryCmd do
    begin
      close;
      sql.Clear;
      sql.Add('update  JYOrdercon_Main SET status=''2'' ');
      sql.Add('where mainID=' + quotedstr(trim(Order_Main.fieldbyname('mainID').AsString)));
      sql.Add('insert into SY_SysLog(operor,opertime,Model,acction,opevent,result) values( ');
      sql.Add(' ' + quotedstr(trim(DName)));
      sql.Add(',getdate() ');
      sql.Add(',' + quotedstr(trim(self.Caption)));
      sql.Add(',' + quotedstr(trim('外销合同取消')));
      sql.Add(',' + quotedstr(trim('合同号：' + trim(Order_Main.FieldByName('conNo').AsString))));
      sql.Add(',' + quotedstr(trim('成功')));
      sql.Add(')');
      execsql;
    end;
    application.MessageBox('合同取消成功！', '提示信息');
    TBRafresh.Click;
  except
    application.MessageBox('合同取消失败！', '提示信息', 0);
  end;
end;

procedure TfrmContractList.TNOQXClick(Sender: TObject);
begin
  if Order_Main.IsEmpty then
    exit;
  try
    with ADOQueryCmd do
    begin
      close;
      sql.Clear;
      sql.Add('update  JYOrdercon_Main SET status=''0'' ');
      sql.Add('where mainID=' + quotedstr(trim(Order_Main.fieldbyname('mainID').AsString)));
      sql.Add('insert into SY_SysLog(operor,opertime,Model,acction,opevent,result) values( ');
      sql.Add(' ' + quotedstr(trim(DName)));
      sql.Add(',getdate() ');
      sql.Add(',' + quotedstr(trim(self.Caption)));
      sql.Add(',' + quotedstr(trim('外销合同撤销取消')));
      sql.Add(',' + quotedstr(trim('合同号：' + trim(Order_Main.FieldByName('conNo').AsString))));
      sql.Add(',' + quotedstr(trim('成功')));
      sql.Add(')');
      execsql;
    end;
    application.MessageBox('撤销合同取消成功！', '提示信息');
    TBRafresh.Click;
  except
    application.MessageBox('撤销合同取消失败！', '提示信息', 0);
  end;
end;

procedure TfrmContractList.ToolButton3Click(Sender: TObject);
begin
  if Order_Main.IsEmpty then
    Exit;
  try
    frmFjList_RZ := TfrmFjList_RZ.Create(Application);
    with frmFjList_RZ do
    begin
    //  PState:=1;
    //  if Trim(DParameters1)<>'高权限'  then cxButton1.Visible:=false;
      fkeyNO := Trim(Self.Order_Main.fieldbyname('MainId').AsString);
      fType := '合同';
      if ShowModal = 1 then
      begin

      end;
    end;
  finally
    frmFjList_RZ.Free;
  end;
end;

procedure TfrmContractList.Tv1CustomDrawCell(Sender: TcxCustomGridTableView; ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean);
begin
  if AViewInfo.GridRecord.Values[tv1.GetColumnByFieldName('status').Index] = '2' then
    ACanvas.Brush.Color := clLime;
end;

procedure TfrmContractList.ToolButton5Click(Sender: TObject);
var
  excelApp, WorkBook: Variant;
  i, j, k, ExcelRowCount: integer;
  maxId, M1, M2, M3: string;
  FMessage: string;
begin
  try
    excelApp := CreateOleObject('Excel.Application');
    openDialog1.Filter := '*.CSV;*.xls';
    if opendialog1.Execute then
    begin
      WorkBook := excelApp.WorkBooks.Open(OpenDialog1.FileName);
    end
    else
      exit;
    excelApp.Visible := false;
    ExcelRowCount := WorkBook.WorkSheets[1].UsedRange.Rows.Count;
  except
    application.MessageBox('加载EXCEL错误！', '错误信息', MB_ICONERROR);
    exit;
  end;
  try
    k := 0;
    for i := 1 to 100 do
    begin
      //遍历界面绑定界面中显示的字段和名称
      for j := 1 to Tv3.ColumnCount - 1 do
      begin
        if trim(Tv3.Columns[j].Caption) = '总成品数量' then
          continue;
        if trim(Tv3.Columns[j].Caption) = '样品类型' then
          continue;
        if trim(Tv3.Columns[j].Caption) = '选择' then
          continue;
        if trim(Tv3.Columns[j].Caption) = '录入人' then
          continue;
        if trim(Tv3.Columns[j].Caption) = '录入时间' then
          continue;
        if trim(Tv3.Columns[j].Caption) = '修改人' then
          continue;
        if trim(Tv3.Columns[j].Caption) = '修改时间' then
          continue;
        if trim(excelApp.Cells[1, i].value) = trim(Tv3.Columns[j].Caption) then
        begin
          dFdDy[k].inc := i;
          dFdDy[k].FDdys := trim(Tv3.Columns[j].DataBinding.FieldName);
          dFdDy[k].FdDysName := trim(Tv3.Columns[j].Caption);
        end;
      end;
      k := k + 1;
    end;
  except
  end;

  with ADOQueryCmd do
  begin
    close;
    sql.Clear;
    sql.Add('delete jyorder_main_DR ');
    execsql;
  end;
//  ShowMessage(IntToStr(k));
  ADOQueryCmd.Connection.BeginTrans;
  try
    for i := 2 to ExcelRowCount do
    begin
      with ADOQueryCmd do
      begin
        close;
        sql.Clear;
        sql.Add('select * from jyorder_main_DR where 1=2');
        open;
      end;
      ADOQueryCmd.Append;
      for j := 0 to k - 1 do
      begin
        if trim(dFdDy[j].FDdys) = '' then
          continue;
        M1 := dFdDy[j].FDdys;   //字段名称
        M2 := inttostr(dFdDy[j].inc);   //当前列
        M3 := excelApp.Cells[i, dFdDy[j].inc].Value;  //当前单元格内容
        ADOQueryCmd.fieldbyname(dFdDy[j].FDdys).Value := excelApp.Cells[i, dFdDy[j].inc].Value;
      end;

      ADOQueryCmd.Post;

    end;

    with ADOQueryCmd do
    begin
      Close;
      sql.Clear;
      sql.Add('exec P_Get_Con_DR_copy1 ''' + trim(DName) + ''' ');
      ExecSQL;
    end;

    WorkBook.Close;
    excelApp.Quit;
    excelApp := Unassigned;
    WorkBook := Unassigned;

    ADOQueryCmd.Connection.CommitTrans;
    Application.MessageBox('导入成功!', '提示', 0);
    InitGrid();
  except
    WorkBook.Close;
    excelApp.Quit;
    excelApp := Unassigned;
    WorkBook := Unassigned;
    ADOQueryCmd.Connection.RollbackTrans;
  end;
end;

procedure TfrmContractList.ToolButton6Click(Sender: TObject);
var
  fPrintFile: string;
  EngMoney: string;
  fRMXLSExport1: TRMXLSExport;
begin

  if Order_Main.IsEmpty then
    Exit;
  if Order_Main.Locate('SSel', True, []) = False then
  begin
    Application.MessageBox('没有选择数据!', '提示', 0);
    Exit;
  end;
  with ADOqueryCmd do
  begin
    Close;
    sql.Clear;
    sql.Add('delete TBSubID where DName=''' + Trim(DCode) + '''');
    ExecSQL;
  end;
  with ADOqueryCmd do
  begin
    Close;
    sql.Clear;
    sql.Add('select * FROM TBSubID where 1=2 ');
    open;
  end;
  ADOqueryCmd.Connection.BeginTrans;
  try
    Order_Main.DisableControls;
    with Order_Main do
    begin
      First;
      while not Eof do
      begin
        if FieldByName('SSel').AsBoolean then
        begin
          ADOQueryCmd.append;
          ADOQueryCmd.fieldbyname('SubId').Value := Trim(fieldbyname('Mainid').AsString);
          ADOQueryCmd.fieldbyname('Dname').Value := Trim(DCode);
          ADOQueryCmd.post;
        end;
        Next;
      end;
    end;
    Order_Main.EnableControls;
    ADOqueryCmd.Connection.CommitTrans;
  except
    ADOQueryCmd.Connection.RollbackTrans;
  end;

  fRMXLSExport1 := TRMXLSExport.Create(self);
  fPrintFile := ExtractFilePath(Application.ExeName) + 'Report\合并合同.rmf';
  with ADOQueryPrint do
  begin
    Close;
    sql.Clear;
    sql.Add('select A.*,B.*,ConMoney=B.PRTOrderQty*B.PRTPrice,COL=''COL:''  ');
    sql.Add(',Case when substring(PriceNote,1,3)=''FOB'' then '' ''+A.FromPlace else '' ''+A.ToPlace end as PriceNote10 ');
    sql.Add(',PrtImage=(select Top 1 FilesOther from TP_File X where X.WBID=B.PRTCode) ');
    sql.Add(' from JYOrderCon_Main A inner join JYOrderCon_Sub B on A.MainId=B.MainId ');
    sql.Add(' where EXISTS(select SubId from TBSubID X where X.SubId=A.Mainid and X.DName=''' + trim(DCode) + ''' )');
    Open;
  end;
  SCreateCDS20(ADOQueryPrint, CDS_Print1);
  SInitCDSData20(ADOQueryPrint, CDS_Print1);
  //
  with ADOQueryTemp do
  begin
    close;
    sql.Clear;
    sql.Add('select TolConMoney=Sum(PRTOrderQty*PRTPrice)');
    sql.Add(' from JYOrderCon_Main A inner join JYOrderCon_Sub B on A.MainId=B.MainId ');
    sql.Add(' where EXISTS(select SubId from TBSubID X where X.SubId=A.Mainid and X.DName=''' + trim(DCode) + ''')');
    Open;
  end;
  EngMoney := num2cengnum(ADOQueryTemp.fieldbyname('TolConMoney').AsString);
  EngMoney := UpperCase(EngMoney);
  if FileExists(fPrintFile) then
  begin
    RMVariables['EngMoney'] := EngMoney;
   // RM1.PreviewButtons:=[pbZoom,pbLoad,pbSave,pbPrint,pbFind,pbPageSetup,pbExit,pbSaveToXLS,pbExport,pbNavigator];
    //RMVariables['enddate']:=enddate.DateTime;
    //RMVariables['printtime']:=Now;
    //RMVariables['printer']:=Trim(gUserName);
    RM1.LoadFromFile(fPrintFile);
    RM1.ShowReport;
  end
  else
  begin
    Application.MessageBox(PChar('没有找' + ExtractFilePath(Application.ExeName) + 'Report\合并合同.rmf'), '提示', 0);
  end;
  fRMXLSExport1.Free;
end;

procedure TfrmContractList.ToolButton7Click(Sender: TObject);
begin
  try
    frmLabelList := TfrmLabelList.Create(Application);
    with frmLabelList do
    begin
      if ShowModal = 1 then
      begin
        with ADOQueryCmd do
        begin
          Close;
          sql.Clear;
          sql.Add('Update JYOrderCon_Main Set LBName=''' + Trim(ADOQueryLabel.fieldbyname('labelCaption').AsString) + '''');
          sql.Add(' where Mainid=''' + Trim(Order_Main.fieldbyname('Mainid').AsString) + '''');
          ExecSQL;
        end;
        TBRafresh.Click;
      end;
    end;
  finally
    frmLabelList.Free;
  end;
end;

procedure TfrmContractList.ToolButton8Click(Sender: TObject);
begin
//  if Order_Main.Locate('SSel', True, []) = False then
//  begin
//    Application.MessageBox('没有选择数据!', '提示', 0);
//    Exit;
//  end;
//  if Order_Main.IsEmpty then
//    Exit;
//
  if Trim(Order_Main.fieldbyname('LBName').AsString) = '' then
  begin
    Exit;
  end;
  panel2.Visible := True;
end;


//var
//  fPrintFile: string;
//  EngMoney: string;
//  fRMXLSExport1: TRMXLSExport;
//begin
//  if Order_Main.IsEmpty then
//    Exit;
//
//  if Trim(Order_Main.fieldbyname('LBName').AsString) = '' then
//  begin
//    Exit;
//  end;
//
//  fRMXLSExport1 := TRMXLSExport.Create(self);
//  fPrintFile := ExtractFilePath(Application.ExeName) + 'Report\' + Order_Main.fieldbyname('LBName').AsString + '.rmf';
//  with ADOQueryPrint do
//  begin
//    Close;
//    sql.Clear;
//    sql.Add('select A.*,B.*,ConMoney=B.PRTOrderQty*B.PRTPrice,COL=''COL:''  ');
//    sql.Add(',Case when substring(PriceNote,1,3)=''FOB'' then '' ''+A.FromPlace else '' ''+A.ToPlace end as PriceNote10 ');
//    sql.Add(',PrtImage=(select Top 1 FilesOther from TP_File X where X.WBID=B.PRTCode) ');
//    sql.Add(' from JYOrderCon_Main A inner join JYOrderCon_Sub B on A.MainId=B.MainId ');
//    sql.Add(' where B.Subid=''' + Trim(Order_sub.fieldbyname('subid').AsString) + '''');
//    Open;
//  end;
//  SCreateCDS20(ADOQueryPrint, CDS_Print);
//  SInitCDSData20(ADOQueryPrint, CDS_Print);
//
//  if FileExists(fPrintFile) then
//  begin
//    RM1.LoadFromFile(fPrintFile);
//    RM1.DefaultCopies :=StrToInt(Order_sub.fieldbyname('PRTOrderQty').AsString) ;
//    RM1.ShowReport;
//  end
//  else
//  begin
//    Application.MessageBox(PChar('没有找' + ExtractFilePath(Application.ExeName) + 'Report\' + Order_Main.fieldbyname('LBName').AsString), '提示', 0);
//  end;
//  fRMXLSExport1.Free;
//end;

procedure TfrmContractList.ToolButton9Click(Sender: TObject);
var
  excelApp, WorkBook: Variant;
  i, j, k, ExcelRowCount: integer;
  maxId, M1, M2, M3: string;
  FMessage: string;
begin
  try
    excelApp := CreateOleObject('Excel.Application');
    openDialog1.Filter := '*.CSV;*.xls';
    if opendialog1.Execute then
    begin
      WorkBook := excelApp.WorkBooks.Open(OpenDialog1.FileName);
    end
    else
      exit;
    excelApp.Visible := false;
    ExcelRowCount := WorkBook.WorkSheets[1].UsedRange.Rows.Count;
  except
    application.MessageBox('加载EXCEL错误！', '错误信息', MB_ICONERROR);
    exit;
  end;
  try
    k := 0;
    for i := 1 to 100 do
    begin
      //遍历界面绑定界面中显示的字段和名称
      for j := 1 to Tv4.ColumnCount - 1 do
      begin
        if trim(Tv4.Columns[j].Caption) = '总成品数量' then
          continue;
        if trim(Tv4.Columns[j].Caption) = '样品类型' then
          continue;
        if trim(Tv4.Columns[j].Caption) = '选择' then
          continue;
        if trim(Tv4.Columns[j].Caption) = '录入人' then
          continue;
        if trim(Tv4.Columns[j].Caption) = '录入时间' then
          continue;
        if trim(Tv4.Columns[j].Caption) = '修改人' then
          continue;
        if trim(Tv4.Columns[j].Caption) = '修改时间' then
          continue;
        if trim(excelApp.Cells[1, i].value) = trim(Tv4.Columns[j].Caption) then
        begin
          dFdDy[k].inc := i;
          dFdDy[k].FDdys := trim(Tv4.Columns[j].DataBinding.FieldName);
          dFdDy[k].FdDysName := trim(Tv4.Columns[j].Caption);
        end;
      end;
      k := k + 1;
    end;
  except
  end;

  with ADOQueryCmd do
  begin
    close;
    sql.Clear;
    sql.Add('delete jyorder_main_DR ');
    execsql;
  end;
//  ShowMessage(IntToStr(k));
  ADOQueryCmd.Connection.BeginTrans;
  try
    for i := 2 to ExcelRowCount do
    begin
      with ADOQueryCmd do
      begin
        close;
        sql.Clear;
        sql.Add('select * from jyorder_main_DR where 1=2');
        open;
      end;
      ADOQueryCmd.Append;
      for j := 0 to k - 1 do
      begin
        if trim(dFdDy[j].FDdys) = '' then
          continue;
        M1 := dFdDy[j].FDdys;   //字段名称
        M2 := inttostr(dFdDy[j].inc);   //当前列
        M3 := excelApp.Cells[i, dFdDy[j].inc].Value;  //当前单元格内容
        ADOQueryCmd.fieldbyname(dFdDy[j].FDdys).Value := excelApp.Cells[i, dFdDy[j].inc].Value;
      end;

      ADOQueryCmd.Post;

    end;

    with ADOQueryCmd do
    begin
      Close;
      sql.Clear;
      sql.Add('exec P_Get_Con_DR2_copy1 ''' + trim(DName) + ''' ');
      ExecSQL;
    end;

    WorkBook.Close;
    excelApp.Quit;
    excelApp := Unassigned;
    WorkBook := Unassigned;

    ADOQueryCmd.Connection.CommitTrans;
    Application.MessageBox('导入成功!', '提示', 0);
    InitGrid();
  except
    WorkBook.Close;
    excelApp.Quit;
    excelApp := Unassigned;
    WorkBook := Unassigned;
    ADOQueryCmd.Connection.RollbackTrans;
  end;
end;

procedure TfrmContractList.Button2Click(Sender: TObject);
var
  FMainid: string;
  fPrintFile: string;
  Porderno: string;
  i, j: Integer;
begin

  with ADOQueryCmd do
  begin
    Close;
    sql.Clear;
    sql.Add('delete TBSubID where DName=''' + Trim(DCode) + '''');
    ExecSQL;
  end;
  with ADOQueryCmd do
  begin
    Close;
    sql.Clear;
    sql.Add('SELECT * FROM TBSubID where 1=2 ');
    open;
  end;
  FMainid := '';
  Order_Main.DisableControls;
  try
    ADOQueryCmd.Connection.BeginTrans;
    with Order_Main do
    begin
      First;
      while not Eof do
      begin
        if Fieldbyname('Ssel').AsBoolean then
        begin
          if FMainid = '' then
          begin
            FMainid := Trim(Order_Main.fieldbyname('CustomerNoName').AsString);
          end
          else
          begin
            if Trim(Order_Main.fieldbyname('CustomerNoName').AsString) <> FMainid then
            begin
              application.MessageBox('选择的不是同一个客户，不能一起打印！', '提示信息', 0);
              ADOQueryCmd.Connection.RollbackTrans;
              EnableControls;
              exit;
            end;
          end;
          ADOQueryCmd.append;
          ADOQueryCmd.fieldbyname('SubId').Value := Trim(Order_Main.fieldbyname('Mainid').AsString);
          ADOQueryCmd.fieldbyname('Dname').Value := Trim(DCode);
          ADOQueryCmd.post;
        end;
        Next;
      end;
    end;
    ADOQueryCmd.Connection.CommitTrans;
  except
    ADOQueryCmd.Connection.RollbackTrans;
  end;
  order_main.EnableControls;

//  fPrintFile := ExtractFilePath(Application.ExeName) + 'Report\生产指示单.rmf';
//  fPrintFile := ExtractFilePath(Application.ExeName) + 'Report\' + Order_Main.fieldbyname('LBName').AsString + '.rmf';
  with ADOQueryPrint do
  begin
    Close;
    sql.Clear;
    sql.Add('exec P_Print_OrderBQdy ''' + trim(DCode) + '''');
    sql.Add(',''' + trim(Edit1.Text) + ''' ');
//    showmessage(sql.Text);
    Open;
  end;
  SCreateCDS20(ADOQueryPrint, CDS_Print);
  SCreateCDS20(ADOQueryPrint, CDS_Print1);
  SInitCDSData20(ADOQueryPrint, CDS_Print);
  fPrintFile := ExtractFilePath(Application.ExeName) + 'Report\' + CDS_Print.fieldbyname('LBName').AsString + '.rmf';
  try
    with CDS_Print do
    begin
      DisableControls;
      first;
      while not eof do
      begin
        CDS_Print1.EmptyDataSet;
        CDS_Print1.Append;
        for i := 0 to FieldCount - 1 do
        begin
          CDS_Print1.fields[i].value := CDS_Print.Fields[i].Value;
        end;
        CDS_Print1.Post;

        if (trim(CDS_Print1.fieldbyname('subid').AsString) <> '') then
        begin
          if FileExists(fPrintFile) then
          begin
            RM1.LoadFromFile(fPrintFile);
            RM1.DefaultCopies := StrToInt(CDS_Print1.fieldbyname('PRTOrderQty').AsString);
            RM1.ShowReport;
//            RM1.PrintReport;
          end
          else
          begin
//    Application.MessageBox(PChar('没有找' + ExtractFilePath(Application.ExeName) + 'Report\生产指示单.rmf'), '提示', 0);
            Application.MessageBox(PChar('没有找' + ExtractFilePath(Application.ExeName) + 'Report\' + Order_Main.fieldbyname('LBName').AsString), '提示', 0);
            exit;
          end;

        end;

        Next;
      end;
      EnableControls;
    end;

  finally

  end;
//  with ADOQueryPrint do
//  begin
//    Close;
//    sql.Clear;
//    sql.Add('select A.*,B.*,ConMoney=B.PRTOrderQty*B.PRTPrice,COL=''COL:''  ');
//    sql.Add(',Case when substring(PriceNote,1,3)=''FOB'' then '' ''+A.FromPlace else '' ''+A.ToPlace end as PriceNote10 ');
//    sql.Add(',PrtImage=(select Top 1 FilesOther from TP_File X where X.WBID=B.PRTCode) ');
//    sql.Add(' from JYOrderCon_Main A inner join JYOrderCon_Sub B on A.MainId=B.MainId ');
//    sql.Add(' where B.Subid=''' + Trim(ADOQueryTemp.fieldbyname('subid').AsString) + '''');
//    Open;
//  end;
//  SCreateCDS20(ADOQueryPrint, CDS_Print);
//  SInitCDSData20(ADOQueryPrint, CDS_Print);
//  if FileExists(fPrintFile) then
//  begin
//    RM1.LoadFromFile(fPrintFile);
//    RM1.DefaultCopies := StrToInt(Order_sub.fieldbyname('PRTOrderQty').AsString);
//    RM1.ShowReport;
//  end
//  else
//  begin
////    Application.MessageBox(PChar('没有找' + ExtractFilePath(Application.ExeName) + 'Report\生产指示单.rmf'), '提示', 0);
//    Application.MessageBox(PChar('没有找' + ExtractFilePath(Application.ExeName) + 'Report\' + Order_Main.fieldbyname('LBName').AsString), '提示', 0);
//    exit;
//  end;
//  end;
end;

procedure TfrmContractList.Button3Click(Sender: TObject);
begin
  Panel2.Visible := false;
end;

procedure TfrmContractList.ToolButton10Click(Sender: TObject);
begin
  try
    frmLabelListts := TfrmLabelListts.Create(Application);
    with frmLabelListts do
    begin
      if ShowModal = 1 then
      begin
        with ADOQueryCmd do
        begin
          Close;
          sql.Clear;
          sql.Add('Update JYOrderCon_Main Set LBName=''' + Trim(ADOQueryLabel.fieldbyname('labelCaption').AsString) + '''');
          sql.Add(' where Mainid=''' + Trim(Order_Main.fieldbyname('Mainid').AsString) + '''');
          ExecSQL;
        end;
//        TBRafresh.Click;
      end;
    end;
  finally
    frmLabelListts.Free;
  end;
end;

end.

