瀏覽代碼

修改发票云发票状态

yaoyu 2 年之前
父節點
當前提交
632d685187

+ 345 - 349
pu/pu/src/client/nc/pub/filesystem/newui/ThOCRAction.java

@@ -1,349 +1,345 @@
-package nc.pub.filesystem.newui;
-
-import java.awt.event.ActionEvent;
-import java.io.File;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Enumeration;
-import java.util.List;
-
-import javax.swing.AbstractAction;
-import javax.swing.Action;
-
-import org.apache.commons.httpclient.HttpException;
-
-import com.alibaba.fastjson.JSONArray;
-import com.alibaba.fastjson.JSONObject;
-
-import nc.bs.framework.common.NCLocator;
-import nc.bs.framework.common.RuntimeEnv;
-import nc.funcnode.ui.action.AbstractNCAction;
-import nc.itf.bd.defdoc.IDefdocService;
-import nc.itf.th.IThOcrService;
-import nc.itf.uap.IUAPQueryBS;
-import nc.jdbc.framework.processor.BeanListProcessor;
-import nc.jdbc.framework.processor.ColumnProcessor;
-import nc.ui.ml.NCLangRes;
-import nc.ui.pub.beans.MessageDialog;
-import nc.vo.bd.defdoc.DefdocVO;
-import nc.vo.pub.BusinessException;
-
-
-
-public class ThOCRAction extends AbstractNCAction{
-
-	/**
-	 * OCR识别
-	 */
-	private static final long serialVersionUID = -5178574564280732585L;
-	private static final String upurl="https://up.mypiaojia.com/api/invoiceApi/file/uploadFileSpilit";
-	private static final String inverurl="https://api.mypiaojia.com/api/invoiceApi/invoice/ocr";
-	private static final String appId="773676128773832704";
-	private static final Long   cid=773676128725336064l;
-	private static final String secret="6726dea9883f4f6bb2725ac8750d01de";
-	private static final String useid="2108";
-	private IUAPQueryBS iuap= (IUAPQueryBS) NCLocator.getInstance().lookup(IUAPQueryBS.class.getName());
-	private ThFileContentPanel parentpanel ;
-	public ThOCRAction(ThFileContentPanel para){
-		parentpanel = para;
-		this.putValue(AbstractAction.NAME,"OCR识别");
-		this.putValue(Action.SHORT_DESCRIPTION, "OCR识别");
-	}
-
-	@Override
-	public void actionPerformed(ActionEvent actionevent) {
-		MessageDialog.showHintDlg(parentpanel, "提示","开始OCR识别!");
-		
-		String vdef17 =(String) parentpanel.editor_.getBillCardPanel().getHeadItem("vdef17").getValueObject();//附件id
-		String pk_org = (String) parentpanel.editor_.getBillCardPanel().getHeadItem("pk_org").getValueObject();
-		String pk_group = (String) parentpanel.editor_.getBillCardPanel().getHeadItem("pk_group").getValueObject();
-		
-		IThOcrService  ocrservice=(IThOcrService) NCLocator.getInstance().lookup(IThOcrService.class.getName());
-		
-//		IInvoiceOCRMaintain iInvoiceOCRMaintain = (IInvoiceOCRMaintain) NCLocator.getInstance().lookup(IInvoiceOCRMaintain.class.getName());
-		
-//		String filepath =  RuntimeEnv.getInstance().getNCHome()
-//			      +File.separator +"uploadfile" + File.separator+ vdef17; // 文件保存的路径
-//		List<String> filewjlis=getFileNames(filepath);
-		
-		List<String> filewjlis=ocrservice.getInvoiceInfo(vdef17);//获取"+vdef17+"文件夹下所有发票名
-		
-		 if(null==filewjlis||filewjlis.size()==0){
-	        	MessageDialog.showErrorDlg(parentpanel, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000000")/*错误*/
-						,"请先上传发票,再进行OCR识别!");
-				return;
-	      }
-		 
-		 
-		//获取token
-		String token="";
-		try {
-			 token=ocrservice.getToken(appId,cid,secret,useid);
-		} catch (HttpException e) {
-	//		Logger.error(e.getMessage(), e);
-			MessageDialog.showErrorDlg(parentpanel, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000000")/*错误*/
-					,"获取token:\n"+e.getMessage());
-			return;
-		} catch (IOException e) {
-			MessageDialog.showErrorDlg(parentpanel, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000000")/*错误*/
-					,"获取token:\n"+e.getMessage());
-			return;
-		} catch (BusinessException e) {
-			MessageDialog.showErrorDlg(parentpanel, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000000")/*错误*/
-					,"获取token:\n"+e.getMessage());
-			return;
-		}
-		
-//		MessageDialog.showHintDlg(parentpanel, "提示","token:"+token);
-		StringBuffer sb=new StringBuffer();
-		StringBuffer sb2=new StringBuffer();
-		StringBuffer sb3=new StringBuffer();
-		for(int i=0;i<filewjlis.size();i++){
-		//	File file=new File(filepath+File.separator+filewjlis.get(i));
-			//发票上传
-			String idjson="";
-			try {
-//				idjson=ocrservice.uploadInvoice(upurl,token, file);
-				idjson=ocrservice.uploadInvoice(upurl,token, vdef17,filewjlis.get(i));
-			} catch (Exception e) {
-				MessageDialog.showErrorDlg(parentpanel, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000000")/*错误*/
-						,"发票上传:\n"+e.getMessage());
-				return;
-			}
-			
-			sb.append(idjson).append("\n");
-			
-			//发票识别
-			String ocrinvoicejson=ocrservice.ocrIdentification(inverurl, token,idjson);
-			sb2.append(ocrinvoicejson).append("\n");
-			
-            //识别数据保存数据库 add by pcy
-//			JSONObject json =iInvoiceOCRMaintain.startInvoiceOCR(file);
-			JSONObject json = JSONObject.parseObject(ocrinvoicejson);
-			String checkresult;
-			try {
-				checkresult = checkJson(json);
-				if(checkresult != null){
-					MessageDialog.showErrorDlg(parentpanel, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000000")/*错误*/
-							,"ocr返回数据校验:\n"+checkresult);
-					return;
-				}
-			} catch (Exception e) {
-				// TODO 自动生成的 catch 块
-				e.printStackTrace();
-			}
-			JSONObject data = json.getJSONObject("data");
-			JSONArray infos = data.getJSONArray("infos");
-			for(int j = 0;j < infos.size();j++){
-				JSONObject info = infos.getJSONObject(j).getJSONObject("info");
-//				String code = info.getString("code");//发票代码
-				String fid = info.getString("fid");
-				String ext = info.getString("ext");
-				JSONObject extobj = JSONObject.parseObject(ext);
-				String trate = extobj.getString("trate");//税率
-				
-				JSONArray flist = info.getJSONArray("flist");
-				String name = filewjlis.get(i);
-				String memo = info.getString("number");//发票号
-				String code = info.getString("number");//发票代码
-				JSONObject comm_info = info.getJSONObject("comm_info");
-				JSONObject pro = comm_info.getJSONObject("pro");
-				String date = pro.getString("date");//发票日期
-				String type = pro.getString("type");//发票类型
-				String cname = pro.getString("cname");//发票类型名称
-				JSONObject price = comm_info.getJSONObject("price");
-				String amount = "";
-				String total = "";
-				String dtax = "";
-				//专票带税额,不是专票无税金额=价税合计
-				if(type.equals("1")||type.equals("28")){
-					amount = price.getString("amount");//无税金额
-					total = price.getString("total");//价税合计
-					dtax = price.getString("dtax");//可抵扣税额
-				}
-				else{
-					amount = price.getString("total");//无税金额
-					total = amount;//价税合计
-					dtax = "0";//可抵扣税额
-					trate = "0";//非专票税率也为0
-				}
-				JSONObject buyer = comm_info.getJSONObject("buyer");
-				String mnecode = buyer.getString("tcode");//购买方纳税人识别号
-				String name2 = buyer.getString("company");//购买方公司名称
-				JSONObject payer = comm_info.getJSONObject("payer");
-				String name3 = payer.getString("tcode");//销售方纳税人识别号
-				String name4 = payer.getString("company");//购买方公司名称
-				
-				IDefdocService idefservice = NCLocator.getInstance().lookup(IDefdocService.class);
-				
-				DefdocVO[] updatevos=QryDefdocvoInfo(code);
-				
-				if(updatevos.length>0){
-					//自定义档案存在这个编码,走修改
-					DefdocVO defvo =updatevos[0];
-					//赋值
-//					defvo.setAttributeValue("name", name);
-//					defvo.setAttributeValue("memo", memo);
-					defvo.setAttributeValue("name", memo);
-					defvo.setAttributeValue("memo", name);
-					defvo.setAttributeValue("mnecode", mnecode);
-					defvo.setAttributeValue("name2", name2);
-					defvo.setAttributeValue("name3", name3);
-					defvo.setAttributeValue("name4", name4);
-					defvo.setAttributeValue("name5", fid);
-					defvo.setAttributeValue("name6", vdef17);
-					defvo.setAttributeValue("shortname", amount);
-					defvo.setAttributeValue("shortname2", total);
-					defvo.setAttributeValue("shortname3", dtax);
-					defvo.setAttributeValue("shortname4", date);
-					defvo.setAttributeValue("shortname5", cname);
-					defvo.setAttributeValue("shortname6", trate);
-					defvo.setAttributeValue("enablestate", 2);
-					try {
-						idefservice.updateDefdocs(pk_group,updatevos);
-					} catch (BusinessException e1) {
-						MessageDialog.showErrorDlg(parentpanel, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000000")/*错误*/
-								,"修改自定义档案数据:\n"+e1.getMessage());
-						return;
-					}
-				}else{
-					DefdocVO[] vos = new DefdocVO[1];
-					DefdocVO defvo = new DefdocVO();
-					//赋值
-					defvo.setAttributeValue("code", code);
-//					defvo.setAttributeValue("name", name);
-//					defvo.setAttributeValue("memo", memo);
-					defvo.setAttributeValue("name", memo);
-					defvo.setAttributeValue("memo", name );
-					defvo.setAttributeValue("mnecode", mnecode);
-					defvo.setAttributeValue("name2", name2);
-					defvo.setAttributeValue("name3", name3);
-					defvo.setAttributeValue("name4", name4);
-					defvo.setAttributeValue("name5", fid);
-					defvo.setAttributeValue("name6", vdef17);
-					defvo.setAttributeValue("pk_defdoclist", QryOCRPk());
-					defvo.setAttributeValue("pk_group", pk_group);
-				//	defvo.setAttributeValue("pk_org", pk_org);
-					defvo.setAttributeValue("pk_org", pk_group);
-					defvo.setAttributeValue("datatype", 1);
-					defvo.setAttributeValue("enablestate", 2);
-					defvo.setAttributeValue("shortname", amount);
-					defvo.setAttributeValue("shortname2", total);
-					defvo.setAttributeValue("shortname3", dtax);
-					defvo.setAttributeValue("shortname4", date);
-					defvo.setAttributeValue("shortname5", cname);
-					defvo.setAttributeValue("shortname6", trate);
-					vos[0] = defvo;
-					try {
-				//		idefservice.insertDefdocs(pk_org, vos);
-						idefservice.insertDefdocs(pk_group, vos);
-					} catch (BusinessException e) {
-						// TODO 自动生成的 catch 块
-						//ExceptionUtils.wrappBusinessException(e.getMessage());
-						MessageDialog.showErrorDlg(parentpanel, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000000")/*错误*/
-									,"保存自定义档案数据:\n"+e.getMessage());
-						return;
-					}
-				}
-				
-
-			}
-			
-		}
-		
-/*		MessageDialog.showHintDlg(parentpanel, "提示","发票上传json:\n"+sb.toString());
-		MessageDialog.showHintDlg(parentpanel, "提示","ocr识别json:\n"+sb2.toString());
-//		MessageDialog.showHintDlg(parentpanel, "提示","ocr识别YY:\n"+sb3.toString());*/
-		MessageDialog.showHintDlg(parentpanel, "提示","识别成功!");
-	}
-	
-
-	/**
-     * 得到文件名称
-     *
-     * @param path 路径
-     * @return {@link List}<{@link String}>
-     */
-   /* private  List<String> getFileNames(String path) {
-        File file = new File(path);
-        if (!file.exists()) {
-            return null;
-        }
-        List<String> fileNames = new ArrayList<String>();
-        return getFileNames(file, fileNames);
-    }*/
-
-/**
-     * 得到文件名称
-     *
-     * @param file      文件
-     * @param fileNames 文件名
-     * @return {@link List}<{@link String}>
-     */
-/*    private  List<String> getFileNames(File file, List<String> fileNames) {
-        File[] files = file.listFiles();
-        for (File f : files) {
-            if (f.isDirectory()) {
-                getFileNames(f, fileNames);
-            } else {
-                fileNames.add(f.getName());
-            }
-        }
-        return fileNames;
-    }*/
-    
-    private String checkJson(JSONObject json) throws Exception {
-		
-  		StringBuffer mags = new StringBuffer();
-  		Boolean empty = true;
-  		
-  		JSONObject oprepObjectBs = json.getJSONObject("data");
-  		
-  		if (oprepObjectBs == null || oprepObjectBs.size() == 0) {
-  			return "返回值不可为空!";
-  		}
-  		
-  		
-  		return null;
-  	}
-      
-      //查询自定义档案的pk
-      private String QryOCRPk(){
-      	String sql = "select pk_defdoclist from bd_defdoclist where code='OCRTHNC' and nvl(dr,0)=0";
-      	Object object = null;
-  		try {
-  			object = iuap.executeQuery(sql, new ColumnProcessor());
-  		} catch (BusinessException e) {
-  			// TODO 自动生成的 catch 块
-  			e.printStackTrace();
-  		}
-  		if (object==null) {
-  			return null;
-  		}else {
-  			return object.toString();
-  		}
-      }
-      
-      
-      
-    @SuppressWarnings("unchecked")
-	private DefdocVO[]  QryDefdocvoInfo(String code){
-        	String sql = "select * from  bd_defdoc where  nvl(dr, 0) = 0 and pk_defdoclist="
-        			+ "(select pk_defdoclist from bd_defdoclist where code='OCRTHNC' and nvl(dr,0)=0) and code='" + code + "' ";
-        	ArrayList<Object> arrayvos=null;
-        	try {
-				arrayvos=(ArrayList<Object>) iuap.executeQuery(sql, new BeanListProcessor(DefdocVO.class));
-			} catch (BusinessException e) {
-				// TODO 自动生成的 catch 块
-				e.printStackTrace();
-			}
-        	
-        	if (arrayvos==null||arrayvos.size()==0) {
-      			return new DefdocVO[0];
-      		}else {
-      			return arrayvos.toArray(new DefdocVO[0]);
-      		}
-        	
-        } 
-      
-}
+package nc.pub.filesystem.newui;
+
+import java.awt.event.ActionEvent;
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Enumeration;
+import java.util.List;
+
+import javax.swing.AbstractAction;
+import javax.swing.Action;
+
+import org.apache.commons.httpclient.HttpException;
+
+import com.alibaba.fastjson.JSONArray;
+import com.alibaba.fastjson.JSONObject;
+
+import nc.bs.framework.common.NCLocator;
+import nc.bs.framework.common.RuntimeEnv;
+import nc.funcnode.ui.action.AbstractNCAction;
+import nc.itf.bd.defdoc.IDefdocService;
+import nc.itf.th.IThOcrService;
+import nc.itf.uap.IUAPQueryBS;
+import nc.jdbc.framework.processor.BeanListProcessor;
+import nc.jdbc.framework.processor.ColumnProcessor;
+import nc.ui.ml.NCLangRes;
+import nc.ui.pub.beans.MessageDialog;
+import nc.vo.bd.defdoc.DefdocVO;
+import nc.vo.pub.BusinessException;
+
+
+
+public class ThOCRAction extends AbstractNCAction{
+
+	/**
+	 * OCR识别
+	 */
+	private static final long serialVersionUID = -5178574564280732585L;
+	
+	
+	private IUAPQueryBS iuap= (IUAPQueryBS) NCLocator.getInstance().lookup(IUAPQueryBS.class.getName());
+	private ThFileContentPanel parentpanel ;
+	public ThOCRAction(ThFileContentPanel para){
+		parentpanel = para;
+		this.putValue(AbstractAction.NAME,"OCR识别");
+		this.putValue(Action.SHORT_DESCRIPTION, "OCR识别");
+	}
+
+	@Override
+	public void actionPerformed(ActionEvent actionevent) {
+		MessageDialog.showHintDlg(parentpanel, "提示","开始OCR识别!");
+		
+		String vdef17 =(String) parentpanel.editor_.getBillCardPanel().getHeadItem("vdef17").getValueObject();//附件id
+		String pk_org = (String) parentpanel.editor_.getBillCardPanel().getHeadItem("pk_org").getValueObject();
+		String pk_group = (String) parentpanel.editor_.getBillCardPanel().getHeadItem("pk_group").getValueObject();
+		
+		IThOcrService  ocrservice=(IThOcrService) NCLocator.getInstance().lookup(IThOcrService.class.getName());
+		
+//		IInvoiceOCRMaintain iInvoiceOCRMaintain = (IInvoiceOCRMaintain) NCLocator.getInstance().lookup(IInvoiceOCRMaintain.class.getName());
+		
+//		String filepath =  RuntimeEnv.getInstance().getNCHome()
+//			      +File.separator +"uploadfile" + File.separator+ vdef17; // 文件保存的路径
+//		List<String> filewjlis=getFileNames(filepath);
+		
+		List<String> filewjlis=ocrservice.getInvoiceInfo(vdef17);//获取"+vdef17+"文件夹下所有发票名
+		
+		 if(null==filewjlis||filewjlis.size()==0){
+	        	MessageDialog.showErrorDlg(parentpanel, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000000")/*错误*/
+						,"请先上传发票,再进行OCR识别!");
+				return;
+	      }
+		 
+		 
+		//获取token
+		String token="";
+		try {
+			 token=ocrservice.getToken();
+		} catch (HttpException e) {
+	//		Logger.error(e.getMessage(), e);
+			MessageDialog.showErrorDlg(parentpanel, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000000")/*错误*/
+					,"获取token:\n"+e.getMessage());
+			return;
+		} catch (IOException e) {
+			MessageDialog.showErrorDlg(parentpanel, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000000")/*错误*/
+					,"获取token:\n"+e.getMessage());
+			return;
+		} catch (BusinessException e) {
+			MessageDialog.showErrorDlg(parentpanel, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000000")/*错误*/
+					,"获取token:\n"+e.getMessage());
+			return;
+		}
+		
+//		MessageDialog.showHintDlg(parentpanel, "提示","token:"+token);
+		StringBuffer sb=new StringBuffer();
+		StringBuffer sb2=new StringBuffer();
+		StringBuffer sb3=new StringBuffer();
+		for(int i=0;i<filewjlis.size();i++){
+		//	File file=new File(filepath+File.separator+filewjlis.get(i));
+			//发票上传
+			String idjson="";
+			try {
+//				idjson=ocrservice.uploadInvoice(upurl,token, file);
+				idjson=ocrservice.uploadInvoice(token, vdef17,filewjlis.get(i));
+			} catch (Exception e) {
+				MessageDialog.showErrorDlg(parentpanel, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000000")/*错误*/
+						,"发票上传:\n"+e.getMessage());
+				return;
+			}
+			
+			sb.append(idjson).append("\n");
+			
+			//发票识别
+			String ocrinvoicejson=ocrservice.ocrIdentification(token,idjson);
+			sb2.append(ocrinvoicejson).append("\n");
+			
+            //识别数据保存数据库 add by pcy
+//			JSONObject json =iInvoiceOCRMaintain.startInvoiceOCR(file);
+			JSONObject json = JSONObject.parseObject(ocrinvoicejson);
+			String checkresult;
+			try {
+				checkresult = checkJson(json);
+				if(checkresult != null){
+					MessageDialog.showErrorDlg(parentpanel, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000000")/*错误*/
+							,"ocr返回数据校验:\n"+checkresult);
+					return;
+				}
+			} catch (Exception e) {
+				// TODO 自动生成的 catch 块
+				e.printStackTrace();
+			}
+			JSONObject data = json.getJSONObject("data");
+			JSONArray infos = data.getJSONArray("infos");
+			for(int j = 0;j < infos.size();j++){
+				JSONObject info = infos.getJSONObject(j).getJSONObject("info");
+//				String code = info.getString("code");//发票代码
+				String fid = info.getString("fid");
+				String ext = info.getString("ext");
+				JSONObject extobj = JSONObject.parseObject(ext);
+				String trate = extobj.getString("trate");//税率
+				
+				JSONArray flist = info.getJSONArray("flist");
+				String name = filewjlis.get(i);
+				String memo = info.getString("number");//发票号
+				String code = info.getString("number");//发票代码
+				JSONObject comm_info = info.getJSONObject("comm_info");
+				JSONObject pro = comm_info.getJSONObject("pro");
+				String date = pro.getString("date");//发票日期
+				String type = pro.getString("type");//发票类型
+				String cname = pro.getString("cname");//发票类型名称
+				JSONObject price = comm_info.getJSONObject("price");
+				String amount = "";
+				String total = "";
+				String dtax = "";
+				//专票带税额,不是专票无税金额=价税合计
+				if(type.equals("1")||type.equals("28")){
+					amount = price.getString("amount");//无税金额
+					total = price.getString("total");//价税合计
+					dtax = price.getString("dtax");//可抵扣税额
+				}
+				else{
+					amount = price.getString("total");//无税金额
+					total = amount;//价税合计
+					dtax = "0";//可抵扣税额
+					trate = "0";//非专票税率也为0
+				}
+				JSONObject buyer = comm_info.getJSONObject("buyer");
+				String mnecode = buyer.getString("tcode");//购买方纳税人识别号
+				String name2 = buyer.getString("company");//购买方公司名称
+				JSONObject payer = comm_info.getJSONObject("payer");
+				String name3 = payer.getString("tcode");//销售方纳税人识别号
+				String name4 = payer.getString("company");//购买方公司名称
+				
+				IDefdocService idefservice = NCLocator.getInstance().lookup(IDefdocService.class);
+				
+				DefdocVO[] updatevos=QryDefdocvoInfo(code);
+				
+				if(updatevos.length>0){
+					//自定义档案存在这个编码,走修改
+					DefdocVO defvo =updatevos[0];
+					//赋值
+//					defvo.setAttributeValue("name", name);
+//					defvo.setAttributeValue("memo", memo);
+					defvo.setAttributeValue("name", memo);
+					defvo.setAttributeValue("memo", name);
+					defvo.setAttributeValue("mnecode", mnecode);
+					defvo.setAttributeValue("name2", name2);
+					defvo.setAttributeValue("name3", name3);
+					defvo.setAttributeValue("name4", name4);
+					defvo.setAttributeValue("name5", fid);
+					defvo.setAttributeValue("name6", vdef17);
+					defvo.setAttributeValue("shortname", amount);
+					defvo.setAttributeValue("shortname2", total);
+					defvo.setAttributeValue("shortname3", dtax);
+					defvo.setAttributeValue("shortname4", date);
+					defvo.setAttributeValue("shortname5", cname);
+					defvo.setAttributeValue("shortname6", trate);
+					defvo.setAttributeValue("enablestate", 2);
+					try {
+						idefservice.updateDefdocs(pk_group,updatevos);
+					} catch (BusinessException e1) {
+						MessageDialog.showErrorDlg(parentpanel, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000000")/*错误*/
+								,"修改自定义档案数据:\n"+e1.getMessage());
+						return;
+					}
+				}else{
+					DefdocVO[] vos = new DefdocVO[1];
+					DefdocVO defvo = new DefdocVO();
+					//赋值
+					defvo.setAttributeValue("code", code);
+//					defvo.setAttributeValue("name", name);
+//					defvo.setAttributeValue("memo", memo);
+					defvo.setAttributeValue("name", memo);
+					defvo.setAttributeValue("memo", name );
+					defvo.setAttributeValue("mnecode", mnecode);
+					defvo.setAttributeValue("name2", name2);
+					defvo.setAttributeValue("name3", name3);
+					defvo.setAttributeValue("name4", name4);
+					defvo.setAttributeValue("name5", fid);
+					defvo.setAttributeValue("name6", vdef17);
+					defvo.setAttributeValue("pk_defdoclist", QryOCRPk());
+					defvo.setAttributeValue("pk_group", pk_group);
+				//	defvo.setAttributeValue("pk_org", pk_org);
+					defvo.setAttributeValue("pk_org", pk_group);
+					defvo.setAttributeValue("datatype", 1);
+					defvo.setAttributeValue("enablestate", 2);
+					defvo.setAttributeValue("shortname", amount);
+					defvo.setAttributeValue("shortname2", total);
+					defvo.setAttributeValue("shortname3", dtax);
+					defvo.setAttributeValue("shortname4", date);
+					defvo.setAttributeValue("shortname5", cname);
+					defvo.setAttributeValue("shortname6", trate);
+					vos[0] = defvo;
+					try {
+				//		idefservice.insertDefdocs(pk_org, vos);
+						idefservice.insertDefdocs(pk_group, vos);
+					} catch (BusinessException e) {
+						// TODO 自动生成的 catch 块
+						//ExceptionUtils.wrappBusinessException(e.getMessage());
+						MessageDialog.showErrorDlg(parentpanel, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000000")/*错误*/
+									,"保存自定义档案数据:\n"+e.getMessage());
+						return;
+					}
+				}
+				
+
+			}
+			
+		}
+		
+/*		MessageDialog.showHintDlg(parentpanel, "提示","发票上传json:\n"+sb.toString());
+		MessageDialog.showHintDlg(parentpanel, "提示","ocr识别json:\n"+sb2.toString());
+//		MessageDialog.showHintDlg(parentpanel, "提示","ocr识别YY:\n"+sb3.toString());*/
+		MessageDialog.showHintDlg(parentpanel, "提示","识别成功!");
+	}
+	
+
+	/**
+     * 得到文件名称
+     *
+     * @param path 路径
+     * @return {@link List}<{@link String}>
+     */
+   /* private  List<String> getFileNames(String path) {
+        File file = new File(path);
+        if (!file.exists()) {
+            return null;
+        }
+        List<String> fileNames = new ArrayList<String>();
+        return getFileNames(file, fileNames);
+    }*/
+
+/**
+     * 得到文件名称
+     *
+     * @param file      文件
+     * @param fileNames 文件名
+     * @return {@link List}<{@link String}>
+     */
+/*    private  List<String> getFileNames(File file, List<String> fileNames) {
+        File[] files = file.listFiles();
+        for (File f : files) {
+            if (f.isDirectory()) {
+                getFileNames(f, fileNames);
+            } else {
+                fileNames.add(f.getName());
+            }
+        }
+        return fileNames;
+    }*/
+    
+    private String checkJson(JSONObject json) throws Exception {
+		
+  		StringBuffer mags = new StringBuffer();
+  		Boolean empty = true;
+  		
+  		JSONObject oprepObjectBs = json.getJSONObject("data");
+  		
+  		if (oprepObjectBs == null || oprepObjectBs.size() == 0) {
+  			return "返回值不可为空!";
+  		}
+  		
+  		
+  		return null;
+  	}
+      
+      //查询自定义档案的pk
+      private String QryOCRPk(){
+      	String sql = "select pk_defdoclist from bd_defdoclist where code='OCRTHNC' and nvl(dr,0)=0";
+      	Object object = null;
+  		try {
+  			object = iuap.executeQuery(sql, new ColumnProcessor());
+  		} catch (BusinessException e) {
+  			// TODO 自动生成的 catch 块
+  			e.printStackTrace();
+  		}
+  		if (object==null) {
+  			return null;
+  		}else {
+  			return object.toString();
+  		}
+      }
+      
+      
+      
+    @SuppressWarnings("unchecked")
+	private DefdocVO[]  QryDefdocvoInfo(String code){
+        	String sql = "select * from  bd_defdoc where  nvl(dr, 0) = 0 and pk_defdoclist="
+        			+ "(select pk_defdoclist from bd_defdoclist where code='OCRTHNC' and nvl(dr,0)=0) and code='" + code + "' ";
+        	ArrayList<Object> arrayvos=null;
+        	try {
+				arrayvos=(ArrayList<Object>) iuap.executeQuery(sql, new BeanListProcessor(DefdocVO.class));
+			} catch (BusinessException e) {
+				// TODO 自动生成的 catch 块
+				e.printStackTrace();
+			}
+        	
+        	if (arrayvos==null||arrayvos.size()==0) {
+      			return new DefdocVO[0];
+      		}else {
+      			return arrayvos.toArray(new DefdocVO[0]);
+      		}
+        	
+        } 
+      
+}

+ 772 - 690
pu/pu/src/private/nc/impl/th/ThOcrServiceImpl.java

@@ -1,690 +1,772 @@
-package nc.impl.th;
-
-import java.io.BufferedOutputStream;
-import java.io.BufferedReader;
-import java.io.ByteArrayOutputStream;
-import java.io.DataOutputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.OutputStreamWriter;
-import java.net.HttpURLConnection;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.UUID;
-import java.io.FileOutputStream;
-import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
-import nc.bs.dao.BaseDAO;
-import nc.bs.dao.DAOException;
-import nc.bs.framework.common.InvocationInfoProxy;
-import nc.bs.framework.common.NCLocator;
-import nc.bs.framework.common.RuntimeEnv;
-import nc.itf.uap.IUAPQueryBS;
-import nc.jdbc.framework.processor.ArrayListProcessor;
-import nc.jdbc.framework.processor.BeanListProcessor;
-import nc.log.NcLog;
-import nc.ui.pub.beans.MessageDialog;
-import nc.vo.bd.defdoc.DefdocVO;
-import nc.vo.pu.m25.entity.InvoiceItemVO;
-import nc.vo.pu.m25.entity.InvoiceVO;
-import nc.vo.pub.BusinessException;
-import nc.bs.framework.common.NCLocator;
-import nc.bs.pub.filesystem.IFileSystemService;
-import nc.itf.uap.IVOPersistence;
-
-import org.apache.commons.codec.digest.DigestUtils;
-import org.apache.commons.httpclient.HttpClient;
-import org.apache.commons.httpclient.HttpException;
-import org.apache.commons.httpclient.methods.PostMethod;
-import org.apache.commons.httpclient.methods.RequestEntity;
-import org.apache.commons.httpclient.methods.StringRequestEntity;
-
-import com.alibaba.fastjson.JSONArray;
-import com.alibaba.fastjson.JSONObject;
-import nc.itf.bd.defdoc.IDefdocService;
-import nc.itf.th.IThOcrService;
-import nc.pub.toolkits.Toolkits;
-import nc.th.redistoken.RedisTokenManager;
-import nc.vo.pub.BusinessException;
-import nc.vo.pub.filesystem.NCFileNode;
-import nc.vo.th.ocr.OCRInvoiceVO;
-import net.sf.json.JSONString;
-/**
- * OCR接口实现
- * @author Administrator
- *
- */
-public class ThOcrServiceImpl implements IThOcrService{
-	
-	private IVOPersistence IVOPersistence = (IVOPersistence) NCLocator.getInstance().lookup(IVOPersistence.class);
-	
-	public String[] insert(ArrayList<?> arrlist) throws BusinessException {
-		return this.IVOPersistence.insertVOList(arrlist);
-	}
-	
-	
-	@Override
-	/**
-	 * 获取token
-	 */
-	public String getToken(String appId,Long cid,String secret,String userid) throws HttpException, IOException, BusinessException {
-		NcLog.info("=======获取token开始=======");
-		//redis中获取用户token
-		String userToken = RedisTokenManager.getToken(userid);
-		//token为空
-		if(Toolkits.isEmpty(userToken)){
-			//调用OCR接口
-			userToken=getOcrToken(appId,cid,secret,userid);
-			//保存到redis,设置失效时间36000秒
-			RedisTokenManager.setTokenTTL(userid,36000, userToken);
-		}
-		NcLog.info("=======token======="+userToken);
-		NcLog.info("=======获取token结束=======");
-		 return userToken;
-	}
-
-	
-	
-	/**
-	 * 上传发票
-	 * @throws Exception 
-	 */
-	public String uploadInvoice(String url,String token,String vdef17,String invoicename) throws Exception {
-		NcLog.info("=======上传发票开始=======");
-		File file=new File(RuntimeEnv.getInstance().getNCHome()
-			      +File.separator +"uploadfile" + File.separator+ vdef17+File.separator+invoicename);
-		String resmsg=httpFilePost(url,token,file);
-		String id="";
-		if(null!=resmsg&&resmsg.indexOf("uploading")!=-1){
-			 JSONObject json = JSONObject.parseObject(resmsg);
-			 JSONObject data=json.getJSONObject("data");
-			 if(null!=data){
-				 id=data.getString("id");
-			 }else{
-				 String msg=json.getJSONObject("res_base").getString("message");
-				 throw new BusinessException(msg);
-			 }
-			
-		}
-		
-		return resmsg;
-	}
-
-
-
-	/**
-	 * OCR识别
-	 */
-	@Override
-	public String ocrIdentification(String pathUrl, String token,String data) {
-		// TODO 自动生成的方法存根
-		 NcLog.info("=======发票OCR识别开始=======");
-		 JSONObject json = JSONObject.parseObject(data);
-		 JSONObject jsonobject = new JSONObject();
-         jsonobject.put("image_index", json.getJSONObject("data").getString("id"));
-         jsonobject.put("fileTypeStr", json.getJSONObject("data").getString("fileType"));
-         jsonobject.put("flag", "13");
-         jsonobject.put("is_save", "0");
-         jsonobject.put("is_sync", "1");
-         jsonobject.put("ocrMap","");
-         jsonobject.put("operate_type",0);
-		 return doPost(pathUrl,token,jsonobject.toString());
-	}
-	
-	
-	/**
-	 * OCR识别数据保存数据库
-	 * @throws BusinessException 
-	 */
-	public void insertOCRdataInfo(ArrayList<OCRInvoiceVO> vos) throws BusinessException {
-		insert(vos);
-	}
-	
-	
-
-	public String getOcrToken(String appId,Long cid,String secret,String userid)  throws HttpException, IOException, BusinessException{
-    	HttpClient httpClient = new HttpClient();
-    	httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
-        httpClient.getHttpConnectionManager().getParams().setSoTimeout(5000);
-        PostMethod postMethod = new PostMethod("https://api.mypiaojia.com/api/invoiceApi/token/buildToken");
-        postMethod.setRequestHeader("content-type", "application/json");
-        postMethod.setRequestHeader("appkey", appId);
-        long l = System.currentTimeMillis();
-        Map<String, Object> map = new HashMap<String, Object>();
-        map.put("role", 1);
-        map.put("name", "dmy06");
-        map.put("name", "dmy06");
-        map.put("userId", userid);//OA用户体系的用户id 2108
-        map.put("cid", cid);
-        String s1 = JSONObject.toJSONString(map);
-        String s2 = s1 + "&time=" + l + "&secret="+secret;
-        String newMd5 = DigestUtils.md5Hex(s2);
-        String s4 = s1 + "&time=" + l + "&md5=" + newMd5;
-        RequestEntity entity = new StringRequestEntity (s4 ,"application/json" ,"UTF-8");
-        postMethod.setRequestEntity(entity);
-        httpClient.executeMethod(postMethod);
-		String responseMsg = postMethod.getResponseBodyAsString().trim();
-		//返回结果{"data":"WEAPPe8Ke9pFzz9fbZ3qCcN6itq1zLHCKOgPmXHz6uIg8eOg","actionMsg":{"code":0,"message":"执行成功"}}
- //       System.out.println("返回结果"+ responseMsg);
-
-		 JSONObject json = JSONObject.parseObject(responseMsg);
-		 String token=json.getString("data");
-		 String status=json.getString("status");
-		 //保存token返回值到日志文件里
-		 NcLog.info("token:"+token);
-		 
-		 if(null!=status){
-			 throw new BusinessException(responseMsg);
-		 }
-		 
-		 return token;
-	  }
-	
-	
-
-
-	 public  String httpFilePost(String uploadUrl,String token, File file) throws Exception {
-		 
-		//File file = new File(file);
-		 String LINEND = "\r\n";
-		 String boundary = UUID.randomUUID().toString();
-		 FileInputStream fileInputStream = new FileInputStream(file);
-	     URL url = new URL(uploadUrl);
-	     HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
-	     httpURLConnection.setDoInput(true);
-	     httpURLConnection.setUseCaches(false);
-	     httpURLConnection.setDoOutput(true);
-	     httpURLConnection.setRequestMethod("POST");
-	     httpURLConnection.setRequestProperty("connection", "keep-alive");
-	     httpURLConnection.setRequestProperty("Charsert", "UTF-8");
-	     httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
-	     httpURLConnection.setRequestProperty("token", token);
-	     httpURLConnection.setRequestProperty("Accept","*/*");
-	     DataOutputStream outStream = new DataOutputStream(httpURLConnection.getOutputStream());
-         StringBuilder stringBuilder = new StringBuilder();
-         stringBuilder.append("--").append(boundary).append(LINEND);
-         stringBuilder.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + LINEND);
-         stringBuilder.append("Content-Type: " + HttpURLConnection.guessContentTypeFromName(file.getName()) + LINEND);
-         stringBuilder.append("Content-Transfer-Encoding: binary"+ LINEND);
-         stringBuilder.append(LINEND);
- //        outStream.write(stringBuilder.toString().getBytes());
-         outStream.writeUTF(stringBuilder.toString());
-    	 InputStream is = new FileInputStream(file);
-    	 byte[] buffer = new byte[1024];
-    	 int len = 0;
-    	 while ((len = is.read(buffer)) != -1){
-    		 outStream.write(buffer, 0, len);
-    	 }
-    	 is.close();
-    	 outStream.write(LINEND.getBytes());
-    	 byte[] end_data = ("--" + boundary + "--" + LINEND).getBytes();
-    	 outStream.write(end_data);
-    	 outStream.flush();
-         fileInputStream.close();
-         String response = readStream(httpURLConnection.getInputStream());
-         outStream.close();
-         httpURLConnection.disconnect(); 
-         NcLog.info("发票上传返回json:"+response);
-		 return response;
-			
-		}
-		 
-		 
-		 private  String readStream(InputStream inputStream) throws IOException {
-		        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
-		        byte[] buffer = new byte[1024];
-		        int bytesRead;
-		        while ((bytesRead = inputStream.read(buffer)) != -1) {
-		            outputStream.write(buffer, 0, bytesRead);
-		        }
-		        byte[] bytes = outputStream.toByteArray();
-		        String result = new String(bytes, "UTF-8");
-		        outputStream.close();
-		        return result;
-		    }
-
-
-
-		 public  String doPost(String pathUrl, String token,String data){
-			OutputStreamWriter out = null;
-	        BufferedReader br = null;
-	        String result = "";
-	        try {
-	        	URL url = new URL(pathUrl);
-	        	//打开和url之间的连接
-	            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
-	            //设定请求的方法为"POST",默认是GET
-	            //post与get的不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。
-	            conn.setRequestMethod("POST");
-	  
-	            //设置30秒连接超时
-	            conn.setConnectTimeout(30000);
-	            //设置30秒读取超时
-	            conn.setReadTimeout(30000);
-	  
-	            // 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在http正文内,因此需要设为true, 默认情况下是false;
-	            conn.setDoOutput(true);
-	            // 设置是否从httpUrlConnection读入,默认情况下是true;
-	            conn.setDoInput(true);
-	  
-	            // Post请求不能使用缓存
-	            conn.setUseCaches(false);
-	  
-	            //设置通用的请求属性
-	            conn.setRequestProperty("accept", "*/*");
-	            conn.setRequestProperty("connection", "Keep-Alive");  //维持长链接
-	            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
-	            conn.setRequestProperty("token", token);
-	  
-	            //连接,从上述url.openConnection()至此的配置必须要在connect之前完成,
-	            conn.connect();
-	  
-	            /**
-	             * 下面的三句代码,就是调用第三方http接口
-	             */
-	            //获取URLConnection对象对应的输出流
-	            //此处getOutputStream会隐含的进行connect(即:如同调用上面的connect()方法,所以在开发中不调用上述的connect()也可以)。
-	            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
-	            //发送请求参数即数据
-	            out.write(data);
-	            //flush输出流的缓冲
-	            out.flush();
-	  
-	            /**
-	             * 下面的代码相当于,获取调用第三方http接口后返回的结果
-	             */
-	            //获取URLConnection对象对应的输入流
-	            InputStream is = conn.getInputStream();
-	            //构造一个字符流缓存
-	            br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
-	            String str = "";
-	            while ((str = br.readLine()) != null){
-	                result += str;
-	            }
-	         //   System.out.println(result);
-	            
-	           /* JSONObject json = JSONObject.parseObject(result);
-	            //获取主要数据
-	            JSONObject datajson = json.getJSONObject("data");
-	            System.out.println("datajson===="+datajson.toString());
-	            JSONArray infosjson = datajson.getJSONArray("infos");
-	            System.out.println("infosjson===="+infosjson.toString());
-	            
-	            for (Object infos : infosjson) {
-	            	JSONObject infosObject =(JSONObject)infos;
-	                String total=infosObject.getJSONObject("info").getJSONObject("comm_info").getJSONObject("price").getString("total");
-	                System.out.println("total===="+total);
-	            }*/
-	            
-	            //关闭流
-	            is.close();
-	            //断开连接,disconnect是在底层tcp socket链接空闲时才切断,如果正在被其他线程使用就不切断。
-	            conn.disconnect();
-	        }catch (Exception e) {
-	            e.printStackTrace();
-	        }finally {
-	            try {
-	                if (out != null){
-	                    out.close();
-	                }
-	                if (br != null){
-	                    br.close();
-	                }
-	            } catch (IOException e) {
-	                e.printStackTrace();
-	            }
-	        }
-	        
-	        NcLog.info("发票OCR识别返回json:"+result);
-	        
-			return result;
-		 }
-		 
-		 /**
-			 * 
-			 *  发票保存到文件夹里
-			 *  vdef17     发票主键
-			 *  fileName 发票名
-			 *  file     选中的发票
-			 * @throws IOException 
-			 */
-			public String saveUploadFile(String vdef17,String fileName,byte[] bytes) throws Exception {
-		/*		NcLog.info("=====发票保存开始=====");
-				String filepath =  RuntimeEnv.getInstance().getNCHome()
-					      +File.separator +"uploadfile" + File.separator+ vdef17; // 文件保存的路径
-				NcLog.info("文件保存的路径:"+filepath);
-				NcLog.info("原文件路径:"+file.getPath());
-				File folder = new File(filepath);
-				if(!folder.exists() && !folder.isDirectory()){
-					folder.mkdirs();
-				}
-				String newFileName = filepath + File.separator + fileName;
-				NcLog.info("文件保存新路径:"+newFileName);
-				FileOutputStream outputStream = new FileOutputStream(newFileName);
-				NcLog.info("=====FileOutputStream=====");
-				FileInputStream fis = new FileInputStream(file);
-		        byte[] buffer = new byte[1024];
-		        int len;
-		        NcLog.info("=====读取发票信息开始=====");
-		        while ((len = fis.read(buffer)) != -1) {
-		            outputStream.write(buffer, 0, len);
-		        }
-		        NcLog.info("=====读取发票信息结束=====");
-		        outputStream.close();
-		        fis.close();
-		        NcLog.info("=====发票保存结束=====");*/
-				
-			//	byte[] bs = Base64.decode(file.trim());
-				
-				NcLog.info("=====发票保存开始=====");
-			//	NcLog.info("=====bytes:"+bytes.length+"=====");
-				String filepath =  RuntimeEnv.getInstance().getNCHome()
-					      +File.separator +"uploadfile" + File.separator+ vdef17; // 文件保存的文件夹
-				String newFileName = filepath + File.separator + fileName;
-				NcLog.info("文件保存新路径:"+newFileName);
-				
-				String savefilepath=SaveTempFile(filepath,newFileName,bytes);
-//				Upload(vdef17,savefilepath,newFileName,InvocationInfoProxy.getInstance().getUserId());
-				
-				return savefilepath;
-				
-			 }
-			
-			
-			
-			/**
-			 * 保存文件
-			 * 
-			 * @param filepath  文件夹路径
-			 * @param fileName  文件名路径
-			 * @param bs  文件流
-			 * @return  返回文件保存的路径
-			 * @throws Exception 
-			 */
-			public String SaveTempFile(String filepath,String fileName,byte[] bytes) throws Exception  {
-				FileOutputStream fos = null;
-				BufferedOutputStream bos=null;
-				try {
-					File folder = new File(filepath);
-					if(!folder.exists() && !folder.isDirectory()){
-						folder.mkdirs();
-					}
-					fos = new FileOutputStream(fileName);
-					bos = new BufferedOutputStream(fos);
-					bos.write(bytes);
-				} catch (FileNotFoundException e1) {
-					// TODO 自动生成的 catch 块
-					e1.printStackTrace();
-					NcLog.info("保存发票FileNotFoundException异常:"+e1.getMessage());
-					throw new Exception("保存发票FileNotFoundException异常:"+e1.getMessage());
-					
-				} catch (IOException e) {
-					// TODO 自动生成的 catch 块
-					e.printStackTrace();
-					NcLog.info("保存发票IOException异常:"+e.getMessage());
-					throw new Exception("保存发票IOException异常:"+e.getMessage());
-				}finally {
-					if (bos != null) {
-						try {
-							bos.close();
-						} catch (IOException e) {
-							e.printStackTrace();
-							NcLog.info("关闭bos流异常:"+e.getMessage());
-							throw new Exception("关闭bos流异常:"+e.getMessage());
-						}
-					  }
-					}
-					
-					if (fos != null) {
-						try {
-							fos.close();
-						} catch (IOException e) {
-							e.printStackTrace();
-							NcLog.info("关闭fos流异常:"+e.getMessage());
-							throw new Exception("关闭fos流异常:"+e.getMessage());
-						}
-					}
-					
-				       return filepath;
-			      }
-			
-	
-			
-			/**
-			 * NC文件上传
-			 * @param parentPath 单据主键pk_jkbx
-			 * @param newFile 文件路径
-			 * @param filename 文件名
-			 * @param user_code 创建人
-			 * @return 0表示上传成功,-1表示失败
-			 * @throws BusinessException 
-			 * @throws IOException 
-			 */
-			public int Upload(String parentPath, String filepath, String filename,String user_code) throws BusinessException, IOException {
-				NcLog.info("============防止重复上传相同名称的附件开始============");
-				QueryFile(parentPath, filename);
-				NcLog.info("============防止重复上传相同名称的附件结束============");
-				File file = new File(filepath);
-				NcLog.info("文件路径file:"+file.getPath());
-				Long fileLen = file.length();
-				String creator = user_code;
-				NCFileNode node = null;
-				InputStream fileinput = null;
-				try {
-					fileinput = new FileInputStream(file);
-					NcLog.info("FileInputStream:"+fileinput);
-					IFileSystemService service = (IFileSystemService) NCLocator
-							.getInstance().lookup(IFileSystemService.class);
-					NcLog.info("接口service开始:"+service);
-					node = service.createNewFileNodeWithStream(parentPath, filename,
-							creator, fileinput, fileLen);
-					NcLog.info("接口service结束:"+node);
-				} catch (FileNotFoundException e) {
-					e.printStackTrace();
-					NcLog.info("FileNotFoundException保存失败:"+e.getMessage());
-					throw new FileNotFoundException();
-				} catch (IOException e) {
-					e.printStackTrace();
-					NcLog.info("IOException保存失败:"+e.getMessage());
-					throw new IOException();
-				} catch (BusinessException e) {
-					e.printStackTrace();
-					NcLog.info("BusinessException保存失败:"+e.getMessage());
-					throw new BusinessException();
-				} finally {
-					try {
-						fileinput.close();
-					} catch (IOException e) {
-						e.printStackTrace();
-					}
-				}
-				if (node == null) {
-					NcLog.info("-1表示失败:"+"【"+-1+"】");
-					return -1;
-				}
-				NcLog.info("0表示上传成功:"+"【"+0+"】");
-				return 0;
-				
-			}
-		
-			/**
-			 * 防止重复上传相同名称的附件
-			 * 
-			 * @param parentPath
-			 *            单据主键
-			 * @param filename
-			 *            文件名
-			 * @throws BusinessException 
-			 */
-			public void QueryFile(String parentPath, String filename) throws BusinessException  {
-				try {
-					String path = parentPath + "/" + filename;
-					IUAPQueryBS iuap= (IUAPQueryBS) NCLocator.getInstance().lookup(IUAPQueryBS.class.getName());
-					String sql = "select filepath from sm_pub_filesystem where filepath = '"
-							+ path + "'";
-					@SuppressWarnings("unchecked")
-					List<Object[]> filelist = (List<Object[]>) iuap.executeQuery(sql,
-							new ArrayListProcessor());
-					if (filelist != null && filelist.size() > 0) {// 如果有附件,则先删除
-						IFileSystemService service = (IFileSystemService) NCLocator
-								.getInstance().lookup(IFileSystemService.class);
-						String[] arg = new String[] { path };
-						service.deleteNCFileNodes(arg);
-					}
-				} catch (DAOException e) {
-					e.printStackTrace();
-					NcLog.info("=====DAOException防止重复上传相同名称的附件====="+e.getMessage());
-					throw new DAOException();
-				} catch (BusinessException e) {
-					e.printStackTrace();
-					NcLog.info("=====BusinessException防止重复上传相同名称的附件====="+e.getMessage());
-					throw new BusinessException();
-				}
-			}
-		
-			/**
-			 * 获取home路径
-			 */
-			public String getNCHomePath() {
-			
-				return RuntimeEnv.getInstance().getNCHome();
-			}
-
-
-			/**
-			 * 删除home里对应的发票
-			 */
-			public Boolean deleteFile(String filepath)  {
-				 NcLog.info("=====删除home里对应的发票开始=====");
-				//删除home发票文件夹里的对应发票 add by ZTH
-				String deletefilepath =  RuntimeEnv.getInstance().getNCHome()
-					      +File.separator +"uploadfile" + File.separator+ filepath; // 文件保存的路径
-				
-				 File file = new File(deletefilepath);
-				 
-				 Boolean bo= file.delete();
-				 NcLog.info("=====删除home里对应的发票结束=====");
-				 return bo;
-				 
-				
-			}
-
-
-			/**
-			 * 由于删除太慢,改成自定义档案数据停用
-			 * @throws BusinessException 
-			 */
-			public DefdocVO[] enablestateDate(String filepath,String[] filname) throws BusinessException {
-				 NcLog.info("=====改成自定义档案数据停用开始=====");
-				 DefdocVO[] deletevos=QryDefdocvoInfo(filname[1]);
-				 IDefdocService idefservice = NCLocator.getInstance().lookup(IDefdocService.class);
-				 DefdocVO defvo =deletevos[0];
-				 defvo.setAttributeValue("enablestate", 3);//停用
-				 DefdocVO[] defdocVOs= idefservice.updateDefdocs(InvocationInfoProxy.getInstance().getGroupId(),deletevos);
-				 NcLog.info("=====改成自定义档案数据停用结束=====");
-				 return defdocVOs;
-			}
-			
-			
-			private DefdocVO[]  QryDefdocvoInfo(String name){
-		    	String sql = "select * from  bd_defdoc where  nvl(dr, 0) = 0 and pk_defdoclist="
-		    			+ "(select pk_defdoclist from bd_defdoclist where code='OCRTHNC' and nvl(dr,0)=0) and memo='" + name + "' ";
-		    	ArrayList<Object> arrayvos=null;
-		    	try {
-		    		IUAPQueryBS iuap= (IUAPQueryBS) NCLocator.getInstance().lookup(IUAPQueryBS.class.getName());
-					arrayvos=(ArrayList<Object>) iuap.executeQuery(sql, new BeanListProcessor(DefdocVO.class));
-				} catch (BusinessException e) {
-					// TODO 自动生成的 catch 块
-					e.printStackTrace();
-				}
-		    	
-		    	if (arrayvos==null) {
-		  			return new DefdocVO[0];
-		  		}else {
-		  			return arrayvos.toArray(new DefdocVO[0]);
-		  		}
-		    	
-		    }
-
-
-			/**
-			 * 获取"+vdef17+"文件夹下所有发票名
-			 */
-			public List<String> getInvoiceInfo(String vdef17) {
-				String filepath =  RuntimeEnv.getInstance().getNCHome()
-					      +File.separator +"uploadfile" + File.separator+ vdef17; // 文件保存的路径
-				List<String> filewjlis=getFileNames(filepath);
-				
-				return filewjlis;
-			} 
-		 
-			/**
-		     * 得到文件名称
-		     *
-		     * @param path 路径
-		     * @return {@link List}<{@link String}>
-		     */
-		    private  List<String> getFileNames(String path) {
-		        File file = new File(path);
-		        if (!file.exists()) {
-		            return null;
-		        }
-		        List<String> fileNames = new ArrayList<String>();
-		        return getFileNames(file, fileNames);
-		    }
-
-		/**
-		     * 得到文件名称
-		     *
-		     * @param file      文件
-		     * @param fileNames 文件名
-		     * @return {@link List}<{@link String}>
-		     */
-		    private  List<String> getFileNames(File file, List<String> fileNames) {
-		        File[] files = file.listFiles();
-		        for (File f : files) {
-		            if (f.isDirectory()) {
-		                getFileNames(f, fileNames);
-		            } else {
-		                fileNames.add(f.getName());
-		            }
-		        }
-		        return fileNames;
-		    }
-
-
-		@Override
-		public void UpdateInvoiceStatus(String status, InvoiceVO[] vos) {
-			for (InvoiceVO invoiceVO : vos) {
-				//审批结果Y代表通过 N代表不通过 R代表驳回
-				InvoiceItemVO[] arrInvoiceItemVO = (InvoiceItemVO[]) invoiceVO.getChildren(InvoiceItemVO.class);
-				List<String> listVbdef20 = new ArrayList<String>();
-				for (InvoiceItemVO invoiceItemVO : arrInvoiceItemVO) {
-					String[] arrVbdef20 = invoiceItemVO.getVbdef20().split(",");
-					for(String Vbdef20 : arrVbdef20) {
-						listVbdef20.add(Vbdef20);
-					}
-				}
-				String[] fids = (String[]) listVbdef20.toArray();
-				JSONObject bodyJson = new JSONObject();
-				//发票云团队id
-				bodyJson.put("cid", "766941083040768000");
-				//userId报销人id(OA)
-				bodyJson.put("userId", "1");
-				//userId报销人id(OA)
-				bodyJson.put("flag", "3");
-				//发票云发票ID数组
-				bodyJson.put("fids", fids);
-				String str = null;
-				str.toString();
-			}
-			
-		}
-	
-}
+package nc.impl.th;
+
+import java.io.BufferedOutputStream;
+import java.io.BufferedReader;
+import java.io.ByteArrayOutputStream;
+import java.io.DataOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStreamWriter;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.io.FileOutputStream;
+import nc.bs.dao.DAOException;
+import nc.bs.framework.common.InvocationInfoProxy;
+import nc.bs.framework.common.NCLocator;
+import nc.bs.framework.common.RuntimeEnv;
+import nc.itf.uap.IUAPQueryBS;
+import nc.jdbc.framework.processor.ArrayListProcessor;
+import nc.jdbc.framework.processor.BeanListProcessor;
+import nc.jdbc.framework.processor.BeanProcessor;
+import nc.jdbc.framework.processor.MapProcessor;
+import nc.log.NcLog;
+import nc.vo.bd.defdoc.DefdocVO;
+import nc.vo.pu.m25.entity.InvoiceItemVO;
+import nc.vo.pu.m25.entity.InvoiceVO;
+import nc.vo.pub.BusinessException;
+import nc.bs.pub.filesystem.IFileSystemService;
+import nc.itf.uap.IVOPersistence;
+
+import org.apache.commons.codec.digest.DigestUtils;
+import org.apache.commons.httpclient.HttpClient;
+import org.apache.commons.httpclient.HttpException;
+import org.apache.commons.httpclient.methods.PostMethod;
+import org.apache.commons.httpclient.methods.RequestEntity;
+import org.apache.commons.httpclient.methods.StringRequestEntity;
+
+import com.alibaba.fastjson.JSONArray;
+import com.alibaba.fastjson.JSONObject;
+import com.gbase.jdbc.log.Log;
+
+import nc.itf.bd.defdoc.IDefdocService;
+import nc.itf.th.IThOcrService;
+import nc.pub.toolkits.Toolkits;
+import nc.th.redistoken.RedisTokenManager;
+import nc.vo.pub.filesystem.NCFileNode;
+import nc.vo.th.ocr.OCRInvoiceVO;
+import weaver.fna.invoice.utils.InvoiceCloudAESUtil;
+/**
+ * OCR接口实现
+ * @author Administrator
+ *
+ */
+public class ThOcrServiceImpl implements IThOcrService{
+	
+	private IVOPersistence IVOPersistence = (IVOPersistence) NCLocator.getInstance().lookup(IVOPersistence.class);
+	private IUAPQueryBS iuap=(IUAPQueryBS) NCLocator.getInstance().lookup(IUAPQueryBS.class.getName());
+	//锁定发票使用{
+	private String aesKey = "w34xx413y2x23w4y";
+	private String userName = "1438490100786012161";
+	private String password = "80c8664aa7a444049b8ed49ed5095561";
+	private String cid_ = "766941083040768000";
+	private String userid_="1";
+	//}
+	
+	//token使用{
+	
+	private String appId="773676128773832704";
+	private String secret="6726dea9883f4f6bb2725ac8750d01de";
+	private Long cid=773676128725336064l;
+	private String userid="2108";
+	//}
+	private String upurl="https://up.mypiaojia.com/api/invoiceApi/file/uploadFileSpilit";
+	private String inverurl="https://api.mypiaojia.com/api/invoiceApi/invoice/ocr";
+	//发票锁定地址
+	private String ec_comm = "https://api.mypiaojia.com/api/invoiceApi/invoice/ec_comm";
+	private String buildToken="https://api.mypiaojia.com/api/invoiceApi/token/buildToken";
+	public String[] insert(ArrayList<?> arrlist) throws BusinessException {
+		return this.IVOPersistence.insertVOList(arrlist);
+	}
+	
+	
+	@Override
+	/**
+	 * 获取token
+	 */
+	public String getToken() throws HttpException, IOException, BusinessException {
+		NcLog.info("=======获取token开始=======");
+		//redis中获取用户token
+		String userToken = RedisTokenManager.getToken(userid);
+		//token为空
+		if(Toolkits.isEmpty(userToken)){
+			//调用OCR接口
+			userToken=getOcrToken(appId,cid,secret,userid);
+			//保存到redis,设置失效时间36000秒
+			RedisTokenManager.setTokenTTL(userid,36000, userToken);
+		}
+		NcLog.info("=======token======="+userToken);
+		NcLog.info("=======获取token结束=======");
+		 return userToken;
+	}
+
+	
+	
+	/**
+	 * 上传发票
+	 * @throws Exception 
+	 */
+	public String uploadInvoice(String token,String vdef17,String invoicename) throws Exception {
+		NcLog.info("=======上传发票开始=======");
+		File file=new File(RuntimeEnv.getInstance().getNCHome()
+			      +File.separator +"uploadfile" + File.separator+ vdef17+File.separator+invoicename);
+		String resmsg=httpFilePost(upurl,token,file);
+		String id="";
+		if(null!=resmsg&&resmsg.indexOf("uploading")!=-1){
+			 JSONObject json = JSONObject.parseObject(resmsg);
+			 JSONObject data=json.getJSONObject("data");
+			 if(null!=data){
+				 id=data.getString("id");
+			 }else{
+				 String msg=json.getJSONObject("res_base").getString("message");
+				 throw new BusinessException(msg);
+			 }
+			
+		}
+		
+		return resmsg;
+	}
+
+
+
+	/**
+	 * OCR识别
+	 */
+	@Override
+	public String ocrIdentification(String token,String data) {
+		// TODO 自动生成的方法存根
+		 NcLog.info("=======发票OCR识别开始=======");
+		 JSONObject json = JSONObject.parseObject(data);
+		 JSONObject jsonobject = new JSONObject();
+         jsonobject.put("image_index", json.getJSONObject("data").getString("id"));
+         jsonobject.put("fileTypeStr", json.getJSONObject("data").getString("fileType"));
+         jsonobject.put("flag", "13");
+         jsonobject.put("is_save", "0");
+         jsonobject.put("is_sync", "1");
+         jsonobject.put("ocrMap","");
+         jsonobject.put("operate_type",0);
+		 return doPost(inverurl,token,jsonobject.toString());
+	}
+	
+	
+	/**
+	 * OCR识别数据保存数据库
+	 * @throws BusinessException 
+	 */
+	public void insertOCRdataInfo(ArrayList<OCRInvoiceVO> vos) throws BusinessException {
+		insert(vos);
+	}
+	
+	
+
+	public String getOcrToken(String appId,Long cid,String secret,String userid)  throws HttpException, IOException, BusinessException{
+    	HttpClient httpClient = new HttpClient();
+    	httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
+        httpClient.getHttpConnectionManager().getParams().setSoTimeout(5000);
+        PostMethod postMethod = new PostMethod(buildToken);
+        postMethod.setRequestHeader("content-type", "application/json");
+        postMethod.setRequestHeader("appkey", appId);
+        long l = System.currentTimeMillis();
+        Map<String, Object> map = new HashMap<String, Object>();
+        map.put("role", 1);
+        map.put("name", "dmy06");
+        map.put("name", "dmy06");
+        map.put("userId", userid);//OA用户体系的用户id 2108
+        map.put("cid", cid);
+        String s1 = JSONObject.toJSONString(map);
+        String s2 = s1 + "&time=" + l + "&secret="+secret;
+        String newMd5 = DigestUtils.md5Hex(s2);
+        String s4 = s1 + "&time=" + l + "&md5=" + newMd5;
+        RequestEntity entity = new StringRequestEntity (s4 ,"application/json" ,"UTF-8");
+        postMethod.setRequestEntity(entity);
+        httpClient.executeMethod(postMethod);
+		String responseMsg = postMethod.getResponseBodyAsString().trim();
+		//返回结果{"data":"WEAPPe8Ke9pFzz9fbZ3qCcN6itq1zLHCKOgPmXHz6uIg8eOg","actionMsg":{"code":0,"message":"执行成功"}}
+ //       System.out.println("返回结果"+ responseMsg);
+
+		 JSONObject json = JSONObject.parseObject(responseMsg);
+		 String token=json.getString("data");
+		 String status=json.getString("status");
+		 //保存token返回值到日志文件里
+		 NcLog.info("token:"+token);
+		 
+		 if(token == null){
+			 throw new BusinessException(responseMsg);
+		 }
+		 
+		 return token;
+	  }
+	
+	
+
+
+	 public  String httpFilePost(String uploadUrl,String token, File file) throws Exception {
+		 
+		//File file = new File(file);
+		 String LINEND = "\r\n";
+		 String boundary = UUID.randomUUID().toString();
+		 FileInputStream fileInputStream = new FileInputStream(file);
+	     URL url = new URL(uploadUrl);
+	     HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
+	     httpURLConnection.setDoInput(true);
+	     httpURLConnection.setUseCaches(false);
+	     httpURLConnection.setDoOutput(true);
+	     httpURLConnection.setRequestMethod("POST");
+	     httpURLConnection.setRequestProperty("connection", "keep-alive");
+	     httpURLConnection.setRequestProperty("Charsert", "UTF-8");
+	     httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
+	     httpURLConnection.setRequestProperty("token", token);
+	     httpURLConnection.setRequestProperty("Accept","*/*");
+	     DataOutputStream outStream = new DataOutputStream(httpURLConnection.getOutputStream());
+         StringBuilder stringBuilder = new StringBuilder();
+         stringBuilder.append("--").append(boundary).append(LINEND);
+         stringBuilder.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + LINEND);
+         stringBuilder.append("Content-Type: " + HttpURLConnection.guessContentTypeFromName(file.getName()) + LINEND);
+         stringBuilder.append("Content-Transfer-Encoding: binary"+ LINEND);
+         stringBuilder.append(LINEND);
+ //        outStream.write(stringBuilder.toString().getBytes());
+         outStream.writeUTF(stringBuilder.toString());
+    	 InputStream is = new FileInputStream(file);
+    	 byte[] buffer = new byte[1024];
+    	 int len = 0;
+    	 while ((len = is.read(buffer)) != -1){
+    		 outStream.write(buffer, 0, len);
+    	 }
+    	 is.close();
+    	 outStream.write(LINEND.getBytes());
+    	 byte[] end_data = ("--" + boundary + "--" + LINEND).getBytes();
+    	 outStream.write(end_data);
+    	 outStream.flush();
+         fileInputStream.close();
+         String response = readStream(httpURLConnection.getInputStream());
+         outStream.close();
+         httpURLConnection.disconnect(); 
+         NcLog.info("发票上传返回json:"+response);
+		 return response;
+			
+		}
+		 
+	 private  String readStream(InputStream inputStream) throws IOException {
+		 ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
+		 byte[] buffer = new byte[1024];
+		 int bytesRead;
+		 while ((bytesRead = inputStream.read(buffer)) != -1) {
+			 outputStream.write(buffer, 0, bytesRead);
+			 }
+		 byte[] bytes = outputStream.toByteArray();
+		 String result = new String(bytes, "UTF-8");
+		 outputStream.close();
+		 return result;
+		 }
+
+
+
+		 public  String doPost(String pathUrl, String token,String data){
+			OutputStreamWriter out = null;
+	        BufferedReader br = null;
+	        String result = "";
+	        try {
+	        	URL url = new URL(pathUrl);
+	        	//打开和url之间的连接
+	            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
+	            //设定请求的方法为"POST",默认是GET
+	            //post与get的不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。
+	            conn.setRequestMethod("POST");
+	  
+	            //设置30秒连接超时
+	            conn.setConnectTimeout(30000);
+	            //设置30秒读取超时
+	            conn.setReadTimeout(30000);
+	  
+	            // 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在http正文内,因此需要设为true, 默认情况下是false;
+	            conn.setDoOutput(true);
+	            // 设置是否从httpUrlConnection读入,默认情况下是true;
+	            conn.setDoInput(true);
+	  
+	            // Post请求不能使用缓存
+	            conn.setUseCaches(false);
+	  
+	            //设置通用的请求属性
+	            conn.setRequestProperty("accept", "*/*");
+	            conn.setRequestProperty("connection", "Keep-Alive");  //维持长链接
+	            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
+	            conn.setRequestProperty("token", token);
+	  
+	            //连接,从上述url.openConnection()至此的配置必须要在connect之前完成,
+	            conn.connect();
+	  
+	            /**
+	             * 下面的三句代码,就是调用第三方http接口
+	             */
+	            //获取URLConnection对象对应的输出流
+	            //此处getOutputStream会隐含的进行connect(即:如同调用上面的connect()方法,所以在开发中不调用上述的connect()也可以)。
+	            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
+	            //发送请求参数即数据
+	            out.write(data);
+	            //flush输出流的缓冲
+	            out.flush();
+	  
+	            /**
+	             * 下面的代码相当于,获取调用第三方http接口后返回的结果
+	             */
+	            //获取URLConnection对象对应的输入流
+	            InputStream is = conn.getInputStream();
+	            //构造一个字符流缓存
+	            br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
+	            String str = "";
+	            while ((str = br.readLine()) != null){
+	                result += str;
+	            }
+	         //   System.out.println(result);
+	            
+	           /* JSONObject json = JSONObject.parseObject(result);
+	            //获取主要数据
+	            JSONObject datajson = json.getJSONObject("data");
+	            System.out.println("datajson===="+datajson.toString());
+	            JSONArray infosjson = datajson.getJSONArray("infos");
+	            System.out.println("infosjson===="+infosjson.toString());
+	            
+	            for (Object infos : infosjson) {
+	            	JSONObject infosObject =(JSONObject)infos;
+	                String total=infosObject.getJSONObject("info").getJSONObject("comm_info").getJSONObject("price").getString("total");
+	                System.out.println("total===="+total);
+	            }*/
+	            
+	            //关闭流
+	            is.close();
+	            //断开连接,disconnect是在底层tcp socket链接空闲时才切断,如果正在被其他线程使用就不切断。
+	            conn.disconnect();
+	        }catch (Exception e) {
+	            e.printStackTrace();
+	        }finally {
+	            try {
+	                if (out != null){
+	                    out.close();
+	                }
+	                if (br != null){
+	                    br.close();
+	                }
+	            } catch (IOException e) {
+	                e.printStackTrace();
+	            }
+	        }
+	        
+	        NcLog.info("发票OCR识别返回json:"+result);
+	        
+			return result;
+		 }
+		 
+		 /**
+			 * 
+			 *  发票保存到文件夹里
+			 *  vdef17     发票主键
+			 *  fileName 发票名
+			 *  file     选中的发票
+			 * @throws IOException 
+			 */
+			public String saveUploadFile(String vdef17,String fileName,byte[] bytes) throws Exception {
+		/*		NcLog.info("=====发票保存开始=====");
+				String filepath =  RuntimeEnv.getInstance().getNCHome()
+					      +File.separator +"uploadfile" + File.separator+ vdef17; // 文件保存的路径
+				NcLog.info("文件保存的路径:"+filepath);
+				NcLog.info("原文件路径:"+file.getPath());
+				File folder = new File(filepath);
+				if(!folder.exists() && !folder.isDirectory()){
+					folder.mkdirs();
+				}
+				String newFileName = filepath + File.separator + fileName;
+				NcLog.info("文件保存新路径:"+newFileName);
+				FileOutputStream outputStream = new FileOutputStream(newFileName);
+				NcLog.info("=====FileOutputStream=====");
+				FileInputStream fis = new FileInputStream(file);
+		        byte[] buffer = new byte[1024];
+		        int len;
+		        NcLog.info("=====读取发票信息开始=====");
+		        while ((len = fis.read(buffer)) != -1) {
+		            outputStream.write(buffer, 0, len);
+		        }
+		        NcLog.info("=====读取发票信息结束=====");
+		        outputStream.close();
+		        fis.close();
+		        NcLog.info("=====发票保存结束=====");*/
+				
+			//	byte[] bs = Base64.decode(file.trim());
+				
+				NcLog.info("=====发票保存开始=====");
+			//	NcLog.info("=====bytes:"+bytes.length+"=====");
+				String filepath =  RuntimeEnv.getInstance().getNCHome()
+					      +File.separator +"uploadfile" + File.separator+ vdef17; // 文件保存的文件夹
+				String newFileName = filepath + File.separator + fileName;
+				NcLog.info("文件保存新路径:"+newFileName);
+				
+				String savefilepath=SaveTempFile(filepath,newFileName,bytes);
+//				Upload(vdef17,savefilepath,newFileName,InvocationInfoProxy.getInstance().getUserId());
+				
+				return savefilepath;
+				
+			 }
+			
+			
+			
+			/**
+			 * 保存文件
+			 * 
+			 * @param filepath  文件夹路径
+			 * @param fileName  文件名路径
+			 * @param bs  文件流
+			 * @return  返回文件保存的路径
+			 * @throws Exception 
+			 */
+			public String SaveTempFile(String filepath,String fileName,byte[] bytes) throws Exception  {
+				FileOutputStream fos = null;
+				BufferedOutputStream bos=null;
+				try {
+					File folder = new File(filepath);
+					if(!folder.exists() && !folder.isDirectory()){
+						folder.mkdirs();
+					}
+					fos = new FileOutputStream(fileName);
+					bos = new BufferedOutputStream(fos);
+					bos.write(bytes);
+				} catch (FileNotFoundException e1) {
+					// TODO 自动生成的 catch 块
+					e1.printStackTrace();
+					NcLog.info("保存发票FileNotFoundException异常:"+e1.getMessage());
+					throw new Exception("保存发票FileNotFoundException异常:"+e1.getMessage());
+					
+				} catch (IOException e) {
+					// TODO 自动生成的 catch 块
+					e.printStackTrace();
+					NcLog.info("保存发票IOException异常:"+e.getMessage());
+					throw new Exception("保存发票IOException异常:"+e.getMessage());
+				}finally {
+					if (bos != null) {
+						try {
+							bos.close();
+						} catch (IOException e) {
+							e.printStackTrace();
+							NcLog.info("关闭bos流异常:"+e.getMessage());
+							throw new Exception("关闭bos流异常:"+e.getMessage());
+						}
+					  }
+					}
+					
+					if (fos != null) {
+						try {
+							fos.close();
+						} catch (IOException e) {
+							e.printStackTrace();
+							NcLog.info("关闭fos流异常:"+e.getMessage());
+							throw new Exception("关闭fos流异常:"+e.getMessage());
+						}
+					}
+					
+				       return filepath;
+			      }
+			
+	
+			
+			/**
+			 * NC文件上传
+			 * @param parentPath 单据主键pk_jkbx
+			 * @param newFile 文件路径
+			 * @param filename 文件名
+			 * @param user_code 创建人
+			 * @return 0表示上传成功,-1表示失败
+			 * @throws BusinessException 
+			 * @throws IOException 
+			 */
+			public int Upload(String parentPath, String filepath, String filename,String user_code) throws BusinessException, IOException {
+				NcLog.info("============防止重复上传相同名称的附件开始============");
+				QueryFile(parentPath, filename);
+				NcLog.info("============防止重复上传相同名称的附件结束============");
+				File file = new File(filepath);
+				NcLog.info("文件路径file:"+file.getPath());
+				Long fileLen = file.length();
+				String creator = user_code;
+				NCFileNode node = null;
+				InputStream fileinput = null;
+				try {
+					fileinput = new FileInputStream(file);
+					NcLog.info("FileInputStream:"+fileinput);
+					IFileSystemService service = (IFileSystemService) NCLocator
+							.getInstance().lookup(IFileSystemService.class);
+					NcLog.info("接口service开始:"+service);
+					node = service.createNewFileNodeWithStream(parentPath, filename,
+							creator, fileinput, fileLen);
+					NcLog.info("接口service结束:"+node);
+				} catch (FileNotFoundException e) {
+					e.printStackTrace();
+					NcLog.info("FileNotFoundException保存失败:"+e.getMessage());
+					throw new FileNotFoundException();
+				} catch (IOException e) {
+					e.printStackTrace();
+					NcLog.info("IOException保存失败:"+e.getMessage());
+					throw new IOException();
+				} catch (BusinessException e) {
+					e.printStackTrace();
+					NcLog.info("BusinessException保存失败:"+e.getMessage());
+					throw new BusinessException();
+				} finally {
+					try {
+						fileinput.close();
+					} catch (IOException e) {
+						e.printStackTrace();
+					}
+				}
+				if (node == null) {
+					NcLog.info("-1表示失败:"+"【"+-1+"】");
+					return -1;
+				}
+				NcLog.info("0表示上传成功:"+"【"+0+"】");
+				return 0;
+				
+			}
+		
+			/**
+			 * 防止重复上传相同名称的附件
+			 * 
+			 * @param parentPath
+			 *            单据主键
+			 * @param filename
+			 *            文件名
+			 * @throws BusinessException 
+			 */
+			public void QueryFile(String parentPath, String filename) throws BusinessException  {
+				try {
+					String path = parentPath + "/" + filename;
+					IUAPQueryBS iuap= (IUAPQueryBS) NCLocator.getInstance().lookup(IUAPQueryBS.class.getName());
+					String sql = "select filepath from sm_pub_filesystem where filepath = '"
+							+ path + "'";
+					@SuppressWarnings("unchecked")
+					List<Object[]> filelist = (List<Object[]>) iuap.executeQuery(sql,
+							new ArrayListProcessor());
+					if (filelist != null && filelist.size() > 0) {// 如果有附件,则先删除
+						IFileSystemService service = (IFileSystemService) NCLocator
+								.getInstance().lookup(IFileSystemService.class);
+						String[] arg = new String[] { path };
+						service.deleteNCFileNodes(arg);
+					}
+				} catch (DAOException e) {
+					e.printStackTrace();
+					NcLog.info("=====DAOException防止重复上传相同名称的附件====="+e.getMessage());
+					throw new DAOException();
+				} catch (BusinessException e) {
+					e.printStackTrace();
+					NcLog.info("=====BusinessException防止重复上传相同名称的附件====="+e.getMessage());
+					throw new BusinessException();
+				}
+			}
+		
+			/**
+			 * 获取home路径
+			 */
+			public String getNCHomePath() {
+			
+				return RuntimeEnv.getInstance().getNCHome();
+			}
+
+
+			/**
+			 * 删除home里对应的发票
+			 */
+			public Boolean deleteFile(String filepath)  {
+				 NcLog.info("=====删除home里对应的发票开始=====");
+				//删除home发票文件夹里的对应发票 add by ZTH
+				String deletefilepath =  RuntimeEnv.getInstance().getNCHome()
+					      +File.separator +"uploadfile" + File.separator+ filepath; // 文件保存的路径
+				
+				 File file = new File(deletefilepath);
+				 
+				 Boolean bo= file.delete();
+				 NcLog.info("=====删除home里对应的发票结束=====");
+				 return bo;
+				 
+				
+			}
+
+
+			/**
+			 * 由于删除太慢,改成自定义档案数据停用
+			 * @throws BusinessException 
+			 */
+			public DefdocVO[] enablestateDate(String filepath,String[] filname) throws BusinessException {
+				 NcLog.info("=====改成自定义档案数据停用开始=====");
+				 DefdocVO[] deletevos=QryDefdocvoInfo(filname[1]);
+				 IDefdocService idefservice = NCLocator.getInstance().lookup(IDefdocService.class);
+				 DefdocVO defvo =deletevos[0];
+				 defvo.setAttributeValue("enablestate", 3);//停用
+				 DefdocVO[] defdocVOs= idefservice.updateDefdocs(InvocationInfoProxy.getInstance().getGroupId(),deletevos);
+				 NcLog.info("=====改成自定义档案数据停用结束=====");
+				 return defdocVOs;
+			}
+			
+			
+			private DefdocVO[]  QryDefdocvoInfo(String name){
+		    	String sql = "select * from  bd_defdoc where  nvl(dr, 0) = 0 and pk_defdoclist="
+		    			+ "(select pk_defdoclist from bd_defdoclist where code='OCRTHNC' and nvl(dr,0)=0) and memo='" + name + "' ";
+		    	ArrayList<Object> arrayvos=null;
+		    	try {
+		    		IUAPQueryBS iuap= (IUAPQueryBS) NCLocator.getInstance().lookup(IUAPQueryBS.class.getName());
+					arrayvos=(ArrayList<Object>) iuap.executeQuery(sql, new BeanListProcessor(DefdocVO.class));
+				} catch (BusinessException e) {
+					// TODO 自动生成的 catch 块
+					e.printStackTrace();
+				}
+		    	
+		    	if (arrayvos==null) {
+		  			return new DefdocVO[0];
+		  		}else {
+		  			return arrayvos.toArray(new DefdocVO[0]);
+		  		}
+		    	
+		    }
+
+
+			/**
+			 * 获取"+vdef17+"文件夹下所有发票名
+			 */
+			public List<String> getInvoiceInfo(String vdef17) {
+				String filepath =  RuntimeEnv.getInstance().getNCHome()
+					      +File.separator +"uploadfile" + File.separator+ vdef17; // 文件保存的路径
+				List<String> filewjlis=getFileNames(filepath);
+				
+				return filewjlis;
+			} 
+		 
+			/**
+		     * 得到文件名称
+		     *
+		     * @param path 路径
+		     * @return {@link List}<{@link String}>
+		     */
+		    private  List<String> getFileNames(String path) {
+		        File file = new File(path);
+		        if (!file.exists()) {
+		            return null;
+		        }
+		        List<String> fileNames = new ArrayList<String>();
+		        return getFileNames(file, fileNames);
+		    }
+
+		/**
+		     * 得到文件名称
+		     *
+		     * @param file      文件
+		     * @param fileNames 文件名
+		     * @return {@link List}<{@link String}>
+		     */
+		    private  List<String> getFileNames(File file, List<String> fileNames) {
+		        File[] files = file.listFiles();
+		        for (File f : files) {
+		            if (f.isDirectory()) {
+		                getFileNames(f, fileNames);
+		            } else {
+		                fileNames.add(f.getName());
+		            }
+		        }
+		        return fileNames;
+		    }
+
+
+		@Override
+		public void UpdateInvoiceStatus(String status, InvoiceVO[] vos) throws Exception {
+			for (InvoiceVO invoiceVO : vos) {
+				//审批结果Y代表通过 N代表不通过 R代表驳回T报销中
+				InvoiceItemVO[] arrInvoiceItemVO = (InvoiceItemVO[]) invoiceVO.getChildren(InvoiceItemVO.class);
+				List<Map<Object, Object>> listMapVbdef20 = new ArrayList<Map<Object, Object>>();
+				List<String> listVbdef20 = new ArrayList<String>();
+				for (InvoiceItemVO invoiceItemVO : arrInvoiceItemVO) {
+					if(invoiceItemVO.getVbdef20() != null && !"".equals(invoiceItemVO.getVbdef20())) {
+						String[] arrVbdef20 = invoiceItemVO.getVbdef20().split(",");
+						for(String Vbdef20 : arrVbdef20) {
+							StringBuffer sql = new StringBuffer();
+							sql.append("SELECT");
+							sql.append(" shortname2,");
+							sql.append(" name5");
+							sql.append(" FROM");
+							sql.append(" bd_defdoc ");
+							sql.append(" WHERE");
+							sql.append(" pk_defdoc = '"+Vbdef20+"'");
+							Map<Object, Object> mapdoc =  (Map<Object, Object>) iuap.executeQuery(sql.toString(), new MapProcessor());
+							listMapVbdef20.add(mapdoc);
+							listVbdef20.add(mapdoc.get("name5").toString());
+						}
+					}
+				}
+				if(listMapVbdef20.size() > 0) {
+					JSONObject bodyJson = new JSONObject();
+					//发票云团队id
+					bodyJson.put("cid", cid_);
+					//userId报销人id(OA)
+					bodyJson.put("userId", userid);
+					//userId报销人id(OA)
+					bodyJson.put("flag", "3");
+					//发票云发票ID数组
+					bodyJson.put("fids", listVbdef20.toArray());
+					UpdateInvoiceOCR(bodyJson.toString());
+					//0 未报销 1 报销中 2已报销
+					String  sreim = "0";
+					if("Y".equals(status)) {
+						sreim = "2";
+					}else {
+						sreim = "1";
+						
+					}
+					JSONObject bodyJson1 = new JSONObject();
+					bodyJson1.put("cid", cid_);
+					bodyJson1.put("userId", userid);
+					bodyJson1.put("flag", "2");
+					bodyJson1.put("sreim",sreim);
+					JSONArray arrinfos = new JSONArray();
+					for (Map<Object, Object> map : listMapVbdef20) {
+						long date = System.currentTimeMillis()/ 1000;
+						JSONObject bodyJson2 = new JSONObject();
+						bodyJson2.put("dataid", invoiceVO.getParent().getAttributeValue("pk_invoice"));
+						bodyJson2.put("number", invoiceVO.getParent().getAttributeValue("pk_invoice"));
+						bodyJson2.put("amount", "0".equals(sreim) ? "0.00" : map.get("shortname2"));
+						bodyJson2.put("uid", userid);
+						bodyJson2.put("date",Long.toString(date));
+						bodyJson2.put("name", invoiceVO.getParent().getAttributeValue("pk_invoice"));
+						bodyJson2.put("fid", map.get("name5"));
+						bodyJson2.put("cid", cid_);
+						arrinfos.add(bodyJson2);
+					}
+					bodyJson1.put("infos", arrinfos);
+					UpdateInvoiceOCR(bodyJson1.toString());
+				}
+			}
+			String str1 = null;
+			str1.toString();
+		}
+		
+		/**
+		 * 
+		 * @param content
+		 * @throws Exception
+		 */
+		private void UpdateInvoiceOCR(String bodyJson) throws Exception {
+			String content =  InvoiceCloudAESUtil.startAssemble(aesKey, password, bodyJson);
+			HttpClient httpClient = new HttpClient();
+	        PostMethod postMethod = new PostMethod(ec_comm);
+	        postMethod.setRequestHeader("content-type", "application/json");
+	        postMethod.setRequestHeader("appkey", userName);
+	        RequestEntity entity = new StringRequestEntity (content ,"application/json" ,"UTF-8");
+	        postMethod.setRequestEntity(entity);
+	        httpClient.executeMethod(postMethod);
+			String responseMsg = postMethod.getResponseBodyAsString().trim();
+			JSONObject json = JSONObject.parseObject(responseMsg);
+			String data=json.getString("data");
+			if(data == null) {
+				 throw new BusinessException(responseMsg);
+			}
+		}
+}

+ 86 - 0
pu/pu/src/private/weaver/fna/invoice/utils/InvoiceCloudAESUtil.java

@@ -0,0 +1,86 @@
+package weaver.fna.invoice.utils;
+
+import javax.crypto.Cipher;
+import javax.crypto.spec.IvParameterSpec;
+import javax.crypto.spec.SecretKeySpec;
+
+import org.apache.commons.codec.binary.Base64;
+import org.apache.commons.codec.digest.DigestUtils;
+
+/**
+ * @Description:·¢Æ±Ôƹ¤¾ßÀà
+ */
+public class InvoiceCloudAESUtil{
+	
+	
+	
+	
+	public static String startAssemble(String aesKey,String password,String bodyJson) throws Exception {
+		String bodyStr = encrypt(aesKey,bodyJson.toString());
+		String content = invoiceCloudEncode(bodyStr.toString(), password);
+		return content;
+		
+	}
+//	public static void main(String[] args) {
+//		try {
+//			
+//			String bodyJson = "{\"cid\":\"766941083040768000\",\"userId\":1,\"flag\":\"3\",\"fids\":[\"868117722088693763\"]}";
+//			String aesKey = "w34xx413y2x23w4y";
+//			String userName = "1438490100786012161";
+//			String password = "80c8664aa7a444049b8ed49ed5095561";
+//			String bodyStr = encrypt(aesKey,bodyJson.toString());
+//			System.out.println(bodyStr);
+//			String content = invoiceCloudEncode(bodyStr.toString(), password);
+//			System.out.println(content);
+//			Map<String, String> map = new HashMap<String, String>();
+//
+//			map.put("appkey", userName);
+//		} catch (Exception e) {
+//			e.printStackTrace();
+//		}
+//	}
+
+    private static byte[] encrypt(String key, byte[] origData) throws Exception {
+        byte[] keyBytes = getKeyBytes(key);
+        byte[] buf = new byte[16];
+        System.arraycopy(keyBytes, 0, buf, 0, keyBytes.length > buf.length ? keyBytes.length : buf.length);
+        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
+        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(buf, "AES"), new IvParameterSpec(keyBytes));
+        return cipher.doFinal(origData);
+
+    }
+
+    private static byte[] decrypt(String key, byte[] crypted) throws Exception {
+        byte[] keyBytes = getKeyBytes(key);
+        byte[] buf = new byte[16];
+        System.arraycopy(keyBytes, 0, buf, 0, keyBytes.length > buf.length ? keyBytes.length : buf.length);
+        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
+        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(buf, "AES"), new IvParameterSpec(keyBytes));
+        return cipher.doFinal(crypted);
+    }
+
+    private static byte[] getKeyBytes(String key) throws Exception {
+        byte[] bytes = key.getBytes("utf8");
+        return bytes;
+    }
+
+    public static String encrypt(String key, String val) throws Exception {
+        byte[] origData = val.getBytes("utf8");
+        byte[] crypted = encrypt(key, origData);
+        return new String(Base64.encodeBase64(crypted), "UTF-8");
+    }
+
+    public static String decrypt(String key, String val) throws Exception {
+        byte[] crypted = Base64.decodeBase64(val.getBytes("utf8"));
+        byte[] origData = decrypt(key, crypted);
+        return new String(origData, "utf8");
+    }
+    
+    private static String invoiceCloudEncode(String content,String secret) throws Exception {
+    	long time = System.currentTimeMillis();
+    	content = content+"&time="+time;
+    	String md5Content =  DigestUtils.md5Hex(content + "&secret=" + secret);
+    	content = content+"&md5="+md5Content;
+    	return content;
+    }
+}

+ 88 - 88
pu/pu/src/public/nc/itf/th/IThOcrService.java

@@ -1,88 +1,88 @@
-package nc.itf.th;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.UnsupportedEncodingException;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.apache.commons.httpclient.HttpException;
-
-import nc.vo.bd.defdoc.DefdocVO;
-import nc.vo.pu.m25.entity.InvoiceVO;
-import nc.vo.pub.BusinessException;
-import nc.vo.th.ocr.OCRInvoiceVO;
-import net.sf.json.JSONString;
-
-/**
- * OCR接口
- * @author Administrator
- *
- */
-
-public interface IThOcrService {
-	/**
-	 * 
-	 * 获取token
-	 */
-	public String getToken(String appId,Long cid,String secret,String userid) throws HttpException, IOException , BusinessException;
-	
-	/**
-	 * 上传发票
-	 */
-	public String uploadInvoice(String url,String token,String vdef17,String invoicename) throws Exception;
-	
-	/**
-	 * OCR识别
-	 */
-	public String ocrIdentification(String pathUrl, String token,String data);
-	
-	
-	/**
-	 * OCR识别数据保存数据库
-	 */
-	public void insertOCRdataInfo(ArrayList<OCRInvoiceVO> vos) throws BusinessException;
-	
-
-	
-	/**
-	 * 发票保存到文件夹里
-	 */
-	public String saveUploadFile(String vdef17,String fileName,byte[] bytes) throws Exception;
-	
-	
-	/**
-	 * 删除home里对应的发票
-	 */
-	public Boolean deleteFile(String filepath) ;
-	
-	
-	
-	/**
-	 * 由于删除太慢,改成自定义档案数据停用
-	 */
-	public  DefdocVO[]  enablestateDate(String filepath,String[] filname)  throws BusinessException;
-	
-	
-	
-	/**
-	 * 获取home路径
-	 */
-	public  String  getNCHomePath();
-	
-	
-	/**
-	 * 获取"+vdef17+"文件夹下所有发票名
-	 */
-	
-	public  List<String>  getInvoiceInfo(String vdef17);
-	
-	/**
-	 * 修改发票云发票状态
-	 * @param status  发票状态
-	 * @param vos  发票aggvo
-	 */
-	public void UpdateInvoiceStatus(String status,InvoiceVO[] vos);
-	
-}
+package nc.itf.th;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.commons.httpclient.HttpException;
+
+import nc.vo.bd.defdoc.DefdocVO;
+import nc.vo.pu.m25.entity.InvoiceVO;
+import nc.vo.pub.BusinessException;
+import nc.vo.th.ocr.OCRInvoiceVO;
+import net.sf.json.JSONString;
+
+/**
+ * OCR接口
+ * @author Administrator
+ *
+ */
+
+public interface IThOcrService {
+	/**
+	 * 
+	 * 获取token
+	 */
+	public String getToken() throws HttpException, IOException , BusinessException;
+	
+	/**
+	 * 上传发票
+	 */
+	public String uploadInvoice(String token,String vdef17,String invoicename) throws Exception;
+	
+	/**
+	 * OCR识别
+	 */
+	public String ocrIdentification(String token,String data);
+	
+	
+	/**
+	 * OCR识别数据保存数据库
+	 */
+	public void insertOCRdataInfo(ArrayList<OCRInvoiceVO> vos) throws BusinessException;
+	
+
+	
+	/**
+	 * 发票保存到文件夹里
+	 */
+	public String saveUploadFile(String vdef17,String fileName,byte[] bytes) throws Exception;
+	
+	
+	/**
+	 * 删除home里对应的发票
+	 */
+	public Boolean deleteFile(String filepath) ;
+	
+	
+	
+	/**
+	 * 由于删除太慢,改成自定义档案数据停用
+	 */
+	public  DefdocVO[]  enablestateDate(String filepath,String[] filname)  throws BusinessException;
+	
+	
+	
+	/**
+	 * 获取home路径
+	 */
+	public  String  getNCHomePath();
+	
+	
+	/**
+	 * 获取"+vdef17+"文件夹下所有发票名
+	 */
+	
+	public  List<String>  getInvoiceInfo(String vdef17);
+	
+	/**
+	 * 修改发票云发票状态
+	 * @param status  发票状态
+	 * @param vos  发票aggvo
+	 */
+	public void UpdateInvoiceStatus(String status,InvoiceVO[] vos) throws Exception;
+	
+}