Hong-Dell\Hong
2022-11-08 ef8675b8cf493c2b08c428b8f9f5e35a5c52e51c
CB_IMGPSScanImp.pas
@@ -1,5 +1,5 @@
unit CB_IMGPSScanImp;
//Test
{$WARN SYMBOL_PLATFORM OFF}
interface
@@ -9,12 +9,20 @@
  EnDiGrph, { for TDibGraphic }
  EnMisc,   { for MinFloat }
  EnTifGr,  { for TTifGraphic }
  {$IFDEF Production}
  CB_IMGPSScan_TLB,
  {$ENDIF}
  {$IFDEF Test}
  CB_IMGPSScan_test_TLB,
  {$ENDIF}
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  ActiveX, AxCtrls, CB_IMGPSScan_TLB, StdVcl, VCLUnZip, VCLZip, Encryp,
  ActiveX, AxCtrls, StdVcl, VCLUnZip, VCLZip, Encryp,
  ExtCtrls, ComCtrls, Menus, StdCtrls, Gauges, EnImgScr, PJMenuSpeedButtons,
  Buttons, ImgList, SBSimpleSSL, SBHTTPSClient, SBWinCertStorage, SBX509,
  SBCustomCertStorage, SBUtils,mpsBarco,BarcodesFinder,HTTPApp,ErrList,
  Xmltool,inifiles,printers;
  Xmltool,inifiles,printers,IdHashMessageDigest, idHash, LogFile,ShellApi,
  SBSocket;
var
  Ch_WriteNote : Boolean;
@@ -111,7 +119,6 @@
    Splitter1: TSplitter;
    Panel3: TPanel;
    Label7: TLabel;
    TreeView1: TTreeView;
    Panel6: TPanel;
    CB1: TCheckBox;
    ScanDuplexCB: TCheckBox;
@@ -145,7 +152,6 @@
    ISB2: TImageScrollBox;
    imgp1: TPanel;
    lb1: TLabel;
    ISB1: TImageScrollBox;
    Memo1: TMemo;
    Display1: TMemo;
    Panel22: TPanel;
@@ -181,7 +187,6 @@
    PM402: TMenuItem;
    PM403: TMenuItem;
    PM404: TMenuItem;
    HTTPSClient: TElHTTPSClient;
    ElWinCertStorage: TElWinCertStorage;
    ElMemoryCertStorage: TElMemoryCertStorage;
    Panel5: TPanel;
@@ -189,8 +194,6 @@
    Panel11: TPanel;
    SampleScanBtn: TBitBtn;
    WNoteBtn: TBitBtn;
    Panel13: TPanel;
    CaseHelpBtn: TBitBtn;
    PopupMenu1: TPopupMenu;
    PM101: TMenuItem;
    N12: TMenuItem;
@@ -248,13 +251,28 @@
    Edit1: TEdit;
    PM110: TMenuItem;
    Image1: TImage;
    PrtLb: TLabel;
    UseOldCaseLb: TLabel;
    PM111: TMenuItem;
    SmoothCB: TCheckBox;
    ISB_BW: TImageScrollBox;
    N1: TMenuItem;
    N2: TMenuItem;
    ISB1: TImageScrollBox;
    Label3: TLabel;
    LogFile1: TLogFile;
    ScanGrayCB: TCheckBox;
    AttFileGB: TGroupBox;
    AttListBox: TListBox;
    Panel20: TPanel;
    AddAttFileLB: TLabel;
    DelAttFileLB: TLabel;
    Splitter2: TSplitter;
    Panel17: TPanel;
    TreeView1: TTreeView;
    Panel13: TPanel;
    PrtLb: TLabel;
    CaseHelpBtn: TBitBtn;
    HTTPSClient: TElHTTPSClient;
    procedure ActiveFormCreate(Sender: TObject);
    procedure Panel9Resize(Sender: TObject);
    procedure ISB1Click(Sender: TObject);
@@ -370,6 +388,17 @@
    procedure ImageScrollBox1NewGraphic(const Graphic: TDibGraphic);
    procedure SmoothCBClick(Sender: TObject);
    procedure N1Click(Sender: TObject);
    procedure TreeView1MouseEnter(Sender: TObject);
    procedure ScrollBox1MouseEnter(Sender: TObject);
    procedure ScanGrayCBClick(Sender: TObject);
    procedure AddAttFileLBClick(Sender: TObject);
    procedure DelAttFileLBClick(Sender: TObject);
    procedure AttListBoxDblClick(Sender: TObject);
    procedure AttListBoxClick(Sender: TObject);
    procedure TreeView1MouseDown(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    procedure HTTPSClientRedirection(Sender: TObject; const OldURL: string;
      var NewURL: string; var AllowRedirection: Boolean);
  private
    { Private declarations }
    HotKeyId1,HotKeyId2,HotKeyId3,HotKeyId4 :Integer;
@@ -406,6 +435,7 @@
    FImgDelete:string; // Y/N  有權限可在補件時刪除影像
    FIsExternal:string;//Y/N
    FCheck_main_form:string; //Y/N
    FWH_category:string;  //Y/N  Y是歸類時有區分入庫非入庫文件  N 是不區分
    ////////傳入參數///////
    //********Http參數********
@@ -466,6 +496,7 @@
    CaseDocNoList : TStringlist;  //案件裡的DocNo清單(不重複)
    CaseDocNo_CopiesList : TStringlist; //案件裡的DocNo份數清單
    ContextList : TStringlist; //案件裡的檔案清單
    AttContextList : TStringlist; //案件裡的附加檔案清單
    OMRFileList : TStringList; //要OMR檢核的文件(只檢查每種Form的第一頁)
    Cust_DocNoList : TStringlist; //自行定義文件名稱
    IN_WH_DocNoList : TStringlist; //入庫的文件清單
@@ -481,8 +512,12 @@
    NowShowFileList : TStringlist;  //目前顯示的影像清單
    NowSelectFileList : TStringlist; //目前被點選的影像清單
    GuideFormIDList : TStringlist; //要當導引頁表單清單
    DivPageFormIDList:TStringlist; //要當分案頁表單清單
    LastInitFormidList:TStringList;
    LastAddFormidList:TstringList;
    SampleFormIDList:TStringList; //20170627 已存在範本的formid
    ExistImgList:TStringList;  //20170724  已經存在的影像list for ESCAN  //Img的完整路徑
    reSizeExistImgList:TstringList; //20171012被縮放的舊圖MD5存入
    //********清單區********
    //********顯示區********
@@ -554,11 +589,14 @@
    Has_Authorize :String; //是否有授權書影像
    AttName : String; //未歸類目錄名稱
    NowGuideFormID : String;
    NowDivPageFormID:String;
    FirstDocDir : String;
    FMaxUploadSize:String;// 上傳zip大小限制
    FJpgCompression:integer;// 20171211 jpg to tif 的壓縮率
    Draging : Boolean;
    MDown : Boolean;  //20181210 用來判斷滑鼠右鍵要Popupmenu是否有MouseDonw發生
    FEvents: ICB_IMGPSScanXEvents;
@@ -636,6 +674,7 @@
    Procedure initkscan; //檢查掃描器的功能
    procedure LoadImgFile; //載入案件
    procedure LoadImgFile1; //載入案件
    procedure LoadAttFile(CaseID:String); //載入附加檔案
    Procedure DistinctFormCode(CaseID:String); //案件裡的FormCode取出第一頁
    Function OMRCheckCase(CaseID:String):Boolean; //OMR檢核
    Procedure OMRErr2ini(CaseID,Reason,FileName,Site,RelaFileName,RelaSite,Anchor,Anchor1:String;Del,Ingnore,Display:Boolean); //OMR檢核失敗寫入ini
@@ -650,6 +689,7 @@
    Procedure CreateIn_WH(CaseID:String);  //產生In_WH.dat
    Function CreateDocNo_Info(CaseID:String):String; //產生保管袋文件 DocNo[tab]份數[tab]總頁數[tab]是否異動[換行]DocNo[tab]份數[tab]總頁數[tab]是否異動
    Function CreateCustDocNo_Info(CaseID:String):String; //產生自訂文件 DocName[tab]份數[tab]總頁數[tab]是否異動[#13#10]DocName[tab]份數[tab]總頁數[tab]是否異動
    //Function CreateCustDocNo_Info(path,CaseID:String):String; overload
    Function CreateAttach_Info(CaseID:String):String; //產生是否有Attach Y:有 N:沒有
    Function CreateDocnoFrom_Info(CaseID:String):String; //產生被引進的保管袋文件資訊  Docno[tab]份數[tab]案件編號#13#10Docno[tab]份數[tab]案件編號
    Function CreateCustDocNoFrom_Info(CaseID:String):String; //產生被引進的自定文件資訊  Docno[tab]份數[tab]案件編號#13#10Docno[tab]份數[tab]案件編號
@@ -675,7 +715,7 @@
    Function FindFormCodePages(CaseID,FormCode:String):Integer;  //計算案件裡FormID的頁數
    Function GetDataFormCodePages(FormCode:String):Integer;   //取記錄的FormcID的頁數
    Procedure CaseReSize(CaseID:String); //案件的影像縮放
    Procedure ImageReSize(CaseID,FileName:String);  //依十字定位點做縮放
    Procedure ImageReSize_FormID(CaseID,FileName:String);  //依十字定位點做縮放
    Procedure ImageReSize_tmp(FormID,FileName:String);  //依十字定位點做縮放(暫存檔)
    Function TransCaseID(Path,CaseID:String;MainCase:Boolean):Boolean; //傳送案件
    Procedure NewTreeNodeRefresh;
@@ -697,6 +737,9 @@
    Procedure SetCaseList(Mode:Char;Index:Integer;text:String);  //'A:加入,I:插入,D:刪除,E:修改'
    Procedure SetDocNoList(Mode:Char;Index:Integer;CaseNo,DocDir,Copies:String);  //'A:加入,I:插入,D:刪除,E:修改'
    Procedure SetContextList(Mode:Char;Index:Integer;CaseNo,DocDir,FileName:String);  //'A:加入,I:插入,D:刪除,E:修改'
    Procedure SetAttContextList(Mode:Char;Index:Integer;CaseNo,FileName:String);  //'A:加入,I:插入,D:刪除,E:修改'
    Function checkCaseOMRDone:Boolean;  //檢查案件是否完成OMR檢核
    Function CheckCaseID_OK:Boolean;  //檢查是否有未配號的案件
    Procedure CreateEmptyCase(Path,CaseID:String);  //產生空白案號(重掃件用)
@@ -708,7 +751,6 @@
    Procedure PageReplaceFormID(Path,NowFormID,NewFormID:String); //選取頁更換FormID
    Function ModeNeedCheck(OMRMode,ScanMode:String):Boolean; //掃瞄模式是否要做檢核
    procedure WMMOUSEWHEEL(var message: TWMMouseWheel); message WM_MOUSEWHEEL;
    Function GetInputMask:String; //取得輸入的保單號碼
    Function GetCasePage(Path,CaseID:String):Integer;
    Function GetFormIDPage(FileList:TStringlist;FormID:String):Integer;
    Procedure SetFile2Case(CaseID,FileName:String);
@@ -826,6 +868,20 @@
    procedure initParameter;
    procedure LastInitFormidListCreate(path:string);
    function checkFormCodeIsCustom(path,formcode:string):boolean;
    function ISDivPageFormID(FormID: String): Boolean;
    function GetSampleInf: Boolean;
    procedure InitExistImgList(casepath:String);
    function LoadFileGetMD5(const filename:string):string; //20170809 取的檔案的MD5
    function ISExistImg(const filename:string):boolean;  //20170809 確認是否存在原有影像
    procedure _DelTreeForExistImg(ASourceDir:String);   //2017 刪除前確認 有舊影像嗎
    function DocNoIsExistImg(DocNopath: String): boolean; //2017 刪除前確認 有舊影像嗎
    function CheckCaseAttach_OK: Boolean;
    function DeleteDocNoFileForESCAN(Path, DocNo: String): Boolean;     //2017 確認是否有未歸類文件
    function CheckRequiredColumnValues(workno,caseno:String) :Boolean;  //20171003  此大類下此案是否檢核必填
    function logTimeString :String;
    procedure ReduceLogFile ;
    function FindLastestDocDirForPage(CaseID, DocNo, formid: String): String;
    function OMRErrini2ListForLog(CaseID: String):String;
  protected
    { Protected declarations }
    procedure DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage); override;
@@ -945,6 +1001,8 @@
    function Get_isExternal: WideString; safecall;
    procedure Set_check_main_form(const Value: WideString); safecall;
    procedure Set_isExternal(const Value: WideString); safecall;
    function Get_WH_CATEGORY: WideString; safecall;
    procedure Set_WH_CATEGORY(const Value: WideString); safecall;
  public
    { Public declarations }
    procedure Initialize; override;
@@ -1001,32 +1059,89 @@
end;
procedure TCB_IMGPSScanX.WMMOUSEWHEEL(var message: TWMMouseWheel);
var
  I: Integer;
  iISB : TImageScrollBox;
begin
    inherited;
    //lb1.Caption:=IntToStr(message.Keys);
    if (message.WheelDelta = WHEEL_DELTA) Then
    begin
    if (message.WheelDelta = WHEEL_DELTA) Then begin
     if Edit1.Focused then
     begin
       ScrollBox1.VertScrollBar.Increment := 50;
       ScrollBox1.Perform(WM_VSCROLL, SB_LINEUP, 0);
     end
     else if DisplayISB.Focused then
     begin
       DisplayISB.VertScrollBar.Increment := 50;
       DisplayISB.Perform(WM_VSCROLL, SB_LINEUP, 0);
     end;
     end else if (message.WheelDelta = -WHEEL_DELTA) then begin
     if Edit1.Focused then
     begin
       ScrollBox1.VertScrollBar.Increment := 50;
       ScrollBox1.Perform(WM_VSCROLL, SB_LINEDOWN, 0);
     end
     else if DisplayISB.Focused then
     begin
       DisplayISB.VertScrollBar.Increment := 50;
       DisplayISB.Perform(WM_VSCROLL, SB_LINEDOWN, 0);
     end;
      if ScrollBox1.Focused then
      begin
        ScrollBox1.VertScrollBar.Increment := 50;
        ScrollBox1.Perform(WM_VSCROLL,SB_Lineup,0);
      end;
      if DisplayISB <> nil then
      begin
        if (DisplayISB.Focused) and (message.Keys=0) then
        begin
           DisplayISB.VertScrollBar.Increment := 50;
           DisplayISB.Perform(WM_VSCROLL,SB_Lineup,0);
        end;
        if (DisplayISB.Focused) and (message.Keys=50) then
        begin
          DisplayISB.ZoomMode := zmPercent;
          if DisplayISB.ZoomPercent < 90 then
            DisplayISB.ZoomPercent := DisplayISB.ZoomPercent+10;
        end;
      end;
      i:=0;
      while FindComponent(ISBName+inttostr(i)) <> nil do
      begin
        iISB := TImageScrollBox(FindComponent(ISBName+inttostr(i)));
        if iISB.Focused then
        begin
          ScrollBox1.VertScrollBar.Increment := 50;
          ScrollBox1.Perform(WM_VSCROLL,SB_Lineup,0);
        end;
        inc(i);
      end;
    end
    else if (message.WheelDelta = -WHEEL_DELTA) then
    begin
      if ScrollBox1.Focused then
      begin
        ScrollBox1.VertScrollBar.Increment := 50;
        ScrollBox1.Perform(WM_VSCROLL, SB_LINEDOWN, 0);
      end;
      if DisplayISB <> nil then
      begin
        if (DisplayISB.Focused) and (message.Keys=0) then
        begin
           DisplayISB.VertScrollBar.Increment := 50;
           DisplayISB.Perform(WM_VSCROLL,SB_LINEDOWN,0);
        end;
        if (DisplayISB.Focused) and (message.Keys=50) then
        begin
          DisplayISB.ZoomMode := zmPercent;
          if DisplayISB.ZoomPercent > 10 then
            DisplayISB.ZoomPercent := DisplayISB.ZoomPercent-10;
        end;
      end;
      i:=0;
      while FindComponent(ISBName+inttostr(i)) <> nil do
      begin
        iISB := TImageScrollBox(FindComponent(ISBName+inttostr(i)));
        if iISB.Focused then
        begin
          ScrollBox1.VertScrollBar.Increment := 50;
          ScrollBox1.Perform(WM_VSCROLL,SB_Lineup,0);
        end;
        inc(i);
      end;
    end;
end;
procedure TCB_IMGPSScanX.WNoteBtnClick(Sender: TObject);
@@ -1195,6 +1310,31 @@
  PM605Click(nil);
end;
procedure TCB_IMGPSScanX.InitExistImgList(casepath: String);
var
  ST1,ST2,ST3,ST4:TStringList;
  i,j,k:Integer;
begin
  ST1:=TStringList.Create;
  ST2:=TStringList.Create;
  ST3:=TStringList.Create;
  ExistImgList.Clear;
  ST1.LoadFromFile(casepath+'Download\Context.dat');
  for I := 0 to ST1.Count - 1 do
  begin
LogFile1.LogToFile(logTimeString+casepath+'Download\'+ST1.Strings[i]+',MD5='+LoadFileGetMD5(casepath+'Download\'+ST1.Strings[i]));
    ExistImgList.Add(LoadFileGetMD5(casepath+'Download\'+ST1.Strings[i])) ;
  end;
LogFile1.LogToFile(logTimeString+'ExistImgList.text'+ExistImgList.CommaText);
  ST1.Free;
  ST2.Free;
  ST3.Free;
end;
procedure TCB_IMGPSScanX.Initialize;
begin
  inherited Initialize;
@@ -1236,6 +1376,7 @@
    NowPage := p+1;
    PageLV.ItemIndex := P;
  end;
  //DisplayISB.SetFocus;
end;
procedure TCB_IMGPSScanX.ISB1EndScroll(Sender: TObject);
@@ -1264,7 +1405,8 @@
  p : Integer;
begin
  DisplayISB := TImageScrollBox(Sender);
  DisplayISB.SetFocus;
  if NowClick<>0 then
    DisplayISB.SetFocus;
  Shape1.Left := TPanel(TImageScrollBox(Sender).Parent).Left - Seg;
  Shape1.Top := TPanel(TImageScrollBox(Sender).Parent).Top - Seg;
  P := strtoint(copy(DisplayISB.Name,4,1)) + ScrollBar1.Position-2;
@@ -1297,12 +1439,27 @@
procedure TCB_IMGPSScanX.ISB1ImageMouseMove(Sender: TObject; Shift: TShiftState;
  X, Y: Integer);
begin
   Edit1.SetFocus;
   //Edit1.SetFocus;
  //TImageScrollBox(Sender).SetFocus;
  if TImageScrollBox(Sender).FileName = '' then
    TImageScrollBox(Sender).MouseMode := mmUser
  Else
    ViewMouseMode(NowClick);
  ISB1.AlwaysShowAnnotations := False;
//  if TImageScrollBox(Sender).FileName = '' then
//  begin
////ShowMessage('AAA');
//Label3.Caption:='FileName='+TImageScrollBox(Sender).FileName+'  time='+FormatDateTime('yyyy/mm/dd HH:MM:SS', now);
//    TImageScrollBox(Sender).MouseMode := mmUser
//  end
//  Else
//  begin
//Label3.Caption:='FileName='+TImageScrollBox(Sender).FileName;
//    ViewMouseMode(NowClick);
//  end;
end;
procedure TCB_IMGPSScanX.ISB1ImageMouseUp(Sender: TObject; Button: TMouseButton;
@@ -1549,15 +1706,25 @@
  DocNo_List.Free; //DocNo清單
  Context_DocnoList.Free; //案件裡的檔案Docno清單
  ContextList.Free; //案件裡的檔案清單
  AttContextList.Free; //案件裡的附加檔案清單
  NowShowFileList.Free;  //目前顯示的影像清單
  NowSelectFileList.Free; //目前被點選的影像清單
  Cust_DocNoList.Free; //自行定義文件名稱
  IN_WH_DocNoList.Free; //入庫的文件清單
  GuideFormIDList.Free; //要當導引頁表單清單
  DivPageFormIDList.Free; //要當分案頁表單清單
  LastInitFormidList.Free;
  LastAddFormidList.Free;
  SampleFormIDList.Free;
  ExistImgList.Free;
  reSizeExistImgList.Free;
  //********清單區********
  if (FMode = 'DSCAN') or (FMode = 'ESCAN')  then //重掃件及異動件要只能掃指定編號的件
  begin
    if ImagePath<>'' then
      _Deltree(ImagePath);
  end;
  if FEvents <> nil then FEvents.OnDestroy;
end;
@@ -1885,11 +2052,14 @@
  iISB : TImageScrollBox;
  GoAtt : Boolean;
  AttLv : Integer;
  ST1 :TStringList;
begin
  PreNode2Name := '';
  ST1:=TStringList.Create;
  if TreeView1.Selected.Parent = MyTreeNode1 then
    PreNode2Name:= GetNode2Name(MyTreeNode2);
  ShowText := _Msg('文件歸類中,請稍候');
LogFile1.LogToFile(logTimeString+'縮圖  歸類開始');
  DataLoading(True,True);
  GoAtt := False;
  if (MytreeNode2 <> nil) and (Pos('Attach',MyTreeNode2.Text)>0) then
@@ -1901,12 +2071,13 @@
  try
    InitialLanguage(DocListForm); //載入多國語言
    //InitialLanguage(PatchDlg); //載入多國語言
    DocListForm.CheckBox1.Visible:=False;
    for i := 1 to FORM_INF_List.Count - 1 do
    begin
      FormID :=  GetSQLData(FORM_INF_List,'T1.FORM_ID',i);
      FormName := GetSQLData(FORM_INF_List,'T1.FORM_DESC',i);
      DocNo := GetSQLData(FORM_INF_List,'T1.DOC_NO',i)+GetSQLData(FORM_INF_List,'T1.DOC_VERSION',i);
      if not FormIDAppear(FormID) then Continue;
      if not FormIDAppear(FormID) then Continue;   //20170816 先秀全部
      //Showmessage(FORM_INF_List.Text);
      //showmessage(inttostr(FORM_INF_List.Count)+#13+inttostr(self.Doc_Inf_List.Count));
@@ -1926,23 +2097,49 @@
      begin
        if (Components[i] is TShape) and (copy(Components[i].Name,1,2)='SP') then
        begin
          //Showmessage(Components[i].Name);
          iISBName := ShapeName2PreViewISBName(TShape(Components[i]));
          iISB := TImageScrollBox(FindComponent(iISBName));
          OldName := ExtractFileName(iISB.FileName);
          Ext := ExtractFileExt(OldName);
          FormID := DocListForm.DocLV.Selected.Caption;
          DocNo := FormCode2DocNo(FormID);
          if DocListForm.CheckBox1.Checked then
          begin
            FormID := DocListForm.Edit1.Text;
            DocNo := GetNewCustomDocNo(DisplayPath,FormID);
          end
          else
          begin
            FormID := DocListForm.DocLV.Selected.Caption;
            DocNo := FormCode2DocNo(FormID);
          end;
          if DocNoDir2DocNo(Path2DocDir(ExtractFilePath(iISB.FileName),NowCaseno)) = DocNo then
            DocDir := Path2DocDir(ExtractFilePath(iISB.FileName),NowCaseNo)
          Else
            DocDir := FindLastestDocDir(NowCaseno,DocNo);
//ShowMessage('DocNoNeedDiv(DocNo)='+BoolToStr(DocNoNeedDiv(DocNo),true));
//ShowMessage('DocDir='+DocDir);
          if DocNoNeedDiv(DocNo) then   //要分份數
          begin
            if ((FormCode2Page(FormID) = '01') and (GetDocDir_Page(NowCaseno,DocDir)>0)) or (DocDir = '') then
            begin
              DocDir := DocNo2DocNoDir(ImageSavePath + NowCaseno+'\',DocNo);
            end
            else
            begin //20171016  真對補件影響 所加的判斷
              ST1.Clear;
              if FileExists(ImageSavePath + NowCaseno+'\'+DocDir+'\Context.dat') then
              begin
                ST1.LoadFromFile(ImageSavePath + NowCaseno+'\'+DocDir+'\Context.dat');
                if (ST1.Count > 0) and ISExistImg(ImageSavePath + NowCaseno+'\'+DocDir+'\'+ST1.Strings[0]) then   //20181210 多增加判斷ST1>0 否則會有機會出現List out of bound  Hong
                begin
                  DocDir := DocNo2DocNoDir(ImageSavePath + NowCaseno+'\',DocNo);
                end;
              end;
            end;
          end
          Else        //不分份數
          begin
@@ -1961,6 +2158,7 @@
              DocDir:=DocNo2DocNoDir(ImageSavePath+NowCaseno+'\',DocNo);
            SetDocNoList('A',-1,NowCaseno,DocDir);
          end; }
LogFile1.LogToFile(logTimeString+'縮圖  FormID='+FormID);
          if Not DirectoryExists(ImageSavePath+NowCaseno+'\'+DocDir) then
            Mkdir(ImageSavePath+NowCaseno+'\'+DocDir);
          ContextList.Clear;
@@ -1976,6 +2174,7 @@
          //ReNameContext(iISB.FileName,OldName,NewName);
        end;
      end;
//ShowMessage('KKKK');
      ReSortFileName(ExtractFilePath(iISB.FileName));
      DrawDocItem2(MytreeNode1,NowCaseno);
      ClearErrini(NowCaseno,MyTreeNode1);  //清掉檢核記錄
@@ -1990,6 +2189,7 @@
  finally
  DataLoading(False,False);
  DocListForm.Free;
  ST1.Free;
  end;
end;
@@ -2018,17 +2218,18 @@
    GoAtt := True;
  end;
  if InputQuery('輸入其他文件名稱','文件名稱',CustomDocName) then
  if InputQuery(_Msg('輸入其他文件名稱'),_Msg('文件名稱'),CustomDocName) then
  begin
    if FindCustomDocName(DisplayPath,CustomDocName) then
    begin
      Showmessage(Format('文件名稱:"%s"己存在',[CustomDocName]));
      Showmessage(Format(_Msg('文件名稱:"%s"己存在'),[CustomDocName]));
      Exit;
    end;
    CustomDocNo := GetNewCustomDocNo(DisplayPath,CustomDocName);
  end;
  if CustomDocNo = '' then Exit;
  DocDir := CustomDocNo;
LogFile1.LogToFile(logTimeString+'縮圖 歸類自訂文件 DocDir='+DocDir);
  SavePath := ImageSavePath+NowCaseNo+'\'+DocDir+'\';
  Str2Dir(SavePath);
  SetDocNoList('A',-1,NowCaseNo,DocDir,'1');
@@ -2101,7 +2302,7 @@
  iISBName,OldName : String;
  iISB : TImageScrollBox;
begin
  if MessageDlg('是否確定刪除??',mtconfirmation,[mbyes,mbcancel],0) = mrcancel then Exit;
  if MessageDlg(_Msg('是否確定刪除??'),mtconfirmation,[mbyes,mbcancel],0) = mrcancel then Exit;
  for i := 0 to ComponentCount -1 do
  begin
@@ -2110,12 +2311,24 @@
      //Showmessage(Components[i].Name);
      iISBName := ShapeName2PreViewISBName(TShape(Components[i]));
      iISB := TImageScrollBox(FindComponent(iISBName));
//ShowMessage('iISB.FileName='+iISB.FileName);
//ShowMessage(ExtractFilePath(iISB.FileName)+','+ExtractFileName(iISB.FileName)+','+NowCaseNo);
//      if (FMode = 'ESCAN') and (FModeName<>'異動件') then
//      begin
//        if ISExistImg(iISB.FileName) then
//        begin
//          ShowMessage(_Msg('此圖為非當次掃瞄,不可刪除'));
//          Exit;
//        end;
//      end;
LogFile1.LogToFile(logTimeString+'縮圖刪除 iISB.FileName='+iISB.FileName);
      DeleteImageFile(ExtractFilePath(iISB.FileName),ExtractFileName(iISB.FileName),NowCaseNo);
    end;
  end;
//ShowMessage('iISB.FileName='+iISB.FileName);
  ReSortFileName(ExtractFilePath(iISB.FileName));
  DrawDocItem2(MytreeNode1,NowCaseno);
  MyTreeNode1.Text := Format('%s-%d'+_Msg('頁'),[NowCaseno,GetCasePage(ImageSavePath,NowCaseNo)]);
  MyTreeNode1.Text := Format(_Msg('%s-%d頁'),[NowCaseno,GetCasePage(ImageSavePath,NowCaseNo)]);
  NewTreeNodeRefresh;
  ClearErrini(NowCaseno,MyTreeNode1);  //清掉檢核記錄
  TreeView1click(self);
@@ -2125,7 +2338,7 @@
var
  mp:string;
begin
  mp := InputBox('移動頁數','請輸入移入頁碼','');
  mp := InputBox(_Msg('移動頁數'),_Msg('請輸入移入頁碼'),'');
  if (mp <> '') then
  begin
    MoveImage(DisplayPath+NowDocDir+'\',strtoint(mp));
@@ -2146,7 +2359,8 @@
    Showmessage(_msg('資訊尚未下載完成,請稍候或重新進入'));
    Exit;
  end;
  if (FMode = 'RSCAN') or (FMode = 'ESCAN') then
LogFile1.LogToFile(logTimeString+'掃瞄開始');
  if (FMode = 'RSCAN') or (FMode = 'ESCAN') or (FMode = 'DSCAN') then
  begin
    if NewTreeNode.Count > 0 then
    begin
@@ -2154,6 +2368,7 @@
      TreeView1click(nil);
      FirstDocDir := '';
      NowGuideFormID := '';
      NowDivPageFormID :='';
      AddScanBtnclick(nil);
    end;
  end
@@ -2169,10 +2384,12 @@
    ScanPath := '';
    ScanCaseno := '';
    NowGuideFormID := '';
    NowDivPageFormID :='';
    ClearView(1);
    ContextList.Clear;
    Try
      StatrTwainScan;
LogFile1.LogToFile(logTimeString+'掃瞄結束');
    Except
      Panel1.Enabled := True;
      Panel2.Enabled := True;
@@ -2333,8 +2550,10 @@
  P,v,v1,v2,ln,i : Integer;
  iDocDir,iDocNo : String;
begin
LogFile1.LogToFile(logTimeString+'Tree 按下刪除');
  if TreeView1.Selected = NewTreeNode then  //全刪  //新掃描件
  begin
LogFile1.LogToFile(logTimeString+'Tree 全部刪除');
    If Messagedlg(_Msg('是否刪除所有案件?'),mtconfirmation,[mbyes,mbcancel],0) = mrcancel then Exit;
    clearView(1);
    Application.ProcessMessages;
@@ -2349,6 +2568,7 @@
  end
  Else if TreeView1.Selected = MyTreeNode1 then       //案件編號
  begin
LogFile1.LogToFile(logTimeString+'Tree 案件編號刪除 NowCaseno='+NowCaseno);
    If Messagedlg(Format(_Msg('編號(%s)是否刪除?'),[NowCaseno]),mtconfirmation,[mbyes,mbcancel],0) = mrcancel then Exit;
    clearView(1);
    Application.ProcessMessages;
@@ -2393,9 +2613,20 @@
    If Messagedlg(Format(_Msg('文件(%s)是否刪除?'),[DocNo2DocName(NowCaseno,NowDocNo)]),mtconfirmation,[mbyes,mbcancel],0) = mrcancel then Exit;
    ClearView(1);
    Application.ProcessMessages;
    _DelTree(ImageSavePath+NowCaseno+'\'+NowDocDir);
//ShowMessage(NowDocDir);
LogFile1.LogToFile(logTimeString+'Tree 文件層號刪除 NowDocDir='+NowDocDir);
    if (Length(NowDocDir)=8) or (NowDocDir=AttName) then
    begin
//ShowMessage('DeleteDocNoFileForESCAN');
      DeleteDocNoFileForESCAN(ImageSavePath+NowCaseno+'\'+NowDocDir,NowDocDir);
    end
    else
    begin
      _DelTree(ImageSavePath+NowCaseno+'\'+NowDocDir);
      SetDocNoList('D',-1,NowCaseNo,NowDocDir,'');
    end;
    SetUseCase('D',ImageSavePath+NowCaseno+'\',NowDocDir,'','');
    SetDocNoList('D',-1,NowCaseNo,NowDocDir,'');
    if (Copy(NowDocNo,1,5)='ZZZZZ') then   //20140703 刪除自定文件時要刪ini檔資料
      DeleteCustomDocDir(ImageSavePath+NowCaseno+'\',NowDocDir);
@@ -2404,34 +2635,11 @@
    ClearErrini(NowCaseno,MyTreeNode1);  //清掉檢核記錄
    NewTreeNodeRefresh;
    {if (FMode <>'ESCAN') and (ContextList.Count = NowShowFileList.Count) then
    begin
      if Messagedlg(_Msg('刪除後將無影像,案件將刪除,是否確定?'),mtconfirmation,[mbyes,mbcancel],0) = mrcancel then Exit;
      _DelTree(DisplayPath);
      SetCaseList('D',NewTreeNode.IndexOf(MyTreeNode1),'');
      if (FMode = 'ESCAN') then
      begin
        MkDir(ImageSavePath+FCaseID);
        CreateEmptyCase(ImageSavePath,FCaseID);
      end;
      LoadImgFile;
    end
    Else
    begin
      DeleteShowFile(DisplayPath);
      DrawDocItem1(MytreeNode1,Doc_Inf_List,NowCaseno);
      P := ContextList.Count;
      MytreeNode1.Text := Format(_Msg('%s-%d頁'),[NowCaseno,p]);
      ClearErrini(NowCaseno,MyTreeNode1);  //清掉檢核記錄
      NewTreeNodeRefresh;
    end;
    Showmessage(_Msg('刪除完成')); }
    //Showmessage(_Msg('刪除完成'));  //20101102 User要求拿掉
  end
  Else if TreeView1.Selected = MyTreeNode3 then       //FormID層
  begin
    If Messagedlg(Format(_Msg('文件(%s)是否刪除?'),[NowFormName]),mtconfirmation,[mbyes,mbcancel],0) = mrcancel then Exit;
LogFile1.LogToFile(logTimeString+'Tree FormID層號刪除 NowFormCode='+NowFormCode);
    DeleteFormCodeFile(NowCaseNo,NowDocDir,NowFormCode);
    SetRecordEditedDocDir('A',NowCaseNo,NowDocDir);
    DrawDocItem2(MytreeNode1,NowCaseno);
@@ -2439,30 +2647,39 @@
    ClearErrini(NowCaseno,MyTreeNode1);  //清掉檢核記錄
    NewTreeNodeRefresh;
    {if (FMode <>'ESCAN') and (ContextList.Count = NowShowFileList.Count) then
    begin
      if Messagedlg(_Msg('刪除後將無影像,案件將刪除,是否確定?'),mtconfirmation,[mbyes,mbcancel],0) = mrcancel then Exit;
      _DelTree(DisplayPath);
      SetCaseList('D',NewTreeNode.IndexOf(MyTreeNode1),'');
      if (FMode = 'ESCAN') then
      begin
        MkDir(ImageSavePath+FCaseID);
        CreateEmptyCase(ImageSavePath,FCaseID);
      end;
      LoadImgFile;
    end
    Else
    begin
      DeleteShowFile(DisplayPath);
      DrawDocItem1(MytreeNode1,Doc_Inf_List,NowCaseno);
      P := ContextList.Count;
      MytreeNode1.Text := Format(_Msg('%s-%d頁'),[NowCaseno,p]);
      ClearErrini(NowCaseno,MyTreeNode1);  //清掉檢核記錄
      NewTreeNodeRefresh;
    end;
    Showmessage(_Msg('刪除完成'));
    //Showmessage(_Msg('刪除完成'));   //20101102 User要求拿掉 }
  end;
end;
function TCB_IMGPSScanX.DocNoIsExistImg(DocNopath:String):boolean;
var
  i:integer;
  ST:TStringList;
begin
  Result:=False;
  ST:=TStringList.Create;
  if FileExists(DocNopath+'\Context.dat') then   /////20190319 Hong 當有空的Docno目錄時會掛掉,增加這行
    ST.loadFromfile(DocNopath+'\Context.dat');
  for I := 0 to ST.Count - 1 do
  begin
    if ISExistImg(DocNopath+ST.Strings[i]) then
    begin
      Result:=False;
      Exit;
      Break;
    end;
  end;
  Result:=True;
end;
procedure TCB_IMGPSScanX._DelTreeForExistImg(ASourceDir:String);
var
  i:integer;
  ST:TStringList;
begin
end;
procedure TCB_IMGPSScanX.PM102Click(Sender: TObject);
@@ -2509,177 +2726,436 @@
procedure TCB_IMGPSScanX.PM103Click(Sender: TObject);
begin
  if TreeView1.Selected = nil then Exit;
  {if Treeview1.Selected = NewTreeNode then
  begin
    ShowMessage('AAAAA');
  end;
  if Treeview1.Selected = MyTreeNode1 then
  begin
    ShowMessage('BBBBB');
  end;
  if Treeview1.Selected = MyTreeNode2 then
  begin
    ShowMessage('CCCCC');
  end;
  if Treeview1.Selected = MyTreeNode3 then
  begin
    ShowMessage('DDDDD');
  end;
  }
  if (Treeview1.Selected = NewTreeNode) {or (Treeview1.Selected = MyTreeNode1)} then
  begin
//ShowMessage('NewScanBtnClick');
LogFile1.LogToFile(logTimeString+'Tree NewScanBtnClick');
    NewScanBtnClick(self)
  end
  Else
  begin
//ShowMessage('AddScanBtnclick');
LogFile1.LogToFile(logTimeString+'Tree AddScanBtnclick');
    AddScanBtnclick(self);
  end;
end;
procedure TCB_IMGPSScanX.PM104Click(Sender: TObject);
var
  i,n,m,ii,P,v,v1,page,imageCount : Integer;
  FName : String;
  CaseID,DocNo,FormID :String;
  DocDir :String;
  SavePath,SaveFilename:String;
  ISB : TImageScrollBox;
  FileRec:TSearchrec;
begin
Procedure TCB_IMGPSScanX.PM104Click(Sender: TObject);
Var
  i, n, m, ii, P, v, v1, page, imageCount: Integer;
  FName: String;
  CaseID, DocNo, FormID: String;
  DocDir: String;
  SavePath, SaveFilename: String;
  ISB: TImageScrollBox;
  FileRec: TSearchrec;
  iGraphic, iGraphic_First, iGraphic_sec: TTiffGraphic;
  iRect : TRect;
  JpgGr : TJpegGraphic;
  SaveStream     : TFileStream;
  SaveStreamA:TFileStream;
  SaveStreamB:TFileStream;
  cooom:integer;
Begin
  OpenDialog1.Filter := 'Image files|*.TIF;*.JPG';
  if OpenDialog1.Execute then
  begin
  If OpenDialog1.Execute Then
  Begin
    ISB := TImageScrollBox.Create(self);
    try
      ShowText :=_Msg('檔案加入中,請稍候');
      DataLoading(True,True);
      if TreeView1.Selected = nil then Exit;
      FName := OpenDialog1.FileName;
try
    ShowText := _Msg('檔案加入中,請稍候');
LogFile1.LogToFile(logTimeString+'檔案加入中開始');
    DataLoading(True, True);
    If TreeView1.Selected = Nil Then
      Exit;
    FName := OpenDialog1.FileName;
      FindFirst(FName,faAnyfile,FileRec);
      //ShowMessage(IntToStr(FILEREC.Size)+','+IntToStr(FFileSizeLimit));
      if FFileSizeLimit=0 then
      begin
        FFileSizeLimit:=5*1024;
      end;
      if FILEREC.Size > FFileSizeLimit*1024 then //檢查檔案大小
      begin
        ShowMessage(Format('%.3f',[FILEREC.Size / 1024])+' KB, file size over limit.');
        FindClose(FILEREC);
        DataLoading(false,false);
        exit;
      end;
    FindFirst(FName, faAnyfile, FileRec);
      FindClose(FILEREC);
      CaseID := NowCaseno ;
      imageCount := 0;
      P := ISB.ImageCountFromFile(OpenDialog1.FileName);
      for I := 1 to P do
    If FFileSizeLimit = 0 Then
    Begin
      FFileSizeLimit := 5 * 1024;
    End;
//FFileSizeLimit:=20*5*1024;
//ShowMessage(IntToStr(FileRec.Size)+','+IntToStr(FFileSizeLimit * 1024));
    If FileRec.Size > FFileSizeLimit * 1024 Then // 檢查檔案大小
    Begin
      ShowMessage(Format(_Msg('目前檔案大小為 %.3f MB,已超過單一檔案匯入限制%1.f MB'),[FileRec.Size / (1024*1024),FFileSizeLimit/1024]));
      {ShowMessage(Format('目前檔案大小為 %.3f MB', [FileRec.Size / (1024*1024)]) +
        ',已超過單一檔案匯入限制'+Format('%.1f',[FFileSizeLimit/1024])+'MB');}
      FindClose(FileRec);
      DataLoading(false, false);
      Exit;
    End;
    //MessageDlg()
    //cooom:=StrToInt(InputBox('輸入百分比','輸入百分比',''));
    cooom:=FJpgCompression;//20171211彩色tif採jpg壓縮的比例
    FindClose(FileRec);
    CaseID := NowCaseno;
    imageCount := 0;
    P := ISB.ImageCountFromFile(OpenDialog1.FileName);
    For i := 1 To P Do
    Begin
      ShowText := Format(_Msg('檔案加入中,請稍候(%d/%d)'),[i,p]);
      //ShowText := _Msg('檔案加入中,請稍候')+'(' + inttostr(i) + '/' + inttostr(P) + ')';
      DataLoading(True, True);
      ISB.LoadFromFile(FName, i);
      DeskewImg(ISB.Graphic);
      ISB_BW.Graphic.Assign(ISB.Graphic); //20180104
      If ISB.Graphic.ImageFormat <> ifBlackWhite Then   //20180104
      begin
        ShowText :=_Msg('檔案加入中,請稍候('+inttostr(i)+'/'+inttostr(P)+')');
        DataLoading(True,True);
        ISB.LoadFromFile(FName,i);
        DeskewImg(ISB.Graphic);
        if (TreeView1.Selected = NewTreeNode) or (TreeView1.Selected = MyTreeNode1) then
        begin
        ConvertToBW(ISB_BW.Graphic);
      end;
      ///ISB_BW.SaveToFile('KKKKKKKK.tif');
      iGraphic_First := TTiffGraphic.Create;
      iGraphic_sec := TTiffGraphic.Create;
      //ShowMessage(IntToStr(iGraphic_First.Palette.palNumEntries)); //彩色 會為0  黑白 為2
      MpsGetBarcode(ISB_BW.Graphic, MpsBarcodeinf); //判斷A3 有用FormID 所以要先辨條碼
      For n := 1 To MpsBarcodeinf.Count Do
      Begin
        If (MpsBarcodeinf.r180[n] <> 0) and (Length(MpsBarcodeinf.Text[n])=FormIDLength) Then // 依條碼角度轉影像
        Begin
          Rotate(ISB.Graphic, MpsBarcodeinf.r180[n]);
          //MpsGetBarcode(iGraphic_First, MpsBarcodeinf);
          Break;
        End;
      End;
      iGraphic_First.Assign(ISB.Graphic);
      //有必要的話先把影像轉正 再開始切圖
      If CheckNeedCrop(iGraphic_First) Then
      Begin
        // 先取右邊的影像
        iRect.Left := ISB.Graphic.Width Div 2;
        iRect.Right := ISB.Graphic.Width;
        iRect.Top := 0;
        iRect.Bottom := ISB.Graphic.Height;
        CropImg(iGraphic_First, iRect);
        iGraphic_sec.Assign(ISB.Graphic);
        // 再取左邊的影像
        iRect.Left := 0;
        iRect.Right := ISB.Graphic.Width Div 2;
        iRect.Top := 0;
        iRect.Bottom := ISB.Graphic.Height;
        CropImg(iGraphic_sec, iRect);
      End;
      ISB.Graphic.Clear;  //20220711  Hong 覺得ISB後面沒有到了,先清掉減少記憶體使用
      iGraphic := iGraphic_First;
      While Not iGraphic.IsEmpty Do
      Begin
        If (TreeView1.Selected = NewTreeNode) Or
          (TreeView1.Selected = MyTreeNode1) Then
        Begin
          SaveFilename := '';
          MpsGetBarcode(ISB.Graphic,MpsBarcodeinf);
          for n := 1 to MpsBarcodeinf.Count-1  do
          ISB_BW.Graphic.Assign(iGraphic); //20180104
          If iGraphic.ImageFormat <> ifBlackWhite Then   //20180104
          begin
            if MpsBarcodeinf.r180[n] <> 0 then  //依條碼角度轉影像
            begin
              Rotate(ISB.Graphic,MpsBarcodeinf.r180[n]);
              MpsGetBarcode(ISB.Graphic,MpsBarcodeinf);
              Break;
            end;
            ConvertToBW(ISB_BW.Graphic);
          end;
          FormID := BarCode2FormID; //取出FormID
          MpsGetBarcode(ISB_BW.Graphic, MpsBarcodeinf);
//ShowMessage(IntToStr(MpsBarcodeinf.Count));
          For n := 1 To MpsBarcodeinf.Count Do
          Begin
            If (MpsBarcodeinf.r180[n] <> 0) and (Length(MpsBarcodeinf.Text[n])=FormIDLength) Then // 依條碼角度轉影像
            Begin
              Rotate(iGraphic, MpsBarcodeinf.r180[n]);
              MpsGetBarcode(ISB_BW.Graphic, MpsBarcodeinf);
              Break;
            End;
          End;
//ShowMessage('XXX '+IntToStr(MpsBarcodeinf.Count));
          FormID := BarCode2FormID;
//ShowMessage('FormID='+FormID);
          // 取出FormID
          SaveFilename := FormID;
          if (TreeView1.Selected = NewTreeNode) Then
          begin
            if FindDivFormCode(FormID) Then  //只找分案頁上的案件條碼
            begin
          If (TreeView1.Selected = NewTreeNode) Then
          Begin
            If FindDivFormCode(FormID) Then // 只找分案頁上的案件條碼
            Begin
              imageCount := 0;
              ClearView(1);
              ContextList.Clear;
              CaseID := BarCode2CaseID;
              if DirectoryExists(ImageSavePath + CaseID+'\') then
              begin
                _DelTree(ImageSavePath + CaseID+'\');
                SetCaseList('D',-1,CaseID);
              end;
            end;
            if CaseID = '' then
            begin
              If DirectoryExists(ImageSavePath + CaseID + '\') Then
              Begin
                _DelTree(ImageSavePath + CaseID + '\');
                SetCaseList('D', -1, CaseID);
              End;
            End;
            If CaseID = '' Then
            Begin
              CaseID := GetNoNameCase(ImageSavePath);
              ContextList.Clear;
            end;
          end;
          SavePath := ImageSavePath + CaseID+'\';
            End;
          End;
          SavePath := ImageSavePath + CaseID + '\';
          Str2Dir(SavePath);
          DocNo := FormCode2DocNo(FormID);
          DocDir := FindLastestDocDir(CaseID,DocNo);
          if DocNoNeedDiv(DocNo) then   //要分份數
          DocDir := FindLastestDocDir(CaseID, DocNo);
          if (FMode='ESCAN') and (FModeName=_Msg('補件掃描')) then
          begin
            if ((FormCode2Page(FormID) = '01') and (GetDocDir_Page(CaseID,DocDir)>0)) or (DocDir = '') then
              DocDir := DocNo2DocNoDir(ImageSavePath + CaseID+'\',DocNo);
          end
          Else        //不分份數
          begin
            if DocNo <> '' then
              DocDir := DocNo
            else      //Attach 附件
              DocDir := DocNo2DocNoDir(ImageSavePath + CaseID+'\',DocNo);
            DocDir := FindLastestDocDirForPage(CaseID, DocNo,FormID);
//ShowMessage('DocDir='+DocDir);
          end;
          {if ((FormCode2Page(FormID) = '01') and DocNoNeedDiv(DocNo)) or (FormID='') then   //是表單第一頁且要分份
            DocDir := DocNo2DocNoDir(ImageSavePath + CaseID+'\',DocNo)
          Else if not DocNoNeedDiv(DocNo) then
            DocDir := DocNo; }
          if (not DirectoryExists(ImageSavePath + CaseID+'\'+DocDir+'\')) and (DocDir <> AttName) then
            SetDocNoList('A',-1,CaseID,DocDir,'1');
          SavePath := ImageSavePath + CaseID+'\'+DocDir+'\';
          If DocNoNeedDiv(DocNo) Then // 要分份數
          Begin
            If ((FormCode2Page(FormID) = '01') And
              (GetDocDir_Page(CaseID, DocDir) > 0)) Or (DocDir = '') Then
              begin
                DocDir := DocNo2DocNoDir(ImageSavePath + CaseID + '\', DocNo);
              end;
          End
          Else // 不分份數
          Begin
            If DocNo <> '' Then
              DocDir := DocNo
            Else // Attach 附件
              DocDir := DocNo2DocNoDir(ImageSavePath + CaseID + '\', DocNo);
          End;
          If (Not DirectoryExists(ImageSavePath + CaseID + '\' + DocDir + '\'))
            And (DocDir <> AttName) Then
            SetDocNoList('A', -1, CaseID, DocDir, '1');
          SavePath := ImageSavePath + CaseID + '\' + DocDir + '\';
          Str2Dir(SavePath);
          ContextList.Clear;
          if FileExists(SavePath+'Context.dat') then
            ContextList.LoadFromFile(SavePath+'Context.dat');
          If FileExists(SavePath + 'Context.dat') Then
            ContextList.LoadFromFile(SavePath + 'Context.dat');
          WriteCaseIndex(ImageSavePath + CaseID+'\');  //寫入案件索引
          if SaveFilename = '' then //附件
            SaveFilename:= Add_Zoo(ContextList.Count+1,3)+ext
          WriteCaseIndex(ImageSavePath + CaseID + '\');
          // 寫入案件索引
          If SaveFilename = '' Then // 附件
            SaveFilename := Add_Zoo(ContextList.Count + 1, 3) + ext
          Else
            SaveFilename := Add_Zoo(ContextList.Count+1,3)+'_'+SaveFilename+ext;
          ISB.SaveToFile(SavePath+SaveFilename);
            SaveFilename := Add_Zoo(ContextList.Count + 1, 3) + '_' +
              SaveFilename + ext;
          SetContextList('A',-1,CaseID,DocDir,SaveFilename);
          if (TreeView1.Selected = NewTreeNode) Then
          For n := 1 To MpsBarcodeinf.Count Do
          Begin
            If (MpsBarcodeinf.r180[n] <> 0) and (Length(MpsBarcodeinf.Text[n])=FormIDLength) Then // 依條碼角度轉影像
            Begin
              Rotate(iGraphic, MpsBarcodeinf.r180[n]);
              MpsGetBarcode(ISB_BW.Graphic, MpsBarcodeinf);
              Break;
            End;
          End;
//ShowMessage(IntToStr(iGraphic.Palette.palNumEntries));
          if iGraphic.ImageFormat = ifBlackWhite then   //20200806 出現無法匯入,是因color256無法壓JPEG,待報會後再開啟
          begin
            if imageCount = 0 then
            begin
              SetCaseList('A',-1,CaseID);
              MyTreeNode1 := TreeView1.Items.AddChild(NewTreeNode,CaseID);
            iGraphic.Compression:=tcGroup4;
          end
          else if iGraphic.ImageFormat= ifColor256 then
          begin
            ConverttoGray(iGraphic);
            iGraphic.Compression:=tcJPEG;
            iGraphic.JpegQuality:=cooom;
          end
          else if (iGraphic.ImageFormat = ifTrueColor) or (iGraphic.ImageFormat = ifGray256) then
          begin
            iGraphic.Compression:=tcJPEG;
            iGraphic.JpegQuality:=cooom;
          end
          else
          begin
            iGraphic.Compression:=tcLZW;
          end;
          {if (iGraphic.Palette.palNumEntries = 0) or (iGraphic.Palette.palNumEntries = 256) then  //20171130 彩色 會為0  黑白 為2  灰階256     //20200806拿掉
          begin
            iGraphic.Compression:=tcJPEG;
            iGraphic.JpegQuality:=cooom;
          end;}
          If LowerCase(ExtractFileExt(SavePath + SaveFilename)) = '.tif' Then
          Begin
            If FileExists(SavePath + SaveFilename) Then
              SaveStream := TFileStream.Create(SavePath + SaveFilename, fmOpenReadWrite)
            Else
              SaveStream := TFileStream.Create(SavePath + SaveFilename, fmCreate);
            Try
              SaveStream.Seek(0, soFromBeginning);
              iGraphic.AppendToStream(SaveStream);
            Finally
              SaveStream.Free;
            End;
          End
          Else If LowerCase(ExtractFileExt(SavePath + SaveFilename))
            = '.jpg' Then
          Begin
            If FileExists(SavePath + SaveFilename) Then
              DeleteFile(SavePath + SaveFilename);
            // SaveStream := TFileStream.Create( PEFileName ,fmCreate );
            JpgGr := TJpegGraphic.Create;
            Try
              JpgGr.Assign(iGraphic);
              JpgGr.SaveQuality := 30;
              // JpgGr.AppendToStream(SaveStream);
              JpgGr.SaveToFile(SavePath + SaveFilename);
            Finally
              JpgGr.Free;
              // SaveStream.Free;
            End;
          End;
          SetContextList('A', -1, CaseID, DocDir, SaveFilename);
          If (TreeView1.Selected = NewTreeNode) Then
          Begin
            If imageCount = 0 Then
            Begin
              SetCaseList('A', -1, CaseID);
              MyTreeNode1 := TreeView1.Items.AddChild(NewTreeNode, CaseID);
              MyTreeNode1.ImageIndex := 2;
              MyTreeNode1.SelectedIndex := 2;
              Application.ProcessMessages;
            end;
          end;
            End;
          End;
          inc(imageCount);
          //DrawDocItem1(MytreeNode1,Doc_Inf_List,CaseID);
          //DrawDocItem(MyTreeNode1,FORM_INF_List,CaseID);
        end
        Else if TreeView1.Selected = MyTreeNode3 then
        begin
          SavePath := ImageSavePath + CaseID+'\'+NowDocDir+'\';
          // DrawDocItem1(MytreeNode1,Doc_Inf_List,CaseID);
          // DrawDocItem(MyTreeNode1,FORM_INF_List,CaseID);
        End
        Else If TreeView1.Selected = MyTreeNode3 Then
        Begin
          SavePath := ImageSavePath + CaseID + '\' + NowDocDir + '\';
          ContextList.Clear;
          if FileExists(ImageSavePath + CaseID+'\'+NowDocDir+'\Context.dat') then
            ContextList.LoadFromFile(ImageSavePath + CaseID+'\'+NowDocDir+'\Context.dat');
          if NowFormCode <> '' then
            SaveFilename := Add_Zoo(ContextList.Count+1,3)+'_'+NowFormCode+ext
          else
            SaveFilename := Add_Zoo(ContextList.Count+1,3)+ext;
          ISB.SaveToFile(SavePath+SaveFilename);
          If FileExists(ImageSavePath + CaseID + '\' + NowDocDir +
            '\Context.dat') Then
            ContextList.LoadFromFile(ImageSavePath + CaseID + '\' + NowDocDir +
              '\Context.dat');
          If NowFormCode <> '' Then
            SaveFilename := Add_Zoo(ContextList.Count + 1, 3) + '_' +
              NowFormCode + ext
          Else
            SaveFilename := Add_Zoo(ContextList.Count + 1, 3) + ext;
          For n := 1 To MpsBarcodeinf.Count Do
          Begin
            If MpsBarcodeinf.r180[n] <> 0 Then // 依條碼角度轉影像
            Begin
              Rotate(iGraphic, MpsBarcodeinf.r180[n]);
              MpsGetBarcode(iGraphic, MpsBarcodeinf);
              Break;
            End;
          End;
          if (iGraphic.Palette.palNumEntries = 0) or (iGraphic.Palette.palNumEntries = 256) then  //20171130 彩色 會為0  黑白 為2
          begin
            iGraphic.Compression:=tcJPEG;
            iGraphic.JpegQuality:=cooom;
          end;
          If LowerCase(ExtractFileExt(SavePath + SaveFilename)) = '.tif' Then
          Begin
            If FileExists(SavePath + SaveFilename) Then
              SaveStream := TFileStream.Create(SavePath + SaveFilename,
                fmOpenReadWrite)
            Else
              SaveStream := TFileStream.Create(SavePath + SaveFilename,
                fmCreate);
            Try
              SaveStream.Seek(0, soFromBeginning);
              iGraphic.AppendToStream(SaveStream);
            Finally
              SaveStream.Free;
            End;
          End
          Else
          Begin
            If LowerCase(ExtractFileExt(SavePath + SaveFilename)) = '.jpg' Then
            Begin
              If FileExists(SavePath + SaveFilename) Then
                DeleteFile(SavePath + SaveFilename);
              // SaveStream := TFileStream.Create( PEFileName ,fmCreate );
              JpgGr := TJpegGraphic.Create;
              Try
                JpgGr.Assign(iGraphic);
                JpgGr.SaveQuality := 30;
                // JpgGr.AppendToStream(SaveStream);
                JpgGr.SaveToFile(SavePath + SaveFilename);
              Finally
                JpgGr.Free;
                // SaveStream.Free;
              End;
            End;
          End;
          // ISB.SaveToFile(SavePath+SaveFilename);
          ContextList.Add(SaveFilename);
          ContextList.SaveToFile(SavePath+'Context.dat');
        end;
      end;
      ClearErrini(CaseID,MyTreeNode1);  //清掉檢核記錄
      if (TreeView1.Selected = MyTreeNode1) or (TreeView1.Selected = NewTreeNode) then
      begin
        LoadImgFile;
      end
      Else
      begin
        DrawDocItem2(MytreeNode1,CaseID); //長出文件名稱的樹並傳回是否有申請書的影像
        page := GetCasePage(ImageSavePath,CaseID);
        MytreeNode1.Text := Format(_Msg('%s-%d頁'),[CaseID,page]);
      end;
      NewTreeNodeRefresh;
      Application.ProcessMessages;
      DataLoading(False,False);
    finally
    ISB.Free;
    end;
  end;
          ContextList.SaveToFile(SavePath + 'Context.dat');
        End;
        if iGraphic = iGraphic_First then
          iGraphic := iGraphic_Sec
        else
          iGraphic.Assign(nil);
      End //While 結束
    End;
    ClearErrini(CaseID, MyTreeNode1);
    // 清掉檢核記錄
    If (TreeView1.Selected = MyTreeNode1) Or
      (TreeView1.Selected = NewTreeNode) Then
    Begin
      LoadImgFile;
    End
    Else
    Begin
      DrawDocItem2(MyTreeNode1, CaseID);
      // 長出文件名稱的樹並傳回是否有申請書的影像
      page := GetCasePage(ImageSavePath, CaseID);
      // ShowMessage('page='+IntToStr(page));
      MyTreeNode1.Text := Format(_Msg('%s-%d頁'), [CaseID, page]);
    End;
    // ShowMessage('AAAA');
    NewTreeNodeRefresh;
    Application.ProcessMessages;
    DataLoading(false, false);
finally
ISB.Free;
iGraphic_First.Free;
iGraphic_sec.Free;
end;
  End;
End;
procedure TCB_IMGPSScanX.PM106Click(Sender: TObject);
var
@@ -2785,16 +3261,18 @@
  i : Integer;
  DocListForm : TDocListForm;
  OldName,NewName,Ext : String;
  NewFormID,NewFormName : String;
  NewFormID,NewFormName,CustomDocNo : String;
begin
  DocListForm := TDocListForm.Create(self);
  try
    InitialLanguage(PatchDlg); //載入多國語言
LogFile1.LogToFile(logTimeString+'Tree 歸類開始');
    InitialLanguage(DocListForm); //載入多國語言
    DocListForm.CheckBox1.Visible:=True;
    for i := 1 to FORM_INF_List.Count - 1 do
    begin
      NewFormID := GetSQLData(FORM_INF_List,'T1.FORM_ID',i);
      NewFormName := GetSQLData(FORM_INF_List,'T1.FORM_DESC',i);
      if not FormIDAppear(NewFormID) then Continue;
      if not FormIDAppear(NewFormID) then Continue;   //20170816 先秀全部的
      if (NewFormID <> FileName2FormCode(DisplayISB.FileName)) and FormIDExists(NewFormID,False,i) then
      begin
        DocListForm.FormIDList.Add(NewFormID+'#@#'+NewFormName);
@@ -2807,30 +3285,67 @@
    end;
    if DocListForm.ShowModal = mrOk then
    begin
      NewFormID := DocListForm.DocLV.Selected.Caption;
      if NowFormCode <> AttName then
      if not (DocListForm.DocLV.Selected=nil) then
         NewFormID := DocListForm.DocLV.Selected.Caption;
      if DocListForm.CheckBox1.Checked then
      begin
        If Messagedlg(Format(_Msg('是否將"%s"的所有影像歸類成"%s"'),[FormCode2FormName(NowCaseNo,NowFormCode),FormCode2FormName(NowCaseNo,NewFormID)]),MtConfirmation,[mbyes,mbcancel],0) = mrcancel Then
        //歸類到自訂文件
        NewFormID:=DocListForm.Edit1.Text;
        if Trim(DocListForm.Edit1.Text)='' then
        begin
          Showmessage(_Msg('未輸入文件名稱'));
          Exit;
        end;
        if FindCustomDocName(DisplayPath,NewFormID) then
        begin
          Showmessage(Format(_Msg('文件名稱:"%s"己存在'),[NewFormID]));
          Exit;
        end;
        if NowFormCode <> AttName then
        begin
          If Messagedlg(Format(_Msg('是否將"%s"的所有影像歸類成"%s"'),[FormCode2FormName(NowCaseNo,NowFormCode),NewFormID]),MtConfirmation,[mbyes,mbcancel],0) = mrcancel Then
            Exit;
        end
        Else
        begin
          If Messagedlg(Format(_Msg('是否將"%s"的所有影像歸類成"%s"'),[_Msg('附件')+MyTreeNode3.Text,FormCode2FormName(NowCaseNo,NewFormID)]),MtConfirmation,[mbyes,mbcancel],0) = mrcancel Then
            Exit;
        end;
        CustomDocNo := GetNewCustomDocNo(DisplayPath,NewFormID);
//ShowMessage('CustomDocNo='+CustomDocNo);
LogFile1.LogToFile(logTimeString+'Tree 歸類到自訂文件 CustomDocNo='+CustomDocNo);
        ShowText := _Msg('歸類中,請稍侯');
        DataLoading(True,True);
        FormIDReplace(NowCaseNo,NowDocDir,NowFormCode,CustomDocNo+'010101A');
      end
      Else
      else
      begin
        If Messagedlg(Format(_Msg('是否將"%s"的所有影像歸類成"%s"'),[_Msg('附件')+MyTreeNode3.Text,FormCode2FormName(NowCaseNo,NewFormID)]),MtConfirmation,[mbyes,mbcancel],0) = mrcancel Then
          Exit;
        //歸類到既有文件
        if NowFormCode <> AttName then
        begin
          If Messagedlg(Format(_Msg('是否將"%s"的所有影像歸類成"%s"'),[FormCode2FormName(NowCaseNo,NowFormCode),FormCode2FormName(NowCaseNo,NewFormID)]),MtConfirmation,[mbyes,mbcancel],0) = mrcancel Then
            Exit;
        end
        Else
        begin
          If Messagedlg(Format(_Msg('是否將"%s"的所有影像歸類成"%s"'),[_Msg('附件')+MyTreeNode3.Text,FormCode2FormName(NowCaseNo,NewFormID)]),MtConfirmation,[mbyes,mbcancel],0) = mrcancel Then
            Exit;
        end;
        ShowText := _Msg('歸類中,請稍侯');
        DataLoading(True,True);
//ShowMessage('NowDocDir='+NowDocDir);
LogFile1.LogToFile(logTimeString+'Tree 歸類到既有文件 NewFormID='+NewFormID);
        FormIDReplace(NowCaseNo,NowDocDir,NowFormCode,NewFormID);
      end;
      ShowText := _Msg('歸類中,請稍侯');
      DataLoading(True,True);
      //FormIDReplace(DisplayPath,NowFormCode,FormID);
      //ShowFileReplace(DisplayPath,FormID);
      FormIDReplace(NowCaseNo,NowDocDir,NowFormCode,NewFormID);
      ClearErrini(NowCaseno,MyTreeNode1);  //清掉檢核記錄
      DrawDocItem2(MytreeNode1,NowCaseno);
      //DrawDocItem(MytreeNode1,FORM_INF_List,NowCaseno);
      DataLoading(False,False);
      TreeView1.Selected := MyTreeNode1;
      TreeView1Click(self);
    end;
  finally
  DocListForm.Free;
  end;
@@ -2873,8 +3388,9 @@
  CustomDocNo : String;
  DocDir : String;
  SavePath : String;
  ST1:TStringList;
begin
  if InputQuery('輸入其他文件名稱','文件名稱',CustomDocName) then
  if InputQuery(_Msg('輸入其他文件名稱'),_Msg('文件名稱'),CustomDocName) then
  begin
    if CustomDocName <> '' then
    begin
@@ -2883,7 +3399,7 @@
        Showmessage(Format('文件名稱:"%s"己存在',[CustomDocName]));
        Exit;
      end;
      ST1:=TStringList.Create;
      CustomDocNo := GetNewCustomDocNo(DisplayPath,CustomDocName);
      DocDir := CustomDocNo;
      SavePath := ImageSavePath+NowCaseNo+'\'+DocDir+'\';
@@ -2903,26 +3419,26 @@
begin
  oldCopies := GetDocDirCopies(NowCaseno,NowDocDir);
  try
    NewCopies := Strtoint(inputBox('修改份數','請輸入修改後的份數',inttostr(oldCopies)));
    NewCopies := Strtoint(inputBox(_Msg('修改份數'),_Msg('請輸入修改後的份數'),inttostr(oldCopies)));
  except
    Showmessage('輸入錯誤');
    Showmessage(_Msg('輸入錯誤'));
    Exit;
  end;
  if (NewCopies <= 0) and (NewCopies >= 10000) then
  begin
    Showmessage('輸入範圍錯誤');
    Showmessage(_Msg('輸入範圍錯誤'));
    Exit;
  end;
  if (oldCopies <> NewCopies) and (NewCopies > 0) and (NewCopies < 10000) then
  begin
    if DocNoNeedDiv(NowDocNo) and (NewCopies = 1) and (MessageDlg('修改至1份後此文件將無法再進行份數修改,是否確定??',mtConfirmation,[mbyes,mbcancel],0)= mrcancel) then
    if DocNoNeedDiv(NowDocNo) and (NewCopies = 1) and (MessageDlg(_Msg('修改至1份後此文件將無法再進行份數修改,是否確定??'),mtConfirmation,[mbyes,mbcancel],0)= mrcancel) then
      Exit;
    SetDocDirCopies(NowCaseno,NowDocDir,NewCopies);
    SetRecordEditedDocDir('A',NowCaseNo,NowDocDir);
    DrawDocItem2(MytreeNode1,NowCaseno);
    Showmessage('修改完成');
    Showmessage(_Msg('修改完成'));
  end;
end;
@@ -3078,7 +3594,7 @@
  if DisplayISB.FileName = '' then Exit;
  if (ContextList.Count = 1) and ((FMode = 'NSCAN') or (FMode = 'ASCAN') or (FMode = 'DSCAN') or (FMode = 'ISCAN') or (FMode = 'SSCAN') or (FMode = 'MSCAN') or (FMode = 'RI_SCAN')) then
  begin
    if Messagedlg(_Msg('刪除後(%s)案件無影像,將刪除此案件,是否確定刪除?'),mtconfirmation,[mbyes,mbcancel],0) = mrCancel then Exit;
    if Messagedlg(Format(_Msg('刪除後(%s)案件無影像,將刪除此案件,是否確定刪除?'),[NowCaseno]),mtconfirmation,[mbyes,mbcancel],0) = mrCancel then Exit;
    _DelTree(DisplayPath);
    SetCaseList('D',NewTreeNode.IndexOf(MyTreeNode1),'');
    LoadImgFile;
@@ -3149,14 +3665,36 @@
      PM104.Visible := True;   //檔案加入影像
    end;
    if FMode='ESCAN' then
    if FModeName=_Msg('異動件') then
    begin
      PM101.Visible := False;
      PM101.Visible := True;
    end;
//    if FMode='ESCAN' then
//    begin
//      PM101.Visible := True;
//    end;
  end
  Else if TreeView1.Selected = MyTreeNode1 then    //案件層
  begin
    PM101.Visible := True;   //刪除
    if FImgDelete='Y' then
    begin
      PM101.Visible:=True;
    end;
    if FImgDelete='N' then
    begin
      PM101.Visible:=false;
    end;
    if FMode='ESCAN' then
      PM101.Visible:=false;
    if FModeName=_Msg('異動件') then
    begin
      PM101.Visible := True;
    end;
    if not CaseDelete_Enable(NowCaseno) then //
      PM101.Enabled := False
    else
@@ -3164,25 +3702,39 @@
    PM103.Visible := True;   //掃瞄器加入影像
    //PM107.Visible := True;   //寫備註
    //PM109.Visible := True;   //檢核此筆
    if FCustDocYN <> 'N' Then
      PM110.Visible := True;   //新增自訂文件
//    if FCustDocYN <> 'N' Then
//      PM110.Visible := True;   //新增自訂文件  20170914 先不在tree 中做自訂文件  讓user在縮圖做
    PM104.Visible := True;   //檔案加入影像
    if (FMode = 'NSCAN') then
    begin
      PM102.Visible := True;   //修改案件編號
    end;
    if FMode='ESCAN' then
    begin
      PM101.Visible := False;
    end;
//    if FMode='ESCAN' then
//    begin
//      PM101.Visible := True;
//    end;
  end
  Else if TreeView1.Selected = MyTreeNode2 then    //文件層
  begin
    PM101.Visible := True;   //刪除
    //PM107.Visible := True;   //寫備註
    //PM109.Visible := True;   //檢核此筆
    if FCustDocYN <> 'N' Then
      PM110.Visible := True;   //新增自訂文件
//    if FCustDocYN <> 'N' Then
//      PM110.Visible := True;   //新增自訂文件
    if FImgDelete='Y' then
    begin
      PM101.Visible:=True;
    end;
    if FImgDelete='N' then
    begin
      PM101.Visible:=false;
    end;
    if FModeName=_Msg('異動件') then
    begin
      PM101.Visible := True;
    end;
    if GetUseCase('T',DisplayPath,NowDocDir) <> '' then   //沒有被引用走的
      PM101.Enabled := False    //刪除
    Else
@@ -3191,10 +3743,10 @@
      PM111.Visible := True;   //修改份數
    if (FMode = 'NSCAN') then
      PM102.Visible := True;   //修改案件編號
    if FMode='ESCAN' then
    begin
      PM101.Visible := False;
    end;
//    if FMode='ESCAN' then
//    begin
//      PM101.Visible := True;
//    end;
  end
  Else if TreeView1.Selected = MyTreeNode3 then    //表單層
  begin
@@ -3202,10 +3754,26 @@
    PM104.Visible := True;   //檔案加入影像
    PM108.Visible := True;   //歸類
    PM103.Visible := True;   //掃瞄器加入影像
    if FCustDocYN <> 'N' Then
      PM110.Visible := True;   //新增自訂文件
//    if FCustDocYN <> 'N' Then
//      PM110.Visible := True;   //新增自訂文件
    if GetFormIDPage(ContextList,NowFormCode) < 1 Then
    begin
      PM108.Visible := False;   //歸類
    end;
    if FImgDelete='Y' then
    begin
      PM101.Visible:=True;
    end;
    if FImgDelete='N' then
    begin
      PM101.Visible:=false;
    end;
    if FModeName=_Msg('異動件') then
    begin
      PM101.Visible := True;
    end;
    if GetUseCase('T',DisplayPath,NowDocDir) <> '' then   //被引用走的
    begin
      PM101.Enabled := False;   //刪除
@@ -3220,22 +3788,12 @@
    end;
    if (FMode = 'NSCAN') then
      PM102.Visible := True;   //修改案件編號
    //PM103.Visible := True;   //掃瞄器加入影像
    //PM104.Visible := True;   //檔案加入影像
    //PM107.Visible := True;   //寫備註
    //PM109.Visible := True;   //檢核此筆
    if FMode='ESCAN' then
    begin
      PM101.Visible := False;
      PM102.Visible := True;   //修改案件編號
    end;
  end;
  if FImgDelete='Y' then
  begin
    PM101.Visible:=True;
  end;
end;
@@ -3289,28 +3847,52 @@
procedure TCB_IMGPSScanX.PopupMenu6Popup(Sender: TObject);
begin
  PM601.Visible := False;  //歸類
  PM602.Visible := False;  //自行定義文件名稱
  PM601.Visible := True;  //歸類
  PM602.Visible := True;  //自行定義文件名稱
  PM603.Visible := False;  //掃描替換此頁
  PM604.Visible := False;  //歪斜矯正
  PM605.Visible := False;  //刪除
  if ((NowDocNo = 'Attach') or (NowDocNo = 'S_Attach')) and (FCustDocYN <> 'N') then
    PM602.Visible := True;  //自行定義文件名稱
  //PM603.Visible := True;  //掃描替換此頁
  PM604.Visible := True;  //歪斜矯正
  PM601.Visible := True;  //歸類
  PM605.Visible := True;  //刪除
//  if FMode='ESCAN' then
//  begin
//    PM601.Visible := False;  //歸類
//    PM602.Visible := False;  //自行定義文件名稱
//    PM603.Visible := False;  //掃描替換此頁
//    PM604.Visible := False;  //歪斜矯正
//    PM605.Visible := False;  //刪除
//  end;
  if ((NowDocNo = 'Attach') or (NowDocNo = 'S_Attach')) and (FCustDocYN <> 'N') then
  begin
    PM602.Visible := True;  //自行定義文件名稱
    //PM603.Visible := True;  //掃描替換此頁
    PM604.Visible := True;  //歪斜矯正
    PM601.Visible := True;  //歸類
    PM605.Visible := True;  //刪除
  end;
  if  FModeName<>_Msg('異動件') then
  begin
    if (FImgDelete='Y') then
    begin
      PM605.Enabled:=True;
    end;
    if FImgDelete='N' then
    begin
      PM605.Enabled:=false;
    end;
  end;
  if CheckSelectImg_UseCase(DisplayPath,NowCaseNo) then //選擇的影像不可有引用的
  begin
    PM601.Enabled := False;  //歸類
    PM605.Enabled := False;  //刪除
  end
  Else
  begin
    PM601.Enabled := True;  //歸類
    PM605.Enabled := True;  //刪除
  end;
end;
procedure TCB_IMGPSScanX.PrePageBtnClick(Sender: TObject);
@@ -3345,6 +3927,7 @@
var
  SampleFormID : String;
  SendData : String;
  buttonSelected : Integer;
begin
  ScanMode := smSample;
  ClearView(1);
@@ -3357,6 +3940,19 @@
  ShowText := _Msg('範本掃描中,請稍候');
  DataLoading(True,True);
  SampleFormID := UpperCase(InputBox(_Msg('範本檔掃瞄輸入畫面'),_Msg('請輸入文件編號'),''));
  if SampleFormIDList.IndexOf(SampleFormID)<>-1 then
  begin
    // Show a custom dialog
    buttonSelected := messagedlg(SampleFormID+_Msg('已有範本,是否取代?'),mtCustom,
                                [mbYes,mbCancel], 0);
    if buttonSelected = mrCancel then
    begin
      DataLoading(false,false);
      Exit;
    end;
  end;
  if SampleFormID <> '' then
  begin
    if FormIDExists(SampleFormID,False,0) then
@@ -3461,6 +4057,11 @@
end;
procedure TCB_IMGPSScanX.ScrollBox1MouseEnter(Sender: TObject);
begin
ScrollBox1.SetFocus;
end;
procedure TCB_IMGPSScanX.SelectScanBtnClick(Sender: TObject);
begin
  Panel1.Enabled := False;
@@ -3534,6 +4135,36 @@
  end;
end;
procedure TCB_IMGPSScanX.AddAttFileLBClick(Sender: TObject);
var
  i : Integer;
  Addfile : String;
begin
  OpenDialog1.Filter := 'PDF files|*.pdf';
  OpenDialog1.Options := [ofAllowMultiSelect];
  if OpenDialog1.Execute then
  begin
    ShowText :=_Msg('檔案加入中,請稍候');
    DataLoading(True,True);
    for i := 0 to OpenDialog1.Files.Count - 1 do
    begin
      AddFile := HTTPEncode(UTF8Encode(ExtractFileName(OpenDialog1.Files.Strings[i])));
      if FileExists(ImageSavePath+NowCaseno+'\'+AddFile) then
      begin
        if Messagedlg(Format(_Msg('%s己存在,是否覆蓋??'),[Addfile]),mtconfirmation,[mbyes,mbcancel],0) = mrcancel Then
          Continue;
        SetAttContextList('D',-1,NowCaseno,AddFile);
      end;
      // AttFileGB.Visible := True; //附加電子檔窗   //20120207楊玉說不在這加電子檔先拿掉
      //   Splitter2.Visible := True;
      CopyFile(Pchar(OpenDialog1.Files.Strings[i]),Pchar(ImageSavePath+NowCaseno+'\'+AddFile),False);
      SetAttContextList('A',-1,NowCaseno,AddFile);
      LoadAttFile(NowCaseno);
    end;
  end;
  DataLoading(False,False);
end;
procedure TCB_IMGPSScanX.AddCredit1RGClick(Sender: TObject);
begin
  if DisplayPath <> '' then
@@ -3553,7 +4184,7 @@
begin
  IF not InitialOk Then
  begin
    Showmessage(_msg('資訊尚未下載完成,請稍候或重新進入'));
    Showmessage(_Msg('資訊尚未下載完成,請稍候或重新進入'));
    Exit;
  end;
  if MyTreeNode1 = nil then
@@ -3589,6 +4220,26 @@
  TreeView1Click(self);
end;
procedure TCB_IMGPSScanX.AttListBoxClick(Sender: TObject);
begin
  DelAttFileLB.Enabled := False;
  if AttListBox.ItemIndex >= 0 then
    DelAttFileLB.Enabled := True;
end;
procedure TCB_IMGPSScanX.AttListBoxDblClick(Sender: TObject);
var
  AttFile : String;
begin
  if AttListBox.ItemIndex < 0 then Exit;
  AttFile := HTTPEncode(UTF8Encode(AttListBox.Items.Strings[AttListBox.ItemIndex]));
  if FileExists(DisplayPath+AttFile) then
    ShellExecute(Application.Handle,'open',PChar(DisplayPath+AttFile),nil,nil,SW_SHOW)
  else
    Showmessage(Format(_Msg('找不到檔案:%s'),[AttFile]));
end;
procedure TCB_IMGPSScanX.BtnMouseEnter(Sender: TObject);
begin
  AddToolTip(TBitBtn(Sender).Handle,nil,0,Pchar(TBitBtn(Sender).Hint),nil,0,0);
@@ -3608,34 +4259,50 @@
  //CreateFormID_FormName(DisplayPath);  //產生FormID_FormName.dat
  //CreateDocNo_DocName(DisplayPath); //產生DocNo_Name.dat
  //Showmessage(CreateDocNo_Info(DisplayPath));  //產生 Docno,份數,頁數;Docno,份數,頁數 的回傳字串
  //lb1.Caption:='AAAAAAAAAAA';
  //Showmessage(CreateDocnoFrom_Info(NowCaseno));
  //Showmessage(self.CreateCustDocNoFrom_Info(NowCaseno));
   showmessage('FUrl='+FUrl);
   showmessage('FCaseID='+FCaseID);
   showmessage('FMode='+FMode);
   showmessage('FModeName='+FModeName);
   showmessage('FWork_no='+FWork_no);
   showmessage('FUserID='+FUserID);
   showmessage('FUserName='+FUserName);
   showmessage('FUserUnit='+FUserUnit);
   showmessage('FData='+FData);
   showmessage('FVerify='+FVerify);
   showmessage('FReWrite='+FReWrite);
   showmessage('FLanguage='+FLanguage);
   showmessage('FLoanDoc_Value='+FLoanDoc_Value);
   showmessage('FLoanDoc_Enable='+FLoanDoc_Enable);
   showmessage('FUseProxy='+FUseProxy);
   showmessage('FC_DocNoList='+FC_DocNoList);
   showmessage('FC_DocNameList='+FC_DocNameList);
   showmessage('FFixFileList='+FFixFileList);
   showmessage('FIs_In_Wh='+FIs_In_Wh);
   showmessage('FOldCaseInfo='+FOldCaseInfo);
   showmessage('FPrintyn='+FPrintyn);
   showmessage('FIs_OldCase='+FIs_OldCase);
   showmessage('FCustDocYN='+FCustDocYN);
  //ShowMessage('FMaxUploadSize='+FMaxUploadSize);
        //initkscan;
   showmessage('FUrl='+FUrl+#10#13+
   'FCaseID='+FCaseID+#10#13+
   'FMode='+FMode+#10#13+
   'FModeName='+FModeName+#10#13+
   'FWork_no='+FWork_no+#10#13+
   'FUserID='+FUserID+#10#13+
   'FUserName='+FUserName+#10#13+
   'FUserUnit='+FUserUnit+#10#13+
   'FData='+FData+#10#13+
   'FVerify='+FVerify+#10#13+
   'FReWrite='+FReWrite+#10#13+
   'FLanguage='+FLanguage+#10#13+
   'FLoanDoc_Value='+FLoanDoc_Value+#10#13+
   'FLoanDoc_Enable='+FLoanDoc_Enable+#10#13+
   'FUseProxy='+FUseProxy+#10#13+
   'FC_DocNoList='+FC_DocNoList+#10#13+
   'FC_DocNameList='+FC_DocNameList+#10#13+
   'FFixFileList='+FFixFileList+#10#13+
   'FIs_In_Wh='+FIs_In_Wh+#10#13+
   'FOldCaseInfo='+FOldCaseInfo+#10#13+
   'FPrintyn='+FPrintyn+#10#13+
   'FIs_OldCase='+FIs_OldCase+#10#13+
   'FCustDocYN='+FCustDocYN);
  ShowMessage('FImgDPI='+IntToStr(FImgDPI)+#10#13+
    'FScanColor='+    IntToStr(FScanColor)+#10#13+
    'FFileSizeLimit='+  IntToStr(FFileSizeLimit)  +#10#13+
    'FCaseNoLength='+ IntToStr(FCaseNoLength)   +#10#13+
    'FImgDelete='+    FImgDelete+#10#13+
    'FIsExternal='+    FIsExternal+#10#13+
    'FWH_category='+FWH_category+
    'FCheck_main_form='+    FCheck_main_form+#10#13+
    'FMaxUploadSize='+FMaxUploadSize);
    //FImgDelete:='Y';
  LoadImgFile;
 { ShowMessage('UpLPoint='+IntToStr(UpLPoint.X)+','+IntToStr(UpLPoint.Y)+#10#13+
    'UpRPoint='+IntToStr(UpRPoint.X)+','+IntToStr(UpRPoint.Y)+#10#13+
    'DownLPoint='+IntToStr(DownLPoint.X)+','+IntToStr(DownLPoint.Y)+#10#13+
    'DownRPoint='+IntToStr(DownRPoint.X)+','+IntToStr(DownRPoint.Y));
  }
end;
procedure TCB_IMGPSScanX.Button4Click(Sender: TObject);
@@ -3646,6 +4313,8 @@
  //Showmessage(self.Doc_Inf_List.Text);
  //LoadImgFile;
  //LoadImgFile1;
  //ISB1.MouseMode:=mmAmplifier;
  str:='';
  for I := 1 to 11 do // 看 OMRErrInfo 的內容
  begin
@@ -3661,6 +4330,14 @@
  ShowMessage('MEMO_INF_List='+MEMO_INF_List.Text)         ;
  ShowMessage('WORK_INF_List='+WORK_INF_List.Text)          ;
  ShowMessage('LASTEST_FORM_INF_List='+LASTEST_FORM_INF_List.Text)   ;
  ShowMessage('SampleFormIDList='+SampleFormIDList.Text);
  ShowMessage('ExistImgList='+ExistImgList.Text);
  ShowMessage('LastInitFormidList='+LastInitFormidList.Text);
  ShowMessage('IN_WH_DocNoList='+IN_WH_DocNoList.Text);
//  SampleFormIDList.Add('31A00101011706A');
//  SampleFormIDList.Add('31A00101021706A');
//  SampleFormIDList.Add('31A00101031706A');
end;
procedure TCB_IMGPSScanX.StatrTwainScan;
@@ -3678,6 +4355,7 @@
  ScanInfo.Graphic := TTiffGraphic.Create;
  try
    ISB := nil; //規零
//ShowMessage(IntToStr(ScanDpi));
    Scanner.RequestedXDpi := ScanDpi;
    Scanner.RequestedYDpi := ScanDpi;
    Scanner.RequestedImageFormat := ScanColor;
@@ -3686,6 +4364,10 @@
    Try
      Scanner.OpenSource;
      Scanner.Duplex := ScanDuplex; //雙面
      if FMode='SAMPLESCAN' then
        Scanner.Duplex:=False;
      //Scanner.FEEDERENABLED  := not ScanFlatCB.Checked;     // 先拿掉平台
      If ScanImgSetUse Then
      begin
@@ -3798,14 +4480,14 @@
          end;
        end;
        pScanInfo^.Graphic.Compression := tcJpeg;
        pScanInfo^.Graphic.JpegQuality := 70;
        pScanInfo^.Graphic.JpegQuality := FJpgCompression;
    end
    else if pScanInfo^.Graphic.ImageFormat = ifColor256 Then
    begin
      //Ext := '.jpg';
      ConvertToGray(pScanInfo^.Graphic);
      pScanInfo^.Graphic.Compression := tcJpeg;
      pScanInfo^.Graphic.JpegQuality := 70;
      pScanInfo^.Graphic.JpegQuality := FJpgCompression;
    end
    else if pScanInfo^.Graphic.ImageFormat = ifGray256 Then
    begin
@@ -3823,7 +4505,13 @@
        end;
      end;
      pScanInfo^.Graphic.Compression := tcJpeg;
      pScanInfo^.Graphic.JpegQuality := 70;
      pScanInfo^.Graphic.JpegQuality := FJpgCompression;
//ShowMessage(IntToStr(pScanInfo^.Graphic.JpegQuality));
//if pScanInfo^.Graphic.Compression = tcJpeg then
//begin
//ShowMessage('jpg');
//end;
    end
    else
    begin
@@ -3856,6 +4544,19 @@
    end;
    //iGraphic.Assign(iGraphic_First);
    iGraphic := iGraphic_First;
    if iGraphic.ImageFormat=ifGray256 then  //20180104
    begin
      iGraphic.Compression:=tcJPEG;
      iGraphic.JpegQuality:=FJpgCompression;
    end;
    if iGraphic.ImageFormat=ifTrueColor then  //20180104
    begin
      iGraphic.Compression:=tcJPEG;
      iGraphic.JpegQuality:=FJpgCompression;
    end;
//ShowMessage('WTF');
    while not iGraphic.IsEmpty do
    begin
      //Application.ProcessMessages;
@@ -3865,6 +4566,25 @@
        ImageScrollBox1NewGraphic(ImageScrollBox1.Graphic);
        MpsGetBarcode(ISB_BW.Graphic,MpsBarcodeinf);
        For i := 1 To MpsBarcodeinf.Count Do
        Begin
          If MpsBarcodeinf.r180[i] <> 0 Then // 依條碼角度轉影像
          Begin
            Rotate(iGraphic, MpsBarcodeinf.r180[i]);
            Break;
          End;
        End;
        if iGraphic.ImageFormat=ifGray256 then  //20180104 因此旋轉後變為回packbits 所以要改為jpeg
        begin
          iGraphic.Compression:=tcJPEG;
          iGraphic.JpegQuality:=FJpgCompression;
        end;
        if iGraphic.ImageFormat=ifTrueColor then
        begin
          iGraphic.Compression:=tcJPEG;
          iGraphic.JpegQuality:=FJpgCompression;
        end;
        PageEnd;
        IF PEFileName <> '' Then
        begin
@@ -3889,7 +4609,7 @@
            JpgGr := TJpegGraphic.Create;
            try
              JpgGr.Assign(iGraphic);
              JpgGr.SaveQuality := 30;
              JpgGr.SaveQuality := FJpgCompression;
              //JpgGr.AppendToStream(SaveStream);
              JpgGr.SaveToFile(PEFileName);
            finally
@@ -3984,17 +4704,28 @@
          if FormID = '' then
          begin
            FormID := BarCode2FormID; //取出FormID
          end;
          if (FormID <> '') and ISGuideFormID(FormID) then
            NowGuideFormID := FormID;
          if (FormID <> '') and ISDivPageFormID(FormID) then
          begin
            NowDivPageFormID := FormID;
          end;
          if (FormID <> '') and ISGuideFormID(FormID) then
          begin
            NowGuideFormID := FormID;
          end;
//ShowMessage('NowGuideFormID='+NowGuideFormID);
          if (not (FindDivFormCode(FormID))) and (NowGuideFormID <> '') {and (FormID = '')} then
            FormID := NowGuideFormID;
          DocNo := FormCode2DocNo(FormID);
          if (FormID <>'') and FindDivFormCode(FormID) Then  //只找分案頁上的案件條碼
//ShowMessage('FormID='+FormID);
//ShowMessage('ISDivPageFormID(FormID)='+BoolToStr(ISDivPageFormID(FormID),true));
//ShowMessage('FindDivFormCode(FormID)='+BoolToStr(FindDivFormCode(FormID),true));
//ShowMessage('A NowDivPageFormID='+NowDivPageFormID+#10#13+'FormID='+FormID+#10#13+'ScanCaseno='+ScanCaseno);
          if (FormID <>'') and FindDivFormCode(FormID) and (NowDivPageFormID <> '')  Then  //只找分案頁上的案件條碼
          begin
            ScanInfo.ImageCount := 0;
            ClearView(1);
            ContextList.Clear;
@@ -4002,6 +4733,8 @@
            ClearCaseIndex;                //清掉案件索引
            ScanCaseno := BarCode2CaseID; //取出案件編號
            NowGuideFormID := '';
            NowDivPageFormID :='';
//ShowMessage('B NowGuideFormID='+NowGuideFormID+#10#13+'FormID='+FormID+#10#13+'ScanCaseno='+ScanCaseno);
          end;
          if ScanCaseno = '' then //一開始都沒找到
          begin
@@ -4021,7 +4754,10 @@
          Str2Dir(ScanPath);
          ScanDocDir := FindLastestDocDir(ScanCaseno,DocNo);
          if DocNoNeedDiv(DocNo) then   //要分份數
//ShowMessage('AA ScanDocDir='+ScanDocDir);
//ShowMessage('BB ScanDocDir='+ScanDocDir);
          if DocNoNeedDiv(DocNo)then   //要分份數
          begin
            //Showmessage(DocNo+#13+FormCode2Page(FormID)+#13+inttostr(GetDocDir_Page(ScanCaseno,ScanDocDir))+#13+ScanDocDir);
            if ((FormCode2Page(FormID) = '01') and (GetDocDir_Page(ScanCaseno,ScanDocDir)>0))  or (ScanDocDir = '') then
@@ -4090,19 +4826,27 @@
      begin
        ScanSaveFilename := '';
        FormID := BarCode2FormID; //取出FormID
        if (FormID <> '') and ISGuideFormID(FormID) then
        if (FormID <> '') and ISGuideFormID(FormID) then   //20170510 註解 因為DSCAN 會全擠在導引頁下
          NowGuideFormID := FormID;
        //Showmessage('A:'+FormID+#13+'B:'+NowGuideFormID);
        if (NowGuideFormID <> '') {and (FormID = '')} then
        if (NowGuideFormID <> '') {and (FormID = '')} then  //20170510 註解  因為DSCAN 會全擠在導引頁下
          FormID := NowGuideFormID;
        DocNo := FormCode2DocNo(FormID);
        ScanDocDir := FindLastestDocDir(ScanCaseno,DocNo);
        if DocNoNeedDiv(DocNo) then   //要分份數
        if (FMode='ESCAN') and (FModeName=_Msg('補件掃描')) then    //20180207 加入的特殊邏輯
        begin
          if ((FormCode2Page(FormID) = '01') and (GetDocDir_Page(ScanCaseno,ScanDocDir)>0)) or (ScanDocDir = '') then
          ScanDocDir := FindLastestDocDirForPage(ScanCaseno, DocNo,FormID);
        end;
        if (DocNoNeedDiv(DocNo)) then   //要分份數
        begin
          if TreeView1.Selected = MyTreeNode1 then   //20170421 掃瞄插頁時選則在案號上才要分份數 選在FormID上就不分份數
          begin
            ScanInfo.ImageCount := 0;
            ScanDocDir := DocNo2DocNoDir(ImageSavePath + ScanCaseno+'\',DocNo);
            if ((FormCode2Page(FormID) = '01') and (GetDocDir_Page(ScanCaseno,ScanDocDir)>0)) or (ScanDocDir = '') then
            begin
              ScanInfo.ImageCount := 0;
              ScanDocDir := DocNo2DocNoDir(ImageSavePath + ScanCaseno+'\',DocNo);
            end;
          end;
        end
        Else        //不分份數
@@ -4217,7 +4961,7 @@
  DeleteFile(LngPath+'mps.dat');
  end;
  ////壓zip//////
  Showmessage('匯出完成,匯出檔案:'+LngPath+'mps.zip');
  Showmessage(_Msg('匯出完成,匯出檔案:')+LngPath+'mps.zip');
end;
procedure TCB_IMGPSScanX.ImportBtClick(Sender: TObject);
@@ -4244,16 +4988,16 @@
      str2dir(ZipPath);
      if not ExecuteUnZip_Pwd(OpenDialog1.FileName,ZipPath,False,'9338430') then
        Showmessage('無法解壓縮');
        Showmessage(_Msg('無法解壓縮'));
      if not FileExists(ZipPath+'mps.dat') then
      begin
        Showmessage('格式不符,無法匯入');
        Showmessage(_Msg('格式不符,無法匯入'));
        Exit;
      end;
      S.LoadFromFile(ZipPath+'mps.dat');
      if (En_DecryptionStr_Base64('D',S.Strings[0],'9338430')<> ServerDate) then
      begin
        Showmessage('檔案過期,無法匯入');
        Showmessage(_Msg('檔案過期,無法匯入'));
        Exit;
      end;
@@ -4293,7 +5037,7 @@
  S.Free;
  _DelTree(ZipPath);
  end;
  Showmessage('匯入完成');
  Showmessage(_Msg('匯入完成'));
end;
procedure TCB_IMGPSScanX.HotKeyDown (var Msg : TMessage);
@@ -4386,21 +5130,39 @@
  W,H : Integer;
begin
  Result := 0;
//ShowMessage('GetSiteOMR');
  IF (ImageScrollBox1.FileName <> FileName) and (FileName <> '') then
  begin
//ShowMessage('11111'+ImageScrollBox1.FileName+#10#13+FileName);
    ImageScrollBox1.LoadFromFile(FileName,1);
    FindPoint(ImageScrollBox1.Graphic,UpLPoint,UpRPoint,DownLPoint,'NONE');
{
ShowMessage('UpLPoint='+IntToStr(UpLPoint.X)+','+IntToStr(UpLPoint.Y)+#10#13+
'UpRPoint='+IntToStr(UpRPoint.X)+','+IntToStr(UpRPoint.Y)+#10#13+
'DownLPoint='+IntToStr(DownLPoint.X)+','+IntToStr(DownLPoint.Y)+#10#13+
'DownRPoint='+IntToStr(DownRPoint.X)+','+IntToStr(DownRPoint.Y));
    FindPoint(ImageScrollBox1.Graphic,UpLPoint,UpRPoint,DownLPoint,'');
ShowMessage('UpLPoint='+IntToStr(UpLPoint.X)+','+IntToStr(UpLPoint.Y)+#10#13+
'UpRPoint='+IntToStr(UpRPoint.X)+','+IntToStr(UpRPoint.Y)+#10#13+
'DownLPoint='+IntToStr(DownLPoint.X)+','+IntToStr(DownLPoint.Y)+#10#13+
'DownRPoint='+IntToStr(DownRPoint.X)+','+IntToStr(DownRPoint.Y));
}
    ClearLine(ISB_BW.Graphic,bt);
    ISB_BW.Redraw(True);
    Application.ProcessMessages;
  end;
  If ImageScrollBox1.FileName <> '' Then
  begin
//ShowMessage('22222'+ImageScrollBox1.FileName);
    Xdpi := ImagescrollBox1.Graphic.XDotsPerInch;
    Ydpi := ImagescrollBox1.Graphic.YDotsPerInch;
    H := ImageScrollBox1.Graphic.Height;
    W := ImageScrollBox1.Graphic.Width;
//ShowMessage('Xdpi='+IntToStr(Xdpi)+#10#13+'Ydpi='+IntToStr(Ydpi)+#10#13+'H='+IntToStr(H)+#10#13+'W='+IntToStr(W)+#10#13);
//ShowMessage('Site='+Site);
    OMRRect := CM_Str2Rect(Site,Xdpi,UpLPoint);
Display1.Lines.Add('UpLPoint=('+IntToStr(UpLPoint.X)+','+IntToStr(UpLPoint.Y)+');'+Site+';'+IntToStr(OMRRect.Left)+','+IntToStr(OMRRect.top)+','+IntToStr(OMRRect.Right)+','+IntToStr(OMRRect.Bottom));
    if OMRRect.Left < 0 then
      OMRRect.Left := 0;
    if OMRRect.Top < 0  then
@@ -4411,6 +5173,8 @@
      OMRRect.Bottom := ImageScrollBox1.Graphic.Height;
    result := Get_OMR(ISB_BW.Graphic,OMRRect);
//ShowMessage('result='+IntToStr(result));
  end;
end;
@@ -4452,7 +5216,7 @@
          DeviceDeleteSize := ini.ReadInteger('DeviceDelete','Size_New',Def_DeviceDeleteSize);
          ScannerReverse := ini.ReadBool('Scanner','Reverse',Def_ScannerReverse);
          BoardClear := ini.ReadBool('Scanner','BoardClear',Def_BoardClear);
          ScanDpi := ini.ReadInteger('Scanner','Dpi',Def_ScanDpi);
          //ScanDpi := ini.ReadInteger('Scanner','Dpi',Def_ScanDpi);
          //ScanDuplex := ini.ReadBool('Scanner','Duplex',Def_ScanDuplex);
          ScanRotate := ini.ReadInteger('Scanner','ScanRotate',Def_ScanRotate);
          ScanDeskew := ini.ReadBool('Scanner','ScanDeskew',Def_ScanDeskew);
@@ -4466,7 +5230,7 @@
          ini.WriteInteger('DeviceDelete','Size_New',DeviceDeleteSize);
          ini.WriteBool('Scanner','Reverse',ScannerReverse);
          ini.WriteBool('Scanner','BoardClear',BoardClear);
          ini.ReadInteger('Scanner','Dpi',ScanDpi);
          //ini.ReadInteger('Scanner','Dpi',ScanDpi);
          //ini.WriteBool('Scanner','Duplex',ScanDuplex);
          ini.WriteInteger('Scanner','ScanRotate',ScanRotate);
          ini.WriteBool('Scanner','ScanDeskew',ScanDeskew);
@@ -4492,7 +5256,7 @@
  Def_ScannerReverse := False;
  Def_BoardClear := False;
  Def_ScanDpi := 300;
  Def_ScanDuplex := False;
  Def_ScanDuplex := True;
  Def_ScanRotate := 0;
  Def_ScanDeskew := False;
  Def_ScanImgSetUse := False;
@@ -4639,6 +5403,21 @@
    begin
      PARA_CONTENT := GetSQLData(WORK_INF_List,'PARA_CONTENT',i);
      GuideFormIDList.CommaText := PARA_CONTENT;
    end
    Else if UpperCase(GetSQLData(WORK_INF_List,'PARA_NO',i)) = 'DIVPAGEFORMID' Then     //當分案頁的表單
    begin
      PARA_CONTENT := GetSQLData(WORK_INF_List,'PARA_CONTENT',i);
      DivPageFormIDList.CommaText := PARA_CONTENT;
    end
    Else if UpperCase(GetSQLData(WORK_INF_List,'PARA_NO',i)) = 'FILE_COMPRESSION' Then     //20171211 jpg to tif 壓縮比
    begin
      PARA_CONTENT := GetSQLData(WORK_INF_List,'PARA_CONTENT',i);
      FJpgCompression := StrToInt(PARA_CONTENT);
    end
    Else if UpperCase(GetSQLData(WORK_INF_List,'PARA_NO',i)) = 'MAX_UPLOAD_SIZE' Then     //取得 上傳大小的限制(MB)
    begin
      PARA_CONTENT := GetSQLData(WORK_INF_List,'PARA_CONTENT',i);
      FMaxUploadSize := PARA_CONTENT;
    end;
  end;
  ScanDuplex := Def_ScanDuplex;
@@ -4648,6 +5427,12 @@
  X509Certificate: TElX509Certificate; var Validate: Boolean);
begin
  Validate := True;
end;
procedure TCB_IMGPSScanX.HTTPSClientRedirection(Sender: TObject;
  const OldURL: string; var NewURL: string; var AllowRedirection: Boolean);
begin
  AllowRedirection := True;
end;
procedure TCB_IMGPSScanX.EnableImage(v:integer;Sender : TObject);
@@ -4690,6 +5475,7 @@
  Md : TMouseMode;
  ISB : TImageScrollBox;
begin
//ShowMessage(IntToStr(v));
  case v of
   -1 : Md := TMouseMode(mmUser);
    0 : Md := TMouseMode(mmAmplifier);
@@ -4704,6 +5490,7 @@
  begin
    ISB := TImageScrollBox(FindComponent('ISB'+inttostr(i)));
    ISB.MouseMode := TMouseMode(Md);
    //Label3.Caption:='v='+IntToStr(v)+'  time'+FormatDateTime('yyyy/mm/dd HH:MM:SS', now);
  end;
end;
@@ -4795,6 +5582,39 @@
end;
Function TCB_IMGPSScanX.GetSampleInf : Boolean;
var
  str:String;
begin
  Result := False;
  If not ProcessServlet_Get(HTTPSClient,FURL+'service/imgpsc/IMGPSC01/serversampleforocx','work_no='+FWork_no,FReWrite,Memo1,False) Then
  begin
    HttpErrStr := _Msg('錯誤代碼:')+inttostr(HttpError.HttpErrorCode)+','+HttpError.HttpReason;
    Result := False;
    Exit;
  end;
  IF memo1.Lines.Strings[0] = '1' Then
  begin
    HttpErrStr := _Msg('錯誤原因:')+memo1.Lines.Strings[1];
    Result := False;
    Exit;
  end
  Else IF memo1.Lines.Strings[0] = '0' Then
  begin
    str := memo1.Lines.Strings[1];
    SampleFormIDList.CommaText:=str;
    Result := True;
  end
  Else if Pos('<script type="text/javascript" src="scripts/CW00/login.js"></script>',Memo1.Lines.Text) > 0 then
  begin
    HttpErrStr := _Msg('錯誤原因:')+_Msg('閒置過久或被登出,請重新登入');
    Result := False;
    Exit;
  end;
end;
Function TCB_IMGPSScanX.GetSetInf1 : Boolean; //取系統設定資訊Mode1 DOC_INF
Var
  ColumeStr : String;
@@ -4805,6 +5625,7 @@
  Result := False;     // http://192.168.0.101:8080/fbnp/servlet/CWC01?act=getservertime
  EnCodeDateTime := En_DecryptionStr_Base64('E',ServerDate+GetBalance2Time(Balance),Mpskey);
  ColumeStr := 'WORK_NO,DOC_NO,DOC_U_DESC,DOC_TYPE,DOC_VERSION,FORM_PAGES,START_DATE,STOP_DATE,IS_DOC_DIV,IS_IN_WH';
  //If not ProcessServlet(HTTPSClient,FURL+'servlet/CWC02 ','checktime='+EnCodeDateTime+'&mode=1&col='+Doc_Inf_Colume+'&workno='+FWork_No,FReWrite.Text,Memo1) Then
@@ -5102,6 +5923,16 @@
  StringtoFile(IN_WH_DocNoList.Text,'D:\121.txt');}
end;
function TCB_IMGPSScanX.CheckRequiredColumnValues(workno, caseno:String): Boolean;
begin
//
  Result:=False;
  if (workno='HLN') and (caseno[9]='3') then
    Result:=True;
  if (workno='HLN') and (caseno[9]='4') then
    Result:=True;
end;
Procedure TCB_IMGPSScanX.CheckRule2OMRErrInfo;   //檢核規則填入OMRErrINFo Record
var i : Integer;
    CheckNo : String;
@@ -5153,8 +5984,11 @@
  FileList:TStringlist;
  DocDir : String;
begin
  DeleteFile(Path+FileName);
  DocDir := Path2DocDir(Path,CaseID);
//ShowMessage('DocDir='+DocDir);
  SetContextList('D',-1,CaseID,DocDir,FileName);
  {FileList:=TStringlist.Create;
  try
@@ -5191,6 +6025,15 @@
    begin
      if FileName2FormCode(FileList.Strings[i]) = FormID then
      begin
        if (FMode = 'ESCAN') and (FModeName<>_Msg('異動件')) then
        begin
          if ISExistImg(ImageSavePath+CaseID+'\'+DocDir+'\'+FileList.Strings[i]) then
          begin
            //ShowMessage('有圖為非當次掃瞄,不可刪除');
            Break;
          end;
        end;
//ShowMessage(FileList.Strings[i]);
        DeleteImageFile(ImageSavePath+CaseID+'\'+DocDir+'\',FileList.Strings[i],CaseID);
      end;
    end;
@@ -5248,6 +6091,40 @@
    Cust_DocNoList.LoadFromFile(Path+'CustomDocNo.dat');
end;
Function TCB_IMGPSScanX.DeleteDocNoFileForESCAN(Path,DocNo:String):Boolean;  //刪除指定DocNo文件
var
  i,j,k: Integer;
  FName : String;
  ST1,ST2,ST3:TStringList;
begin
  Result := False;
//ShowMessage(DocNo);
  for i := ContextList.Count - 1 downto 0 do
  begin
    FName := ContextList.Strings[i];
    If (DocNo = FormCode2DocNo(FileName2FormCode(FName))) or (DocNo=AttName) then
    begin
      if not ISExistImg(Path+'\'+FName) then
      begin
        DeleteFile(Path+'\'+FName);
        ContextList.Delete(i);
      end;
      Result := True; //有刪到指定文件
    end;
  end;
  ContextList.SaveToFile(Path+'\Context.dat');
  ContextList.LoadFromFile(Path+'\Context.dat');
  if ContextList.Count=0 then
  begin
    _DelTree(Path);
    SetDocNoList('D',-1,NowCaseNo,NowDocDir,'');
  end;
end;
Procedure TCB_IMGPSScanX.DeleteShowFile(Path:String); //刪除顯示中的影像
var
  i : Integer;
@@ -5280,22 +6157,63 @@
Function TCB_IMGPSScanX.CheckCaseDocNoPage(CaseID,DocNo,Version:String;Pages:Integer):Integer; //取案件裡的文件_版本頁數
var
  i,n,Count : integer;
  S : TStringlist;
  S, S2 : TStringlist;
  FormCode,iPage : String;
  docInt,tempInt:integer;
  v,v2:integer;
begin
  Count := 0;
  docInt:=0;
  tempInt:=0;
  S := TStringlist.Create;
  S2 := TStringlist.Create;
//ShowMessage('page='+IntToStr(Pages));
  try
    S.LoadFromFile(ImageSavePath+CaseID+'\upload\Context.dat');
    S2.LoadFromFile(ImageSavePath+CaseID+'\upload\DocDir.dat'); //2017 1220 改成只承認第一份的
    for I := 1 to pages do //從0到pages-1  改成 1到pages 20170316 這樣可以修改檢核的頁數問題
    begin
      iPage := Add_Zoo(i,2);
      for n := 0 to S.Count - 1 do
      begin
        if (FWH_category='N') and (FIs_In_Wh='Y') then
        begin
          if ISExistImg(ImageSavePath+CaseID+'\upload\'+S.Strings[n]) then
          begin
            Continue;
          end;
        end;
        if (Length(S2.Strings[n])>8) and (Pos(DocNo,S2.Strings[n])<>0) then //2017 1220 改成只承認第一份的
        begin
//LogFile1.LogToFile(logTimeString+'有進'+docno+','+S2.Strings[n]+IntToStr(Pos(DocNo,S2.Strings[n])));
          v:=Pos('(',S2.Strings[n]);
          v2:=Pos(')',S2.Strings[n]);
          tempInt:=StrToInt(Copy(S2.Strings[n],v+1,v2-v-1));
          if docInt=0 then
          begin
            docInt:=tempInt;
          end;
          if docInt<>tempInt then
          begin
//LogFile1.LogToFile(logTimeString+'docInt='+IntToStr(docInt)+',tempInt='+IntToStr(tempInt));
            Result := Count;
            Break;
          end;
        end;
        FormCode := FileName2FormCode(S.Strings[n]);
//LogFile1.LogToFile(logTimeString+'S.Strings[n]='+S.Strings[n]);
//Showmessage('1:'+version+','+FormCode2Version(FormCode)+','+DocNo+','+FormCode2DocNo(FormCode)+','+iPage+','+FormCode2Page(FormCode));
//LogFile1.LogToFile(logTimeString+'FormCode='+FormCode);
LogFile1.LogToFile(logTimeString+'CheckCaseDocNoPage caseno='+CaseID+','+version+','+FormCode2Version(FormCode)+','+DocNo+','+FormCode2DocNo(FormCode)+','+iPage+','+FormCode2Page(FormCode));
//ShowMessage(DocNo+','+IntToStr(docInt)+','+IntToStr(tempInt));
//LogFile1.LogToFile(logTimeString+'FormCode='+FormCode);
        if (version = FormCode2Version(FormCode)) and (DocNo = FormCode2DocNo(FormCode)) and (ipage = FormCode2Page(FormCode)) then
        begin
LogFile1.LogToFile(logTimeString+'CheckCaseDocNoPage caseno='+CaseID+','+version+','+FormCode2Version(FormCode)+','+DocNo+','+FormCode2DocNo(FormCode)+','+iPage+','+FormCode2Page(FormCode));
//Showmessage(version+','+DocNo+',iPage='+iPage);
//Showmessage(inttostr(Count+1));
          Inc(Count);
@@ -5305,6 +6223,7 @@
    end;
  finally
  S.Free;
  S2.free;
  end;
  Result := Count;
end;
@@ -5321,6 +6240,13 @@
    S.LoadFromFile(ImageSavePath+CaseID+'\upload\Context.dat');
    for i := 0 to S.Count - 1 do
    begin
      if FWH_category='N' then
      begin
        if ISExistImg(ImageSavePath+CaseID+'\upload\'+S.Strings[i]) then
        begin
          Continue;
        end;
      end;
      iFormCode := FileName2FormCode(S.Strings[i]);
      if FormCode = iFormCode then
      begin
@@ -5360,14 +6286,14 @@
    For i := 0 to S.Count -1 do
    begin
      FileName := S.Strings[i];
      ImageReSize(CaseID,FileName);  //依十字定位點做縮放
      ImageReSize_FormID(CaseID,FileName);  //依十字定位點做縮放
    end;
  finally
  S.Free;
  end;
end;
Procedure TCB_IMGPSScanX.ImageReSize(CaseID,FileName:String);  //依十字定位點做縮放
Procedure TCB_IMGPSScanX.ImageReSize_FormID(CaseID,FileName:String);  //依十字定位點做縮放
var
  FormID : String;
  DH,DW : String;
@@ -5376,7 +6302,9 @@
  SizeStr : String;
  S : TStringlist;
  v,v1:Integer;
  IsRecordMD5:Boolean;
begin
  IsRecordMD5:=False;
  FormID := FileName2FormCode(FileName);
  if FormID = '' then Exit;
@@ -5386,17 +6314,40 @@
    DW := GetFindResult('T1.FORM_WIDTH');
    ANCHOR := UpperCase(GetFindResult('T1.ANCHOR'));
    ANCHOR := Index2Anchor(ANCHOR);
Display1.Lines.Add(FormID+','+DH+','+DW);
//ShowMessage('AAAAAAAAA');
    if ((ANCHOR = 'ANCHOR') or (ANCHOR = 'FRAME')) and (DH <> '') and (DW <> '') then  //有十字定位點
    begin
//ShowMessage('BBBBBBB');
      ImageScrollBox1.LoadFromFile(ImageSavePath+CaseID+'\Upload\'+FileName,1);
      if (FWH_category='N') and  ISExistImg(ImageSavePath+CaseID+'\Upload\'+FileName) then
      begin
        Exit;//20171103  補件  原有的圖不作resize
      end;
      //FindPoint(ImageScrollBox1.Graphic,UpLPoint,UpRPoint,DownLPoint,NowW,NowH);
      FindPoint(ISB_BW.Graphic,UpLPoint,UpRPoint,DownLPoint,NowW,NowH,ANCHOR);
      SizeStr := CheckSize(ISB_BW,UpLPoint,UpRPoint,DownLPoint,DW,DH);
      ImageResize(ImageScrollBox1.Graphic,ISB_BW.Graphic.Width,ISB_BW.Graphic.Height);
      FindPoint(ISB_BW.Graphic,UpLPoint,UpRPoint,DownLPoint,NowW,NowH,ANCHOR);
      v := 5;
      v1 := length(SizeStr);
      IF (SizeStr <> '') and (Copy(SizeStr,1,v) <> 'ERROR') then
      begin
//ShowMessage('CCCCC');
        if (ISExistImg(ImageSavePath+CaseID+'\Upload\'+FileName)) and (reSizeExistImgList.IndexOf(LoadFileGetMD5(ImageSavePath+CaseID+'\Upload\'+FileName))=-1) then
        begin
          IsRecordMD5:=True;
        end;
        ImageScrollBox1.SaveToFile(ImageSavePath+CaseID+'\Upload\'+FileName);
        if IsRecordMD5 then
        begin
          reSizeExistImgList.add(LoadFileGetMD5(ImageSavePath+CaseID+'\Upload\'+FileName));
        end;
//showmessage(ImageSavePath+CaseID+'\Upload\'+FileName);
        S := TStringlist.Create;                     ///20110422拿掉 換成上傳才做
        if FileExists(ImageSavePath+CaseID+'\Upload\ReSize.dat') then
          S.LoadFromFile(ImageSavePath+CaseID+'\Upload\ReSize.dat');
@@ -5477,6 +6428,9 @@
  last_add_formidstr :string;
  casepath:String;
  filesizeInt:integer;
  case_page:string;
  Fname:String;
  FileRec:TSearchrec;
begin
  Result := True;
  TransName := CaseID;
@@ -5486,9 +6440,12 @@
    ContextList.LoadFromFile(Path+'Context.dat');
    Context_DocnoList.LoadFromFile(Path+'Context_DocNo.dat');
  end;
  if FileExists(Path+'CustomDocNo.dat') then
    Cust_DocNoList.LoadFromFile(Path+'CustomDocNo.dat');
  Pages := ContextList.Count;
  case_page:=IntToStr(pages);
  if (FMode = 'NSCAN') or (FMode = 'ESCAN') or (FMode = 'ASCAN') or (FMode = 'DSCAN') or (FMode = 'SSCAN') or (FMode = 'MSCAN') or (FMode = 'RI_SCAN') or (FMode = 'RSCAN')  then
  begin
    //Showmessage('1');
@@ -5533,21 +6490,21 @@
  ST1:=TStringList.Create;
  ST1.LoadFromFile(path+'FormCode_Name.dat');
//ShowMessage(ST1.Text);
//ShowMessage(LastInitFormidList.Text);
  ST2:=TStringList.Create;
  for I := 0 to ST1.Count - 1 do
  begin
    if (Pos('_',St1.Strings[i])<>1) and (Pos('_',St1.Strings[i])<>-11) then
    if (Pos('_',St1.Strings[i])<>1) and (Pos('_',St1.Strings[i])<>-1) then
    begin
      str1:=Copy(ST1.Strings[i],1,Pos('_',St1.Strings[i])-1);
      if ST2.IndexOf(str1) = -1 then
      begin
        ST2.Add(str1);
        must_formidStr:= must_formidStr+str1+'@#,';
      end;
      ST2.Add(str1);
      must_formidStr:= must_formidStr+str1+'@#,';
    end;
  end;
  must_formidStr:=Copy(must_formidStr,1,Length(must_formidStr)-3) ;
//ShowMessage('must_formidStr='+must_formidStr);
//ShowMessage('AST2='+ST2.Text);
  for I := 0 to LastInitFormidList.Count - 1 do
  begin
    if ST2.IndexOf(LastInitFormidList.Strings[i]) <> -1 then
@@ -5555,19 +6512,15 @@
      ST2.Delete(ST2.IndexOf(LastInitFormidList.Strings[i]));
    end;
  end;
//ShowMessage('BST2='+ST2.Text);
  for I := 0 to ST2.Count - 1 do
  begin
    if i <> ST2.Count then
    begin
      last_add_formidstr:=last_add_formidstr+ST2.Strings[i]+'@#,';
    end
    else
    begin
      last_add_formidstr:=last_add_formidstr+ST2.Strings[i]
    end;
  end;
  last_add_formidstr:=Copy(last_add_formidstr,1,Length(last_add_formidstr)-3) ;
  ST1.Free;
  ST2.Free;
//ShowMessage('last_add_formidstr='+last_add_formidstr);
  ///////必要formid 20170315 end //////////////////////////
  ///保留外部影像  start///////////////////////////////
@@ -5596,6 +6549,26 @@
  if HaveMask then
    ZipMaskFile(Path,MaskPath,Path,'MaskImg.zip');  //有遮罩設定的才產生
  /////壓檔////
  ///檢查上傳的zip大小////
   FName :=Path+ 'Img.zip';
    FindFirst(FName, faAnyfile, FileRec);
    //FMaxUploadSize
//ShowMessage(IntToStr(FileRec.Size));
//Result:=False;
//exit;           //目前上傳檔案大小為xxMB,已超過50MB,無法上傳    %.3f  ,[FileRec.Size / 1048576]
    If FileRec.Size > StrtoInt(FMaxUploadSize) * 1048576 Then // 檢查檔案大小
    Begin
      ShowMessage(Format(_Msg('%s目前上傳檔案大小為%.3fMB,已超過%sMB,無法上傳'),[caseid,FileRec.Size / 1048576,FMaxUploadSize]));
      //ShowMessage(Format('%s目前上傳檔案大小為%.3fMB,已超過'+FMaxUploadSize+'MB,無法上傳',[caseid,FileRec.Size / 1048576]) );
      FindClose(FileRec);
      Result := False;
      Exit;
    End;
    FindClose(FileRec);
  ///檢查上傳的zip大小////
//ShowMessage('last_add_formidstr='+last_add_formidstr);
  ////上傳/////
  SendData:='data='+HTTPEncode(UTF8Encode(FData))
  +'&verify='+FVerify
@@ -5605,33 +6578,35 @@
  +'&doc_data='+HTTPEncode(UTF8Encode(Doc_Data))
  +'&doc_data1='+HTTPEncode(UTF8Encode(Doc_Data1))
  +'&attach='+AttachYN
  +'&case_page='+case_page
  +'&file_size='+IntToStr(filesizeInt)
  +'&must_formid='+must_formidStr  //擁有的 formid
  +'&last_add_formid='+last_add_formidstr   //當次新加的 formid
  +'&in_doc1='+HTTPEncode(UTF8Encode(In_Doc1))
  +'&in_doc2='+HTTPEncode(UTF8Encode(In_Doc2));
//ShowMessage('SendData='+SendData);
//exit;
//ShowMessage(FData+#10#13+Doc_Data);
  //Showmessage('Wait');
  if not upFile(HTTPSClient,FUrl,'service/imgpsc/IMGPSC02/caseupload',SendData,'file',Path+'Img.zip',FReWrite,Memo1,False) then
  begin
    Showmessage(Format(_Msg('傳送案件編號(%s)檔案時,網路發生錯誤!!'+_Msg('錯誤代碼:')),[CaseID])+Inttostr(HttpError.HttpErrorCode)+' '+HttpError.HttpReason);
    Showmessage(Inttostr(HttpError.HttpErrorCode)+' '+HttpError.HttpReason+'.');
    Result := False;
    Exit;
  end;
  if memo1.Lines.Strings[0] = '1' then
  begin
    Showmessage(Format(_Msg('傳送案件編號(%s)檔案時,網路發生錯誤!!')+_Msg('錯誤原因:'),[CaseID])+memo1.Lines.Strings[1]);
    Showmessage(Format(_Msg('')+_Msg(''),[CaseID])+memo1.Lines.Strings[1]+'。');
    Result := False;
    Exit;
  end
  Else if Pos('<script type="text/javascript" src="scripts/CW00/login.js"></script>',Memo1.Lines.Text) > 0 then
  Else if Pos('<script type="text/javascript" src="scripts/IMGPS00/login.js"></script>',Memo1.Lines.Text) > 0 then
  begin
    Showmessage(Format(_Msg('傳送案件編號(%s)檔案時,網路發生錯誤!!')+_Msg('錯誤原因:')+_Msg('閒置過久或被登出,請重新登入'),[CaseID]));
    Showmessage(Format(_Msg('')+_Msg('')+_Msg('閒置過久或被登出,請重新登入'),[CaseID]));
    Result := False;
    Exit;
  end;
  ////上傳////
  if FMode = 'ESCAN' then    //上傳舊件引入檔案      //20140616 原本先搬舊件再搬新件,改為先搬新件再搬舊件
  begin
    if not TransOldCaseFile(ImageSavePath+CaseID+'\') then
@@ -5640,9 +6615,6 @@
      Exit;
    end;
  end;
  // 呼叫Server完成 /////
  {If not CaseComplete(Path,CaseID,MainCase) Then
  begin
@@ -5879,17 +6851,17 @@
  end;
  if Memo1.Lines.Strings[0] = '1' then
  begin
    HttpErrStr :=_Msg('錯誤原因:')+memo1.Lines.Strings[1];
    HttpErrStr :=_Msg('錯誤原因:')+memo1.Lines.Strings[1]+'。';
    Result := False;
    Exit;
  end
  Else if Pos('<script type="text/javascript" src="scripts/CW00/login.js"></script>',Memo1.Lines.Text) > 0 then
  Else if Pos('<script type="text/javascript" src="scripts/IMGPS00/login.js"></script>',Memo1.Lines.Text) > 0 then
  begin
    HttpErrStr := _Msg('錯誤原因:')+_Msg('閒置過久或被登出,請重新登入');
    Result := False;
    Exit;
  end;
//ShowMessage('sssss');
//ShowMessage('替換zip');
  AttPath := Path + 'AttFile\';
  if FileExists(Path+CaseID+'.zip') then
  begin
@@ -6201,6 +7173,13 @@
    S.LoadFromFile(Path+'Context.dat');
    for I := 0 to S.Count - 1 do
    begin
      if FWH_category='N' then
      begin
        if (ISExistImg(Path+S.Strings[i])) or (reSizeExistImgList.IndexOf(LoadFileGetMD5(Path+S.Strings[i]))<>-1)  then
        begin
          Continue;
        end;
      end;
      FormCode := FileName2FormCode(S.Strings[i]);
      DocNo := FormCode2DocNo(FormCode);
      Ver := FormCode2Version(FormCode);
@@ -6351,7 +7330,8 @@
            if Index <> -1 then
            begin
              //SetRecordEditedDocDir('D',CaseNo,CaseDocNoList.Strings[Index]);  //20140624 修改刪除文件時也記一筆異動,刪掉會無法通知前端網頁有異動
              SetRecordEditedDocDir('A',CaseNo,CaseDocNoList.Strings[Index]);
              SetRecordEditedDocDir('A',CaseNo,CaseDocNoList.Strings[Index]);  //20170912 要刪除  不然我寫不下去
              CaseDocNoList.Delete(Index);
              CaseDocNo_CopiesList.Delete(Index);
@@ -6363,7 +7343,7 @@
                if DocDir = CaseDocNoList.Strings[i] then
                begin
                  //SetRecordEditedDocDir('D',CaseNo,CaseDocNoList.Strings[i]);  //20140624 修改刪除文件時也記一筆異動,刪掉會無法通知前端網頁有異動
                  SetRecordEditedDocDir('A',CaseNo,CaseDocNoList.Strings[i]);
                  SetRecordEditedDocDir('A',CaseNo,CaseDocNoList.Strings[i]);  //20170912 要刪除  不然我寫不下去
                  CaseDocNoList.Delete(i);
                  CaseDocNo_CopiesList.Delete(i);
                  Break;
@@ -6377,7 +7357,7 @@
          end;
    end;
    //Showmessage('abc'+#13+ImageSavePath+CaseNo+'\CaseDocNo.dat'+#13+inttostr(CaseDocNoList.Count)+#13+CaseDocNoList.Text);
    if CaseDocNoList.Count > 0 then
    if CaseDocNoList.Count >= 0 then
    begin
      CaseDocNoList.SaveToFile(ImageSavePath+CaseNo+'\CaseDocNo.dat');
      CaseDocNo_CopiesList.SaveToFile(ImageSavePath+CaseNo+'\CaseDocNo_Copies.dat');
@@ -6395,6 +7375,7 @@
  //DocNo:String;
begin
  //DocNo := FormCode2DocNo(FileName2FormCode(FileName));
//ShowMessage('FileName='+FileName);
  if DocDir = '' then
    DocDir := AttName ; //附件
  ContextList.Clear;
@@ -6434,6 +7415,49 @@
  if ContextList.Count > 0 then
  begin
    ContextList.SaveToFile(ImageSavePath+CaseNo+'\'+DocDir+'\Context.dat');
  end;
end;
Procedure TCB_IMGPSScanX.SetAttContextList(Mode:Char;Index:Integer;CaseNo,FileName:String);  //'A:加入,I:插入,D:刪除,E:修改'
var
  i : Integer;
begin
  AttContextList.Clear;
  if FileExists(ImageSavePath+CaseNo+'\AttContext.dat') then
    AttContextList.LoadFromFile(ImageSavePath+CaseNo+'\AttContext.dat');
  case Mode of
    'A':begin
          AttContextList.Add(FileName);
        end;
    'I':begin
          AttContextList.Insert(Index,FileName);
        end;
    'E':begin
          AttContextList.Strings[Index] := FileName;
        end;
    'D':begin
          if Index <> -1 then
          begin
            AttContextList.Delete(Index);
          end
          Else if (text <> '') then
          begin
            for i := 0 to AttContextList.Count - 1 do
            begin
              if FileName = AttContextList.Strings[i] then
              begin
                AttContextList.Delete(i);
                Break;
              end;
            end;
          end;
          if AttContextList.Count = 0 then
            DeleteFile(ImageSavePath+CaseNo+'\AttContext.dat');
        end;
  end;
  if AttContextList.Count > 0 then
  begin
    AttContextList.SaveToFile(ImageSavePath+CaseNo+'\AttContext.dat');
  end;
end;
@@ -6484,6 +7508,24 @@
    begin
      Result := False;
      Break;
    end;
  end;
end;
Function TCB_IMGPSScanX.CheckCaseAttach_OK:Boolean;  //檢查是否有未歸類的案件
var
  i,j : Integer;
begin
  Result := True;
  for i := 0 to NewTreeNode.Count - 1 do
  begin
    for j := 0 to NewTreeNode.Item[i].Count - 1 do
    begin
      if Pos(_msg('未歸類'),NewTreeNode.Item[i].Item[j].Text) > 0 then
      begin
        Result := False;
        Break;
      end;
    end;
  end;
end;
@@ -6540,16 +7582,71 @@
  FormID : String;
  OldFile,NewFile:String;
  Ext : String;
  ST1:TStringList;
begin
  ST1:=TStringList.Create;
  OldFileList := TStringlist.Create;
  NewFileList := TStringlist.Create;
  try
    NewDocNo := FormCode2DocNo(NewFormID);
    NewDocDir := FindLastestDocDir(CaseID,NewDocNo);
    if NewDocDir = '' then
      NewDocDir := NewDocNo;
    /////20190319 Hong 原本的程式判斷怪怪的先Mark在下方,改用這段
    if DocNoNeedDiv(NewDocNo) then   //要分份數
    begin
      if ((FormCode2Page(NewFormID) = '01') and (GetDocDir_Page(CaseID,NewDocDir)>0)) or (NewDocDir = '') then
      begin
        NewDocDir := DocNo2DocNoDir(ImageSavePath + CaseID+'\',NewDocNo);
      end
      else
      begin //20171016  真對補件影響 所加的判斷
        ST1.Clear;
        if FileExists(ImageSavePath + CaseID+'\'+NewDocDir+'\Context.dat') then
        begin
          ST1.LoadFromFile(ImageSavePath + CaseID+'\'+NewDocDir+'\Context.dat');
          if (ST1.Count > 0) and ISExistImg(ImageSavePath + CaseID+'\'+NewDocDir+'\'+ST1.Strings[0]) then   //20181210 多增加判斷ST1>0 否則會有機會出現List out of bound  Hong
          begin
            NewDocDir := DocNo2DocNoDir(ImageSavePath + CaseID+'\',NewDocNo);
          end;
        end;
      end;
    end
    Else        //不分份數
    begin
      if NewDocNo <> '' then
        NewDocDir := NewDocNo
      else      //Attach 附件
        NewDocDir := DocNo2DocNoDir(ImageSavePath + CaseID+'\',NewDocNo);
    end;
    {if NewDocDir = '' then
    begin
      if DocNoNeedDiv(NewDocNo) then
      begin
        NewDocDir:=DocNo2DocNoDir(ImageSavePath + NowCaseno+'\',NewDocNo);
      end
      else
      begin
        NewDocDir := NewDocNo;
      end;
    end;
//ShowMessage('NewDocDir='+NewDocDir);
    if DocNoNeedDiv(NewDocNo) and (FormCode2Page(NewFormID)='01') then
    begin
      NewDocDir := DocNo2DocNoDir(ImageSavePath+CaseID+'\',NewDocNo);
    end
    else
    begin
      ST1.Clear;
      if FileExists(ImageSavePath + NowCaseno+'\'+NewDocDir+'\Context.dat') then
      begin
        ST1.LoadFromFile(ImageSavePath + NowCaseno+'\'+NewDocDir+'\Context.dat');
        if ISExistImg(ImageSavePath + NowCaseno+'\'+NewDocDir+'\'+ST1.Strings[0]) then
        begin
          NewDocDir := DocNo2DocNoDir(ImageSavePath + NowCaseno+'\',NewDocNo);
        end;
      end;
    end; }
    if Not DirectoryExists(ImageSavePath+CaseID+'\'+NewDocDir) then
    begin
      MkDir(ImageSavePath+CaseID+'\'+NewDocDir);
@@ -6592,6 +7689,7 @@
  finally
  OldFileList.Free;
  NewFileList.Free;
  ST1.Free;
  end;
end;
@@ -6668,35 +7766,16 @@
    Result := True;
end;
Function TCB_IMGPSScanX.GetInputMask:String; //取得輸入的保單號碼
var
  InputMaskForm: TInputMaskForm;
begin
  Result := '';
  ShowText := _msg('輸入保單號碼中');
  DataLoading(True,True);
  InputMaskForm := TInputMaskForm.Create(self);
  try
    InputMaskForm.MaskEdit1.ClearSelection;
    if InputMaskForm.ShowModal = mrOk then
    begin
      Result := Trim(InputMaskForm.MaskEdit1.Text)+Trim(InputMaskForm.MaskEdit2.Text)+Trim(InputMaskForm.MaskEdit3.Text);
    end;
  finally
  InputMaskForm.Free;
  DataLoading(False,False);
  end;
end;
Function TCB_IMGPSScanX.GetCasePage(Path,CaseID:String):Integer;
var
  DocDirList,FileList :TStringlist;
  DocDirList,FileList,ST1 :TStringlist;
  iDocDir,iDocNo : String;
  i,Count : Integer;
  i,n,Count : Integer;
begin
  Count := 0;
  DocDirList := TStringlist.Create;
  FileList := TStringlist.Create;
  ST1:=TStringList.Create;
  try
    if FileExists(Path+CaseID+'\CaseDocNo.dat') then
      DocDirList.LoadFromFile(Path+CaseID+'\CaseDocNo.dat');
@@ -6711,11 +7790,37 @@
      begin
        Continue;
      end;}
      if not DocNoAppear(iDocNo) then Continue;
      //if not DocNoAppear(iDocNo) then Continue; //20170817 先註解
      FileList.Clear;
      if FileExists(Path+CaseID+'\'+iDocDir+'\Context.dat') then
      begin
        FileList.LoadFromFile(Path+CaseID+'\'+iDocDir+'\Context.dat');
        if (FWH_category='N') and (FIs_In_Wh='Y') then
        begin
          ST1.Clear;
          for n := 0 to FileList.Count - 1 do
          begin
            if ISExistImg(Path+CaseID+'\'+iDocDir+'\'+FileList.Strings[n]) then
            begin
              ST1.Add(FileList.Strings[n]);
            end;
          end;
          for n := 0 to ST1.Count - 1 do
          begin
            if (FileList.IndexOf(ST1.Strings[n])<>-1) and (not DocNoIs_In_WH(iDocNo)) then
            begin
              FileList.Delete(FileList.IndexOf(ST1.Strings[n]));
            end;
          end;
        end
        Else
          if not DocNoAppear(iDocNo) then Continue; //20180925 Hong覺得應該要加這段
      end;
      Count := Count+ FileList.Count;
    end;
    if FileExists(Path+CaseID+'\'+AttName+'\Context.dat') then
@@ -6728,6 +7833,7 @@
  finally
  DocDirList.Free;
  FileList.Free;
  ST1.free;
  end;
end;
@@ -6805,8 +7911,8 @@
Function TCB_IMGPSScanX.GetCase_PageCount(var CaseCount,PageCount:Integer):Boolean; //取出案件的數量及頁數
var
  i,n: Integer;
  CaseList,DocList,FileList : TStringlist;
  i,n,k: Integer;
  CaseList,DocList,FileList,ST1 : TStringlist;
begin
  Result := False;
  CaseCount := 0;
@@ -6814,19 +7920,23 @@
  CaseList := TStringlist.Create;
  DocList := TStringlist.Create;
  FileList := TStringlist.Create;
  ST1:= TStringlist.Create;
  try
    ImageSavePath := ImagePath;
    CaseList.Clear;
    if FileExists(ImageSavePath + 'CaseList.dat') then
      CaseList.LoadFromFile(ImageSavePath + 'CaseList.dat');
    CaseCount :=  CaseCount+CaseList.Count;
//ShowMessage('ImageSavePath='+ImageSavePath+#10#13+'CaseList.Count='+IntToStr(CaseList.Count));
    for i := 0 to CaseList.Count - 1 do
    begin
      DocList.Clear;
      If FileExists(ImageSavePath+CaseList.Strings[i]+'\CaseDocNo.dat') Then
        DocList.LoadFromFile(ImageSavePath+CaseList.Strings[i]+'\CaseDocNo.dat');
//ShowMessage('DocList='+DocList.Text);
      for n := 0 to DocList.Count - 1 do
      begin
//ShowMessage(DocList.Strings[n]+','+BoolToStr(DocNoAppear(DocNoDir2DocNo(DocList.Strings[n])),true));
        if not DocNoAppear(DocNoDir2DocNo(DocList.Strings[n])) then Continue;
        FileList.Clear;
        If FileExists(ImageSavePath+CaseList.Strings[i]+'\'+DocList.Strings[n]+'\Context.dat') Then
@@ -6838,14 +7948,41 @@
      If FileExists(ImageSavePath+CaseList.Strings[i]+'\'+Attname+'\Context.dat') Then
          FileList.LoadFromFile(ImageSavePath+CaseList.Strings[i]+'\'+Attname+'\Context.dat');
      //Showmessage(ImageSavePath+CaseList.Strings[i]+'\'+Attname+'\Context.dat');
      //Showmessage(FileList.Text);
//Showmessage('FileList='+FileList.Text);
      PageCount := PageCount+FileList.Count;
      //Showmessage(inttostr(PageCount));
//Showmessage('PageCount='+inttostr(PageCount));
      if (FWH_category='N') and (FIs_In_Wh='Y') then  //20170912 針對非入庫並當次掃描做頁數計算
      begin
        if FileExists(ImageSavePath+NowCaseno+'\EditedDocDir.dat') then
        begin
          ST1.LoadFromFile(ImageSavePath+NowCaseno+'\EditedDocDir.dat');
          for n := 0 to ST1.Count - 1 do
          begin
            if ST1.Strings[n]=AttName then  Continue;
//ShowMessage(ST1.Strings[n]+','+BoolToStr(DocNoIs_In_WH(DocNoDir2DocNo(ST1.Strings[n])),true));
            if not DocNoIs_In_WH(DocNoDir2DocNo(ST1.Strings[n])) then
            begin
              FileList.Clear;
              if FileExists(ImageSavePath+CaseList.Strings[i]+'\'+ST1.Strings[n]+'\Context.dat') then
              begin
                FileList.LoadFromFile(ImageSavePath+CaseList.Strings[i]+'\'+ST1.Strings[n]+'\Context.dat');
                for k := 0 to FileList.Count - 1 do
                begin
                  if not ISExistImg(ImageSavePath+CaseList.Strings[i]+'\'+ST1.Strings[n]+'\'+FileList.Strings[k]) then
                    PageCount := PageCount+1;
                end;
              end;
            end;
          end;
        end;
      end;
    end;
  Finally
  CaseList.Free;
  DocList.Free;
  FileList.Free;
  ST1.Free
  end;
  Result := True;
end;
@@ -6877,7 +8014,7 @@
begin
  Result := ''; //沒找到
  iCaseID := '';
  for i := 1 to MpsBarcodeinf.Count-1  do
  for i := 1 to MpsBarcodeinf.Count  do    //20180920 拿掉-1
  begin
    if (Length(MpsBarcodeinf.text[i]) = CaseIDLength) then
    begin
@@ -6918,8 +8055,12 @@
  if Path = '' then Exit;
  S := TStringlist.Create;
  try
    S.Add(Case_loandoc);
    S.SaveToFile(Path+'CaseIndex.dat');
    try
      S.Add(Case_loandoc);
      S.SaveToFile(Path+'CaseIndex.dat');
    except on E: Exception do
    end;
  finally
  S.Free;
  end;
@@ -6953,6 +8094,27 @@
end;
procedure TCB_IMGPSScanX.ReduceLogFile; //20171011 必免log檔掌太大
var
  ST1:TStringlist;
  I:integer;
begin
  ST1:=TStringList.Create;
  if FileExists(LngPath+'IMGPSCheck.log') then
  begin
    ST1.LoadFromFile(LngPath+'IMGPSCheck.log');
    if ST1.count>100000 then
    begin
      for I := 0 to 10000 do
      begin
        ST1.Delete(0);
      end;
      ST1.SaveToFile(LngPath+'IMGPSCheck.log');
    end;
  end;
  ST1.Free;
end;
Procedure TCB_IMGPSScanX.ClearCaseIndex;
begin
@@ -7099,6 +8261,18 @@
    end;
    if FileExists(SoPath+'Context.dat') then
      ZipFileList.Add(SoPath+'Context.dat');
    AttContextList.Clear;
    if FileExists(SoPath+'ATTContext.dat') then
      AttContextList.LoadFromFile(SoPath+'ATTContext.dat');
    for n := 0 to AttContextList.Count - 1 do
    begin
      ZipFileList.Add(SoPath+AttContextList.Strings[n]);
    end;
    if FileExists(SoPath+'ATTContext.dat') then
      ZipFileList.Add(SoPath+'ATTContext.dat');
    if FileExists(SoPath+'Context_DocNo.dat') then
      ZipFileList.Add(SoPath+'Context_DocNo.dat');
    if FileExists(SoPath+'scanlist.dat') then
@@ -7246,6 +8420,35 @@
  //R_W_ScanIni('W');       //user要求改成預設後不能改
end;
procedure TCB_IMGPSScanX.ScanGrayCBClick(Sender: TObject);
begin
  if ScanGrayCB.Checked then
  begin
    ScanColor:=ifGray256;
  end
  else
  begin
    if FScanColor = 0 then
    begin
      ScanColor := ifBlackWhite;
    end;
    if FScanColor = 1 then
    begin
      //ScanColor := ifGray256 ;
      ScanColor := ifBlackWhite; //
    end;
    if FScanColor = 2 then
    begin
      ScanColor := ifTrueColor ;
    end;
  end;
end;
Function TCB_IMGPSScanX.GetFormatID(CaseID: string):String;
Var
  S : TStringlist;
@@ -7276,7 +8479,7 @@
begin
  if Mode = 'ID' then
  begin
    Result := '自行輸入';
    Result := _Msg('自行輸入');
    for i := 0 to ID_S.Count - 1 do
    begin
      if Str = ID_S.Strings[i] then
@@ -7511,15 +8714,18 @@
  ErrlistForm : TErrlistForm;
  S : TStringlist;
  UpFormID : String;
  Anchor : String;
begin
  ShowText := _Msg('處理檢核失敗中,請稍候');
  DataLoading(True,True);
LogFile1.LogToFile(logTimeString+'處理檢核失敗中開始');
  ErrlistForm := TErrlistForm.Create(Self);
  RejectCase := False;
  S := TStringlist.Create;
  try
    InitialLanguage(ErrlistForm);
    Application.ProcessMessages;
    ErrlistForm.LogFile1.LogFile:=LogFile1.LogFile;
    ErrlistForm.DeleteBt.Caption := ErrlistForm.DeleteBt.Caption+'(&D)';
    ErrlistForm.iniPath := ImageSavePath + NowCaseNo+'\upload\';
    OMRErrini2List(NowCaseno,ErrlistForm);
@@ -7527,7 +8733,7 @@
    ErrlistForm.Timer1.Enabled := true;
    if ErrlistForm.ShowModal = mrok then
    begin
      TransPath := ImageSavePath+NowCaseNo+'\';
      TransPath := ImageSavePath+NowCaseNo+'\upload\';
      if FMode = 'ISCAN' then
        TransPath :=  ImageSavePath + NowCaseNo+'\DownTemp\';
      ShowText := NowCaseNo+_Msg('資料上傳中,請稍候');
@@ -7551,7 +8757,16 @@
      end;
      CaseHelpBtn.Visible := False;
      LoadImgFile;
      Showmessage(NowCaseNo+_Msg('傳送完成'));
      if (FMode='NSCAN') or (FMode='DSCAN') then
      begin
        Showmessage(NowCaseNo+_Msg('影像上傳完成。此案已進入下一流程。'));
      end;
      if FMode='ESCAN' then
      begin
        Showmessage(NowCaseNo+_Msg('影像已補件完成。'));
      end;
      DataLoading(False,False);
    end
    Else
@@ -7633,12 +8848,15 @@
  FormName : String;
  CaseDocNoList,CaseDocNo_CopiesList,StrList : TStringlist;
  iiDocNo,iiFormID,iiDocVer : String;
  ST1:TStringList;
begin
  Result := False;
  FileList := TStringlist.Create;
  CaseDocNoList := TStringlist.Create;
  CaseDocNo_CopiesList := TStringlist.Create;
  StrList := TStringlist.Create;
  ST1:=TStringList.Create;
LogFile1.LogToFile(logTimeString+'產文件樹開始');
  try
    CaseNode.ImageIndex := 1;
    CaseNode.SelectedIndex := 1;
@@ -7657,24 +8875,55 @@
      //Showmessage(ImageSavePath+Caseno+'\'+CaseDocNoList.Strings[i]+'\Context.dat');
      if FileExists(ImageSavePath+Caseno+'\'+CaseDocNoList.Strings[i]+'\Context.dat') then
        FileList.LoadFromFile(ImageSavePath+Caseno+'\'+CaseDocNoList.Strings[i]+'\Context.dat');
      //Showmessage('aaa '+FileList.Text);
      iDocNo := DocNoDir2DocNo(CaseDocNoList.Strings[i]);
      ST1.Clear;
LogFile1.LogToFile(logTimeString+'FileList.Text='+FileList.CommaText);
      if (FWH_category='N') and (FIs_In_Wh='Y') then
      begin
        for n := 0 to FileList.Count - 1 do
        begin
          if ISExistImg(ImageSavePath+Caseno+'\'+CaseDocNoList.Strings[i]+'\'+FileList.Strings[n]) then
          begin
            ST1.Add(FileList.Strings[n]);
          end;
        end;
        for n := 0 to ST1.Count - 1 do
        begin
          if (FileList.IndexOf(ST1.Strings[n])<>-1) and (not DocNoIs_In_WH(iDocNo)) then
          begin
            FileList.Delete(FileList.IndexOf(ST1.Strings[n]));
          end;
        end;
      end
      Else
        if not DocNoAppear(iDocNo) then Continue;  //20180925 Hong覺得應該加這段
LogFile1.LogToFile(logTimeString+'WH_category='+FWH_category+',Is_In_Wh='+FIs_In_Wh+',FileList.Text='+FileList.CommaText);
      if FileList.Count=0 then Continue;
      DocNoCopies := Strtoint(CaseDocNo_CopiesList.Strings[i]);
      DocNoPage := FileList.Count;
      iDocNo := DocNoDir2DocNo(CaseDocNoList.Strings[i]);
      //Showmessage(iDocNo);
      //Showmessage(DocNo2DocName(Caseno,iDocNo));
//Showmessage(iDocNo);
//Showmessage(DocNo2DocName(Caseno,iDocNo));
//ShowMessage('FileList='+FileList.Text);
      {if (((FIs_In_Wh  = 'Y') and (not DocNoIs_In_WH(iDocNo))) or   //入庫掃描不看非入庫文件
         ((FIs_In_Wh  = 'N') and (DocNoIs_In_WH(iDocNo)))) and
         ((iDocNo <> 'Attach') and (Copy(iDocNo,1,5)<>'ZZZZZ')) then     //非入庫掃描不看入庫文件
      begin
        Continue;
      end;}
      if not DocNoAppear(iDocNo) then Continue;
      //if not DocNoAppear(iDocNo) then Continue;
      //DocNode := TreeView1.Items.AddChild(CaseNode,Format('%s{%s}-%d'+_msg('頁'),[CaseDocNoList.Strings[i],DocNo2DocName(Caseno,iDocNo),DocNoPage]));
      //DocNode := TreeView1.Items.AddChild(CaseNode,Format('%s{%s}-%d'+_msg('份'),[CaseDocNoList.Strings[i],DocNo2DocName(Caseno,iDocNo),DocNoCopies]));
      DocNode := TreeView1.Items.AddChild(CaseNode,Format('%s{%s}-%d'+_msg('份'),[DocNo2DocName(Caseno,iDocNo),CaseDocNoList.Strings[i],DocNoCopies]));
//ShowMessage('iDocNo='+iDocNo);
      DocNode := TreeView1.Items.AddChild(CaseNode,Format(_Msg('%s{%s}-%d份'),[DocNo2DocName(Caseno,iDocNo),CaseDocNoList.Strings[i],DocNoCopies]));
      if GetUseCase('F',ImageSavePath+Caseno+'\',CaseDocNoList.Strings[i]) <> '' Then
      begin
@@ -7704,7 +8953,7 @@
            FormPage := GetFormIDPage(FileList,FormID);
            FormName := FormCode2FormName(Caseno,FormID);
            //FormNode := TreeView1.Items.AddChild(DocNode,FormID+'{'+FormName+'}-'+inttostr(FormPage)+_msg('頁'));
            FormNode := TreeView1.Items.AddChild(DocNode,FormName+'{'+FormID+'}-'+inttostr(FormPage)+_msg('頁'));
            FormNode := TreeView1.Items.AddChild(DocNode,Format(_Msg('%s{%s}-%d頁'),[FormName,FormID,FormPage]));
            FormNode.ImageIndex := 4;
            FormNode.SelectedIndex := 4;
            DocNode.AlphaSort(True);
@@ -7718,7 +8967,8 @@
        FormPage := GetFormIDPage(FileList,FormID);
        FormName := FormCode2FormName(Caseno,FormID);
        //FormNode := TreeView1.Items.AddChild(DocNode,FormID+'{'+FormName+'}-'+inttostr(FormPage)+_msg('頁'));
        FormNode := TreeView1.Items.AddChild(DocNode,FormName+'{'+FormID+'}-'+inttostr(FormPage)+_msg('頁'));
        //FormNode := TreeView1.Items.AddChild(DocNode,FormName+'{'+FormID+'}-'+inttostr(FormPage)+_msg('頁'));
        FormNode := TreeView1.Items.AddChild(DocNode,Format(_Msg('%s{%s}-%d頁'),[FormName,FormID,FormPage]));
        FormNode.ImageIndex := 4;
        FormNode.SelectedIndex := 4;
        DocNode.AlphaSort(True);
@@ -7744,8 +8994,8 @@
            FormPage := GetFormIDPage(FileList,FormID);
            FormName := FormCode2FormName(Caseno,FormID);
            //FormNode := TreeView1.Items.AddChild(DocNode,FormID+'{'+FormName+'}-'+inttostr(FormPage)+_msg('頁'));
            FormNode := TreeView1.Items.AddChild(DocNode,FormName+'{'+FormID+'}-'+inttostr(FormPage)+_msg('頁'));
            //FormNode := TreeView1.Items.AddChild(DocNode,FormName+'{'+FormID+'}-'+inttostr(FormPage)+_msg('頁'));
            FormNode := TreeView1.Items.AddChild(DocNode,Format(_Msg('%s{%s}-%d頁'),[FormName,FormID,FormPage]));
            FormNode.ImageIndex := 4;
            FormNode.SelectedIndex := 4;
            DocNode.AlphaSort(True);
@@ -7767,6 +9017,7 @@
    if DirectoryExists(ImageSavePath+Caseno+'\'+AttName) then
    begin
      FileList.Clear;
      if FileExists(ImageSavePath+Caseno+'\'+AttName+'\Context.dat') then
        FileList.LoadFromFile(ImageSavePath+Caseno+'\'+AttName+'\Context.dat')
@@ -7778,7 +9029,7 @@
      DocNoPage := FileList.Count;
      iDocNo := DocNoDir2DocNo(AttName);
      //DocNode := TreeView1.Items.AddChild(CaseNode,Format('%s{%s}-%d'+_msg('份'),[AttName,DocNo2DocName(Caseno,iDocNo),1]));
      DocNode := TreeView1.Items.AddChild(CaseNode,Format('%s{%s}-%d'+_msg('份'),[DocNo2DocName(Caseno,iDocNo),AttName,1]));
      DocNode := TreeView1.Items.AddChild(CaseNode,Format(_Msg('%s{%s}-%d份'),[DocNo2DocName(Caseno,iDocNo),AttName,1]));
      DocNode.ImageIndex := 2;
      DocNode.SelectedIndex := 2;
      for n := 0 to FileList.Count - 1 do
@@ -7789,18 +9040,58 @@
          FormPage := GetFormIDPage(FileList,FormID);
          FormName := FormCode2FormName(Caseno,FormID);
          //FormNode := TreeView1.Items.AddChild(DocNode,FormID+'{'+FormName+'}-'+inttostr(FormPage)+_msg('頁'));
          FormNode := TreeView1.Items.AddChild(DocNode,FormName+'{'+FormID+'}-'+inttostr(FormPage)+_msg('頁'));
          //FormNode := TreeView1.Items.AddChild(DocNode,FormName+'{'+FormID+'}-'+inttostr(FormPage)+_msg('頁'));
          FormNode := TreeView1.Items.AddChild(DocNode,Format(_Msg('%s{%s}-%d頁'),[FormName,FormID,FormPage]));
          FormNode.ImageIndex := 4;
          FormNode.SelectedIndex := 4;
        end;
      end;
    end;
    if FModeName='件' then  //20170904 先裝死  因為異動 同時存在兩種附件太難寫
    begin
      if DirectoryExists(ImageSavePath+Caseno+'\Attach') then
      begin
        FileList.Clear;
        if FileExists(ImageSavePath+Caseno+'\Attach'+'\Context.dat') then
          FileList.LoadFromFile(ImageSavePath+Caseno+'\Attach'+'\Context.dat')
        Else
        begin
          Rmdir(ImageSavePath+Caseno+'\Attach');
          Exit;
        end;
        DocNoPage := FileList.Count;
        iDocNo := DocNoDir2DocNo(AttName);
        //DocNode := TreeView1.Items.AddChild(CaseNode,Format('%s{%s}-%d'+_msg('份'),[AttName,DocNo2DocName(Caseno,iDocNo),1]));
        //DocNode := TreeView1.Items.AddChild(CaseNode,Format('%s{%s}-%d'+_msg('份'),[DocNo2DocName(Caseno,iDocNo),'Attach',1]));
        DocNode := TreeView1.Items.AddChild(CaseNode,Format(_Msg('%s{%s}-%d份'),[DocNo2DocName(Caseno,iDocNo),'Attach',1]));
        DocNode.ImageIndex := 2;
        DocNode.SelectedIndex := 2;
        for n := 0 to FileList.Count - 1 do
        begin
          FormID := FileName2FormCode(FileList.Strings[n]);
          if not CheckFormIDExists(DocNode,FormID) then
          begin
            FormPage := GetFormIDPage(FileList,FormID);
            FormName := FormCode2FormName(Caseno,FormID);
            //FormNode := TreeView1.Items.AddChild(DocNode,FormID+'{'+FormName+'}-'+inttostr(FormPage)+_msg('頁'));
            //FormNode := TreeView1.Items.AddChild(DocNode,FormName+'{'+FormID+'}-'+inttostr(FormPage)+_msg('頁'));
            FormNode := TreeView1.Items.AddChild(DocNode,Format(_Msg('%s{%s}-%d頁'),[FormName,FormID,FormPage]));
            FormNode.ImageIndex := 4;
            FormNode.SelectedIndex := 4;
          end;
        end;
      end;
    end;
LogFile1.LogToFile(logTimeString+'產文件樹結束');
  Finally
  FileList.Free;
  CaseDocNoList.Free;
  CaseDocNo_CopiesList.Free;
  StrList.Free;
  ST1.Free;
  end;
end;
@@ -7858,6 +9149,7 @@
  if FScanColor = 1 then
  begin
    ScanColor := ifGray256 ;
    ScanGrayCB.Checked:=True;
  end;
  if FScanColor = 2 then
@@ -7876,7 +9168,7 @@
    PrtDialog : TPrintDialog;
    S : String;
begin
  ShowText := '列印中,請稍候';
  ShowText := _Msg('列印中,請稍候');
  DataLoading(True,True);
  Case2upload(NowCaseNo);   //產生原影像結構
@@ -7912,9 +9204,9 @@
        if PrintForm.CheckListBox1.Checked[i] then
        begin
          if S = '' then
            S := S+FileList.Strings[i]
            S := S+PrintForm.CheckListBox1.Items[i]
          Else
            S := S+#13+FileList.Strings[i];
            S := S+#13+PrintForm.CheckListBox1.Items[i];
        end;
      end;
      if S = '' then
@@ -7960,6 +9252,7 @@
  OldCaseInfoForm.IN_WH_DocNoList := TStringlist.Create;
  OldCaseInfoForm.OldCopiesList := TStringlist.Create;
  try
    InitialLanguage(OldCaseInfoForm); //載入多國語言
    OldCaseInfoForm.Notebook1.ActivePage := 'CaseInfo';
    OldCaseInfoForm.ImageSavePath := ImageSavePath;
    OldCaseInfoForm.CaseID := NowCaseNo;
@@ -7986,7 +9279,7 @@
      Year := Caseinfolist.Strings[1];
      BS_No := Caseinfolist.Strings[2];
      IS_Old := Caseinfolist.Strings[3];
      With OldCaseInfoForm.ListView1.Items.Add do
      With OldCaseInfoForm.OldCaseLV.Items.Add do
      begin
        Caption := CaseID;
        SubItems.Add(Year);
@@ -8070,7 +9363,8 @@
      iDocNoList.SaveToFile(NewPath+'CaseDocNo.dat');
      iDocNo_CopiesList.SaveToFile(NewPath+'CaseDocNo_Copies.dat');
      DrawDocItem2(MyTreeNode1,NowCaseNo);
      MyTreeNode1.Text := Format('%s-%d'+_Msg('頁'),[NowCaseno,GetCasePage(ImageSavePath,NowCaseNo)]);
      //MyTreeNode1.Text := Format('%s-%d'+_Msg('頁'),[NowCaseno,GetCasePage(ImageSavePath,NowCaseNo)]);
      MyTreeNode1.Text := Format(_Msg('%s-%d頁'),[NowCaseno,GetCasePage(ImageSavePath,NowCaseNo)]);
      NewTreeNodeRefresh;
      ClearErrini(NowCaseno,MyTreeNode1);  //清掉檢核記錄
    end;
@@ -8100,17 +9394,38 @@
  ST1.LoadFromFile(path+'FormCode_Name.dat');
  for I := 0 to ST1.Count - 1 do
  begin
    if (Pos('_',St1.Strings[i])<>1) and (Pos('_',St1.Strings[i])<>-11) then
    if (Pos('_',St1.Strings[i])<>1) and (Pos('_',St1.Strings[i])<>-1) then
    begin
      str1:=Copy(ST1.Strings[i],1,Pos('_',St1.Strings[i])-1);
      if LastInitFormidList.IndexOf(str1) = -1 then
      begin
        LastInitFormidList.Add(str1);
      end;
      LastInitFormidList.Add(str1);
    end;
  end;
  ST1.Free;
end;
function TCB_IMGPSScanX.LoadFileGetMD5(const filename: string): string;
var
  Stream: TFileStream;
  //Buffer: array[0..1023] of AnsiChar;
  Buffer: array[0..1023] of AnsiChar;
  TempStr: string;
  i: Integer;
  idmd5:TIdHashMessageDigest5;  //import IdHashMessageDigest, idHash
begin
  idmd5 := TIdHashMessageDigest5.Create;
  try
    Stream := TFileStream.Create(filename, fmOpenRead);
    Stream.Read(Buffer[0], SizeOf(Buffer));
    result := idmd5.HashStreamAsHex(Stream) ;
  finally
    idmd5.Free;
    Stream.Free;
  end;
end;
procedure TCB_IMGPSScanX.LoadImgFile;  //載入新件及替換件
@@ -8124,6 +9439,9 @@
begin
  ClearView(1);
  PageLV.Clear;
  AttListBox.Items.Clear;
  AddAttFileLB.Enabled := False;
  DelAttFileLB.Enabled := False;
  DisplayPath := '';
  ClearCaseIndex;
  CaseHelpBtn.Visible := False;
@@ -8157,6 +9475,7 @@
    end;
    CasePage := GetCasePage(ImageSavePath,CaseList.Strings[i]);
//ShowMessage('CasePage='+IntToStr(CasePage));
    MytreeNode1 := TreeView1.Items.AddChild(NewTreeNode,Format(_Msg('%s-%d頁'),[CaseList.Strings[i],CasePage]));
    MytreeNode1.ImageIndex := 1;
    MytreeNode1.SelectedIndex := 1;
@@ -8305,6 +9624,32 @@
  end;
end;
procedure TCB_IMGPSScanX.LoadAttFile(CaseID:String); //載入附加檔案
var
  AttContextList : TStringlist;
  i : Integer;
begin
  AttListBox.Clear;
  AttContextList := TStringlist.Create;
  try
    if FileExists(ImageSavePath+CaseID+'\AttContext.dat') then
    begin
      AttContextList.LoadFromFile(ImageSavePath+CaseID+'\AttContext.dat');
    end;
    for i := 0 to AttContextList.Count - 1 do
    begin
      AttListBox.Items.Add(UTF8Decode(HTTPDEcode(AttContextList.Strings[i])));
    end;
  finally
  AttContextList.Free;
  end;
end;
function TCB_IMGPSScanX.logTimeString: String;
begin
Result:=FormatDateTime('yyyymmdd hh:mm:ss',now) +'  caseNo='+NowCaseno+'  ';
end;
Function TCB_IMGPSScanX.FindDivFormCode(FormCode:String):Boolean; //找有沒有分案的條碼
var
  i : Integer;
@@ -8426,9 +9771,9 @@
  if FileExists(LngPath+'MPSLIC_SCAN.lic') then
    DeleteFile(LngPath+'MPSLIC_SCAN.lic');
  if LegalDate = '' then
    StatusBar1.Panels[4].Text := '註冊號:'+MacID+' 剩餘註冊數:'+inttostr(Totalcount-Nowcount);
    StatusBar1.Panels[4].Text := Format(_Msg('註冊號:%s 剩餘註冊數:%s'),[MacID,inttostr(Totalcount-Nowcount)]);
  if LegalDate <> '' then
    StatusBar1.Panels[4].Text := '*註冊號:'+MacID+'('+inttostr(Lic_Idx)+')'+' 剩餘註冊數:'+inttostr(Totalcount-Nowcount);
    StatusBar1.Panels[4].Text := '*'+Format(_Msg('註冊號:%s 剩餘註冊數:%s'),[MacID+'('+inttostr(Lic_Idx)+')',inttostr(Totalcount-Nowcount)]);
end;
procedure TCB_IMGPSScanX.SmoothCBClick(Sender: TObject);
@@ -8440,7 +9785,7 @@
  end;
end;
Function TCB_IMGPSScanX.Case2Mask(SoPath,DePath:String):Boolean;//產生遮罩影像
Function TCB_IMGPSScanX.Case2Mask(SoPath,DePath:String):Boolean;//產生遮罩影像  20170639 發現沒用到
var
  XT : TXMLTool;
  i : Integer;
@@ -8472,9 +9817,9 @@
      Anchor := FormID2Anchor(FormID);
      //ParserPoint(CropMpsV.FindPoint(Anchor));
      FindPoint(ImageScrollBox1.Graphic,UpLPoint,UpRPoint,DownLPoint,Anchor);
      if FileExists(CheckXmlPath+FormID+'.xml') then  //沒有Xml就不用遮罩
      if FileExists(CheckXmlPath+FWork_no+'\'+FormID+'.xml') then  //沒有Xml就不用遮罩
      begin
        XT.LoadFromFile(CheckXmlPath+FormID+'.xml');
        XT.LoadFromFile(CheckXmlPath+FWork_no+'\'+FormID+'.xml');
        if XT.SubNodes['/form/settype10/'].First then
        Repeat
          ColEName := XT.SubNodes['/form/settype10/'].NodeName;
@@ -8522,6 +9867,8 @@
    end;
  end;
//ShowMessage('FormIDCount='+IntToStr(FormIDCount)+#10#13+'MpsBarcodeinf.count='+IntToStr(MpsBarcodeinf.count));
  if FormIDCount = 2 then
  begin
    Result := True;
@@ -8547,6 +9894,12 @@
    DocNo := 'ZZZZZ'+Add_Zoo(Ct,3);
    if FIs_In_Wh <> 'Y' then //不是入庫文件
      DocNo := 'YYYYY'+Add_Zoo(Ct,3);
    if (FMode='ESCAN') and (FWH_category='N')  then //20170914 補件下改成非入庫的自定文件
    begin
      DocNo := 'YYYYY'+Add_Zoo(Ct,3);
    end;
    FormID := DocNo+'010101A';
    ini.WriteInteger('CustomCount','Count',Ct);
    ini.WriteString(DocNo,'FormID',FormID);
@@ -8662,6 +10015,41 @@
  end;
end;
procedure TCB_IMGPSScanX.DelAttFileLBClick(Sender: TObject);
var
  AttFile : String;
  SelectCount : Integer;
  i : Integer;
begin
  SelectCount := 0;
  for i := 0 to AttListBox.Items.Count - 1 do
  begin
    if AttListBox.Selected[i] then
      inc(SelectCount);
  end;
  if SelectCount = 0 then
  begin
    Showmessage(_Msg('請選擇要刪除的電子檔'));
    Exit;
  end;
  if SelectCount > 0 then
  begin
    if Messagedlg(Format(_Msg('是否刪除這%d筆??'),[SelectCount]),MtConfirmation,[mbyes,mbcancel],0) = mrcancel then Exit;
    for i := 0 to AttListBox.Items.Count - 1 do
    begin
      if AttListBox.Selected[i] then
      begin
        AttFile :=  HTTPEncode(UTF8Encode(AttListBox.Items.Strings[i]));
        DeleteFile(ImageSavePath+NowCaseNo+'\'+AttFile);
        SetAttContextList('D',-1,NowCaseno,AttFile);
      end;
    end;
  end;
  LoadAttFile(NowCaseNo);
  Showmessage(_msg('刪除完成'));
end;
Procedure TCB_IMGPSScanX.DeleteCustomDocDir(Path,DocNo:String); //刪除自定文件DocNo
var
  ini : Tinifile;
@@ -8708,7 +10096,7 @@
          Printer object. Otherwise, if UsePrintJob is True, the Title
          property of the TDibGraphicPrinter object is used to specify the
          job name. }
        Printer.Title := '影像列印';
        Printer.Title := _Msg('影像列印');
      end;
      IF (Page mod 2) = 1 Then
@@ -8733,7 +10121,7 @@
  procedure PrintWithAutoPrintJob;
  begin
      GraphicPrinter.UsePrintJob := True;
      GraphicPrinter.Title       := '影像列印';
      GraphicPrinter.Title       := _Msg('影像列印');
      GraphicPrinter.Print(ImageScrollBox1.Graphic);
  end;
@@ -8741,6 +10129,7 @@
  S := TStringlist.Create;
  GraphicPrinter := TDibGraphicPrinter.Create;
  PrtDialog := TPrintDialog.Create(self);
  //PrtDialog.Copies:=99;
  try
    IF PrtDialog.Execute Then
    begin
@@ -8786,6 +10175,48 @@
  FileList.Free;
  end;
end;
Function TCB_IMGPSScanX.FindLastestDocDirForPage(CaseID,DocNo,formid:String):String; //找出最新的DocDir  20180207  排除隱藏的資料夾
var
  i,j:integer;
  DocNoList,FileList : TStringlist;
  Imglist: TStringlist;
  DirIsHide:Boolean;
begin
  Result := '';
  DocNoList := TStringlist.Create;
  FileList := TStringlist.Create;
  imglist := TStringlist.Create;
  try
  if FileExists(ImageSavePath+CaseID+'\CaseDocNo.dat') then
    DocNoList.LoadFromFile(ImageSavePath+CaseID+'\CaseDocNo.dat');
  for i := DocNoList.Count-1 downto 0 do
  begin
    if Copy(DocNoList.Strings[i],1,length(DocNo)) = DocNo then
    begin
//ShowMessage(ImageSavePath+CaseID+'\'+DocNoList.Strings[i]);
      if not DocNoIsExistImg(ImageSavePath+CaseID+'\'+DocNoList.Strings[i]+'\') then
      begin
//ShowMessage('DDDDD');
        Result := '';
        Break;
      end
      else
      begin
        Result := DocNoList.Strings[i];
        Break;
      end;
    end;
  end;
  finally
    DocNoList.Free;
    FileList.Free;
    imglist.Free;
  end;
end;
Procedure TCB_IMGPSScanX.Create_Cust_DocDir(CaseID:String); //產生外面傳入的文件代號及自定文件
var
@@ -9334,19 +10765,19 @@
        //Showmessage(FUrl+'service/slic/SLIC02/useOther?'+senddata);
        if not upFile(HTTPSClient,FUrl,'service/imgpsc/IMGPSC02/useOther',SendData,'file',OldCasePath+'UseCase.ini',FReWrite,Memo1,False) then
        begin
          Showmessage(Format(_Msg('傳送舊件編號(%s)檔案時,網路發生錯誤!!'+_Msg('錯誤代碼:')),[OldCaseID])+Inttostr(HttpError.HttpErrorCode)+' '+HttpError.HttpReason);
          Showmessage(Format(_Msg('傳送舊件編號(%s)檔案時,網路發生錯誤!!'),[OldCaseID])+_Msg('錯誤代碼:')+Inttostr(HttpError.HttpErrorCode)+' '+HttpError.HttpReason);
          Result := False;
          Exit;
        end;
        if memo1.Lines.Strings[0] = '1' then
        begin
          Showmessage(Format(_Msg('傳送舊件編號(%s)檔案時,網路發生錯誤!!')+_Msg('錯誤原因:'),[OldCaseID])+memo1.Lines.Strings[1]);
          Showmessage(Format(_Msg('傳送舊件編號(%s)檔案時,網路發生錯誤!!'),[OldCaseID])+_Msg('錯誤原因:')+memo1.Lines.Strings[1]);
          Result := False;
          Exit;
        end
        Else if Pos('<script type="text/javascript" src="scripts/CW00/login.js"></script>',Memo1.Lines.Text) > 0 then
        begin
          Showmessage(Format(_Msg('傳送舊件編號(%s)檔案時,網路發生錯誤!!')+_Msg('錯誤原因:')+_Msg('閒置過久或被登出,請重新登入'),[OldCaseID]));
          Showmessage(Format(_Msg('傳送舊件編號(%s)檔案時,網路發生錯誤!!'),[OldCaseID])+_Msg('錯誤原因:')+_Msg('閒置過久或被登出,請重新登入'));
          Result := False;
          Exit;
        end;
@@ -9396,15 +10827,37 @@
     ((FIs_In_Wh  = 'N') and (DocNoIs_In_WH(iDocNo)))) and      //非入庫掃描不看入庫文件
     ((iDocNo <> 'Attach') and (iDocNo <> 'S_Attach') and (Copy(iDocNo,1,5)<>'ZZZZZ')) then
       Result := False;
  if (FIs_In_Wh='Y') and (FWH_category='Y') then //20170816 新加
  begin
    if (((FIs_In_Wh  = 'Y') and (not DocNoIs_In_WH(iDocNo))) or   //入庫掃描不看非入庫文件
     ((FIs_In_Wh  = 'N') and (DocNoIs_In_WH(iDocNo)))) and      //非入庫掃描不看入庫文件
     ((iDocNo <> 'Attach') and (iDocNo <> 'S_Attach') and (Copy(iDocNo,1,5)<>'ZZZZZ')) then
       Result := False;
  end;
  if (FIs_In_Wh='Y') and (FWH_category='N') then //20170816 新加
  begin
    Result:=True;
  end;
end;
Function TCB_IMGPSScanX.DocNoAppear(DocNo:String):Boolean;   //DocNo是否可出現
begin
  Result := True;
  if (((FIs_In_Wh  = 'Y') and (not DocNoIs_In_WH(DocNo)) or (DocNo ='S_Attach')) or   //入庫掃描不看非入庫文件
  {if (((FIs_In_Wh  = 'Y') and (not DocNoIs_In_WH(DocNo)) or (DocNo ='S_Attach')) or   //入庫掃描不看非入庫文件
     ((FIs_In_Wh  = 'N') and (DocNoIs_In_WH(DocNo)) or (DocNo ='Attach') )) {and      //非入庫掃描不看入庫文件
     (Copy(DocNo,1,5)<>'ZZZZZ')} {then
       {Result := False;}
  //20181031 應該要換成下面的判斷比較對,FIs_In_Wh傳空的話才會出全部
  if (((FIs_In_Wh  = 'Y') and ((not DocNoIs_In_WH(DocNo)) or (DocNo ='S_Attach'))) or   //入庫掃描不看非入庫文件
     ((FIs_In_Wh  = 'N') and ((DocNoIs_In_WH(DocNo)) or (DocNo ='Attach') ))) {and      //非入庫掃描不看入庫文件
     (Copy(DocNo,1,5)<>'ZZZZZ')} then
       Result := False;
end;
Function TCB_IMGPSScanX.GetDocNoCount(CaseID,DocNo:String):Integer; //取DocNo數量
@@ -9610,6 +11063,34 @@
  end;
end;
Function TCB_IMGPSScanX.ISDivPageFormID(FormID:String):Boolean;
var
  i : Integer;
begin
  Result := False;
  for i := 0 to DivPageFormIDList.Count - 1 do
  begin
    if FormID = DivPageFormIDList.Strings[i] then
    begin
      Result := True;
      Break;
    end;
  end;
end;
function TCB_IMGPSScanX.ISExistImg(const filename: string): boolean;
begin
  if ExistImgList.IndexOf(LoadFileGetMD5(filename))<>-1 then
  begin
    Result:=True;
  end
  else
  begin
    Result:=False;
  end;
end;
Function TCB_IMGPSScanX.CaseDelete_Enable(CaseID:String):Boolean;  //案件可否被刪除
var
  i : Integer;
@@ -9792,16 +11273,18 @@
var
  i,n:Integer;
  OldPath,NewPath,DocDir : String;
  OldFile,NewFile : String;
  OldFile,NewFile,AttFile : String;
  DocNoList,FileList:TStringlist;
  iFileList,iFile_DocNoList :TStringlist;
  iDocDirList : TStringlist;
  iAttFileList : TStringlist;
begin
  DocNoList := TStringlist.Create;
  FileList := TStringlist.Create;
  iFileList := TStringlist.Create;
  iFile_DocNoList := TStringlist.Create;
  iDocDirList := TStringlist.Create;
  iAttFileList := TStringlist.Create;
  try
    OldPath := ImageSavePath+CaseID+'\';
    NewPath := ImageSavePath+CaseID+'\Upload\';
@@ -9886,6 +11369,18 @@
        end;
      end;
    end;
    OldPath := ImageSavePath+CaseID+'\';
    if FileExists(OldPath+'AttContext.dat') then
    begin
      iAttFileList.LoadFromFile(OldPath+'AttContext.dat');
      for n := 0 to iAttFileList.Count - 1 do
      begin
        AttFile := iAttFileList.Strings[n];
        CopyFile(PWideChar(OldPath+AttFile),PWideChar(NewPath+AttFile),False);
      end;
      iAttFileList.SaveToFile(NewPath+'AttContext.dat');
    end;
    iFileList.SaveToFile(NewPath+'Context.dat');
    iFile_DocNoList.SaveToFile(NewPath+'Context_DocNo.dat');
@@ -9893,6 +11388,7 @@
  finally
  iFileList.Free;
  iAttFileList.Free;
  iFile_DocNoList.Free;
  DocNoList.Free;
  FileList.Free;
@@ -9903,9 +11399,10 @@
var
  i,n : Integer;
  DocDir:String;
  OldFile,NewFile:String;
  OldFile,NewFile,AttFile:String;
  DocNoList,FileList : TStringlist;
  iFileList,iFile_DocDirList :TStringlist;
  iAttFileList :TStringlist;
  AA,AA2,AA3,AA4:Boolean;
begin
@@ -9930,6 +11427,7 @@
  FileList := TStringlist.Create;
  iFileList := TStringlist.Create;
  iFile_DocDirList := TStringlist.Create;
  iAttFileList := TStringlist.Create;
  try
    //if Not FileExists(SoDir+'Context.dat') then  Exit;
    //iFileList.LoadFromFile(SoDir+'Context.dat');
@@ -10043,6 +11541,23 @@
        CaseDocNo_CopiesList.SaveToFile(DeDir+'CaseDocNo_Copies.dat');
      end;
    end;}
    if FileExists(SoDir+'AttContext.dat') then
    begin
      iAttFileList.LoadFromFile(SoDir+'AttContext.dat');
      for i := 0 to iAttFileList.Count - 1 do
      begin
        AttFile := iAttFileList.Strings[i];
        CopyFile(PWideChar(SoDir+AttFile),PWideChar(DeDir+AttFile),False);
      end;
      iAttFileList.SaveToFile(DeDir+'AttContext.dat');
    end;
    if FMode='ESCAN' then
    begin
      InitExistImgList(DeDir);
    end;
  finally
  iFileList.Free;
@@ -10250,6 +11765,7 @@
  begin
    If FindSQLData(Doc_Inf_List,'DOC_U_DESC','DOC_NO',DocNo,0,FindResult) Then
    begin
//ShowMessage(FindResult.Text);
      Result := GetFindResult('DOC_U_DESC');
    end;
  end;
@@ -10427,6 +11943,17 @@
    S.LoadFromFile(ImageSavePath + CaseID+'\upload\Context.dat');
    for i := 0 to S.Count - 1 do
    begin
LogFile1.LogToFile(logTimeString+S.Strings[i]+' ISExistImg='+BoolToStr(ISExistImg(ImageSavePath+CaseID+'\upload\'+S.Strings[i]),true));
LogFile1.LogToFile(logTimeString+S.Strings[i]+' reSizeExistImgList='+BoolToStr(reSizeExistImgList.IndexOf(LoadFileGetMD5(ImageSavePath+CaseID+'\upload\'+S.Strings[i]))<>-1,true));
      if FWH_category='N' then
      begin
        if (ISExistImg(ImageSavePath+CaseID+'\upload\'+S.Strings[i]))
        or  (reSizeExistImgList.IndexOf(LoadFileGetMD5(ImageSavePath+CaseID+'\upload\'+S.Strings[i]))<>-1)  then
        begin
          Continue;
        end;
      end;
      LForm := FileName2FormCode(S.Strings[i]);
      AddOk := True;
      for n := 0 to OMRFileList.Count - 1 do
@@ -10477,6 +12004,8 @@
  OMROkCount : Integer;
  //Casecheck : Boolean;  //是否要做檢核
  //AllCheck : Boolean;  //是否要做完整檢核
  ISB8W,ISB8H:integer;
begin
  ///OMRErrInfo  1: 必要文件  2:相依文件 3:互斥文件  4:必填 5:欄位有值附文件  6:欄位有值不附文件
  ///            7: 欄位有值相關欄位也要有值  8:欄位有值要寫備註 9:停用日期 10:最大頁數
@@ -10505,25 +12034,29 @@
        end;
//ShowMessage('MainFormID='+MainFormID);
LogFile1.LogToFile(logTimeString+' '+FModeName+' '+CaseID+' '+'MainFormID='+MainFormID);
        if MainFormID = ''then
        begin
          //20131203 yuu說不檢查這個,先拿掉   20170315 楷琳說未歸類要擋
          if FCheck_main_form='Y' then
          //20131203 yuu說不檢查這個,先拿掉   20170315 楷琳說未歸類要擋  20170726 因此有檢查必要FormID  所以 可以拿掉
          {if FCheck_main_form='Y' then
          begin
            if (FMode <> 'SSCAN') then  //簽署章件會換主FormID,先跳過
            if (FMode <> 'SSCAN') AND (FMode<>'ESCAN') then  //簽署章件會換主FormID,先跳過 20170629 ESCAN 也不檢查
            begin
              ErrStr:=_Msg('找不到分案文件');   //找不到主文件
              OMRErr2ini(CaseID,ErrStr,'','','','','','',False,False,True);
              CaseOk := false;
//ShowMessage('AAAAA');
            end;
          end;
          }
        end
        Else
        begin
          //////主要非主要文件//////
          DistinctDocinCase(ImageSavePath+CaseID+'\upload\');
//ShowMessage(DocNo_VerinCase.Text);
//DocNo_VerinCase.Add('31A00101_1706A');
LogFile1.LogToFile(logTimeString+' '+CaseID+' '+'DocNo_VerinCase.Text='+DocNo_VerinCase.Text);
          if ModeNeedCheck(OMRErrInfo[1].Mode,FMode) then //是否要檢核
          begin
            for i := 0 to DocNo_VerinCase.Count - 1 do
@@ -10534,6 +12067,8 @@
              MainVersion :=Copy(DocNo_VerinCase.Strings[i],v+1,v1-v); //FormCode2Version(MainFormID);
              MainFormPage := GetDataDocNoPage(MainDocNo,MainVersion); //資料庫記錄主文件頁數
              CaseFormPage := CheckCaseDocNoPage(CaseID,MainDocNo,MainVersion,MainFormPage); //案件主文件的頁數
LogFile1.LogToFile(logTimeString+CaseID+',MainDocNo='+MainDocNo+',MainVersion='+MainVersion+',MainFormPage='+IntToStr(MainFormPage)+',CaseFormPage='+IntToStr(CaseFormPage));
              //CheckFirstDocNoPage
              IF (MainFormPage > 0) and (MainFormPage <> CaseFormPage) then
              begin
                ErrStr:=MainDocNo+Format(OMRErrInfo[1].Info,[Inttostr(MainFormPage),Inttostr(CaseFormPage)]); //主要文件需有XX頁僅附XX頁
@@ -10544,7 +12079,7 @@
            end;
          end;
          //////主要非主要文件/////
          //showmessage(MainFormID);
//showmessage(MainFormID);
          MainDocNo := FormCode2DocNo(MainFormID);
          MainVersion := FormCode2Version(MainFormID);
          if FindSQLData(DM_FORM_INF_List,'DEPE_FORM_ID,MUTEX_FORM_ID','MAIN_FORM_ID,DOC_VERSION',MainDocNo+','+MainVersion,0,FindResult) then
@@ -10566,6 +12101,13 @@
            begin
              if not Case_DocNoExists(CaseID,List.Strings[i]) then  //沒附相依文件
              begin
                if FWH_category='N' then
                begin
                  if ISExistImg(ImageSavePath+CaseID+'\upload\'+List.Strings[i]) then
                  begin
                    Continue;
                  end;
                end;
                ErrStr:=Format(OMRErrInfo[2].Info,[DocNo2DocName(CaseID,List.Strings[i])]);   //沒附相依文件
                OMRErr2ini(CaseID,ErrStr,'','','','','','',False,OMRErrInfo[2].Ignore,OMRErrInfo[2].Display);
                if OMRErrInfo[2].Display then
@@ -10583,6 +12125,13 @@
            begin
              if Case_DocNoExists(CaseID,List.Strings[i]) then  //附了互斥文件
              begin
                if FWH_category='N' then
                begin
                  if ISExistImg(ImageSavePath+CaseID+'\upload\'+List.Strings[i]) then
                  begin
                    Continue;
                  end;
                end;
                ErrStr:=Format(OMRErrInfo[3].Info,[DocNo2DocName(CaseID,List.Strings[i])]);   //有附互斥文件
                OMRErr2ini(CaseID,ErrStr,'','','','','','',False,OMRErrInfo[3].Ignore,OMRErrInfo[3].Display);
                if OMRErrInfo[3].Display then
@@ -10591,7 +12140,7 @@
            end;
          end;
          //////互斥文件/////
        end;
        end; //MainFormID結束
      //end;
      List.LoadFromFile(ImageSavePath + CaseID+'\upload\Context.dat');
      for i := 0 to List.Count - 1 do
@@ -10631,12 +12180,24 @@
    end;
    //if AllCheck then
    //begin
      //////最大頁數/////
      //////最大頁數///
LogFile1.LogToFile(logTimeString+'最大頁數A段 '+CaseID+' '+'OMRFileList.Text='+OMRFileList.Text);
      DistinctFormCode(CaseID);
      if ModeNeedCheck(OMRErrInfo[10].Mode,FMode) then //是否要檢核
      begin
//ShowMessage('AAA'+OMRFileList.Text);
LogFile1.LogToFile(logTimeString+'最大頁數B段 '+CaseID+' '+'OMRFileList.Text='+OMRFileList.Text);
        For i := 0 to OMRFileList.Count - 1 do
        begin
          if FModeName=_Msg('異動件') then Continue;
          if FWH_category='N' then
          begin
            if ISExistImg(ImageSavePath+CaseID+'\upload\'+OMRFileList.Strings[i]) then
            begin
              Continue;
            end;
          end;
          FormCode := FileName2FormCode(OMRFileList.Strings[i]);
          FormDataPages := GetDataFormCodePages(FormCode);
@@ -10659,22 +12220,30 @@
      DistinctFormCode(CaseID);
      ValueXT := TXmltool.Create;
      Try
//ShowMessage('必填'+OMRFileList.Text);
LogFile1.LogToFile(logTimeString+'必填 '+CaseID+' '+'OMRFileList.Text='+OMRFileList.Text);
        For i := 0 to OMRFileList.Count - 1 do
        begin
//ShowMessage('OMRFileList.Strings['+IntToStr(i)+']'+OMRFileList.Strings[i]);
          if CheckRequiredColumnValues(FWork_NO,CaseID) then Continue;
          OMRFile := OMRFileList.Strings[i];
          OMRFormCode := FileName2FormCode(OMRFileList.Strings[i]);
          OMRFormName := FormCode2FormName(CaseID,OMRFormCode);
          Anchor := FormID2Anchor(OMRFormCode);
          ///依十字定位點縮放////
          ImageReSize(CaseID,OMRFile);
          ////依十字定位點縮放////
          if not FileExists(CheckXmlPath+OMRFormCode+'.xml') then  //沒有Xml就不用檢核
          ImageReSize_FormID(CaseID,OMRFile);
          ////依十字定位點縮放///
//Display1.Lines.Add('OMRFile='+OMRFile+',OMRFormCode='+OMRFormCode+',OMRFormName='+OMRFormName);
LogFile1.LogToFile(logTimeString+'OMRFile='+OMRFile+',OMRFormCode='+OMRFormCode+',OMRFormName='+OMRFormName);
//ShowMessage('KKKKK');
          if not FileExists(CheckXmlPath+FWork_no+'\'+OMRFormCode+'.xml') then  //沒有Xml就不用檢核
            Continue;
          XT := TXmltool.Create(CheckXmlPath+OMRFormCode+'.xml');
//ShowMessage('11638 OMRFileList.Strings['+IntToStr(i)+']'+OMRFileList.Strings[i]);
          XT := TXmltool.Create(CheckXmlPath+FWork_no+'\'+OMRFormCode+'.xml');
          RelaXT := TXmltool.Create;
//ShowMessage('ModeNeedCheck='+BoolToStr(ModeNeedCheck(OMRErrInfo[4].Mode,FMode),true));
          try
            //*******必填********
            if ModeNeedCheck(OMRErrInfo[4].Mode,FMode) then //是否要檢核
@@ -10699,6 +12268,9 @@
                      SiteRec := SiteRec+'@'+Site;
                    //有填就ok
                    //Showmessage(ColCName +','+ inttostr(OMRMpsV1.GetSiteOMR(ImageSavePath+CaseID+'\upload\'+OMRFile,Site))+','+inttostr(Pixel + SafePixel));
//SafePixel:=90000;
Display1.Lines.Add(ColEName+' '+ColCName+'   圖像實際點數='+IntToStr(GetSiteOMR(ImageSavePath+CaseID+'\upload\'+OMRFile,Site,Bt))+' 設定點數='+IntToStr( (Pixel + SafePixel)));
//FindPoint(ISB_BW.Graphic,UpLPoint,UpRPoint,DownLPoint,ANCHOR);
                    if GetSiteOMR(ImageSavePath+CaseID+'\upload\'+OMRFile,Site,Bt) > (Pixel + SafePixel)  then
                    begin
                      //Showmessage('oh');
@@ -10721,7 +12293,7 @@
              Until not XT.SubNodes['/form/settype1/'].Next ;
            end;
            //*******必填********
//ShowMessage('11692 OMRFileList.Strings['+IntToStr(i)+']'+OMRFileList.Strings[i]);
            //if AllCheck then
            //begin
            //*******有值相關文件的欄位也要有值*******
@@ -10740,6 +12312,7 @@
                else
                  SiteRec := SiteRec+'@'+Site;
                Pixel := XT.Node['/form/settype3/'+ColEName+'/'].Attributes['pixel'];
Display1.Lines.Add(ColEName+' '+ColCName+'   圖像實際點數='+IntToStr(GetSiteOMR(ImageSavePath+CaseID+'\upload\'+OMRFile,Site,Bt))+' 設定點數='+IntToStr( (Pixel + SafePixel)));
                if GetSiteOMR(ImageSavePath+CaseID+'\upload\'+OMRFile,Site,Bt) > (Pixel + SafePixel) then
                begin
                  ////有填寫////
@@ -10757,7 +12330,18 @@
                      RelaFile := FormCode2FileName(RelaFormCode,ContextList);
                      RelaFormName := FormCode2FormName(CaseID,RelaFormCode);
                      Anchor1 := FormID2Anchor(RelaFormCode);
                      RelaXT.LoadFromFile(CheckXmlPath+RelaFormCode+'.xml');
                      RelaXT.LoadFromFile(CheckXmlPath+FWork_no+'\'+RelaFormCode+'.xml');
Display1.Lines.Add(RelaFile+','+RelaFormName);
//ShowMessage(RelaFile);
//ShowMessage(ImageSavePath+CaseID+'\upload\'+RelaFile);
                      if RelaFile<>'' then
                      begin
                        ISB8.LoadFromFile(ImageSavePath+CaseID+'\upload\'+RelaFile,1); //20170815
                        ISB8W:= ISB8.Graphic.Width;
                        ISB8H:= ISB8.Graphic.Height;
                        FindPoint(ISB8.Graphic,UpLPoint,UpRPoint,DownLPoint,ISB8W,ISB8H,ANCHOR);  //20170815  抓相關然欄位所在圖檔的定位
                      end;
                      OMROK := False;
                      //OMROK := False;
                      //if RelaXT.SubNodes['/form/settype2/'].First then
@@ -10778,17 +12362,18 @@
                              RelaSiteRec := RelaSiteRec+'@'+RelaSite;
                            if  FileExists(ImageSavePath+CaseID+'\upload\'+RelaFile) then
                            begin
Display1.Lines.Add(ColEName+' '+ColCName+'   圖像實際點數='+IntToStr(GetSiteOMR(ImageSavePath+CaseID+'\upload\'+OMRFile,Site,Bt))+' 設定點數='+IntToStr( (Pixel + SafePixel)));
                              if GetSiteOMR(ImageSavePath+CaseID+'\upload\'+RelaFile,RelaSite,Bt) > (RelaPixel + SafePixel)  then
                              begin
                                OMROK := True;
                                Break;
                              end;
                              ///依十字定位點縮放////
                              ImageReSize_FormID(CaseID,OMRFile); //20170815 重新抓定位
                              ////依十字定位點縮放////
                            end;
                          end;
                          //Else
                          //begin
                            //ColCName := XT['/form/settype1/'+ColEName+'/'+nodename+'/'];
                          //end;
                        Until not RelaXT.SubNodes['/form/settype2/'+RelaColEName+'/'].Next;
                        if not OMROk then
                        begin
@@ -10810,6 +12395,7 @@
              Until not XT.SubNodes['/form/settype3/'].Next ;
            end;
            //*******有值相關文件的欄位也要有值*******
//ShowMessage('11788 OMRFileList.Strings['+IntToStr(i)+']'+OMRFileList.Strings[i]);
            //*******有值相關文件的欄位不能有值*******
            if ModeNeedCheck(OMRErrInfo[11].Mode,FMode) then //是否要檢核
@@ -10828,6 +12414,7 @@
                else
                  SiteRec := SiteRec+'@'+Site;
                Pixel := XT.Node['/form/settype8/'+ColEName+'/'].Attributes['pixel'];
Display1.Lines.Add(ColEName+' '+ColCName+'   圖像實際點數='+IntToStr(GetSiteOMR(ImageSavePath+CaseID+'\upload\'+OMRFile,Site,Bt))+' 設定點數='+IntToStr( (Pixel + SafePixel)));
                if GetSiteOMR(ImageSavePath+CaseID+'\upload\'+OMRFile,Site,Bt) > (Pixel + SafePixel) then
                begin
@@ -10847,7 +12434,16 @@
                    RelaFile := FormCode2FileName(RelaFormCode,ContextList);
                    RelaFormName := FormCode2FormName(CaseID,RelaFormCode);
                    Anchor1 := FormID2Anchor(RelaFormCode);
                    RelaXT.LoadFromFile(CheckXmlPath+RelaFormCode+'.xml');
                    RelaXT.LoadFromFile(CheckXmlPath+FWork_no+'\'+RelaFormCode+'.xml');
                    if RelaFile<>'' then
                    begin
                      ISB8.LoadFromFile(ImageSavePath+CaseID+'\upload\'+RelaFile,1); //20170815
                      ISB8W:= ISB8.Graphic.Width;
                      ISB8H:= ISB8.Graphic.Height;
                      FindPoint(ISB8.Graphic,UpLPoint,UpRPoint,DownLPoint,ISB8W,ISB8H,ANCHOR);  //20170815  抓相關然欄位所在圖檔的定位
                    end;
                    OMROK := False;
                    //OMROK := False;
                    //if RelaXT.SubNodes['/form/settype2/'].First then
@@ -10868,12 +12464,16 @@
                            RelaSiteRec := RelaSiteRec+'@'+RelaSite;
                          if  FileExists(ImageSavePath+CaseID+'\upload\'+RelaFile) then
                          begin
Display1.Lines.Add(ColEName+' '+ColCName+'   圖像實際點數='+IntToStr(GetSiteOMR(ImageSavePath+CaseID+'\upload\'+OMRFile,Site,Bt))+' 設定點數='+IntToStr( (Pixel + SafePixel)));
                            if GetSiteOMR(ImageSavePath+CaseID+'\upload\'+RelaFile,RelaSite,Bt) > (RelaPixel + SafePixel)  then
                            begin
                              inc(OMROkCount);
                              //OMROK := True;
                              //Break;
                            end;
                            ///依十字定位點縮放////
                            ImageReSize_FormID(CaseID,OMRFile);
                            ////依十字定位點縮放////
                          end;
                        end;
                        //Else
@@ -10901,7 +12501,7 @@
            end;
            //*******有值相關文件的欄位不能有值*******
//ShowMessage('11889 OMRFileList.Strings['+IntToStr(i)+']'+OMRFileList.Strings[i]);
              //*******有值相依文件*******
            if ModeNeedCheck(OMRErrInfo[5].Mode,FMode) then //是否要檢核
@@ -10919,6 +12519,8 @@
                else
                  SiteRec := SiteRec+'@'+Site;
                Pixel := XT.Node['/form/settype4/'+ColEName+'/'].Attributes['pixel'];
 Display1.Lines.Add(ColEName+' '+ColCName+'   圖像實際點數='+IntToStr(GetSiteOMR(ImageSavePath+CaseID+'\upload\'+OMRFile,Site,Bt))+' 設定點數='+IntToStr( (Pixel + SafePixel)));
                if GetSiteOMR(ImageSavePath+CaseID+'\upload\'+OMRFile,Site,Bt) > (Pixel + SafePixel) then
                begin
                  ////有填寫////
@@ -10963,6 +12565,8 @@
                else
                  SiteRec := SiteRec+'@'+Site;
                Pixel := XT.Node['/form/settype5/'+ColEName+'/'].Attributes['pixel'];
 Display1.Lines.Add(ColEName+' '+ColCName+'   圖像實際點數='+IntToStr(GetSiteOMR(ImageSavePath+CaseID+'\upload\'+OMRFile,Site,Bt))+' 設定點數='+IntToStr( (Pixel + SafePixel)));
                if GetSiteOMR(ImageSavePath+CaseID+'\upload\'+OMRFile,Site,Bt) > (Pixel + SafePixel) then
                begin
                  ////有填寫////
@@ -11007,6 +12611,9 @@
                  SiteRec := Site
                else
                  SiteRec := SiteRec+'@'+Site;
 Display1.Lines.Add(ColEName+' '+ColCName+'   圖像實際點數='+IntToStr(GetSiteOMR(ImageSavePath+CaseID+'\upload\'+OMRFile,Site,Bt))+' 設定點數='+IntToStr( (Pixel + SafePixel)));
                if GetSiteOMR(ImageSavePath+CaseID+'\upload\'+OMRFile,Site,Bt) > (Pixel + SafePixel) then
                begin
                  ////有填寫////
@@ -11037,6 +12644,8 @@
                    OMRValue := XT.Node['/form/settype7/'+ColEName+'/'+nodename+'/'].Attributes['getvalue'];
                    //有填就ok
 Display1.Lines.Add(ColEName+' '+ColCName+'   圖像實際點數='+IntToStr(GetSiteOMR(ImageSavePath+CaseID+'\upload\'+OMRFile,Site,Bt))+' 設定點數='+IntToStr( (Pixel + SafePixel)));
                    if GetSiteOMR(ImageSavePath+CaseID+'\upload\'+OMRFile,Site,Bt) > (Pixel + SafePixel)  then
                    begin
                      ValueXT['/content/'+ColEName+'/@savevalue'] := OMRValue;  //有填就換成設定的值
@@ -11055,6 +12664,7 @@
          RelaXT.Free;
          end;
        end;
        //必填迴圈結束
      Finally
      ValueXT.Free;
      end;
@@ -11133,11 +12743,49 @@
  end;
end;
function TCB_IMGPSScanX.OMRErrini2ListForLog(CaseID: String): String;
var
  ini : Tinifile;
  Errcount : Integer;
  Del : Boolean;
  i,j : Integer;
  ST,CaseList:TStringList;
begin
  Result:='';
  //CaseList.dat
  ST:=TStringList.Create;
  CaseList:=TStringList.Create;
  CaseList.LoadFromFile(ImageSavePath+'CaseList.dat');
  for I := 0 to CaseList.Count - 1 do
  begin
    ini := Tinifile.Create(ImageSavePath + CaseList.Strings[i]+'\upload\Checkerr.ini');
    try
      Errcount := ini.ReadInteger('OMRCount','Count',0);
      for j := 1 to ErrCount do
      begin
        Del := ini.ReadBool(inttostr(j),'Del',False); //是否被移除了
        if Not Del then
        begin
          ST.Add(ini.ReadString(inttostr(j),'Reason','')) ;
        end;
      end;
    finally
    ini.Free;
    end;
  end;
  Result:=ST.Text;
  ST.Free;
  CaseList.Free;
end;
Function TCB_IMGPSScanX.DownLanguage:Boolean;  //下載多國語言檔
begin
  Result := True;     // http://192.168.0.101:8080/fbnp/servlet/CWC01?act=getservertime
  //dnFile(HTTPSClient,FUrl+'Language.Lng','','',LngPath+'Language.Lng',FReWrite.Text,Memo1,False,DownImgStatus)
  If not dnFile_Get(HTTPSClient,FUrl+'Language.Lng','','',LngPath+'Language.Lng',FReWrite,Memo1,False,'') Then
  If not dnFile_Get(HTTPSClient,FUrl+'Language.Lng','','',LngPath+'Language.Lng',FReWrite,Memo1,False,DownImgStatus) Then
  begin
    HttpErrStr := _Msg('錯誤代碼:')+inttostr(HttpError.HttpErrorCode)+','+HttpError.HttpReason;
    Result := False;
@@ -11167,7 +12815,7 @@
    List_FormCode,Err_FormCode: String;
    iFormID : String;
begin
   ShowText := '影像顯示中,請稍候';
   ShowText := _Msg('影像顯示中,請稍候');
   DataLoading(True,True);
   IF FormCode = 'ShowAll' then  //顯示所有的影像 (因為附件會傳空字串,所以用ShowAll)
@@ -11281,10 +12929,13 @@
    v ,v1 : Integer;
    List_DocNo,Trans_DocNo,List_FormCode,Form_Page: String;
    iDocNo : String;
    iGroupNo,page,Ct : Integer;
    iGroupNo,page,Ct,int1 : Integer;
    ST1:TStringList;
begin
   ShowText := '影像顯示中,請稍候';
   ShowText := _Msg('影像顯示中,請稍候');
   DataLoading(True,True);
ST1:=TStringList.Create;
//Display1.Lines.Clear;
   IF DocNo = 'ShowAll' then  //顯示所有的影像 (因為附件會傳空字串,所以用ShowAll)
   begin
     ClearView(1);
@@ -11294,37 +12945,66 @@
       Exit;
     end;
     CreatePreViewISB(GetCasePage(ImageSavePath,NowCaseno));
     //Showmessage(inttostr(GetCasePage(ImageSavePath,NowCaseno)));
//Showmessage(inttostr(GetCasePage(ImageSavePath,NowCaseno)));
     Ct := 0;
     For i := 0 to CaseDocNoList.Count-1 do
     begin
       {iDocno := DocNoDir2DocNo(CaseDocNoList.Strings[i]);
       if (((FIs_In_Wh  = 'Y') and (not DocNoIs_In_WH(iDocNo))) or   //入庫掃描不看非入庫文件
          ((FIs_In_Wh  = 'N') and (DocNoIs_In_WH(iDocNo)))) and
          ((iDocNo <> 'Attach') and (Copy(iDocNo,1,5)<>'ZZZZZ')) then     //非入庫掃描不看入庫文件
       if (FWH_category='N') and (FIs_In_Wh='Y') then
       begin
         Continue;
       end; }
         if FileExists(ImageSavePath+NowCaseno+'\EditedDocDir.dat') then
         begin
           ST1.LoadFromFile(ImageSavePath+NowCaseno+'\EditedDocDir.dat');
         end;
       end;
       iDocNo := CaseDocNoList.Strings[i];
       if not DocNoAppear(DocNoDir2DocNo(iDocNo)) then continue;
//ShowMessage('ST1.Count='+IntToStr(ST1.Count));
       if ST1.Count<>0 then
       begin
         if ST1.IndexOf(iDocNo)<>-1 then
         begin
         end
         else
         begin
           if not DocNoAppear(DocNoDir2DocNo(iDocNo)) then continue;  //20170817 這不能被註解
         end;
       end
       else
       begin
         if not DocNoAppear(DocNoDir2DocNo(iDocNo)) then continue;  //20170817 這不能被註解
       end;
       ContextList.Clear;
       if FileExists(Path+iDocNo+'\Context.dat') then
         ContextList.LoadFromFile(Path+iDocNo+'\Context.dat');
//ShowMessage('ContextList='+ContextList.Text);
       for n := 0 to ContextList.Count - 1 do
       begin
         if (FWH_category='N') and (FIs_In_Wh='Y') then
         begin
           if ISExistImg(Path+iDocNo+'\'+ContextList.Strings[n]) then
           begin
             if not DocNoIs_In_WH(Copy(iDocNo,1,8)) then
             begin
               Continue;
             end;
           end;
         end;
         inc(Ct);
         ISB := TImageScrollBox(FindComponent(ISBName+intToStr(Ct)));
         ISB.AntiAliased := False;
         ISB.AntiAliased := True;
         if ISB.ZoomPercent > 100  then
           ISB.AntiAliased := False;
         ISB.LoadFromFile(Path+iDocNo+'\'+ContextList.Strings[n],1);
         DpiResize(ISB.Graphic,36);
         DpiResize(ISB.Graphic,36,False);
         ISB.Redraw(true);
       end;
     end;
     //if DirectoryExists(Path+'Attach') then
     if DirectoryExists(Path+AttName) then
@@ -11344,23 +13024,43 @@
         ISB.LoadFromFile(Path+iDocNo+'\'+ContextList.Strings[n],1);
       end;
     end;
     FitPreViewISB;
   end
   Else if (DocNo <> '') and (FormID = '') then  //顯示指定DocNo+組別的影像  附件傳 Attach
   begin
   begin                               //顯示 文件層下的影像
     iDocNo := DocNo;
     ContextList.Clear;
     if FileExists(Path+iDocNo+'\Context.dat') then
       ContextList.LoadFromFile(Path+iDocNo+'\Context.dat');
//ShowMessage('ContextList.Count='+IntToStr(ContextList.Count));
     CreatePreViewISB(ContextList.Count);
//ShowMessage(IntToStr(ContextList.Count));
     int1:=0;
//ShowMessage(BoolToStr(DocNoIs_In_WH(Copy(iDocNo,1,8)),true));
     For i := 0 to ContextList.Count -1 do
     begin
       ISB := TImageScrollBox(FindComponent(ISBName+intToStr(i+1)));
       if (FWH_category='N') and (FIs_In_Wh='Y')  then
       begin
         if ISExistImg(Path+iDocNo+'\'+ContextList.Strings[i]) then
         begin
           if not DocNoIs_In_WH(Copy(iDocNo,1,8)) and ( iDocNo<>'Attach') then
           begin
             inc(int1);
             Continue;
           end;
         end;
       end;
//ShowMessage(Path+iDocNo+'\'+ContextList.Strings[i]);
       ISB := TImageScrollBox(FindComponent(ISBName+intToStr(i+1-int1)));
       ISB.AntiAliased := True;
       if ISB.ZoomPercent > 100  then
         ISB.AntiAliased := False;
       ISB.LoadFromFile(Path+iDocNo+'\'+ContextList.Strings[i],1);
       DpiResize(ISB.Graphic,36);
       DpiResize(ISB.Graphic,36,False);
       ISB.Redraw(true);
     end;
     FitPreViewISB;
@@ -11377,60 +13077,42 @@
       page := 0;
       Ct := 0;
       CreatePreViewISB(Pages);
//ShowMessage('formID page'+IntToStr(Pages)+', ContextList='+ContextList.Text);
       For i := 0 to ContextList.Count -1 do
       begin
         if FileName2FormCode(ContextList.Strings[i]) = FormID then
         begin
           if (FWH_category='N') and (FIs_In_Wh='Y') then
           begin
//ShowMessage(Path+iDocNo+'\'+ContextList.Strings[i]);
//ShowMessage(BoolToStr(ISExistImg(Path+iDocNo+'\'+ContextList.Strings[i]),true));
             if ISExistImg(Path+iDocNo+'\'+ContextList.Strings[i]) then
             begin
               if not DocNoIs_In_WH(FormCode2DocNo(FormID)) then
                 Continue;
             end;
           end;
           inc(Ct);
           ISB := TImageScrollBox(FindComponent(ISBName+intToStr(Ct)));
//ShowMessage(ISB.Name);
           ISB.AntiAliased := True;
           if ISB.ZoomPercent > 100  then
             ISB.AntiAliased := False;
           ISB.LoadFromFile(Path+iDocNo+'\'+ContextList.Strings[i],1);
           DpiResize(ISB.Graphic,36);
           DpiResize(ISB.Graphic,36,False);
           ISB.Redraw(true);
           //NowShowFileList.Add(ContextList.Strings[i]);
         end;
       end;
       FitPreViewISB;
     end;
   end;
   {Else if (DocNo = 'Attach') and (FormID = 'Attach') then  //附件傳 Attach
   begin
     If (TreeView1.Selected <> nil) Then
     begin
       iGroupNo := 0;
       page := 0;
       CreatePreViewISB(Pages);
       For i := 0 to ContextList.Count -1 do
       begin
         List_FormCode := FileName2FormCode(ContextList.Strings[i]);
         Form_Page := FormCode2Page(List_FormCode);
         List_DocNo := FormCode2DocNo(List_FormCode);
         Trans_DocNo := Context_DocnoList.Strings[i];
         if (Trans_DocNo = DocNo) then
         begin
           if List_FormCode = FormID then
           begin
             inc(Page);
             if Page = GroupNo+1 then
             begin
               ISB := TImageScrollBox(FindComponent(ISBName+intToStr(1)));
               ISB.AntiAliased := True;
               if ISB.ZoomPercent > 100  then
                 ISB.AntiAliased := False;
               ISB.LoadFromFile(Path+ContextList.Strings[i],1);
               NowShowFileList.Add(ContextList.Strings[i]);
             end;
           end;
         end;
       end;
       FitPreViewISB;
     end;
   end;}
   if FindComponent(ISBName+'1') <> nil then
   begin
     ISBClick(TImageScrollBox(FindComponent(ISBName+'1')));
   end;
   ISB1Click(ISB1);
   DataLoading(False,False);
end;
@@ -11547,6 +13229,7 @@
  ISB : TImageScrollBox;
  Panel : TPanel;
  i,W,H : Integer;
  myDate : TDateTime;
begin
  FreePreViewISB;
  ScrollBox1.HorzScrollBar.Visible := False;
@@ -11554,32 +13237,38 @@
  H := 250;
  for I := 1 to Count do
  begin
    Panel := TPanel.Create(Self);
    Panel.Name := 'M_Pl'+inttostr(i);
    Panel.Left := 4;
    Panel.Top := (i-1)*H+(6*i);
    Panel.Height := H;
    Panel.Width := W;
    Panel.Parent := ScrollBox1;
    Panel.Caption :='';
    ISB := TImageScrollBox.Create(Self);
    ISB.Name := ISBName+inttostr(i);
    ISB.Parent := Panel;
    ISB.Align := alClient;
    ISB.ZoomMode := zmFullPage;
    ISB.DragMode := dmAutomatic;
    ISB.MouseMode := mmuser;
    ISB.OnImageClick := ISBClick;
    ISB.OnImageMouseMove := ISBMouseMove;
    ISB.PopupMenu := PopupMenu6;
    ISB.OnImageMouseDown := ISBImageMouseDown;
    ISB.OnImageMouseUp := ISBImageMouseUp;
    //ISB.OnStartDrag := ISBStartDrag;
    ISB.OnEndDrag := ISBEndDrag;
//    ISB.OnImageDragDrop := ISBDragDrop;
//    ISB.OnImageDragOver := ISBDragOver;
    ISB.OnDragDrop := ISBDragDrop;
    ISB.OnDragOver := ISBDragOver;
    if FindComponent('M_Pl'+inttostr(i))=nil then
    begin
      Panel := TPanel.Create(Self);
      Panel.Name := 'M_Pl'+inttostr(i);//FormatDateTime('yyyymmddhhnnsszzz', now)
      Panel.Left := 4;
      Panel.Top := (i-1)*H+(6*i);
      Panel.Height := H;
      Panel.Width := W;
      Panel.Parent := ScrollBox1;
      Panel.Caption :='';
      if FindComponent(ISBName+inttostr(i))=nil then
      begin
        ISB := TImageScrollBox.Create(Self);
        ISB.Name := ISBName+inttostr(i);
        ISB.Parent := Panel;
        ISB.Align := alClient;
        ISB.ZoomMode := zmFullPage;
        ISB.DragMode := dmAutomatic;
        ISB.MouseMode := mmuser;
        ISB.OnImageClick := ISBClick;
        ISB.OnImageMouseMove := ISBMouseMove;
        ISB.PopupMenu := PopupMenu6;
        ISB.OnImageMouseDown := ISBImageMouseDown;
        ISB.OnImageMouseUp := ISBImageMouseUp;
        ISB.OnEndDrag := ISBEndDrag;
        ISB.OnDragDrop := ISBDragDrop;
        ISB.OnDragOver := ISBDragOver;
      end;
    end;
  end;
end;
@@ -11588,25 +13277,29 @@
var
  i : Integer;
begin
try
  For i:= ComponentCount -1 downto 0 do
  begin
    IF Components[i] is TImageScrollBox Then
    IF (Components[i] is TImageScrollBox) and (Components[i]<>nil) Then
    begin
      IF Pos(ISBName,Components[i].Name) > 0 Then
        Components[i].Free;
    end
    Else If Components[i] is TPanel Then
    Else If (Components[i] is TPanel) and  (Components[i]<>nil) Then
    begin
      IF Pos('M_Pl',Components[i].Name) > 0  Then
        Components[i].Free;
    end
    Else If Components[i] is TShape Then
    Else If (Components[i] is TShape) and (Components[i]<>nil) Then
    begin
      IF Pos('SP',Components[i].Name) > 0  Then
        Components[i].Free;
    end;
  end;
  Application.ProcessMessages;
except on E: Exception do
end;
  //showmessage(inttostr(Count));
end;
@@ -11753,6 +13446,9 @@
  ln := length(SelectISB.Name);
  SelectPage := Strtoint(Copy(SelectISB.Name,v+1,ln-v));
  ISB1.ZoomMode := zmFittoPage;
//ShowMessage('SelectISB.FileName='+SelectISB.FileName);
  //if SelectISB.FileName='' then exit;
  ISB1.LoadFromFile(SelectISB.FileName,1);
  if (ISB1.Graphic.ImageFormat <> ifBlackWhite) and (SmoothCB.Checked)then
    Image_Smooth(ISB1.Graphic);
@@ -11763,7 +13459,7 @@
Procedure TCB_IMGPSScanX.ISBMouseMove(Sender: TObject; Shift: TShiftState;
  X, Y: Integer);
begin
  Edit1.SetFocus;
  //Edit1.SetFocus;
  if Draging then
  begin
    if not (TShape(FindComponent('SP'+Copy(TImageScrollBox(Sender).Name,length(ISBName)+1,length(TImageScrollBox(Sender).Name)-length(ISBName)))) = nil) then
@@ -11925,6 +13621,11 @@
  for I := 0 to ContextList.Count - 1 do
  begin
    FileFormID := FileName2FormCode(ContextList.Strings[i]);
    if DivPageFormIDList.IndexOf(FileFormID)<>-1 then //20170509 跳過分案頁的formid
    begin
      Continue;
    end;
    if FindDivFormCode(FileFormID) then
    begin
      Result := FileFormID;
@@ -12105,6 +13806,7 @@
    Str := '';
    if Not FileExists(ImageSavePath+CaseID+'\CaseDocNo.dat') then Exit;
    DocDirList.LoadFromFile(ImageSavePath+CaseID+'\CaseDocNo.dat');
//ShowMessage(DocDirList.Text);
    while DocDirList.Count > 0 do
    begin
      iDocDir := DocDirList.Strings[0];
@@ -12463,6 +14165,7 @@
        OldName := Filelist.Strings[i];
        //NewName := Add_Zoo(i+1,3)+Copy(OldName,4,length(OldName)-3);
        NewName := Add_Zoo(i+1,3)+FileName2NoQuene_Filename(OldName);
//ShowMessage(OldName+#10#13+NewName);
        ReNameFile(Path+OldName,Path+NewName);
        Filelist.Strings[i] := NewName;
      end;
@@ -12554,7 +14257,7 @@
    end;
    if FileExists(CheckXmlPath+'OMRSet.zip') then   //有更新
    begin
      ExecuteUnZip(CheckXmlPath+'OMRSet.zip',CheckXmlPath,False);
      ExecuteUnZip(CheckXmlPath+'OMRSet.zip',CheckXmlPath,True);
      S.Clear;
      S.Add(ServerDate+GetBalance2Time(Balance));
      S.SaveToFile(CheckXmlPath+'LastDateTime.dat');
@@ -12612,7 +14315,7 @@
    end;
    if FileExists(SitePath+'KeyinSet.zip') then  //有更新
    begin
      ExecuteUnZip(SitePath+'KeyinSet.zip',SitePath,False);
      ExecuteUnZip(SitePath+'KeyinSet.zip',SitePath,True);
      S.Clear;
      S.Add(ServerDate+GetBalance2Time(Balance));
      S.SaveToFile(SitePath+'LastDateTime.dat');
@@ -12648,9 +14351,11 @@
var
  SendData : String;
begin
//Memo1.Clear;
  SendData := 'data='+HTTPEncode(UTF8Encode(FData))+'&verify='+FVerify+'&case_no='+CaseID+'&work_no='+FWork_no;
  if (FMode = 'NSCAN') then
  if (FMode = 'NSCAN') or (FMode = 'DSCAN') then
  begin
//ShowMessage('JJJJJ');
    If not ProcessServlet_Get(HTTPSClient,FURL+'service/imgpsc/IMGPSC05/isnew',SendData,FReWrite,Memo1,False) Then
    begin
      HttpErrStr := _Msg('錯誤代碼:')+inttostr(HttpError.HttpErrorCode)+','+HttpError.HttpReason;
@@ -12658,10 +14363,11 @@
      Exit;
    end;
  end;
//ShowMessage(SendData);
  IF memo1.Lines.Strings[0] <> '0' Then
  begin
    HttpErrStr := _Msg('錯誤原因:')+memo1.Lines.Strings[1];
    HttpErrStr := _Msg('')+memo1.Lines.Strings[1]+'。';
    Result := -1;
    Exit;
  end
@@ -12669,7 +14375,7 @@
  begin
    if (memo1.Lines.Count < 2) then
    begin
      HttpErrStr := _Msg('錯誤原因:')+'OCX:Index Count error';
      HttpErrStr := _Msg('')+'OCX:Index Count error';
      Result := -1;
      Exit;
    end
@@ -12683,7 +14389,7 @@
        Result := 1
      Else
      begin
        HttpErrStr := _Msg('錯誤原因:')+'OCX:Value error';
        HttpErrStr := _Msg('')+'OCX:Value error';
        Result := -1;
        Exit;
      end;
@@ -12926,11 +14632,16 @@
  i: Integer;
begin
  Timer1.Enabled := False;
  //FIs_In_Wh:='Y'; /// test 記得關掉
  //FWH_category :='N';  // test 記得關掉
//  FImgDelete := 'Y'; //test 記得關掉
  //Showmessage('a');
  //self.FIs_OldCase := 'Y';
  PageLVclear := True;
  InitialOk := False;
  FMaxUploadSize:='10';
  FJpgCompression:=50;
  //FMode := 'DSCAN' ;
  //FIs_In_Wh := 'Y';
  if FIs_In_Wh = 'Y' then
@@ -12959,6 +14670,9 @@
    Panel6.Visible := True;
    Panel21.Visible := True;
    Panel23.Visible := True;
    AttFileGB.Visible := True;
    Splitter2.Visible := True;
    ScanDuplexCB.Visible := True; //雙面掃描
  end
  Else if FMode = 'FSCAN' then
@@ -12973,11 +14687,18 @@
    Panel6.Visible := True;
    Panel21.Visible := True;
    Panel23.Visible := True;
    AttFileGB.Visible := True;
    Splitter2.Visible := True;
  end;
  DisplayMode(1,1,1,Panel9);
  Application.ProcessMessages;
  StatusBar1.Panels[0].Text := 'Ver'+GetCurrentVersionNo;
  StatusBar1.Panels[1].Text := _Msg('登入人員:')+FUserName;
  StatusBar1.Panels[1].Text := 'Login User:'+FUserName;
  {$IFDEF Test}
    StatusBar1.Panels[0].Text := StatusBar1.Panels[0].Text+'(test)';
  {$ENDIF}
    StatusBar1.Panels[0].Text := StatusBar1.Panels[0].Text;
  if FPrintyn = 'Y' then
    PrtLB.Visible := True;
@@ -12985,11 +14706,24 @@
  InitScrollRec;
  If FUrl = '' then
  begin
    Showmessage(_Msg('URL不能為空白,請洽詢程式人員'));
    Showmessage(_Msg('URL cannot be empty,please contact system administrator'));
    Exit;
  end;
  if FUrl[length(FUrl)]<>'/' then
    FUrl := FUrl + '/';
  //20221028 把語言檔改放至 Local目錄裡,才不會有些文字來不及使用
  LngPath := GetLocalAppDir(Handle)+'MPS\CB_IMGPS\';
  Str2Dir(LngPath);
  ////下載語言檔/////  20170218 先拿調以便測試
  If not DownLanguage Then
  begin
    Showmessage('Language File error!!'+HttpErrStr);
    DataLoading(False,False);
    Exit;
  end;
  InitialLanguage(Self);  //載入多國語言
  if FWork_no='' then
  begin
@@ -13024,6 +14758,7 @@
  CaseList := TStringList.Create;    //記錄掃瞄案件的順序
  Context_DocnoList := TStringlist.Create; //案件裡的檔案Docno清單
  ContextList := TStringlist.Create; //案件裡的檔案清單
  AttContextList := TStringlist.Create; //案件裡的附加檔案清單
  NoSaveBarCodeList := TStringlist.Create; //不儲存的條碼清單
  FormID_List := TStringlist.Create;  //FormID清單
  DocNo_List := TStringlist.Create; //DocNo清單
@@ -13032,8 +14767,12 @@
  Cust_DocNoList := TStringlist.Create; //自行定義的文件名稱
  IN_WH_DocNoList := TStringlist.Create; //入庫的文件清單
  GuideFormIDList := TStringlist.Create; //要當導引頁表單清單
  DivPageFormIDList := TStringList.Create; //要當分案頁表單清單
  LastInitFormidList :=TStringList.Create;
  LastAddFormidList := TStringList.Create;
  SampleFormIDList := TStringList.Create;//20170627 加入
  ExistImgList := TStringList.Create;  //20170724 新增
  reSizeExistImgList :=TStringList.Create; //20171012 新增
  //********清單區********
  ShowText := _Msg('資料載入中,請稍候');
@@ -13045,6 +14784,19 @@
    DataLoading(False,False);
    Exit;
  end;
  if FMode='SAMPLESCAN' then
  begin
    IF not GetSampleInf Then  //取已存在sample
    begin
      Showmessage(_Msg('取存在範本資訊時,網路發生錯誤!!')+HttpErrStr);
      DataLoading(False,False);
      Exit;
    end;
  end;
//ShowMessage('GetServerDate  '+ServerDate+' , '+ServerTime);
  ////下載系統資訊////
  IF not GetSetInf1 Then  //取DOC_INF  文件資訊
@@ -13118,13 +14870,21 @@
  initkscan;
  if ImagePath[Length(ImagePath)] <> '\' then
    ImagePath := ImagePath + '\';
  CheckXmlPath := ImagePath+'OMRSITE\'+FWork_No;
  SitePath := ImagePath+'Site\'+FWork_No+'\';
  LngPath := ImagePath;
//ShowMessage('ImagePath='+ImagePath);
  //CheckXmlPath := ImagePath+'OMRSITE\'+FWork_No;
  CheckXmlPath := ImagePath+'OMRSITE\';  // 20200612 發現影像平台是取回所有業務的設定,所以不能有業務別目錄
//ShowMessage('CheckXmlPath='+CheckXmlPath);
  //SitePath := ImagePath+'Site\'+FWork_No+'\';
  SitePath := ImagePath+'Site\';  // 20200612 發現影像平台是取回所有業務的設定,所以不能有業務別目錄
  //LngPath := ImagePath; //改放至上面取Local目錄
  SamplePath := ImagePath+'Sample\'+FWork_No+'\';
  ImagePath := ImagePath + 'Scantemp\';
//ShowMessage('AA  ImagePath='+ImagePath);
  ScaniniPath :=ImagePath+FWork_No+'\'+FUserUnit +'\';
//ShowMessage('ScaniniPath='+ScaniniPath);
  ImagePath := ImagePath + FWork_No+'\'+FUserUnit+'\'+FMode+'\';
  ImagePath := StringReplace(ImagePath, '\\', '\',[rfReplaceAll, rfIgnoreCase]);
//ShowMessage('BB  ImagePath='+ImagePath);
  ImageSavePath := ImagePath;
  str2dir(CheckXmlPath);
  str2dir(SitePath);
@@ -13133,7 +14893,11 @@
  Del_Sub_NothingPath(ImagePath);  //清掉案件目錄是空的
  LogFile1.LogFile:=LngPath+'IMGPSCheck.log';
  ReduceLogFile;
  LogFile1.LogToFile(logTimeString+'OCX取表data結束');
  ShowText := _Msg('資料載入中,請稍候');
  DataLoading(True,True);
@@ -13151,15 +14915,8 @@
  ShowText := _Msg('資料載入中,請稍候');
  DataLoading(True,True);
   ////下載語言檔/////  20170218 先拿調以便測試
  If not DownLanguage Then
  begin
    Showmessage('Language File error!!'+HttpErrStr);
    DataLoading(False,False);
    Exit;
  end;
  InitialLanguage(Self);  //載入多國語言
  StatusBar1.Panels[1].Text := _Msg('登入人員:')+FUserName;
  //FCaseID:='20150302180133';//測試用
  ////下載語言檔/////
//ShowMessage('OOOO');
@@ -13173,7 +14930,7 @@
    MkDir(ImageSavePath+FCaseID);
    CreateEmptyCase(ImageSavePath,FCaseID);
    MkDir(ImageSavePath+FCaseID+'\Download');
    IF (FMode = 'ESCAN') then  //異動件先下載影像
    IF (FMode = 'ESCAN') or (FMode = 'DSCAN') then  //異動件先下載影像
    begin
      ShowText := _Msg('案件下載中,請稍候');
      DataLoading(True,True);
@@ -13205,7 +14962,8 @@
//        //LoadImgFile;
//      end;
      Create_Cust_DocDir(FCaseID); //產生外面傳入的文件
      LastInitFormidListCreate(ImageSavePath+FCaseID+'\Download\');
      if FMode='ESCAN' then
        LastInitFormidListCreate(ImageSavePath+FCaseID+'\Download\');
    end;
  end;
@@ -13233,8 +14991,11 @@
    DenialTimeLb.Visible := True;
    DenialTimeLb.Caption := Format(ScanDenialHint,[ScanDenialTime]);
  end;
//ShowMessage(IntToStr(ScanDpi));
  R_W_Scanini('R'); //掃瞄設定的ini
//ShowMessage(IntToStr(ScanDpi));
//ShowMessage('停掉DataLoading');
//DataLoading(False,False);
  ScanDuplexCB.Checked := ScanDuplex;
  if FMode <> 'SAMPLESCAN' then
    LoadImgFile;
@@ -13252,9 +15013,43 @@
  Splitter2.Visible := True;
  AttFileGB.Visible := False; //附加電子檔窗
  Splitter2.Visible := False; }
//ShowMessage('ImageSavePath='+ImageSavePath);
  DataLoading(False,False);
//ShowMessage('初始話執行完成');
  LogFile1.LogToFile(logTimeString+'OCX初始化結束');
  LogFile1.LogToFile(logTimeString+'FUrl='+FUrl+
   ',FCaseID='+FCaseID+
   ',FMode='+FMode+
   ',FModeName='+FModeName+
   ',FWork_no='+FWork_no+
   ',FUserID='+FUserID+
   ',FUserName='+FUserName+
   ',FUserUnit='+FUserUnit+
   ',FData='+FData+
   ',FVerify='+FVerify+
   ',FReWrite='+FReWrite+
   ',FLanguage='+FLanguage+
   ',FLoanDoc_Value='+FLoanDoc_Value+
   ',FLoanDoc_Enable='+FLoanDoc_Enable+
   ',FUseProxy='+FUseProxy+
   ',FC_DocNoList='+FC_DocNoList+
   ',FC_DocNameList='+FC_DocNameList+
   ',FFixFileList='+FFixFileList+
   ',FIs_In_Wh='+FIs_In_Wh+
   ',FOldCaseInfo='+FOldCaseInfo+
   ',FPrintyn='+FPrintyn+
   ',FIs_OldCase='+FIs_OldCase+
   ',FCustDocYN='+FCustDocYN);
  LogFile1.LogToFile(logTimeString+'FImgDPI='+IntToStr(FImgDPI)+
    ',FScanColor='+    IntToStr(FScanColor)+
    ',FFileSizeLimit='+  IntToStr(FFileSizeLimit)+
    ',FCaseNoLength='+ IntToStr(FCaseNoLength)+
    ',FImgDelete='+FImgDelete+
    ',FIsExternal='+FIsExternal+
    ',FWH_category='+FWH_category+
    ',FCheck_main_form='+FCheck_main_form+
    ',FMaxUploadSize='+FMaxUploadSize);
end;
procedure TCB_IMGPSScanX.Timer2Timer(Sender: TObject);
@@ -13277,23 +15072,33 @@
  AreaStr : String;
  S : TStringlist;
  CheckStr : String;
  uploadMsg:String;//20171122 新增 配合不同mode下要秀不能上傳訊息
begin
  IF not InitialOk Then
  begin
    Showmessage(_msg('資訊尚未下載完成,請稍候或重新進入'));
    Exit;
  end;
LogFile1.LogToFile(logTimeString+'按下上傳');
  ClearView(1);
  CaseHelpBtn.Visible := False;
  DisplayPath := '';
  ClearCaseIndex;
  RejectCase := False;
  uploadMsg:='';
  if not CheckCaseID_OK then  //檢查是否有未配號的案件
  begin
    Showmessage(_Msg('尚有未配號案件,無法上傳'));
    Showmessage(_Msg('尚有「無案件編號」之案件,無法上傳'));
    Exit;
  end;
  if not CheckCaseAttach_OK then  //20170911檢查是否有未歸類的案件
  begin
    Showmessage(_Msg('尚有未歸類文件,無法上傳'));
    Exit;
  end;
  if NewTreeNode.Count = 0  then
  begin
    Showmessage(_Msg('無影像需傳送'));
@@ -13320,7 +15125,6 @@
    CreateIn_WH(CaseID);    //產生入庫文件文字檔 In_Wh.dat
    Case2upload(CaseID);   //產生原影像結構
    TransPath := ImageSavePath+CaseID+'\Upload\';
    {if FMode = 'ESCAN' then    //20140320 yuu說拿掉此檢查
    begin
      S := TStringlist.Create;
@@ -13337,7 +15141,7 @@
      s.Free;
      end;
    end;}
    if (FMode = 'NSCAN') then
    if (FMode = 'NSCAN') or (FMode = 'DSCAN')  then //20170406 待掃瞄也要問一下
    begin
      /////訊問是否可上傳/////
      CaseTrans := CaseAsk(CaseID);
@@ -13349,7 +15153,7 @@
    end;
    if CaseTrans = -1 then  //失敗
    begin
      Showmessage(_Msg('詢問案件可否傳送時,網路發生錯誤!!')+HttpErrStr);
      Showmessage(_Msg('')+HttpErrStr+'.');
      DataLoading(False,False);
      LoadImgFile;
      Exit;
@@ -13375,7 +15179,7 @@
          begin
            ShowText := CaseID+_Msg('檢核中,請稍候');
            DataLoading(True,True);
            If not OMRCheckCase(CaseID) then
            If not OMRCheckCase(CaseID) then  //進檢核
            begin
              Inc(CheckErrCount);
              Continue;
@@ -13391,7 +15195,7 @@
      ///////檢核//////
      ShowText := CaseID+_Msg('資料上傳中,請稍候');
      DataLoading(True,True);
//ShowMessage('NNNNN');
//ShowMessage('退出');DataLoading(False,False);Exit;
      If Not TransCaseID(TransPath,CaseID,True) Then  //傳送案件
      begin
        DataLoading(False,False);
@@ -13402,13 +15206,32 @@
    end;
  end;
  DataLoading(False,False);
  TransMsg := Format(_Msg('成功件%d件'),[SuccessCount]);
  TransMsg := Format(_Msg('成功件【%d】件'),[SuccessCount]);
  if ReCasecount > 0 then
    TransMsg := TransMsg + #13#10 + Format(_Msg('無法上傳件%d件'),[ReCasecount]);
    TransMsg := TransMsg + #13#10 + Format(_Msg('無法上傳件【%d】件'),[ReCasecount]);
  if CheckErrCount > 0 then
    TransMsg := TransMsg + #13#10 + Format(_Msg('檢核失敗件%d件'),[CheckErrCount]);
  begin
    TransMsg := TransMsg + #13#10 + Format(_Msg('檢核失敗件【%d】件,請先點選「案件編號」,再點選「問號」查看錯誤原因'),[CheckErrCount]);
LogFile1.LogToFile(logTimeString+'檢核失敗原因:'+OMRErrini2ListForLog(''));
  end;
  Showmessage(_Msg('傳送完成')+#13#10+TransMsg);
  if (FMode = 'DSCAN') and (SuccessCount = 1)  then
  begin
    uploadMsg:=NowCaseNo+_Msg('影像上傳完成。此案已進入下一流程');
  end;
  if (FMode='ESCAN') and (FModeName=_Msg('補件掃描')) and (SuccessCount = 1) then
  begin
    uploadMsg:=NowCaseNo+_Msg('影像已補件完成');
  end;
//ShowMessage('uploadMsg='+uploadMsg);
  if uploadMsg<>'' then
  begin
    ShowMessage(uploadMsg);
  end
  else
  begin
    Showmessage(_Msg('傳送完成')+#13#10+TransMsg);
  end;
  LoadImgFile;
  if (FMode = 'ESCAN') and (SuccessCount = 1) then
@@ -13443,13 +15266,15 @@
  NowDocNo := '';
  NowFormCode := '';
  NowFormName := '';
  NowPage := 0;
  NowShowFileList.Clear;
  StatusBar1.Panels[2].Text := '';
  ClearCaseIndex;
  PageLv.Items.Clear;  //頁數清單
  //Panel18.Enabled:= False;
  AttListBox.Items.Clear;
  AddAttFileLB.Enabled := False;
  DelAttFileLB.Enabled := False;
  UseOldCaseLb.Visible := False;
  PM107.Visible := False; //備註功能
  CaseHelpBtn.Visible := False; //檢核失敗原因鈕
@@ -13525,9 +15350,9 @@
      DisplayPath := ImageSavePath+NowCaseNo+'\';
      if GetUseCase('F',DisplayPath,NowDocDir) <> '' then
        StatusBar1.Panels[2].Text := Format('從%s引用',[GetUseCase('F',DisplayPath,NowDocDir)]);
        StatusBar1.Panels[2].Text := Format(_Msg('從%s引用'),[GetUseCase('F',DisplayPath,NowDocDir)]);
      if GetUseCase('T',DisplayPath,NowDocDir) <> '' then
        StatusBar1.Panels[2].Text := Format('被%s引用',[GetUseCase('T',DisplayPath,NowDocDir)]);
        StatusBar1.Panels[2].Text := Format(_Msg('被%s引用'),[GetUseCase('T',DisplayPath,NowDocDir)]);
      if FLoanDoc_Enable = 'Y' then
      begin
        AddCredit1RG.Enabled := True;
@@ -13601,9 +15426,9 @@
      DisplayPath := ImageSavePath+NowCaseNo+'\';
      if GetUseCase('F',DisplayPath,NowDocDir) <> '' then
        StatusBar1.Panels[2].Text := Format('從%s引用',[GetUseCase('F',DisplayPath,NowDocDir)]);
        StatusBar1.Panels[2].Text := Format(_Msg('從%s引用'),[GetUseCase('F',DisplayPath,NowDocDir)]);
      if GetUseCase('T',DisplayPath,NowDocDir) <> '' then
        StatusBar1.Panels[2].Text := Format('被%s引用',[GetUseCase('T',DisplayPath,NowDocDir)]);
        StatusBar1.Panels[2].Text := Format(_Msg('被%s引用'),[GetUseCase('T',DisplayPath,NowDocDir)]);
      if FLoanDoc_Enable = 'Y' then
      begin
@@ -13630,7 +15455,12 @@
      if FileExists(DisplayPath+'CustomDocNo.dat') then
        Cust_DocNoList.LoadFromFile(DisplayPath+'CustomDocNo.dat');
    end;
     MyTreeNode1.Expand(True);
    MyTreeNode1.Expand(True);
    AddAttFileLB.Enabled := True;
    if FileExists(DisplayPath+'ATTContext.dat') then
    begin
      LoadAttFile(NowCaseno);
    end;
  end
  Else     //點在NewTreenode or MyTreenode1 上
  begin
@@ -13863,13 +15693,37 @@
procedure TCB_IMGPSScanX.TreeView1KeyUp(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
  TreeView1Click(nil);
  IF TreeView1.Selected.Parent <> nil Then
  begin
    TreeView1Click(nil);
  end
  else
  begin
    ClearView(1);
  end;
end;
procedure TCB_IMGPSScanX.TreeView1MouseDown(Sender: TObject;
  Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
  IF Button = TMouseButton(MbRight) Then
  begin
    MDown := True;
    If TreeView1.GetNodeAt(X,Y) = nil then Exit;
    TreeView1.Selected := TreeView1.GetNodeAt(X,Y);
  end;
end;
procedure TCB_IMGPSScanX.TreeView1MouseEnter(Sender: TObject);
begin
TreeView1.SetFocus;
end;
procedure TCB_IMGPSScanX.TreeView1MouseMove(Sender: TObject; Shift: TShiftState;
  X, Y: Integer);
begin
  TreeView1.SetFocus;
  //TreeView1.SetFocus;
  {UnRegisterHotKey(Handle, HotKeyId1);
  UnRegisterHotKey(Handle, HotKeyId2); }
end;
@@ -13880,9 +15734,13 @@
  IF Button = TMouseButton(MbRight) Then
  begin
    If TreeView1.GetNodeAt(X,Y) = nil then Exit;
    TreeView1.Selected := TreeView1.GetNodeAt(X,Y);
    TreeView1Click(self);
    TreeView1.PopupMenu.Popup(Mouse.CursorPos.X ,Mouse.CursorPos.Y);
    if MDown then
    begin
      TreeView1Click(self);
      TreeView1.PopupMenu.Popup(Mouse.CursorPos.X ,Mouse.CursorPos.Y);
    end;
    Application.ProcessMessages; //需加這行,不然有些全域變數會沒變到
    MDown:= False;
  end;
end;
@@ -14177,6 +16035,7 @@
procedure TCB_IMGPSScanX.Set_filesizelimit(const Value: WideString);
begin
//ShowMessage(Value);
  FFileSizeLimit:=0;
  if Value ='' then
  begin
    FFileSizeLimit := 5*1024;
@@ -14259,6 +16118,16 @@
  FIsExternal:=Value;
end;
function TCB_IMGPSScanX.Get_WH_CATEGORY: WideString;
begin
end;
procedure TCB_IMGPSScanX.Set_WH_CATEGORY(const Value: WideString);
begin
  FWH_category:=Value;
end;
initialization
  TActiveFormFactory.Create(
    ComServer,
@@ -14270,14 +16139,22 @@
    OLEMISC_SIMPLEFRAME or OLEMISC_ACTSLIKELABEL,
    tmApartment);
  SetLicenseKey('5B4451E676A1D2976FBB0F3BB18341336AF114C80B5ABAE7F6926B1CAF671F44' +
  {SetLicenseKey('5B4451E676A1D2976FBB0F3BB18341336AF114C80B5ABAE7F6926B1CAF671F44' +
  'BD2F098CCEDA922F6389BFAE398DA6AEE67F97EEA0C17234C20D75C12173DBDA' +
  '594924D56DD8E342F454389C836AD880BB4352CA3BE62C4933B1BA3828E7462C' +
  '60514F2ECDAD322E6128D841F12D24DA00B623106D3F08EBCAA917D8A97CAA34' +
  '3D65F2DA567316457395BF9123EE53DF235D181F191A5712DBB27735284AA92D' +
  '5DFA0C8308308505F384707E900C6063F53F1BFF4C6972607955D1AE517B19D0' +
  '82CDD16301885403AD229D57BAEF98C056F31430861E5F68F339D658D72E1F92' +
  '63899412EC2D07891FE3AFD35F3E4A4390B2F0A8A1BF1B7D6160E5F1CC009B17');
  '63899412EC2D07891FE3AFD35F3E4A4390B2F0A8A1BF1B7D6160E5F1CC009B17'); }
  SetLicenseKey('4B2CF65E8C2A86CE8A0DD0F6A7DB03BC0B0126168B48AE4C27EBD78CAE75CF0F' +
   'A612190861E0D99F6FAE3ED97AC1941B5E97843CFFCF705A3787989072D4EB2C' +
   'AE6CAB3F5B69B86616ACC8A37AD6A2AB21C7BDD5C9AE1EDF9E4193D353805C9A' +
   '403631CE8A3D0803FEBB1BE4C209CE7A63B1298EF080EB34B8628CED567D2B68' +
   'E777FAC58E2E32B7411FC217A04336231D1E861A93474759DAA6EDF53F6EB632' +
   'A3055229A52F3053FB844754741409022DDE3DFB19473510F2BE63328E74BE20' +
   'A6A29AA24878F91ADA9DF8CE1F320AF4DAF58EBF95D9BE761D70EEA274E19475' +
   '1C15948B184264C5C49E60493F3BCD2FFAE2CA8B021D00B96F45550C5F050D8A');
  SetLicenseKey('A6A94A8D91B08A9D58F300C0573EA9EF1B9DB0BF69B90E13B958DB4CB6B44F5A' +