package com.tenwa.makeContract.util; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.MalformedURLException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; import org.jbarcode.JBarcode; import org.jbarcode.encode.Code128Encoder; import org.jbarcode.paint.BaseLineTextPainter; import org.jbarcode.paint.WidthCodedPainter; import com.amarsoft.are.jbo.BizObject; import com.amarsoft.are.jbo.BizObjectManager; import com.amarsoft.are.jbo.JBOException; import com.amarsoft.are.jbo.JBOFactory; import com.amarsoft.are.jbo.JBOTransaction; import com.amarsoft.are.util.json.JSONDecoder; import com.amarsoft.are.util.json.JSONObject; import com.amarsoft.awe.Configure; import com.amarsoft.dict.als.manage.NameManager; import com.caucho.hessian.client.HessianProxyFactory; import com.itextpdf.text.Image; import com.itextpdf.text.pdf.PdfContentByte; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.PdfStamper; import com.sun.image.codec.jpeg.JPEGCodec; import com.sun.image.codec.jpeg.JPEGEncodeParam; import com.sun.image.codec.jpeg.JPEGImageEncoder; import com.tenwa.app.dao.ContractSignInfo; import com.tenwa.channelportal.action.ContractSignAction; import com.tenwa.channelportal.action.generativecontract.WordToPDFUtil; import com.tenwa.comm.util.date.DateAssistant; import com.tenwa.comm.util.jboutil.DataOperatorUtil; import com.tenwa.doc.action.DocListAction; import com.tenwa.doc.util.BASE64; import com.tenwa.lease.app.service.HttpRequestAppService; import com.tenwa.officetempalte.util.FileOperatorUtil; import com.tenwa.reckon.util.UUIDUtil; import jbo.app.tenwa.customer.CUSTOMER_INFO; import jbo.app.tenwa.customer.CUSTOMER_PERSON; import jbo.app.tenwa.doc.LB_DOCATTRIBUTE; import jbo.app.tenwa.doc.LB_DOCRELATIVE; import jbo.app.tenwa.doc.LB_DOC_CONTRACT_LIST; import jbo.app.tenwa.doc.LB_ONEDIMENSIONALCODE; import jbo.com.tenwa.entity.comm.officetempalte.BF_TEMPLATE; import jbo.com.tenwa.lease.carbrand.LB_CONTRACT_SIGN_LOG; import jbo.com.tenwa.lease.comm.LB_CONTRACT_TEMPLATE; import jbo.com.tenwa.lease.comm.LB_UNION_LESSEE; public class MakeOneCodeAndContractModel { private static Logger logger=Logger.getLogger(ContractSignAction.class); public HessianProxyFactory factory = new HessianProxyFactory(); public HttpRequestAppService requestService; public String MOneDimensionalCode(String contractNo,String contractId,String projectId,String diskPath,JBOTransaction tx) throws Exception{ JBarcode localJBarcode = new JBarcode(Code128Encoder.getInstance(), WidthCodedPainter.getInstance(), BaseLineTextPainter.getInstance()); localJBarcode.setEncoder(Code128Encoder.getInstance()); localJBarcode.setPainter(WidthCodedPainter.getInstance()); localJBarcode.setBarHeight(10); localJBarcode.setTextPainter(BaseLineTextPainter.getInstance()); localJBarcode.setShowCheckDigit(false); BufferedImage localBufferedImage = null; localBufferedImage = localJBarcode.createBarcode(contractNo); //获取当前时间,根据时间创建一维码存放的路径 Calendar now = Calendar.getInstance(); String path = now.get(Calendar.YEAR)+"//"+(now.get(Calendar.MONTH) + 1) + "//"+now.get(Calendar.DAY_OF_MONTH); File file = new File(diskPath+path); if (!file.exists()) { file.mkdirs(); } path=path+"//"+contractId+".jpg"; OutputStream jos = null; jos = new FileOutputStream(diskPath+path); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(jos); JPEGEncodeParam jpegEP = JPEGCodec.getDefaultJPEGEncodeParam(localBufferedImage); jpegEP.setQuality((float) 1, true); try { encoder.encode(localBufferedImage, jpegEP); jos.flush(); } catch (IOException e) { e.printStackTrace(); } finally { try { jos.close(); } catch (IOException e) { e.printStackTrace(); } } BizObjectManager attrBm = JBOFactory.getBizObjectManager(LB_ONEDIMENSIONALCODE.CLASS_NAME,tx); // BizObjectManager attrBm=JBOFactory.getBizObjectManager("jbo.app.tenwa.doc.LB_ONEDIMENSIONALCODE"); BizObject attr=attrBm.newObject(); attr.setAttributeValue("PROJECT_ID", projectId); attr.setAttributeValue("CONTRACT_ID", contractId); attr.setAttributeValue("CONTRACT_NO", contractNo); attr.setAttributeValue("FileName", contractId+".jpg"); Date date= new Date(System.currentTimeMillis()); String pattern="yyyy/MM/dd HH:mm:ss"; SimpleDateFormat sdf= new SimpleDateFormat(pattern); attr.setAttributeValue("InputTime",sdf.format(date)); attr.setAttributeValue("objectType", "OneDimensionalCode"); attr.setAttributeValue("FilePath",path); attr.setAttributeValue("FullPath",diskPath+path); attr.setAttributeValue("Content_Type", "jpg"); // tx.join(attrBm); attrBm.saveObject(attr); return diskPath+path; } /** * 生成word文档 * @param sTemplateParam 生成word文档的参数 * @param tempid 模板的id * @param tx * @return * @throws Exception */ public String createBqWord(String sTemplateParam,String tempid,JBOTransaction tx) throws Exception{ List message=new ArrayList(); //生成参数 JSONObject paramJson=JSONDecoder.decode(sTemplateParam); MapsourceMap=FileOperatorUtil.getJsonObjectToMap(paramJson); BqCreateOfficeService officeSer=new BqCreateOfficeService(tx); if(tempid.length()>0){ BizObjectManager bmbt = JBOFactory.getBizObjectManager(BF_TEMPLATE.CLASS_NAME); tx.join(bmbt); BizObject bobt=bmbt.createQuery("id=:id").setParameter("id",tempid).getSingleResult(false); String TWO_CLASSIFY = bobt.getAttribute("TWOCLASSIFY").toString(); String THREE_CLASSIFY = bobt.getAttribute("THREECLASSIFY").toString(); String FOUR_CLASSIFY = bobt.getAttribute("FOURCLASSIFY").toString(); String TEMPLATEVERSION = bobt.getAttribute("TEMPLATEVERSION").toString(); if(bobt==null||TWO_CLASSIFY==null||THREE_CLASSIFY==null||FOUR_CLASSIFY==null||TEMPLATEVERSION==null){ message.add(NameManager.getItemName("ProductContractTemplate", THREE_CLASSIFY)+"未找到模板配置!"); }else{ // 保存LB_CONTRACT_TEMPLATE表 BizObjectManager bm = JBOFactory.getBizObjectManager(LB_CONTRACT_TEMPLATE.CLASS_NAME); tx.join(bm); BizObject bo = bm.newObject(); String id=UUIDUtil.getUUID(); bo.setAttributeValue("id", id); bo.setAttributeValue("ONE_CLASSIFY", TWO_CLASSIFY); bo.setAttributeValue("TWO_CLASSIFY", THREE_CLASSIFY); bo.setAttributeValue("THREE_CLASSIFY", FOUR_CLASSIFY); bo.setAttributeValue("FOUR_CLASSIFY", TEMPLATEVERSION); // bo.setAttributeValue("CONTRACT_NUMBER", boc.getAttribute("CONTRACT_NUMBER").getString()); bo.setAttributeValue("CONTRACT_ID", sourceMap.get("CONTRACT_ID")); bo.setAttributeValue("FLOWUNID", sourceMap.get("FLOW_UNID")); bm.saveObject(bo); bo.getKey(); sourceMap.put("TEMPLATE_ID", id); BizObject rela=JBOFactory.createBizObjectQuery(LB_DOCRELATIVE.CLASS_NAME,"TEMPLATE_ID=:tempid").setParameter("tempid", tempid).getSingleResult(false); if(rela!=null){ DocListAction doc=new DocListAction(); doc.setRelativeId(rela.getAttribute("id").getString()); doc.deleteRelative(tx); } officeSer.createOfficeByTemplateNo(bobt.getAttribute("id").getString(), sourceMap); } } return message.toString(); } //word转pdf public String wordTopdf(String projectId,String contractId,JBOTransaction tx) throws Exception{ String pdfPath=""; BizObjectManager contBom = JBOFactory.getBizObjectManager(LB_DOC_CONTRACT_LIST.CLASS_NAME, tx); BizObjectManager attrBom = JBOFactory.getBizObjectManager(LB_DOCATTRIBUTE.CLASS_NAME, tx); BizObjectManager lulManage = JBOFactory.getBizObjectManager(LB_UNION_LESSEE.CLASS_NAME, tx); BizObject lul = lulManage.createQuery("project_id=:projectid").setParameter("projectid", projectId).getSingleResult(false); String customername = null; String telephone = null; String ids =null; if(lul!=null){ ids = lul.getAttribute("CUSTOMER_ID").toString(); customername = lul.getAttribute("CUSTOMER_NAME").toString(); BizObjectManager ciManage = JBOFactory.getBizObjectManager(CUSTOMER_INFO.CLASS_NAME, tx); BizObject ci = ciManage.createQuery("customerid=:customerid").setParameter("customerid", lul.getAttribute("CUSTOMER_ID").getString()).getSingleResult(false); BizObjectManager cpManage = JBOFactory.getBizObjectManager(CUSTOMER_PERSON.CLASS_NAME, tx); BizObject cp = cpManage.createQuery("customerid=:customerid").setParameter("customerid", lul.getAttribute("CUSTOMER_ID").getString()).getSingleResult(false); if(ci!=null&&"03".equals(ci.getAttribute("customertype").getString())){ telephone = (cp==null?"":cp.getAttribute("mobile").getString()); } } WordToPDFUtil wordTopdf = new WordToPDFUtil(); File file = null; Boolean result = null; List bo = contBom.createQuery("contract_id=:contractId and file_flag='yes' and process='1'").setParameter("contractId", contractId).getResultList(true); if (bo != null) { for (BizObject contBo : bo) { String attrId = contBo.getAttribute("ATTRIBUTE_ID").toString(); BizObject attrBo = attrBom.createQuery("id='" +attrId+"'").getSingleResult(true); String path = attrBo.getAttribute("FULLPATH").toString(); String lastFilePath = path.replace(".docx", ".pdf"); File filePath = new File(path); if(!filePath.exists()){ logger.info("word转换pdf的源文件不存在"); continue; } String lastFilePathpdf = filePath.getParent(); try { result = wordTopdf.Word2Pdf(path, lastFilePathpdf); } catch (Exception e) { result = false; e.printStackTrace(); } if (result) { file =new File(lastFilePath); contBo.setAttributeValue("FULLPATH",lastFilePath); contBo.setAttributeValue("FILENAME",contBo.getAttribute("FILENAME").toString().replace(".docx",".pdf" )); contBo.setAttributeValue("FILEPATH",contBo.getAttribute("FILEPATH").toString().replace(".docx", ".pdf")); contBo.setAttributeValue("CONTENT_TYPE","application/pdf"); contBo.setAttributeValue("PROCESS","2"); contBo.setAttributeValue("PROJECT_ID",projectId); contBo.setAttributeValue("CUSTOMERNAME",customername); contBo.setAttributeValue("TELEPHONE",telephone); contBo.setAttributeValue("IDS",ids); contBom.saveObject(contBo); pdfPath=attrBo.getAttribute("FULLPATH").toString().replace(".docx", ".pdf"); attrBo.setAttributeValue("FULLPATH",attrBo.getAttribute("FULLPATH").toString().replace(".docx", ".pdf")); attrBo.setAttributeValue("FILENAME",attrBo.getAttribute("FILENAME").toString().replace(".docx", ".pdf")); attrBo.setAttributeValue("FILEPATH",attrBo.getAttribute("FILEPATH").toString().replace(".docx", ".pdf")); attrBo.setAttributeValue("FileSize",file.length()); attrBo.setAttributeValue("CONTENT_TYPE","application/pdf"); attrBom.saveObject(attrBo); }else{ contBo.setAttributeValue("PROCESS","3"); contBom.saveObject(contBo); } } } return pdfPath; } /** * 向pdf插入一维码图片 * @param outPdfFile 插入后输出的路径 * @param markImagePath 一维码的图片路径 * @param tx 事务 * @return * @throws Exception */ public String pdfAndMark(String outPdfFile, String markImagePath,String contractId,String leasform,JBOTransaction tx) throws Exception{ BizObjectManager contBom = JBOFactory.getBizObjectManager(LB_DOC_CONTRACT_LIST.CLASS_NAME, tx); BizObjectManager attrBom = JBOFactory.getBizObjectManager(LB_DOCATTRIBUTE.CLASS_NAME, tx); BizObjectManager loscBom = JBOFactory.getBizObjectManager(LB_ONEDIMENSIONALCODE.CLASS_NAME, tx); BizObject losc = loscBom.createQuery("CONTRACT_ID=:contractId").setParameter("contractId", contractId).getSingleResult(true); if(markImagePath.length()<=0){ if(losc!=null){ markImagePath = losc.getAttribute("FULLPATH").getString(); } } BizObject cont = contBom.createQuery("contract_id=:contractId and file_flag='yes'").setParameter("contractId", contractId).getSingleResult(true); String newPath = ""; String split =""; String InPdfFile=""; if(cont!=null){ InPdfFile=cont.getAttribute("fullpath").toString(); split = cont.getAttribute("filepath").toString(); File file = new File(outPdfFile+split.substring(0,split.lastIndexOf("/"))); if (!file.exists()) { file.mkdirs(); } newPath=outPdfFile+split; }else{ return "error"; } PdfReader reader = new PdfReader(InPdfFile, "PDF".getBytes()); int pages = reader.getNumberOfPages();//获取pdf的总页数 PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(newPath)); Image img = Image.getInstance(markImagePath);//插入水印 //设置图片宽度和高度 img.scaleAbsolute(160, 22); //设置图片水印的位置。 img.setAbsolutePosition(400, 785); PdfContentByte under = stamp.getUnderContent(1); under.addImage(img); if(pages>2&&"02".equals(leasform)){ PdfContentByte under2 = stamp.getUnderContent(3); under2.addImage(img); } stamp.close();// 关闭 File tempfile = new File(InPdfFile); //删除原文件 if(tempfile.exists()) { tempfile.delete(); } cont.setAttributeValue("FULLPATH",newPath); contBom.saveObject(cont); BizObject attr = attrBom.createQuery("ID=:id").setParameter("id", cont.getAttribute("attribute_id").getString()).getSingleResult(true); if(attr!=null){ attr.setAttributeValue("FULLPATH",newPath); attrBom.saveObject(attr); } return newPath; } //公司盖章 public String compnySignIng(String contract_Id,JBOTransaction tx) throws Exception { requestService = (HttpRequestAppService) factory.create(HttpRequestAppService.class, this.getConfigRequestUrl()); BizObjectManager contBom = JBOFactory.getBizObjectManager(LB_DOC_CONTRACT_LIST.CLASS_NAME, tx); Map map = new HashMap(); ContractSignInfo con = null; List bo = null; BizObject ldclBo = null; // 查询lb_doc_contract_list表 bo = contBom.createQuery("contract_id=:contractId and file_flag='yes' and (sendprocess='0' or sendprocess='2' ) ").setParameter("contractId", contract_Id).getResultList(true); for (BizObject keys : bo) { String info = keys.getAttribute("id").toString(); con = new ContractSignInfo(); con.setCustname(keys.getAttribute("DOC_NAME").toString()); con.setCustphone(keys.getAttribute("TELEPHONE").toString()); con.setFileid(keys.getAttribute("ATTRIBUTE_ID").toString()); con.setFilename(keys.getAttribute("FILENAME").toString()); // 获取生成文件路径 String makefullPath = keys.getAttribute("FULLPATH").toString(); File file = new File(makefullPath); if (!file.exists()) { throw new RuntimeException("要读取的文件不存在"); } con.setInputfile(BASE64.encodeImgageToBase64(file)); map.put(info, con); } Map fromCondtion = new HashMap(); Map otherProperty = new HashMap(); Map resultMap = requestService.compnySign(map); if (!resultMap.containsKey("error")) { for (String key : resultMap.keySet()) { // 存储契约锁返回的合同id和合同文件id if (key.indexOf("contract_") == -1) { fromCondtion.clear(); otherProperty.clear(); // 契约锁合同号 String contractId = resultMap.get("contract_" + key); String sendProcess = resultMap.get("contract_" + contractId); ldclBo = contBom.createQuery("ATTRIBUTE_ID='" + key + "'").getSingleResult(true); ldclBo.setAttributeValue("DOCUMENT_ID", resultMap.get(key)); ldclBo.setAttributeValue("SINGCONTRACT_ID", contractId); ldclBo.setAttributeValue("SIGN_TYPE", "COMPLETE");//法人客户当盖完章改为完成状态 ldclBo.setAttributeValue("SENDPROCESS", sendProcess); contBom.saveObject(ldclBo); String contractDocId = ldclBo.getAttribute("id").toString(); fromCondtion.put("id", contractDocId); otherProperty.put("SIGNPROCESS", "0");// 发起电子签约 otherProperty.put("CONTRACTDOCID", contractDocId);// 发起电子签约 otherProperty.put("INPUTTIME",DateAssistant.getTodayNow()); //拷表的方法 DataOperatorUtil.copySingleJBO(LB_DOC_CONTRACT_LIST.CLASS_NAME, fromCondtion, LB_CONTRACT_SIGN_LOG.CLASS_NAME, null, otherProperty, tx); } } downloadDoc(contract_Id,tx); return "success"; } else { Boolean flag = false; String getMessage = resultMap.get("error"); logger.info("契约锁反馈的异常信息" + getMessage); for (String key : resultMap.keySet()) { // 存储契约锁返回的合同id和合同文件id if (key.indexOf("contract_") == -1 && !"error".equals(key)) { fromCondtion.clear(); otherProperty.clear(); // 契约锁合同号 String contractId = resultMap.get("contract_" + key); String sendProcess = resultMap.get("contract_" + contractId); ldclBo = contBom.createQuery("ATTRIBUTE_ID='" + key + "'").getSingleResult(true); ldclBo.setAttributeValue("DOCUMENT_ID", resultMap.get(key)); ldclBo.setAttributeValue("SINGCONTRACT_ID", contractId); ldclBo.setAttributeValue("SENDPROCESS", sendProcess); if ("1".equals(sendProcess)) { flag = true; ldclBo.setAttributeValue("SIGN_TYPE", "SIGNING"); }else if("2".equals(sendProcess)){ ldclBo.setAttributeValue("MESSAGE",getMessage ); } contBom.saveObject(ldclBo); String contractDocId = ldclBo.getAttribute("id").toString(); fromCondtion.put("ID", contractDocId); otherProperty.put("SIGNPROCESS", "0");//发起电子签约 otherProperty.put("CONTRACTDOCID",contractDocId);//发起电子签约 otherProperty.put("INPUTTIME",DateAssistant.getTodayNow()); DataOperatorUtil.copySingleJBO(LB_DOC_CONTRACT_LIST.CLASS_NAME, fromCondtion, LB_CONTRACT_SIGN_LOG.CLASS_NAME, null, otherProperty, tx); } } // 判断不同的异常反馈给前端 if (getMessage.indexOf("用户认证信息与合同签署方信息不匹配") != -1) { getMessage = getMessage.substring((getMessage.indexOf("message")) + 10, (getMessage.indexOf("code")) - 3); return flag + "@" + getMessage; } else if (getMessage.indexOf("contractId不能为空") != -1) { return flag + "@" + getMessage; } else { return flag + "@" + "error"; } } } /** * 根据document_id下载合同 * * @param tx * @return * @throws Exception * @throws Exception * @throws MalformedURLException */ public String downloadDoc(String contract_id,JBOTransaction tx) throws MalformedURLException, Exception { requestService = (HttpRequestAppService) factory.create(HttpRequestAppService.class, this.getConfigRequestUrl()); BizObjectManager contBom = JBOFactory.getBizObjectManager(LB_DOC_CONTRACT_LIST.CLASS_NAME, tx); String sql = ""; sql = "contract_id=:contractid and file_flag='yes'"; try { @SuppressWarnings("unchecked") List bo = contBom.createQuery(sql).setParameter("contractid", contract_id).getResultList(true); if (bo != null) { Map map = new HashMap(); for (BizObject keys : bo) { map.put(keys.getAttribute("DOCUMENT_ID").toString(), keys.getAttribute("FULLPATH").toString()); } Map result = requestService.downloadDoc(map); if (!result.containsKey("error")) { for (String contractId : map.keySet()) { try { if ("success".equals(result.get(contractId))) { String fileString = result.get("file_" + contractId); InputStream fileInput = BASE64.encodeFileToBase64(fileString); OutputStream fileOut = new FileOutputStream(map.get(contractId));// TODO byte[] buffByte = new byte[1024]; int size = 0; while ((size = fileInput.read(buffByte)) != -1) { fileOut.write(buffByte, 0, size); } fileInput.close(); fileOut.close(); } else if ("error".equals(result.get(contractId))) { return "error"; } } catch (Exception e) { e.printStackTrace(); } } return "success"; } else { return "error"; } } } catch (Exception e) { return "error"; } return "success"; } @SuppressWarnings("deprecation") public static String getConfigRequestUrl() throws Exception{ return Configure.getInstance().getConfigure("RequestHessionUrl"); } public Map fileBase(String contractId){ Map fileNameBase = new HashMap(); try { BizObjectManager contBom = JBOFactory.getBizObjectManager(LB_DOC_CONTRACT_LIST.CLASS_NAME); BizObject cont = contBom.createQuery(" contract_id=:contractid and file_flag='yes' and (sendprocess='0' or sendprocess='2' ) ").setParameter("contractid", contractId).getSingleResult(false); if(cont==null){ return fileNameBase; } String newPath = cont.getAttribute("fullpath").getString(); File file = new File(newPath); if (!file.exists()) { return fileNameBase; } // return BASE64.encodeImgageToBase64(file); fileNameBase.put("fileName", newPath.substring(newPath.lastIndexOf("/")+1)); fileNameBase.put("outputFile", BASE64.encodeImgageToBase64(file)); } catch (JBOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return fileNameBase; } /** * 北汽合同变更方法 * @throws Exception */ public void BqChangecontract(String contractId,JBOTransaction tx) throws Exception{ //删除之前生成的文件 BizObjectManager contBom = JBOFactory.getBizObjectManager(LB_DOC_CONTRACT_LIST.CLASS_NAME,tx); List conts = contBom.createQuery(" contract_id=:contractid ").setParameter("contractid", contractId).getResultList(true); for (BizObject cont : conts) { cont.setAttributeValue("file_flag", "no"); contBom.saveObject(cont); } BizObjectManager lctBom = JBOFactory.getBizObjectManager(LB_CONTRACT_TEMPLATE.CLASS_NAME,tx); List lcts = lctBom.createQuery(" contract_id=:contractid ").setParameter("contractid", contractId).getResultList(true); for (BizObject lct : lcts) { lctBom.deleteObject(lct); } } }