From 2631324407b8c12fe557f225688211d75d5ee02b Mon Sep 17 00:00:00 2001
From: doom4ster <doom4ster@gmail.com>
Date: 星期二, 26 九月 2017 17:57:04 +0800
Subject: [PATCH] CB_IMGPSScan.cab ver2.0.1.44 加入 A3 匯入切頁功能

---
 CB_IMGPSScanImp.pas | 1596 +++++++++++++++++++++++++++++++++++++++++++++-------------
 1 files changed, 1,220 insertions(+), 376 deletions(-)

diff --git a/CB_IMGPSScanImp.pas b/CB_IMGPSScanImp.pas
index 46a1807..b7252a3 100644
--- a/CB_IMGPSScanImp.pas
+++ b/CB_IMGPSScanImp.pas
@@ -14,7 +14,7 @@
   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;
 
 var
   Ch_WriteNote : Boolean;
@@ -145,7 +145,6 @@
     ISB2: TImageScrollBox;
     imgp1: TPanel;
     lb1: TLabel;
-    ISB1: TImageScrollBox;
     Memo1: TMemo;
     Display1: TMemo;
     Panel22: TPanel;
@@ -255,6 +254,8 @@
     ISB_BW: TImageScrollBox;
     N1: TMenuItem;
     N2: TMenuItem;
+    ISB1: TImageScrollBox;
+    Label3: TLabel;
     procedure ActiveFormCreate(Sender: TObject);
     procedure Panel9Resize(Sender: TObject);
     procedure ISB1Click(Sender: TObject);
@@ -406,6 +407,7 @@
     FImgDelete:string; // Y/N  有權限可在補件時刪除影像
     FIsExternal:string;//Y/N
     FCheck_main_form:string; //Y/N
+    FWH_category:string;  //Y/N  Y是歸類時有區分入庫非入庫文件  N 是不區分
     ////////傳入參數///////
 
     //********Http參數********
@@ -484,6 +486,8 @@
     DivPageFormIDList:TStringlist; //要當分案頁表單清單
     LastInitFormidList:TStringList;
     LastAddFormidList:TstringList;
+    SampleFormIDList:TStringList; //20170627 已存在範本的formid
+    ExistImgList:TStringList;  //20170724  已經存在的影像list for ESCAN  //Img的完整路徑
     //********清單區********
 
     //********顯示區********
@@ -830,6 +834,14 @@
     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 確認是否有未歸類文件
   protected
     { Protected declarations }
     procedure DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage); override;
@@ -949,6 +961,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;
@@ -1199,6 +1213,60 @@
   PM605Click(nil);
 end;
 
+procedure TCB_IMGPSScanX.InitExistImgList(casepath: String);
+var
+  ST1,ST2,ST3,ST4:TStringList;
+  i,j,k:Integer;
+begin
+//ShowMessage('casepath='+casepath);
+  ST1:=TStringList.Create;
+  ST2:=TStringList.Create;
+  ST3:=TStringList.Create;
+
+//FImgDelete:='Y';
+  {if FileExists(casepath+'CaseDocNo.dat') then
+  begin
+    ST1.LoadFromFile(casepath+'CaseDocNo.dat');
+    for I := 0 to ST1.Count - 1 do
+    begin
+      ST2.LoadFromFile(casepath+ST1.Strings[i]+'\Context.dat');
+      for j := 0 to ST2.Count - 1 do
+      begin
+        ExistImgList.Add(casepath+ST1.Strings[i]+'\'+ST2.Strings[j])
+      end;
+    end;
+  end;
+
+  if FileExists(casepath+'S_Attach\Context.dat') then
+  begin
+    ST3.LoadFromFile(casepath+'S_Attach\Context.dat');
+    for I := 0 to ST3.Count - 1 do
+    begin
+      ExistImgList.Add(casepath+'S_Attach\'+ST3.Strings[i])
+    end;
+  end;
+
+  if FileExists(casepath+'Attach\Context.dat') then
+  begin
+    ST3.LoadFromFile(casepath+'Attach\Context.dat');
+    for I := 0 to ST3.Count - 1 do
+    begin
+      ExistImgList.Add(casepath+'Attach\'+ST3.Strings[i])
+    end;
+  end; }
+  ExistImgList.Clear;
+  ST1.LoadFromFile(casepath+'Download\Context.dat');
+  for I := 0 to ST1.Count - 1 do
+  begin
+    ExistImgList.Add(LoadFileGetMD5(casepath+'Download\'+ST1.Strings[i])) ;
+  end;
+
+  ST1.Free;
+  ST2.Free;
+  ST3.Free;
+//ShowMessage('ExistImgList='+ExistImgList.Text);
+end;
+
 procedure TCB_IMGPSScanX.Initialize;
 begin
   inherited Initialize;
@@ -1259,7 +1327,7 @@
 
 procedure TCB_IMGPSScanX.ISB1Enter(Sender: TObject);
 begin
-  ISB1.SetFocus;
+  //ISB1.SetFocus;
 end;
 
 procedure TCB_IMGPSScanX.ISB1ImageMouseDown(Sender: TObject; Button: TMouseButton;
@@ -1268,7 +1336,7 @@
   p : Integer;
 begin
   DisplayISB := TImageScrollBox(Sender);
-  DisplayISB.SetFocus;
+  //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;
@@ -1301,12 +1369,19 @@
 procedure TCB_IMGPSScanX.ISB1ImageMouseMove(Sender: TObject; Shift: TShiftState;
   X, Y: Integer);
 begin
-   Edit1.SetFocus;
+   //Edit1.SetFocus;
   //TImageScrollBox(Sender).SetFocus;
   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;
@@ -1561,6 +1636,8 @@
   DivPageFormIDList.Free; //要當分案頁表單清單
   LastInitFormidList.Free;
   LastAddFormidList.Free;
+  SampleFormIDList.Free;
+  ExistImgList.Free;
   //********清單區********
   if FEvents <> nil then FEvents.OnDestroy;
 end;
@@ -1910,7 +1987,7 @@
       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));
@@ -1942,7 +2019,7 @@
           Else
             DocDir := FindLastestDocDir(NowCaseno,DocNo);
 
-
+//ShowMessage('DocNoNeedDiv(DocNo)='+BoolToStr(DocNoNeedDiv(DocNo),true));
           if DocNoNeedDiv(DocNo) then   //要分份數
           begin
             if ((FormCode2Page(FormID) = '01') and (GetDocDir_Page(NowCaseno,DocDir)>0)) or (DocDir = '') then
@@ -2114,9 +2191,21 @@
       //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;
+
       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)]);
@@ -2341,6 +2430,7 @@
 begin
   if TreeView1.Selected = NewTreeNode then  //全刪  //新掃描件
   begin
+
     If Messagedlg(_Msg('是否刪除所有案件?'),mtconfirmation,[mbyes,mbcancel],0) = mrcancel then Exit;
     clearView(1);
     Application.ProcessMessages;
@@ -2355,6 +2445,7 @@
   end
   Else if TreeView1.Selected = MyTreeNode1 then       //案件編號
   begin
+
     If Messagedlg(Format(_Msg('編號(%s)是否刪除?'),[NowCaseno]),mtconfirmation,[mbyes,mbcancel],0) = mrcancel then Exit;
     clearView(1);
     Application.ProcessMessages;
@@ -2399,9 +2490,19 @@
     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);
+    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);
 
@@ -2410,34 +2511,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;
+
     DeleteFormCodeFile(NowCaseNo,NowDocDir,NowFormCode);
     SetRecordEditedDocDir('A',NowCaseNo,NowDocDir);
     DrawDocItem2(MytreeNode1,NowCaseno);
@@ -2445,30 +2523,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;
+  ST.loadFromfile(DocNopath+'\Context.dat');
+//ShowMessage(ST.Text);
+  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);
@@ -2547,171 +2634,328 @@
   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;
+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('檔案加入中,請稍候');
+    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
-      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
+    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;
+
+    FindClose(FileRec);
+    CaseID := NowCaseno;
+    imageCount := 0;
+    P := ISB.ImageCountFromFile(OpenDialog1.FileName);
+    For i := 1 To P Do
+    Begin
+      ShowText := _Msg('檔案加入中,請稍候(' + inttostr(i) + '/' + inttostr(P) + ')');
+      DataLoading(True, True);
+      ISB.LoadFromFile(FName, i);
+      // ISB.SaveToFile('C:\OCX\aaaaaa'+IntToStr(i)+'.tif');
+      DeskewImg(ISB.Graphic);
+      // ISB.SaveToFile('C:\OCX\bbbbbb'+IntToStr(i)+'.tif');
+
+      iGraphic_First := TTiffGraphic.Create;
+      iGraphic_sec := TTiffGraphic.Create;
+
+      iGraphic_First.Assign(ISB.Graphic);
+      MpsGetBarcode(ISB.Graphic, MpsBarcodeinf); //判斷A3 有用FormID 所以要先辨條碼
+      //有必要的話先把影像轉正 再開始切圖
+      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;
+
+      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
-          begin
-            if MpsBarcodeinf.r180[n] <> 0 then  //依條碼角度轉影像
-            begin
-              Rotate(ISB.Graphic,MpsBarcodeinf.r180[n]);
-              MpsGetBarcode(ISB.Graphic,MpsBarcodeinf);
+          MpsGetBarcode(iGraphic, MpsBarcodeinf);
+          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;
-          FormID := BarCode2FormID; //取出FormID
+            End;
+          End;
+          FormID := BarCode2FormID;
+          // 取出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   //要分份數
-          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 := FindLastestDocDir(CaseID, DocNo);
+          If DocNoNeedDiv(DocNo) 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);
-          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+'\';
+            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
-          begin
-            if imageCount = 0 then
-            begin
-              SetCaseList('A',-1,CaseID);
-              MyTreeNode1 := TreeView1.Items.AddChild(NewTreeNode,CaseID);
+          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 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;
+
+          // Rotate(ISB.Graphic,MpsBarcodeinf.r180[n]);  //20170705 加入有條碼就轉正
+          // ISB.SaveToFile(SavePath+SaveFilename);
+
+          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;
+          // Rotate(ISB.Graphic,MpsBarcodeinf.r180[n]); //20170705 加入有條碼就轉正
+
+          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;
 end;
+
+
+  End;
+End;
+
+
 
 procedure TCB_IMGPSScanX.PM106Click(Sender: TObject);
 var
@@ -2826,7 +3070,7 @@
     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);
@@ -3181,14 +3425,36 @@
       PM104.Visible := True;   //檔案加入影像
     end;
 
-    if FMode='ESCAN' then
+    if FModeName='異動件' 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='異動件' then
+    begin
+      PM101.Visible := True;
+    end;
+
     if not CaseDelete_Enable(NowCaseno) then //
       PM101.Enabled := False
     else
@@ -3196,25 +3462,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='異動件' then
+    begin
+      PM101.Visible := True;
+    end;
+
     if GetUseCase('T',DisplayPath,NowDocDir) <> '' then   //沒有被引用走的
       PM101.Enabled := False    //刪除
     Else
@@ -3223,10 +3503,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
@@ -3234,10 +3514,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='異動件' then
+    begin
+      PM101.Visible := True;
+    end;
+
     if GetUseCase('T',DisplayPath,NowDocDir) <> '' then   //被引用走的
     begin
       PM101.Enabled := False;   //刪除
@@ -3252,22 +3548,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;
 
@@ -3321,28 +3607,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<>'異動件' 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);
@@ -3377,6 +3687,7 @@
 var
   SampleFormID : String;
   SendData : String;
+  buttonSelected : Integer;
 begin
   ScanMode := smSample;
   ClearView(1);
@@ -3389,6 +3700,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+'已有範本,是否取代?',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
@@ -3640,7 +3964,7 @@
   //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));
 
@@ -3674,8 +3998,15 @@
     'FCaseNoLength='+ IntToStr(FCaseNoLength)   +#10#13+
     'FImgDelete='+    FImgDelete+#10#13+
     'FIsExternal='+    FIsExternal+#10#13+
+    'FWH_category='+FWH_category+
     'FCheck_main_form='+    FCheck_main_form);
-
+    //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);
@@ -3686,6 +4017,8 @@
   //Showmessage(self.Doc_Inf_List.Text);
   //LoadImgFile;
   //LoadImgFile1;
+  //ISB1.MouseMode:=mmAmplifier;
+
   str:='';
   for I := 1 to 11 do // 看 OMRErrInfo 的內容
   begin
@@ -3701,6 +4034,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;
@@ -3718,6 +4059,7 @@
   ScanInfo.Graphic := TTiffGraphic.Create;
   try
     ISB := nil; //規零
+//ShowMessage(IntToStr(ScanDpi));
     Scanner.RequestedXDpi := ScanDpi;
     Scanner.RequestedYDpi := ScanDpi;
     Scanner.RequestedImageFormat := ScanColor;
@@ -4040,6 +4382,9 @@
             FormID := NowGuideFormID;
           DocNo := FormCode2DocNo(FormID);
 //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
 
@@ -4051,7 +4396,7 @@
             ScanCaseno := BarCode2CaseID; //取出案件編號
             NowGuideFormID := '';
             NowDivPageFormID :='';
-//ShowMessage('NowGuideFormID='+NowGuideFormID+#10#13+'FormID='+FormID+#10#13+'ScanCaseno='+ScanCaseno);
+//ShowMessage('B NowGuideFormID='+NowGuideFormID+#10#13+'FormID='+FormID+#10#13+'ScanCaseno='+ScanCaseno);
           end;
           if ScanCaseno = '' then //一開始都沒找到
           begin
@@ -4440,21 +4785,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
@@ -4465,6 +4828,8 @@
       OMRRect.Bottom := ImageScrollBox1.Graphic.Height;
 
     result := Get_OMR(ISB_BW.Graphic,OMRRect);
+//ShowMessage('result='+IntToStr(result));
+
   end;
 end;
 
@@ -4506,7 +4871,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);
@@ -4520,7 +4885,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);
@@ -4546,7 +4911,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;
@@ -4749,6 +5114,7 @@
   Md : TMouseMode;
   ISB : TImageScrollBox;
 begin
+//ShowMessage(IntToStr(v));
   case v of
    -1 : Md := TMouseMode(mmUser);
     0 : Md := TMouseMode(mmAmplifier);
@@ -4763,6 +5129,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;
 
@@ -4843,6 +5210,39 @@
     ServerTime := Copy(ServerDate,9,6);
     ServerDate := Copy(ServerDate,1,8);
     Balance := GetBalance(ServerTime); //Server 跟Local的時間差
+    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.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
@@ -5212,8 +5612,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
@@ -5250,6 +5653,15 @@
     begin
       if FileName2FormCode(FileList.Strings[i]) = FormID then
       begin
+        if (FMode = 'ESCAN') and (FModeName<>'異動件') 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;
@@ -5307,6 +5719,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;
@@ -5351,6 +5797,14 @@
       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;
         FormCode := FileName2FormCode(S.Strings[n]);
 //Showmessage('1:'+version+','+FormCode2Version(FormCode)+','+DocNo+','+FormCode2DocNo(FormCode)+','+iPage+','+FormCode2Page(FormCode));
         if (version = FormCode2Version(FormCode)) and (DocNo = FormCode2DocNo(FormCode)) and (ipage = FormCode2Page(FormCode)) then
@@ -5380,6 +5834,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
@@ -5445,7 +5906,7 @@
     DW := GetFindResult('T1.FORM_WIDTH');
     ANCHOR := UpperCase(GetFindResult('T1.ANCHOR'));
     ANCHOR := Index2Anchor(ANCHOR);
-//showmessage(FormID+#13+DH+#13+DW+#13);
+Display1.Lines.Add(FormID+','+DH+','+DW);
 //ShowMessage('AAAAAAAAA');
     if ((ANCHOR = 'ANCHOR') or (ANCHOR = 'FRAME')) and (DH <> '') and (DW <> '') then  //有十字定位點
     begin
@@ -5605,6 +6066,7 @@
   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
@@ -5612,14 +6074,13 @@
     if (Pos('_',St1.Strings[i])<>1) and (Pos('_',St1.Strings[i])<>-11) 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
@@ -5627,19 +6088,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///////////////////////////////
@@ -5685,8 +6142,6 @@
   +'&in_doc2='+HTTPEncode(UTF8Encode(In_Doc2));
 //ShowMessage('SendData='+SendData);
 //ShowMessage(FData+#10#13+Doc_Data);
-
-//exit;
   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);
@@ -5964,7 +6419,7 @@
     Result := False;
     Exit;
   end;
-//ShowMessage('sssss');
+//ShowMessage('替換zip');
   AttPath := Path + 'AttFile\';
   if FileExists(Path+CaseID+'.zip') then
   begin
@@ -6276,6 +6731,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]) then
+        begin
+          Continue;
+        end;
+      end;
       FormCode := FileName2FormCode(S.Strings[i]);
       DocNo := FormCode2DocNo(FormCode);
       Ver := FormCode2Version(FormCode);
@@ -6426,7 +6888,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);
 
@@ -6438,7 +6901,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;
@@ -6452,7 +6915,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');
@@ -6470,6 +6933,7 @@
   //DocNo:String;
 begin
   //DocNo := FormCode2DocNo(FileName2FormCode(FileName));
+//ShowMessage('FileName='+FileName);
   if DocDir = '' then
     DocDir := AttName ; //附件
   ContextList.Clear;
@@ -6559,6 +7023,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;
@@ -6765,13 +7247,14 @@
 
 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');
@@ -6786,11 +7269,35 @@
       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;
+      end;
+
+
       Count := Count+ FileList.Count;
     end;
     if FileExists(Path+CaseID+'\'+AttName+'\Context.dat') then
@@ -6803,6 +7310,7 @@
   finally
   DocDirList.Free;
   FileList.Free;
+  ST1.free;
   end;
 end;
 
@@ -6880,8 +7388,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;
@@ -6889,19 +7397,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
@@ -6913,14 +7425,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;
@@ -6993,8 +7532,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;
@@ -7586,6 +8129,7 @@
   ErrlistForm : TErrlistForm;
   S : TStringlist;
   UpFormID : String;
+  Anchor : String;
 begin
   ShowText := _Msg('處理檢核失敗中,請稍候');
   DataLoading(True,True);
@@ -7602,7 +8146,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('資料上傳中,請稍候');
@@ -7708,12 +8252,14 @@
   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;
   try
     CaseNode.ImageIndex := 1;
     CaseNode.SelectedIndex := 1;
@@ -7732,19 +8278,47 @@
       //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;
+//ShowMessage(FileList.Text);
+      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;
+
+
+      if FileList.Count=0 then Continue;
+
+
+//Showmessage('aaa '+FileList.Text);
       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]));
@@ -7842,6 +8416,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')
@@ -7871,11 +8446,48 @@
         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.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.ImageIndex := 4;
+            FormNode.SelectedIndex := 4;
+          end;
+        end;
+      end;
+    end;
+
   Finally
   FileList.Free;
   CaseDocNoList.Free;
   CaseDocNo_CopiesList.Free;
   StrList.Free;
+  ST1.Free;
   end;
 end;
 
@@ -8178,14 +8790,35 @@
     if (Pos('_',St1.Strings[i])<>1) and (Pos('_',St1.Strings[i])<>-11) 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;  //載入新件及替換件
@@ -8232,6 +8865,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;
@@ -8515,7 +9149,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;
@@ -8597,6 +9231,8 @@
     end;
 
   end;
+
+//ShowMessage('FormIDCount='+IntToStr(FormIDCount)+#10#13+'MpsBarcodeinf.count='+IntToStr(MpsBarcodeinf.count));
   if FormIDCount = 2 then
   begin
     Result := True;
@@ -8622,6 +9258,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);
@@ -8816,6 +9458,7 @@
   S := TStringlist.Create;
   GraphicPrinter := TDibGraphicPrinter.Create;
   PrtDialog := TPrintDialog.Create(self);
+  //PrtDialog.Copies:=99;
   try
     IF PrtDialog.Execute Then
     begin
@@ -9471,6 +10114,20 @@
      ((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是否可出現
@@ -9480,6 +10137,7 @@
      ((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數量
@@ -9698,6 +10356,18 @@
       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;
 
@@ -10135,6 +10805,12 @@
       end;
     end;}
 
+    if FMode='ESCAN' then
+    begin
+      InitExistImgList(DeDir);
+    end;
+
+
   finally
   iFileList.Free;
   FileList.Free;
@@ -10518,6 +11194,14 @@
     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;
+
       LForm := FileName2FormCode(S.Strings[i]);
       AddOk := True;
       for n := 0 to OMRFileList.Count - 1 do
@@ -10568,6 +11252,8 @@
   OMROkCount : Integer;
   //Casecheck : Boolean;  //是否要做檢核
   //AllCheck : Boolean;  //是否要做完整檢核
+
+  ISB8W,ISB8H:integer;
 begin
   ///OMRErrInfo  1: 必要文件  2:相依文件 3:互斥文件  4:必填 5:欄位有值附文件  6:欄位有值不附文件
   ///            7: 欄位有值相關欄位也要有值  8:欄位有值要寫備註 9:停用日期 10:最大頁數
@@ -10598,23 +11284,24 @@
 //ShowMessage('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);
           if ModeNeedCheck(OMRErrInfo[1].Mode,FMode) then //是否要檢核
           begin
             for i := 0 to DocNo_VerinCase.Count - 1 do
@@ -10657,6 +11344,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
@@ -10674,6 +11368,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
@@ -10726,8 +11427,16 @@
       DistinctFormCode(CaseID);
       if ModeNeedCheck(OMRErrInfo[10].Mode,FMode) then //是否要檢核
       begin
+//ShowMessage('AAA'+OMRFileList.Text);
         For i := 0 to OMRFileList.Count - 1 do
         begin
+          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);
 
@@ -10750,22 +11459,31 @@
       DistinctFormCode(CaseID);
       ValueXT := TXmltool.Create;
       Try
+//ShowMessage('必填'+OMRFileList.Text);
         For i := 0 to OMRFileList.Count - 1 do
         begin
+//          if FWH_category='N' then
+//          begin
+//            if ISExistImg(ImageSavePath+CaseID+'\upload\'+OMRFileList.Strings[i]) then
+//            begin
+//              Continue;
+//            end;
+//          end;
           OMRFile := OMRFileList.Strings[i];
           OMRFormCode := FileName2FormCode(OMRFileList.Strings[i]);
           OMRFormName := FormCode2FormName(CaseID,OMRFormCode);
           Anchor := FormID2Anchor(OMRFormCode);
           ///依十字定位點縮放////
           ImageReSize_FormID(CaseID,OMRFile);
-          ////依十字定位點縮放////
+          ////依十字定位點縮放///
+//Display1.Lines.Add('OMRFile='+OMRFile+',OMRFormCode='+OMRFormCode+',OMRFormName='+OMRFormName);
           if not FileExists(CheckXmlPath+OMRFormCode+'.xml') then  //沒有Xml就不用檢核
             Continue;
 
 
           XT := TXmltool.Create(CheckXmlPath+OMRFormCode+'.xml');
           RelaXT := TXmltool.Create;
-
+//ShowMessage('ModeNeedCheck='+BoolToStr(ModeNeedCheck(OMRErrInfo[4].Mode,FMode),true));
           try
             //*******必填********
             if ModeNeedCheck(OMRErrInfo[4].Mode,FMode) then //是否要檢核
@@ -10790,6 +11508,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');
@@ -10831,6 +11552,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
                   ////有填寫////
@@ -10849,6 +11571,11 @@
                       RelaFormName := FormCode2FormName(CaseID,RelaFormCode);
                       Anchor1 := FormID2Anchor(RelaFormCode);
                       RelaXT.LoadFromFile(CheckXmlPath+RelaFormCode+'.xml');
+Display1.Lines.Add(RelaFile+','+RelaFormName);
+                      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  抓相關然欄位所在圖檔的定位
                       OMROK := False;
                       //OMROK := False;
                       //if RelaXT.SubNodes['/form/settype2/'].First then
@@ -10869,17 +11596,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
@@ -10919,6 +11647,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
@@ -10939,6 +11668,10 @@
                     RelaFormName := FormCode2FormName(CaseID,RelaFormCode);
                     Anchor1 := FormID2Anchor(RelaFormCode);
                     RelaXT.LoadFromFile(CheckXmlPath+RelaFormCode+'.xml');
+                    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  抓相關然欄位所在圖檔的定位
                     OMROK := False;
                     //OMROK := False;
                     //if RelaXT.SubNodes['/form/settype2/'].First then
@@ -10959,12 +11692,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
@@ -11010,6 +11747,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
                   ////有填寫////
@@ -11054,6 +11793,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
                   ////有填寫////
@@ -11098,6 +11839,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
                   ////有填寫////
@@ -11128,6 +11872,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;  //有填就換成設定的值
@@ -11372,10 +12118,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 := '影像顯示中,請稍候';
    DataLoading(True,True);
+ST1:=TStringList.Create;
+//Display1.Lines.Clear;
    IF DocNo = 'ShowAll' then  //顯示所有的影像 (因為附件會傳空字串,所以用ShowAll)
    begin
      ClearView(1);
@@ -11385,29 +12134,57 @@
        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);
@@ -11416,6 +12193,7 @@
          ISB.Redraw(true);
 
        end;
+
      end;
      //if DirectoryExists(Path+'Attach') then
      if DirectoryExists(Path+AttName) then
@@ -11435,18 +12213,38 @@
          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;
@@ -11468,60 +12266,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);
            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;
@@ -11638,6 +12418,7 @@
   ISB : TImageScrollBox;
   Panel : TPanel;
   i,W,H : Integer;
+  myDate : TDateTime;
 begin
   FreePreViewISB;
   ScrollBox1.HorzScrollBar.Visible := False;
@@ -11645,32 +12426,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;
@@ -11679,25 +12466,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;
 
@@ -11844,6 +12635,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);
@@ -12560,6 +13354,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;
@@ -13026,6 +13821,9 @@
   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;
@@ -13135,6 +13933,8 @@
   DivPageFormIDList := TStringList.Create; //要當分案頁表單清單
   LastInitFormidList :=TStringList.Create;
   LastAddFormidList := TStringList.Create;
+  SampleFormIDList := TStringList.Create;//20170627 加入
+  ExistImgList := TStringList.Create;  //20170724 新增
   //********清單區********
 
   ShowText := _Msg('資料載入中,請稍候');
@@ -13146,6 +13946,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  文件資訊
@@ -13219,14 +14032,19 @@
   initkscan;
   if ImagePath[Length(ImagePath)] <> '\' then
     ImagePath := ImagePath + '\';
+//ShowMessage('ImagePath='+ImagePath);
   CheckXmlPath := ImagePath+'OMRSITE\'+FWork_No;
+//ShowMessage('CheckXmlPath='+CheckXmlPath);
   SitePath := ImagePath+'Site\'+FWork_No+'\';
   LngPath := ImagePath;
   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+'\';
-//ShowMessage('ImagePath='+ImagePath);
+  ImagePath := StringReplace(ImagePath, '\\', '\',[rfReplaceAll, rfIgnoreCase]);
+//ShowMessage('BB  ImagePath='+ImagePath);
   ImageSavePath := ImagePath;
   str2dir(CheckXmlPath);
   str2dir(SitePath);
@@ -13335,8 +14153,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;
@@ -13354,11 +14175,9 @@
   Splitter2.Visible := True;
   AttFileGB.Visible := False; //附加電子檔窗
   Splitter2.Visible := False; }
-
+//ShowMessage('ImageSavePath='+ImageSavePath);
   DataLoading(False,False);
-//ShowMessage('初始話執行完成');
-//ShowMessage('GuideFormIDList='+GuideFormIDList.Text);
-//ShowMessage('DivPageFormIDList='+DivPageFormIDList.Text);
+
 end;
 
 procedure TCB_IMGPSScanX.Timer2Timer(Sender: TObject);
@@ -13398,6 +14217,14 @@
     Showmessage(_Msg('尚有未配號案件,無法上傳'));
     Exit;
   end;
+
+  if not CheckCaseAttach_OK then  //20170911檢查是否有未歸類的案件
+  begin
+    Showmessage(_Msg('尚有未歸類文件,無法上傳'));
+    Exit;
+  end;
+
+
   if NewTreeNode.Count = 0  then
   begin
     Showmessage(_Msg('無影像需傳送'));
@@ -13479,7 +14306,7 @@
           begin
             ShowText := CaseID+_Msg('檢核中,請稍候');
             DataLoading(True,True);
-            If not OMRCheckCase(CaseID) then
+            If not OMRCheckCase(CaseID) then  //進檢核
             begin
               Inc(CheckErrCount);
               Continue;
@@ -13495,7 +14322,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);
@@ -13547,7 +14374,6 @@
   NowDocNo := '';
   NowFormCode := '';
   NowFormName := '';
-
   NowPage := 0;
   NowShowFileList.Clear;
   StatusBar1.Panels[2].Text := '';
@@ -13967,7 +14793,15 @@
 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.TreeView1MouseMove(Sender: TObject; Shift: TShiftState;
@@ -14363,6 +15197,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,

--
Gitblit v1.8.0