unit U_ZHCPInPut;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage,
  cxEdit, DB, cxDBData, cxGridLevel, cxGridCustomTableView, cxGridTableView,
  cxGridDBTableView, cxClasses, cxControls, cxGridCustomView, cxGrid, cxMemo,
  cxRichEdit, ComCtrls, cxContainer, cxTextEdit, cxMaskEdit, cxButtonEdit,
  StdCtrls, ToolWin, DBClient, ADODB, ExtCtrls, BtnEdit, cxCalendar, StrUtils,
  cxDropDownEdit, jpeg, IdBaseComponent, IdComponent, IdTCPConnection,
  IdTCPClient, IdFTP, cxPC, cxGridCustomPopupMenu, cxGridPopupMenu, cxGroupBox,
  cxCheckBox, RM_Dataset, RM_System, RM_Common, RM_Class, RM_GridReport,
  IniFiles, Menus;

type
  TfrmZHCPInPut = class(TForm)
    ToolBar1: TToolBar;
    TBClose: TToolButton;
    ADOTemp: TADOQuery;
    ADOCmd: TADOQuery;
    ADOQuery1: TADOQuery;
    TBSave: TToolButton;
    Label26: TLabel;
    CDS_PRT: TClientDataSet;
    RM1: TRMGridReport;
    Panel3: TPanel;
    Panel5: TPanel;
    Label12: TLabel;
    Label14: TLabel;
    Label15: TLabel;
    Label16: TLabel;
    Label2: TLabel;
    ZIKZ: TEdit;
    ZIMF: TEdit;
    ZICF: TEdit;
    ODPat: TOpenDialog;
    IdFTP1: TIdFTP;
    SaveDialog1: TSaveDialog;
    Panel66: TPanel;
    Image2: TImage;
    Panel2: TPanel;
    Label3: TLabel;
    Button2: TButton;
    ToolButton1: TToolButton;
    Label4: TLabel;
    ZIID: TEdit;
    adoqueryPicture: TADOQuery;
    Panel1: TPanel;
    RMDBMain: TRMDBDataSet;
    ZIGY: TMemo;
    Label7: TLabel;
    Label8: TLabel;
    ZIName: TEdit;
    Label9: TLabel;
    Note: TMemo;
    ADOQueryCmd: TADOQuery;
    Label10: TLabel;
    ZICL: TEdit;
    Label11: TLabel;
    Label13: TLabel;
    Label17: TLabel;
    Label18: TLabel;
    MianBu: TBtnEditA;
    ZhongJianC: TBtnEditA;
    DiBu: TBtnEditA;
    Label19: TLabel;
    Label20: TLabel;
    Label21: TLabel;
    DiBuName: TBtnEditA;
    ZhongJianCName: TEdit;
    ZhongJianCID: TEdit;
    Label22: TLabel;
    DiBuID: TEdit;
    Label23: TLabel;
    MianBuName: TBtnEditA;
    HXNO: TBtnEditC;
    Label24: TLabel;
    MBCBDJ: TEdit;
    Label25: TLabel;
    DBCBDJ: TEdit;
    Label27: TLabel;
    MHDJ: TEdit;
    Label28: TLabel;
    XHJGFDJ: TEdit;
    Label29: TLabel;
    CPCBDJ: TEdit;
    Panel4: TPanel;
    Button3: TButton;
    Button4: TButton;
    Label30: TLabel;
    TSHGYCB: TEdit;
    Label31: TLabel;
    CPSSL: TEdit;
    Panel12: TPanel;
    Label32: TLabel;
    Panel13: TPanel;
    img1: TImage;
    WJName: TEdit;
    Cancel: TButton;
    WJPach: TEdit;
    Rename: TButton;
    image22: TImage;
    Label1: TLabel;
    HXNM: TEdit;
    pm1: TPopupMenu;
    MenuItem2: TMenuItem;
    procedure TBCloseClick(Sender: TObject);
    procedure FormShow(Sender: TObject);
    procedure TBSaveClick(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure FormCreate(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure ToolButton1Click(Sender: TObject);
    procedure Image1DblClick(Sender: TObject);
    procedure Image2DblClick(Sender: TObject);
    procedure HXNO1BtnClick(Sender: TObject);
    procedure MianBuBtnClick(Sender: TObject);
    procedure ZhongJianCBtnClick(Sender: TObject);
    procedure DiBuBtnClick(Sender: TObject);
    procedure DiBuNameBtnClick(Sender: TObject);
    procedure MianBuNameBtnClick(Sender: TObject);
    procedure Button3Click(Sender: TObject);
    procedure Button4Click(Sender: TObject);
    procedure HXNOBtnDnClick(Sender: TObject);
    procedure HXNOBtnUpClick(Sender: TObject);
    procedure MBCBDJChange(Sender: TObject);
    procedure MenuItem2Click(Sender: TObject);
    procedure RenameClick(Sender: TObject);
    procedure CancelClick(Sender: TObject);
    procedure img1Click(Sender: TObject);
  private
    lstPat, lstPat2: TStringList;
    FangXiang1, FangXiang2: string;
    procedure InitData();
    procedure SaveImage(maxnoWB: string; FIMNO: string);
    procedure ReadINIFile10();
    function SaveData(): Boolean;
    function BJData(maxno: string): Boolean;
    function StrFenHang(FStr: string; var FHStr: string): Boolean;
    { Private declarations }
  public
    canshu1, ZT: string;
    PState, CopyInt: Integer;
    FMainId, FZIType: string;
    { Public declarations }
  end;

var
  frmZHCPInPut: TfrmZHCPInPut;

implementation    //ZH_KH_DJ

uses
  U_DataLink, U_ZDYHelp, U_RTFun, U_ZHCPBigTP, U_ZdyAttachCP_HX, U_MLMangeRSSel,
  U_MCP, U_MLMangeYH;

{$R *.dfm}

function TfrmZHCPInPut.BJData(maxno: string): Boolean;
var
  BJmaxmxno, FMXID, FBaoJia, FZIID, FZIIDAdd, FAdd, FZIIDYS: string;
  FXH: Integer;
  FDate: TDateTime;
begin
  Result := False;
  FDate := SGetServerDate(ADOTemp);
  try
    if GetLSNo(ADOCmd, BJmaxmxno, 'ZC', 'ZH_KH_DJ_CP', 4, 1) = False then
    begin
//      Order_Sub.EnableControls;
      ADOCmd.Connection.RollbackTrans;
      Application.MessageBox('取明细最大号失败', '提示', 0);
      Exit;
    end;
    with ADOCmd do
    begin
      Close;
      sql.Clear;
      sql.Add('select * from ZH_KH_DJ_CP where ZCID=''' + Trim(BJmaxmxno) + '''');
      Open;
    end;
    with ADOCmd do
    begin
      Append;
      FieldByName('Filler').Value := Trim(DName);
      FieldByName('FillerCode').Value := Trim(DCode);
      FieldByName('Valid').Value := 'Y';
      FieldByName('ZIID').Value := maxno;
      FieldByName('ZIName').Value := Trim(ZIName.text);
      FieldByName('ZIMF').Value := Trim(ZIMF.text);
      FieldByName('ZIKZ').Value := Trim(ZIKZ.text);
      FieldByName('ZICF').Value := Trim(ZICF.text);
      FieldByName('ZICL').Value := Trim(ZICL.text);
      FieldByName('ZIIDYS').Value := maxno;
      FieldByName('ZCID').Value := Trim(BJmaxmxno);
//      FieldByName('CPFiller').Value := Trim(DName);
      FieldByName('LeiBie').Value := '登记样';
      FieldByName('MBBJ').Value := StrToFloatDef(MBCBDJ.text, 0);
      FieldByName('DBBJ').Value := StrToFloatDef(DBCBDJ.text, 0);
      FieldByName('BaoJia').Value := StrToFloatDef(CPCBDJ.text, 0);
      FieldByName('BaoJiaYW').Value := StrToFloatDef(CPCBDJ.text, 0);
      Post;
    end;
//    ADOCmd.Connection.CommitTrans;
//    FMainId := Trim(maxno);
    Result := True;
  except
    Result := False;
//    Panel1.Visible := False;
//    ADOCmd.Connection.RollbackTrans;
    Application.MessageBox('保存失败！', '提示', 0);
  end;
end;

procedure TfrmZHCPInPut.TBCloseClick(Sender: TObject);
begin
  Close;
end;

procedure TfrmZHCPInPut.InitData();
var
  jpg: TJpegImage;
  myStream: TADOBlobStream;
  FStr: string;
begin
  with ADOQuery1 do
  begin
    Close;
    sql.Clear;
    sql.Add(' select * ');
    sql.Add(' from ZH_CP_Info   ');
    sql.Add(' where ZIID=''' + Trim(FMainId) + '''');
    Open;
  end;

  SCSHDataNew(ADOQuery1, Panel5, 9);
  SCSHDataNew(ADOQuery1, Panel5, 2);
  SCSHDataNew(ADOQuery1, Panel3, 9);

  with adoqueryPicture do
  begin
    Close;
    sql.Clear;
    sql.Add('select * from Image_Info A');
    sql.Add(' inner join Image_File B on A.IMID=B.IMID');
    sql.Add(' and A.WBID=''' + Trim(FMainId) + '''');
    sql.Add(' and isnull(A.IMNo,''图片'')=''图片'' and A.Valid=''Y'' ');
    Open;
  end;

  if (adoqueryPicture.IsEmpty = False) and (CopyInt <> 99) then
  begin
    FStr := Trim(adoqueryPicture.fieldbyname('ImageName').AsString);
    jpg := TJpegImage.Create();
    myStream := tadoblobstream.Create(tblobfield(adoqueryPicture.fieldbyname('ImageFile')), bmread);
    jpg.LoadFromStream(myStream);
    Image2.Picture.Assign(jpg);
    Image2.Width := adoqueryPicture.fieldbyname('ImageWidth').Value;
    Image2.Height := adoqueryPicture.fieldbyname('ImageHeight').Value;
    if Trim(adoqueryPicture.fieldbyname('FangXiang').AsString) = '垂直' then
    begin
      Image2.Top := 1;
      Image2.Left := Round((Panel66.Width - Image2.Width) / 2);
    end
    else
    begin
      Image2.Left := 1;
      Image2.Top := Round((Panel66.Height - Image2.Height) / 2);
    end;
    Image2.Visible := True;
  end;

  if TBSave.Visible = False then
  begin
    Button2.Visible := False;
    ZIMF.Color := ZIID.Color;
    ZIKZ.Color := ZIID.Color;
    ZICF.Color := ZIID.Color;
    ZIName.Color := ZIID.Color;
    ZIGY.Color := ZIID.Color;
    Note.Color := ZIID.Color;
  end;

  if CopyInt = 99 then
  begin
    PState := 0;
    FMainId := '';
    ZIID.Text := ''
  end;
end;

procedure TfrmZHCPInPut.FormShow(Sender: TObject);
begin
  InitData();
end;

function TfrmZHCPInPut.SaveData(): Boolean;
var
  maxno: string;
begin
  Result := False;
  try
    ADOCmd.Connection.BeginTrans;
    ///保存主表
    if Trim(FMainId) = '' then
    begin
      if Trim(FZIType) <> '75D绗绣面料' then
      begin
        if GetLSNoHZ(ADOCmd, maxno, 'Y', 'ZH_CP_Info', 4, 1, 1) = False then
        begin
          ADOCmd.Connection.RollbackTrans;
          Application.MessageBox('取最大号失败!', '提示', 0);
          Exit;
        end;
      end
      else
      begin
        if GetLSNoHZ(ADOCmd, maxno, 'A', 'ZH_CP_Info', 4, 1, 1) = False then
        begin
          ADOCmd.Connection.RollbackTrans;
          Application.MessageBox('取最大号失败!', '提示', 0);
          Exit;
        end;
      end;

    end
    else
    begin
      maxno := Trim(FMainId);
    end;
    with ADOCmd do
    begin
      Close;
      sql.Clear;
      SQL.Add('select * from ZH_CP_Info where ZIId=''' + Trim(maxno) + '''');
      Open;
    end;

    with ADOCmd do
    begin
      if Trim(FMainId) = '' then
      begin
        Append;
        FieldByName('ZIType').Value := FZIType;
      end
      else
      begin
        Edit;
      end;
      FieldByName('ZIId').Value := Trim(maxno);

      if Trim(FMainId) = '' then
      begin
        FieldByName('ZIIdYS').Value := Trim(maxno);
        FieldByName('Filler').Value := Trim(DName);
        FieldByName('FillerCode').Value := Trim(DCode);
        FieldByName('Valid').Value := 'Y';
        FieldByName('ZIDate').Value := SGetServerDate(ADOTemp);
      end
      else
      begin
        FieldByName('Editer').Value := Trim(DName);
        FieldByName('EditerCode').Value := Trim(DCode);
        FieldByName('EditTime').Value := SGetServerDateTime(ADOTemp);
      end;
      RTSetsavedata(ADOCmd, 'ZH_CP_Info', Panel5, 2);
      RTSetsavedata(ADOCmd, 'ZH_CP_Info', Panel3, 9);
//      FieldByName('HXNM').Value := Trim(HXNO.TxtCode);
      Post;
    end;

    if Trim(Image2.Hint) <> '' then
    begin
      SaveImage(maxno, '图片');
    end;
    if trim(FZIType) <> '单面料' then
    begin
      if not BJData(maxno) then
      begin
        ADOCmd.Connection.RollbackTrans;
        Application.MessageBox('保存异常!', '提示', 0);
        exit;
      end;
    end;

    ADOCmd.Connection.CommitTrans;
    FMainId := Trim(maxno);
    Result := True;
  except
    Result := False;
    ADOCmd.Connection.RollbackTrans;
    Application.MessageBox('保存失败！', '提示', 0);
  end;
end;

procedure TfrmZHCPInPut.TBSaveClick(Sender: TObject);
begin
  ToolBar1.SetFocus;

  if Trim(ZIName.Text) = '' then
  begin
    Application.MessageBox('品名不能为空!', '提示', 0);
    Exit;
  end;

  if Trim(ZIMF.Text) = '' then
  begin
    Application.MessageBox('门幅不能为空!', '提示', 0);
    Exit;
  end;
  if Trim(ZIKZ.Text) = '' then
  begin
    Application.MessageBox('克重不能为空!', '提示', 0);
    Exit;
  end;
  if Trim(ZICF.Text) = '' then
  begin
    Application.MessageBox('成份不能为空!', '提示', 0);
    Exit;
  end;

  if trim(FZIType) <> '单面料' then
  begin

    if Trim(HXNO.Text) = '' then
    begin
      Application.MessageBox('花型号不能为空!', '提示', 0);
      Exit;
    end;

  end;

  if Trim(ZICL.Text) = '' then
  begin
    if Application.MessageBox('产量为空，确定要保存数据吗？', '提示', 32 + 4) <> IDYES then
      Exit;
  end;
  Panel1.Visible := True;
  Panel1.Refresh;
  if SaveData() then
  begin
    Panel1.Visible := False;
    Application.MessageBox('保存成功！', '提示', 0);
    ModalResult := 1;
  end;
end;

procedure TfrmZHCPInPut.ReadINIFile10();
var
  programIni: Tinifile;  //配置文件名
  FileName: string;
begin
  FileName := ExtractFilePath(Paramstr(0)) + 'SYSTEMSET.INI';
  programIni := Tinifile.create(FileName);
  server := programIni.ReadString('SERVER', '服务器地址', '127.0.0.1');
  programIni.Free;
end;

procedure TfrmZHCPInPut.SaveImage(maxnoWB: string; FIMNO: string);
var
  ImagePath, ImagName, MaxNo, MaxNoFile: string;
  AJpeg: TJPEGImage;
  myStream: TADOBlobStream;
  LocalFileName: string; // 添加的本地变量
begin
  try
    if Trim(FIMNO) = '图片' then
    begin
      if lstPat2.Count > 0 then
      begin
        LocalFileName := lstPat2[0]; // 使用列表中的路径，确保是最新的
        // 检查文件是否存在
        if not FileExists(LocalFileName) then
        begin
          Application.MessageBox('找不到图片文件，请重新选择!', '错误', 0);
          Exit;
        end;
      end;
    end;
    ImagePath := ExtractFilePath(LocalFileName); // 文件路径
    ImagName := ExtractFileName(LocalFileName);  // 纯文件名（含扩展名）
    AJpeg := TJpegImage.Create();
    with ADOCmd do
    begin
      Close;
      sql.Clear;
      SQL.Add('UPdate Image_File Set Valid=''N'' ');
      sql.Add(' where IMID=(select IMID from Image_Info');
      Sql.Add('where WBID=''' + Trim(maxnoWB) + ''' and Valid=''Y'' and IMNO=''' + Trim(FIMNO) + ''')');
      ExecSQL;
    end;
    with ADOCmd do
    begin
      Close;
      sql.Clear;
      SQL.Add('UPdate Image_Info Set Editer=''' + Trim(DName) + ''',EditerCode=''' + Trim(DCode) + ''',EditTime=getdate()');
      sql.Add(',Valid=''N''  where WBID=''' + Trim(maxnoWB) + ''' and Valid=''Y'' and IMNO=''' + Trim(FIMNO) + ''' ');
      ExecSQL;
    end;
    if GetLSNo(ADOCmd, MaxNo, 'IM', 'Image_Info', 4, 1) = False then
    begin
      ADOCmd.Connection.RollbackTrans;
      Application.MessageBox('取图片信息最大号失败！', '提示', 0);
      Exit;
    end;
    with ADOCmd do
    begin
      Close;
      SQL.Clear;
      SQL.Add('select * from Image_Info where 1=2');
      Open;
    end;
    with ADOCmd do
    begin
      Append;
      FieldByName('IMID').Value := Trim(MaxNo);
      FieldByName('IMNo').Value := FIMNO;
      FieldByName('WBID').Value := Trim(maxnoWB);
      FieldByName('ImageName').Value := Trim(ImagName);
      FieldByName('ImagePath').Value := Trim(MaxNo) + Trim(ImagName);
      FieldByName('ImageDate').Value := SGetServerDate(ADOTemp);
      Fieldbyname('ImageType').value := Trim('YP');
      Fieldbyname('Valid').value := Trim('Y');
      Post;
    end;
    if GetLSNo(ADOCmd, MaxNoFile, 'IF', 'Image_File', 4, 1) = False then
    begin
      ADOCmd.Connection.RollbackTrans;
      Application.MessageBox('取图片文件最大号失败！', '提示', 0);
      Exit;
    end;
    with ADOCmd do
    begin
      close;
      sql.Clear;
      sql.Add(' select *  from Image_File where 1=2');
      open;
    end;

    with ADOCmd do
    begin
      Append;
      FieldByName('IMID').Value := Trim(MaxNo);
      FieldByName('IFID').Value := Trim(MaxNoFile);
      Fieldbyname('Valid').value := Trim('Y');
      if Trim(FIMNO) = '图片' then
      begin
        FieldByName('ImageWidth').Value := Image2.Width;
        FieldByName('ImageHeight').Value := Image2.Height;
        FieldByName('FangXiang').Value := FangXiang2;
      end;
      FieldByName('IFType').Value := '小';
      myStream := TADOBlobStream.Create(TBlobField(ADOCmd.FieldByName('ImageFile')), bmWrite);
      if Trim(FIMNO) = '图片' then
      begin
        AJpeg.Assign(Image2.Picture.Graphic);
      end;
      AJpeg.SaveToStream(myStream);
      myStream.Free;
      Post;
    end;

    with ADOCmd do
    begin
      Append;
      FieldByName('IMID').Value := Trim(MaxNo);
      FieldByName('IFID').Value := Trim(MaxNoFile) + 'D';
      Fieldbyname('Valid').value := Trim('Y');
      if Trim(FIMNO) = '图片' then
      begin
        FieldByName('ImageWidth').Value := Image22.Width;
        FieldByName('ImageHeight').Value := Image22.Height;
        FieldByName('FangXiang').Value := FangXiang2;
      end;
      FieldByName('IFType').Value := '大';
      myStream := TADOBlobStream.Create(TBlobField(ADOCmd.FieldByName('ImageFile')), bmWrite);
      if Trim(FIMNO) = '图片' then
      begin
        AJpeg.Assign(Image22.Picture.Graphic);
      end;
      AJpeg.SaveToStream(myStream);
      myStream.Free;
      Post;
    end;

    try
      ReadINIFile10();
      server := ReadINIFileStr('SYSTEMSET.INI', 'SERVER', '服务器地址', '127.0.0.1');
      IdFTP1.Host := server; //PicSvr;
      IdFTP1.Username := 'three';
      IdFTP1.Password := '641010';
      IdFTP1.Connect();
    except
      IdFTP1.Quit;
      Application.MessageBox('无法连接到文件服务器，请检查！', '提示', MB_ICONWARNING);
      Exit;
    end;

    if IdFTP1.Connected then
    begin
      if Trim(FIMNO) = '内容' then
      begin
        IdFTP1.Put(lstPat[0], 'YP' + '\' + Trim(MaxNo) + Trim(ImagName));
      end
      else if Trim(FIMNO) = '图片' then
      begin
        IdFTP1.Put(LocalFileName, 'YP' + '\' + Trim(MaxNo) + ImagName);
      end;
    end;
    if IdFTP1.Connected then
      IdFTP1.Quit;

  except
    ADOCmd.Connection.RollbackTrans;
    Application.MessageBox('图片保存失败！', '提示', 0);
  end;
end;

procedure TfrmZHCPInPut.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  ModalResult := 1;
end;

function TfrmZHCPInPut.StrFenHang(FStr: string; var FHStr: string): Boolean;
var
  i, j: Integer;
  LSStr: string;
begin
  Result := False;
  FStr := Trim(FStr);
  FHStr := '';
  j := 1;
  i := Pos(' ', FStr);
  while i > 0 do
  begin
    if j = 1 then
    begin
      LSStr := Copy(FStr, 1, i - 1);  //'1234  5678 456'
      FHStr := '1:' + LSStr;
    end
    else
    begin
      LSStr := Copy(FStr, 1, i - 1);
      if Trim(LSStr) = '' then
      begin
        FStr := Copy(FStr, i + 1, Length(FStr) - i);
      end
      else
        FHStr := FHStr + #13 + #10 + inttostr(j) + ':' + LSStr;
    end;
    if Trim(LSStr) <> '' then
    begin
      j := j + 1;
      FStr := Copy(FStr, i + 1, Length(FStr) - i);
    end;
    i := Pos(' ', FStr);
  end;
  if j = 1 then
  begin
    FHStr := FStr;
  end
  else
  begin
    if Trim(FStr) <> '' then
    begin
      FHStr := FHStr + #13 + #10 + inttostr(j) + ':' + FStr;
    end;
  end;
  Result := True;
end;

procedure TfrmZHCPInPut.FormCreate(Sender: TObject);
begin
  lstPat := TStringList.Create;
  lstPat2 := TStringList.Create;
end;

procedure TfrmZHCPInPut.Button2Click(Sender: TObject);
var
  AJpeg: TJPEGImage;
  Bitmap, Bitmap22: TBitmap;
  ARect, ARect22: TRect;
  TPHeight: Integer;
  TPWidth: Integer;
  WZFlag: string;
  FullFileName: string;
  FileExt: string;
begin
  // 初始化变量
  WZFlag := ''; // 重要：初始化变量

  lstPat2.Clear;
  
  // 文件选择对话框
  if ODPat.Execute then
  begin
    lstPat2.AddStrings(ODPat.Files);
  end
  else
  begin
    Exit;
  end;
  
  // 文件数量验证
  if lstPat2.Count > 1 then
  begin
    lstPat2.Clear;
    Application.MessageBox('不能上传多个图片!', '提示', 0);
    Exit;
  end
  else if lstPat2.Count < 1 then
  begin
    Exit;
  end;
  
  // 显示加载面板
  Panel1.Visible := True;
  Panel1.Refresh;
  
  // 使用完整文件路径
  FullFileName := ODPat.FileName; // 获取完整路径
  // 检查文件是否存在
  if not FileExists(FullFileName) then
  begin
    Application.MessageBox(PChar('文件不存在: ' + FullFileName), '错误', 0);
    Panel1.Visible := False;
    Exit;
  end;

  AJpeg := TJpegImage.Create();
  Bitmap := nil;
  Bitmap22 := nil;

  try
    try
      // 加载JPEG文件（使用完整路径）
      AJpeg.LoadFromFile(FullFileName);
      
      // 验证JPEG文件是否有效
      if (AJpeg.Width <= 0) or (AJpeg.Height <= 0) then
      begin
        Application.MessageBox('图片文件已损坏或格式不支持!', '错误', 0);
        Exit;
      end;
      
      // 存储完整路径到Hint
      Image2.Hint := FullFileName;
      
      // 改进的文件格式检查
      FileExt := LowerCase(ExtractFileExt(FullFileName));
      if (FileExt <> '.jpg') and (FileExt <> '.jpeg') then
      begin
        Application.MessageBox('图片必须是jpg格式', '提示', 0);
        Exit;
      end;
      
      // 获取图片尺寸
      TPWidth := AJpeg.Width;
      TPHeight := AJpeg.Height;
      
      // 创建位图对象
      Bitmap := TBitmap.Create;
      Bitmap22 := TBitmap.Create;
      
      // 计算缩放尺寸
      Bitmap.Width := Panel66.Width - 2;
      Bitmap.Height := Round(Panel66.Width / TPWidth * TPHeight);
      
      // 如果高度超出面板，则按高度缩放
      if Bitmap.Height > Panel66.Height then
      begin
        WZFlag := '垂直';
        Bitmap.Height := Panel66.Height - 2;
        Bitmap.Width := Round(Panel66.Height / TPHeight * TPWidth);
      end;
      
      // 创建双倍尺寸的位图
      Bitmap22.Width := Bitmap.Width * 2;
      Bitmap22.Height := Bitmap.Height * 2;
      
      // 绘制小图
      Bitmap.Canvas.FillRect(Rect(0, 0, Bitmap.Width, Bitmap.Height));
      ARect := Rect(0, 0, Bitmap.Width, Bitmap.Height);
      Bitmap.Canvas.StretchDraw(ARect, AJpeg);
      
      // 显示小图
      Image2.Height := Bitmap.Height;
      Image2.Width := Bitmap.Width;
      Image2.Picture.Assign(Bitmap);
      
      // 根据方向设置图片位置
      if Trim(WZFlag) = '垂直' then
      begin
        Image2.Top := 1;
        Image2.Left := Round((Panel66.Width - Image2.Width) / 2);
      end
      else
      begin
        Image2.Left := 1;
        Image2.Top := Round((Panel66.Height - Image2.Height) / 2);
      end;
      
      // 保存方向信息
      FangXiang2 := WZFlag;
      
      // 绘制大图
      Bitmap22.Canvas.FillRect(Rect(0, 0, Bitmap22.Width, Bitmap22.Height));
      ARect22 := Rect(0, 0, Bitmap22.Width, Bitmap22.Height);
      Bitmap22.Canvas.StretchDraw(ARect22, AJpeg);
      
      // 显示大图
      Image22.Height := Bitmap22.Height;
      Image22.Width := Bitmap22.Width;
      Image22.Picture.Assign(Bitmap22);

      Image2.Visible := True;
      ZIName.Text := ChangeFileExt(ExtractFileName(FullFileName), '');

      Panel12.Visible := True;
      WJName.Text := ChangeFileExt(ExtractFileName(Image2.Hint), '');
      WJName.Hint := ChangeFileExt(ExtractFileName(Image2.Hint), '');

    except
      on E: Exception do
      begin
        Application.MessageBox(PChar('加载图片时发生错误: ' + E.Message), '错误', 0);
      end;
    end;

  finally
    // 确保资源被释放
    if Assigned(AJpeg) then
      AJpeg.Free;
    if Assigned(Bitmap) then
      Bitmap.Free;
    if Assigned(Bitmap22) then
      Bitmap22.Free;

    Panel1.Visible := False;
  end;
end;

procedure TfrmZHCPInPut.ToolButton1Click(Sender: TObject);
var
  fPrintFile, Txt, fImagePath, maxno: string;
  i, j: Integer;
  Moudle: THandle;
  Makebar: TMakebar;
  Mixtext: TMixtext;
begin
  if Trim(FMainId) = '' then
  begin
    Application.MessageBox('没有保存数据，不能打印!', '提示', 0);
    Exit;
  end;
  fPrintFile := ExtractFilePath(Application.ExeName) + 'Report\展会产品标签85.rmf';
  if FileExists(fPrintFile) = False then
  begin
    Application.MessageBox(PChar('没有找' + ExtractFilePath(Application.ExeName) + 'Report\展会产品标签85.rmf'), '提示', 0);
    exit;
  end;
  with ADOTemp do
  begin
    Close;
    SQL.Clear;
    sql.Add(' select A.* ,C.ImageFile');
    sql.Add(' from ZH_CP_Info A');
    sql.Add(' inner join Image_Info B on A.ZIID=B.WBID');
    sql.Add(' inner join Image_File C on B.IMID=C.IMID');
    sql.Add(' where A.ZIID=''' + Trim(FMainId) + '''');
    sql.Add(' and B.IMNO=''图片'' and A.Valid=''Y'' and B.Valid=''Y'' and C.Valid=''Y'' ');
    Open;
  end;
  SCreateCDS20(ADOTemp, CDS_PRT);
  SInitCDSData20(ADOTemp, CDS_PRT);
  try
    ADOQueryCmd.Connection.BeginTrans;
    if GetLSNo(ADOQueryCmd, maxno, 'DYKC', 'ZH_CP_Info_KC', 4, 1, ) = False then
    begin
      ADOQueryCmd.Connection.RollbackTrans;
      Application.MessageBox('取样品打印最大号失败!', '提示', 0);
      Exit;
    end;
    with ADOQueryCmd do
    begin
      Close;
      sql.Clear;
      SQL.Add('select * from ZH_CP_Info_KC where DYId=''' + Trim(maxno) + '''');
      Open;
    end;
    with ADOQueryCmd do
    begin
      Append;
      FieldByName('ZIId').Value := Trim(FMainId);
      FieldByName('DYId').Value := Trim(maxno);
      FieldByName('Filler').Value := Trim(DName);
      FieldByName('FillerCode').Value := Trim(DCode);
      FieldByName('Valid').Value := 'Y';
      Post;
    end;
    with ADOQueryCmd do
    begin
      Close;
      sql.Clear;
      sql.Add('Update ZH_CP_Info_KC Set DYXH=isnull((select max(DYXH) from ZH_CP_Info_KC A ');
      sql.Add(' where A.ZIID=''' + Trim(FMainId) + '''),0)+1 ');
      sql.Add(' where DYID=''' + Trim(maxno) + '''');
      ExecSQL;
    end;
    ADOQueryCmd.Connection.CommitTrans;
  except
    ADOQueryCmd.Connection.RollbackTrans;
    Application.MessageBox('保存打印流水号异常！', '提示', 0);
    Exit;
  end;
  try
    Moudle := LoadLibrary('MakeQRBarcode.dll');
    @Makebar := GetProcAddress(Moudle, 'Make');
    @Mixtext := GetProcAddress(Moudle, 'MixText');
    Txt := Trim(maxno);
    fImagePath := ExtractFilePath(Application.ExeName) + 'image\temp.bmp';
    if not DirectoryExists(pchar(ExtractFilePath(Application.ExeName) + 'image')) then
      CreateDirectory(pchar(ExtractFilePath(Application.ExeName) + 'image'), nil);
    if FileExists(fImagePath) then
      DeleteFile(fImagePath);
    Makebar(pchar(Txt), Length(Txt), 3, 3, 0, PChar(fImagePath), 3);
  except
    application.MessageBox('二维码生成失败！', '提示信息', MB_ICONERROR);
    exit;
  end;
  RMVariables['QRBARCODE'] := fImagePath;
  RMVariables['DYID'] := maxno;
  RM1.LoadFromFile(fPrintFile);
  //RM1.ShowReport;
  RM1.PrintReport;
end;

procedure TfrmZHCPInPut.Image1DblClick(Sender: TObject);
begin
  if Trim(FMainId) = '' then
  begin
    Application.MessageBox('没有保存数据，不能查看大图!', '提示', 0);
    Exit;
  end;
  try
    frmZHCPBigTP := TfrmZHCPBigTP.Create(Application);
    with frmZHCPBigTP do
    begin
      frmZHCPBigTP.FMainId := Self.FMainId;
      if Trim(ZIID.Text) <> '' then
        frmZHCPBigTP.FIMNO := '内容';
      if ShowModal = 1 then
      begin

      end;
    end;
  finally
    frmZHCPBigTP.Free;
  end;
end;

procedure TfrmZHCPInPut.Image2DblClick(Sender: TObject);
begin
  if Trim(FMainId) = '' then
  begin
    Application.MessageBox('没有保存数据，不能查看大图!', '提示', 0);
    Exit;
  end;
  try
    frmZHCPBigTP := TfrmZHCPBigTP.Create(Application);
    with frmZHCPBigTP do
    begin
      frmZHCPBigTP.FMainId := Self.FMainId;
      if Trim(ZIID.Text) <> '' then
        frmZHCPBigTP.FIMNO := '图片';
      if ShowModal = 1 then
      begin

      end;
    end;
  finally
    frmZHCPBigTP.Free;
  end;
end;

procedure TfrmZHCPInPut.HXNO1BtnClick(Sender: TObject);
begin
  try
    frmZdyAttachCP_HX := TfrmZdyAttachCP_HX.Create(Application);
    with frmZdyAttachCP_HX do
    begin
      if ShowModal = 1 then
      begin
        HXNO.text := Trim(CDS_HZ.fieldbyname('zdyCode').AsString);
        ZICL.text := Trim(CDS_HZ.fieldbyname('defstr1').AsString);
      end;
    end;
  finally
    frmZdyAttachCP_HX.Free;
  end;
end;

procedure TfrmZHCPInPut.MianBuBtnClick(Sender: TObject);
begin
  try
    frmMLMangeYH := TfrmMLMangeYH.Create(Application);
    with frmMLMangeYH do
    begin
      if ShowModal = 1 then
      begin
        MianBu.text := Trim(CDS_Main.fieldbyname('MLXXNO').AsString);
        MianBuName.text := Trim(CDS_Main.fieldbyname('MLName').AsString);
        with ADOTemp do
        begin
          Close;
          sql.Clear;
          sql.Add('select top 1 MBCBDJ from ZH_CP_Info  where MianBu=''' + Trim(CDS_Main.fieldbyname('MLXXNO').AsString) + ''' and Valid=''Y'' order by ZIDate desc ');
          Open;
        end;
        MBCBDJ.text := Trim(ADOTemp.fieldbyname('MBCBDJ').AsString);
      end;
    end;
  finally
    frmMLMangeYH.Free;
  end;

end;

procedure TfrmZHCPInPut.ZhongJianCBtnClick(Sender: TObject);
begin
  Panel4.Visible := True;
  ZT := 'ZJC';
end;

procedure TfrmZHCPInPut.DiBuBtnClick(Sender: TObject);
begin
  Panel4.Visible := True;
  ZT := 'DB';
end;

procedure TfrmZHCPInPut.DiBuNameBtnClick(Sender: TObject);
begin
  try
    frmZDYHelp := TfrmZDYHelp.Create(Application);
    with frmZDYHelp do
    begin
      flag := 'DiBuName';
      flagname := '底布名称';
      if ShowModal = 1 then
      begin
        DiBuName.text := Trim(ClientDataSet1.fieldbyname('ZDYName').AsString);
      end;
    end;
  finally
    frmZDYHelp.Free;
  end;
end;

procedure TfrmZHCPInPut.MianBuNameBtnClick(Sender: TObject);
begin
  try
    frmZDYHelp := TfrmZDYHelp.Create(Application);
    with frmZDYHelp do
    begin
      flag := 'MianBuName';
      flagname := '面布名称';
      if ShowModal = 1 then
      begin
        MianBuName.text := Trim(ClientDataSet1.fieldbyname('ZDYName').AsString);
//        with ADOTemp do
//        begin
//          Close;
//          sql.Clear;
//          sql.Add('select top 1 MBCBDJ from ZH_CP_Info  where MianBuName=''' + Trim(ClientDataSet1.fieldbyname('ZDYName').AsString) + ''' order by ZIDate desc ');
//          Open;
//        end;
//        MBCBDJ.text := Trim(ADOTemp.fieldbyname('MBCBDJ').AsString);
      end;
    end;
  finally
    frmZDYHelp.Free;
  end;
end;

procedure TfrmZHCPInPut.Button3Click(Sender: TObject);
begin
  Self.Panel4.Visible := false;
  frmMCP := TfrmMCP.create(self);
  with frmMCP do
  begin
    flag := 'MName';
    flagName := '棉';
    ViewFlag := true;
    Panel4.Align := alClient;
    ToolBar3.Visible := false;
    ToolBar2.Enabled := false;
    Button1.Visible := False;
    if ShowModal = 1 then
    begin
      if ZT = 'ZJC' then
      begin
        ZhongJianCName.text := Trim(ClientDataSet1.fieldbyname('BPKZ').AsString) + 'G' + Trim(ClientDataSet1.fieldbyname('BPName').AsString);
        ZhongJianC.text := Trim(ClientDataSet1.fieldbyname('BPCode').AsString);
        ZhongJianCID.text := Trim(ClientDataSet1.fieldbyname('BPID').AsString);
      end
      else if ZT = 'DB' then
      begin
        DiBuName.text := Trim(ClientDataSet1.fieldbyname('BPKZ').AsString) + 'G' + Trim(ClientDataSet1.fieldbyname('BPName').AsString);
        DiBu.text := Trim(ClientDataSet1.fieldbyname('BPCode').AsString);
        DiBuID.text := Trim(ClientDataSet1.fieldbyname('BPID').AsString);
      end;

    end;
    free;
  end;

end;

procedure TfrmZHCPInPut.Button4Click(Sender: TObject);
begin
  Self.Panel4.Visible := false;
  try
    frmMLMangeYH := TfrmMLMangeYH.Create(Application);
    with frmMLMangeYH do
    begin
      if ShowModal = 1 then
      begin
        if ZT = 'ZJC' then
        begin
          ZhongJianCName.text := Trim(CDS_Main.fieldbyname('MLName').AsString);
          ZhongJianC.text := Trim(CDS_Main.fieldbyname('MLXXNO').AsString);
        end
        else if ZT = 'DB' then
        begin
          DiBuName.text := Trim(CDS_Main.fieldbyname('MLName').AsString);
          DiBu.text := Trim(CDS_Main.fieldbyname('MLXXNO').AsString);
        end;
      end;
    end;
  finally
    frmMLMangeYH.Free;
  end;
end;

procedure TfrmZHCPInPut.HXNOBtnDnClick(Sender: TObject);
begin
  TBtnEditC(Sender).Text := '';
  TBtnEditC(Sender).TxtCode := '';
end;

procedure TfrmZHCPInPut.HXNOBtnUpClick(Sender: TObject);
begin
  try
    frmZdyAttachCP_HX := TfrmZdyAttachCP_HX.Create(Application);
    with frmZdyAttachCP_HX do
    begin
      if ShowModal = 1 then
      begin
        HXNO.text := Trim(CDS_HZ.fieldbyname('zdyCode').AsString);
        ZICL.text := Trim(CDS_HZ.fieldbyname('defstr1').AsString);
//        HXNO.TxtCode := Trim(CDS_HZ.fieldbyname('ZdyName').AsString);
        HXNM.text := Trim(CDS_HZ.fieldbyname('ZdyName').AsString);
      end;
    end;
  finally
    frmZdyAttachCP_HX.Free;
  end;
end;

procedure TfrmZHCPInPut.MBCBDJChange(Sender: TObject);
begin
  if (Trim(MBCBDJ.Text) <> '') and (Trim(DBCBDJ.Text) <> '') and (Trim(MHDJ.Text) <> '') and (Trim(XHJGFDJ.Text) <> '') and (Trim(TSHGYCB.Text) <> '') then
  begin
    CPCBDJ.Text := FloatToStr(StrToFloatdef(Trim(MBCBDJ.Text), 0) + StrToFloatdef(Trim(DBCBDJ.Text), 0) + StrToFloatdef(Trim(MHDJ.Text), 0) + StrToFloatdef(Trim(XHJGFDJ.Text), 0) + StrToFloatdef(Trim(TSHGYCB.Text), 0));
  end
  else
  begin
    CPCBDJ.Text := '';
  end;

end;

procedure TfrmZHCPInPut.MenuItem2Click(Sender: TObject);
begin
  if lstPat2.Count < 1 then
    exit;
  Panel12.Visible := True;
  Cancel.Visible := True;
  Rename.Visible := True;
  Panel12.Refresh;
  WJName.Text := ChangeFileExt(ExtractFileName(Image2.Hint), '');
  WJName.Hint := ChangeFileExt(ExtractFileName(Image2.Hint), '');
end;

procedure TfrmZHCPInPut.RenameClick(Sender: TObject);
var
  OldFileName, NewFileName, FileExt: string;
begin
  // 检查是否有图片被加载
  if Trim(Image2.Hint) = '' then
  begin
    Application.MessageBox('请先选择图片!', '提示', 0);
    Exit;
  end;
  
  // 检查新文件名是否为空
  if Trim(WJName.Text) = '' then
  begin
    Application.MessageBox('请输入新文件名!', '提示', 0);
    Exit;
  end;

  // 检查原文件是否存在
  if not FileExists(Image2.Hint) then
  begin
    Application.MessageBox('原图片文件不存在，可能已被删除或移动!', '错误', 0);
    Exit;
  end;
  
  // 获取当前文件名和扩展名
  OldFileName := Image2.Hint;
  FileExt := ExtractFileExt(OldFileName); // 获取原文件的扩展名
  // 构建新文件名（保持相同目录和扩展名）
  NewFileName := ExtractFilePath(OldFileName) + Trim(WJName.Text) + FileExt;
  
  // 检查新文件是否已存在（且不是同一个文件）
  if (NewFileName <> OldFileName) and FileExists(NewFileName) then
  begin
    if Application.MessageBox(PChar('文件 "' + ExtractFileName(NewFileName) + '" 已存在，是否覆盖?'), '提示', MB_YESNO + MB_ICONQUESTION) = IDNO then
      Exit;
  end;
  
  // 执行重命名
  if RenameFile(OldFileName, NewFileName) then
  begin
    // 更新所有相关变量
    Image2.Hint := NewFileName;  // 更新Hint中的完整路径
    // 更新lstPat2中的文件路径
    if lstPat2.Count > 0 then
      lstPat2[0] := NewFileName
    else
      lstPat2.Add(NewFileName);
      
    // 更新界面显示（只显示文件名，不含扩展名）
//    Edit2.Text := Trim(WJName.Text);
    // 如果CopyInt不是99，也更新ZIName
    if CopyInt <> 99 then
      ZIName.Text := Trim(WJName.Text);

    Application.MessageBox(PChar('文件已成功重命名为: ' + ExtractFileName(NewFileName)), '成功', MB_ICONINFORMATION);
    
    // 可选：记录操作日志
    // WriteToLog('图片重命名: ' + ExtractFileName(OldFileName) + ' -> ' + ExtractFileName(NewFileName));

    Panel12.Visible := False;
  end
  else
  begin
    Application.MessageBox('重命名失败，请检查文件是否被占用或权限不足!', '错误', MB_ICONERROR);
  end;
end;

procedure TfrmZHCPInPut.CancelClick(Sender: TObject);
begin
  panel12.Visible := False;
end;

procedure TfrmZHCPInPut.img1Click(Sender: TObject);
begin
  Panel12.Visible := False;
end;

end.

