package com.jgqz.jgutil;

import cn.myapps.base.web.WebUser;
import cn.myapps.common.data.ParamsTable;
import cn.myapps.common.model.activity.ActivityType;
import cn.myapps.common.model.workflow.BillDefiVO;
import cn.myapps.common.util.PropertyUtil;
import cn.myapps.common.util.SpringApplicationContextUtil;
import cn.myapps.common.util.cache.MemoryCacheUtil;
import cn.myapps.conf.FeignConfig;
import cn.myapps.designtime.common.service.DesignTimeServiceManager;
import cn.myapps.designtime.form.service.FormDesignTimeService;
import cn.myapps.runtime.common.feign.service.KmsFeignService;
import cn.myapps.runtime.common.service.RunTimeServiceManager;
import cn.myapps.runtime.dynaform.PermissionType;
import cn.myapps.runtime.dynaform.document.ejb.Document;
import cn.myapps.runtime.dynaform.document.ejb.DocumentProcess;
import cn.myapps.runtime.dynaform.form.ejb.ButtonField;
import cn.myapps.runtime.dynaform.form.ejb.Form;
import cn.myapps.runtime.dynaform.form.ejb.FormField;
import cn.myapps.runtime.dynaform.form.ejb.ValidateMessage;
import cn.myapps.runtime.macro.runner.IRunner;
import cn.myapps.runtime.macro.runner.JavaScriptFactory;
import cn.myapps.runtime.workflow.element.FlowDiagram;
import cn.myapps.runtime.workflow.element.Node;
import cn.myapps.runtime.workflow.element.Relation;
import cn.myapps.runtime.workflow.engine.StateMachine;
import cn.myapps.runtime.workflow.storage.runtime.ejb.FlowStateRT;
import cn.myapps.runtime.workflow.storage.runtime.ejb.NodeRT;
import cn.myapps.util.ProcessFactory;
import cn.myapps.util.StringUtil;
import cn.myapps.util.http.CookieUtil;
import cn.myapps.util.sequence.Sequence;
import com.kinggrid.pdf.KGPdfHummer;
import com.kinggrid.pdf.executes.DeleteElectronicSeal;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.io.IOUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

public class PdfSignatureUtil {

    /**
     * '生成pdf文件(路径：obpm-demo/uploads/pdf/年月)
     *
     * @param applicationId 软件id
     * @param formId        需要生成pdf的表单id
     * @param docId         文档id
     * @param user          当前登录用户
     * @param request
     * @param response
     * @return
     */
    public String createPdf(String fileName, String applicationId, String formId, String docId, WebUser user, ParamsTable params, HttpServletRequest request) {
        FileOutputStream out = null;
        try {
            DocumentProcess proxy = RunTimeServiceManager.documentProcess(applicationId);
            Document doc = (Document) proxy.doView(docId);
            boolean flag = true;
            if (doc == null) {
                flag = false;
                doc = (Document) MemoryCacheUtil.getFromPrivateSpace(docId, user);
            }

            String pTotalLable = "";
            String cTotalLable = "";

            String language = CookieUtil.getMultiLanguage(request);

            if ("CN".equals(language)) {
                pTotalLable = "当前页小计";
                cTotalLable = "总计";
            } else if ("TW".equals(language)) {
                pTotalLable = "當前頁小計";
                cTotalLable = "總計";
            } else if ("EN".equals(language)) {
                pTotalLable = "Current page total";
                cTotalLable = "Grand total";
            }

            FormDesignTimeService formService = DesignTimeServiceManager.formDesignTimeService();
            Form form = formService.doView(formId);
            StringBuffer html = new StringBuffer();
            html.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
            html.append("<html>\n<head>\n");
            html.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n");
            String pdfA4CssFilePath = PropertyUtil.getPath() + File.separator + "pdf" + File.separator + "pdf-a4.css";
            html.append(getCssContent(pdfA4CssFilePath));
            html.append("</head>\n");
            html.append("<body>\n");
            html.append("<div id=\"container\">\n");
            html.append("<table id=\"toAll\">");
            html.append("<tr>\n");
            html.append("<td valign=\"top\" colspan=\"2\">\n");
            html.append(form.toPdfHtml(doc, params, user, new ArrayList<ValidateMessage>())).append("\n");
            html.append("</td></tr></table>");
            html.append("</div>\n");
            html.append("</body>\n");
            html.append("</html>\n");
            String pdfHtml = html.toString().replace("{*[cn.myapps.runtime.dynaform.view.current_page_total]*}", pTotalLable)
                    .replace("{*[cn.myapps.runtime.dynaform.view.Grant_Total]*}", cTotalLable);
            pdfHtml = pdfHtml.replaceAll("&nbsp;","<span style=\"color:white;\">n</span>");
            // 加上以当前年份月份命名的文件夹
            Calendar cal = Calendar.getInstance();
            int year = cal.get(Calendar.YEAR);
            int month = cal.get(Calendar.MONTH) + 1;
            String path = File.separator + "uploads" + File.separator + "pdf" + File.separator + year + month + File.separator;
            String realPath = PropertyUtil.getPath() + path;
            File folder = new File(realPath);
            if (!folder.exists()) {
                folder.mkdirs();
            }
            if (StringUtil.isBlank(fileName)) {
                fileName = Sequence.getSequence() + ".pdf";
            }

            String filePath = realPath + "temp.html";
            FileOutputStream fos = new FileOutputStream(filePath);
            //String s = "";
            fos.write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">".getBytes());
            fos.write(pdfHtml.getBytes());
            fos.close();
            FeignConfig.ACCESS_TOKEN = user.getACCESS_TOKEN(request);
            String outputPDF = realPath + fileName + ".pdf";
            String pdfPath = File.separator + "uploads"+ File.separator +"exportPdf" + File.separator + fileName + ".pdf";
            //通过feign服务调用kms的html转pdf接口

            KmsFeignService kmsFeignService = SpringApplicationContextUtil.getBean(KmsFeignService.class);
            kmsFeignService.htmlConvertPdf(filePath,outputPDF);

            String savePath = outputPDF.substring(realPath.lastIndexOf("uploads") - 1).replace("\\", "/");

            String kinggridSignature = doc.getKinggridSignature();

            if (StringUtil.isBlank(kinggridSignature)) {
                JSONObject kinggridSignatureJson = new JSONObject();
                JSONObject pdfSignature = new JSONObject();
                pdfSignature.put("pdfUrl", savePath);
                kinggridSignatureJson.put("pdfSignature", pdfSignature);
                doc.setKinggridSignature(kinggridSignatureJson.toString());
            } else {
                JSONObject kinggridSignatureJson = JSONObject.fromObject(kinggridSignature);
                JSONObject pdfSignatureJson = new JSONObject();
                pdfSignatureJson.put("pdfUrl", savePath);
                kinggridSignatureJson.put("pdfSignature", pdfSignatureJson);
                doc.setKinggridSignature(kinggridSignatureJson.toString());
            }

            if (flag) {
                proxy.doUpdate(doc);
            }

            Document document = (Document)MemoryCacheUtil.getFromPrivateSpace(doc.getId(), user);
            document.setKinggridSignature(doc.getKinggridSignature());
            MemoryCacheUtil.putToPrivateSpace(doc.getId(), document, user);

            return pdfPath;
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 判断该位置是否已经签章
     *
     * @param applicationId
     * @param docId
     * @param position
     * @return
     */
    public boolean isSignature(String applicationId, String docId, String position) {
        try {
            DocumentProcess process = (DocumentProcess) ProcessFactory.createRuntimeProcess(DocumentProcess.class, applicationId);
            Document doc = (Document) process.doView(docId);
            if (doc != null) {
                String kinggridSignature = doc.getKinggridSignature();
                if (!StringUtil.isBlank(kinggridSignature)) {
                    JSONObject kinggridSignatureJson = JSONObject.fromObject(kinggridSignature);
                    Object pdfSignature = kinggridSignatureJson.get("pdfSignature");
                    if (pdfSignature != null) {
                        JSONObject pdfSignatureJson = (JSONObject) pdfSignature;
                        Object signatures = pdfSignatureJson.get("signatures");
                        if (signatures != null) {
                            JSONObject signaturesJson = (JSONObject) signatures;
                            Object data = signaturesJson.get("data");
                            if (data != null) {
                                Collection dataList = (Collection) data;
                                Iterator iterator = dataList.iterator();
                                while (iterator.hasNext()) {
                                    JSONObject signature = (JSONObject) iterator.next();
                                    String pos = signature.getString("position");
                                    if (position.equals(pos)) {
                                        return true;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 记录当前节点需要签章的数量
     *
     * @param applicationId
     * @param docId
     * @param params
     * @param user
     */
    public void recordSignatrueAmounts(String applicationId, String docId, String recordDocId, ParamsTable params, WebUser user) {
        try {
            DocumentProcess process = (DocumentProcess) ProcessFactory.createRuntimeProcess(DocumentProcess.class, applicationId);
            Document doc = (Document) process.doView(docId);
            if (doc != null) {
                if(!StringUtil.isBlank(recordDocId)){
                    Document recordDoc = (Document) process.doView(recordDocId);
                    if(recordDoc != null){
                        //需要签章的按钮
                        FlowStateRT flowStateRT = doc.getState();
                        if(flowStateRT != null){
                            Collection<NodeRT> nodeRTs = flowStateRT.getNoderts();
                            FlowDiagram fd = flowStateRT.getFlowVO().toFlowDiagram();
                            for (NodeRT nodeRT : nodeRTs){
                                Node currnode = fd.getNodeByID(nodeRT.getNodeid());

                                //当前节点没有需要签章的
                                String kinggridSignature = recordDoc.getKinggridSignature();
                                if (!StringUtil.isBlank(kinggridSignature)) {
                                    JSONObject kinggridSignatureJson = JSONObject.fromObject(kinggridSignature);
                                    Object pdfSignature = kinggridSignatureJson.get("pdfSignature");
                                    if (pdfSignature != null) {
                                        JSONObject pdfSignatureJson = (JSONObject) pdfSignature;
                                        Object signatures = pdfSignatureJson.get("signatures");
                                        if(signatures != null){
                                            JSONObject signaturesJson = (JSONObject) signatures;
                                            Object data = signaturesJson.get("data");
                                            if(data != null){
                                                JSONArray dataArr = (JSONArray) data;

                                                //获取最大的签章记录数
                                                int maxSignatureNum = 0;
                                                //是否已存在当前节点的信息
                                                boolean isExist = false;
                                                Iterator iterator = dataArr.iterator();
                                                while(iterator.hasNext()){
                                                    JSONObject signature = (JSONObject) iterator.next();
                                                    int signatureNum = signature.getInt("signatureNum");
                                                    String nodeId = signature.getString("nodeId");
                                                    if(signatureNum > maxSignatureNum){
                                                        maxSignatureNum = signatureNum;
                                                    }
                                                    if(nodeId.equalsIgnoreCase(currnode.id)){
                                                        isExist = true;
                                                    }
                                                }

                                                if(!isExist){
                                                    JSONObject signature = new JSONObject();
                                                    signature.put("position", "ignore");
                                                    signature.put("userId", "ignore");
                                                    signature.put("isSignature", false);
                                                    signature.put("signatureNum", ++maxSignatureNum);
                                                    signature.put("nodeId", currnode.id);
                                                    signature.put("statelabel", currnode.statelabel);
                                                    dataArr.add(signature);
                                                    signaturesJson.put("data", dataArr);
                                                }
                                            } else {
                                                JSONArray dataArr = new JSONArray();
                                                JSONObject signature = new JSONObject();
                                                signature.put("position", "ignore");
                                                signature.put("userId", "ignore");
                                                signature.put("isSignature", false);
                                                signature.put("signatureNum", 0);
                                                signature.put("nodeId", currnode.id);
                                                signature.put("statelabel", currnode.statelabel);
                                                dataArr.add(signature);
                                                signaturesJson.put("data", dataArr);
                                            }
                                            pdfSignatureJson.put("signatures", signaturesJson);
                                        } else {
                                            JSONObject signaturesJson = new JSONObject();
                                            JSONArray data = new JSONArray();
                                            JSONObject signature = new JSONObject();
                                            signature.put("position", "ignore");
                                            signature.put("userId", "ignore");
                                            signature.put("isSignature", false);
                                            signature.put("signatureNum", 0);
                                            signature.put("nodeId", currnode.id);
                                            signature.put("statelabel", currnode.statelabel);
                                            data.add(signature);
                                            signaturesJson.put("data", data);
                                            pdfSignatureJson.put("signatures", signaturesJson);
                                        }
                                        kinggridSignatureJson.put("pdfSignature", pdfSignatureJson);
                                        recordDoc.setKinggridSignature(kinggridSignatureJson.toString());
                                        process.doUpdate(recordDoc);
                                    } else {
                                        JSONObject pdfSignatureJson = new JSONObject();
                                        JSONObject signaturesJson = new JSONObject();
                                        JSONArray dataArr = new JSONArray();
                                        JSONObject signature = new JSONObject();
                                        signature.put("position", "ignore");
                                        signature.put("userId", "ignore");
                                        signature.put("isSignature", false);
                                        signature.put("signatureNum", 0);
                                        signature.put("nodeId", currnode.id);
                                        signature.put("statelabel", currnode.statelabel);
                                        dataArr.add(signature);
                                        signaturesJson.put("data", dataArr);
                                        pdfSignatureJson.put("signatures", signaturesJson);
                                        kinggridSignatureJson.put("pdfSignature", pdfSignatureJson);
                                        recordDoc.setKinggridSignature(kinggridSignatureJson.toString());
                                        process.doUpdate(recordDoc);
                                    }
                                } else {
                                    JSONObject kinggridSignatureJson = new JSONObject();
                                    JSONObject pdfSignatureJson = new JSONObject();
                                    JSONObject signaturesJson = new JSONObject();
                                    JSONArray dataArr = new JSONArray();
                                    JSONObject signature = new JSONObject();
                                    signature.put("position", "ignore");
                                    signature.put("userId", "ignore");
                                    signature.put("isSignature", false);
                                    signature.put("signatureNum", 0);
                                    signature.put("nodeId", currnode.id);
                                    signature.put("statelabel", currnode.statelabel);
                                    dataArr.add(signature);
                                    signaturesJson.put("data", dataArr);
                                    pdfSignatureJson.put("signatures", signaturesJson);
                                    kinggridSignatureJson.put("pdfSignature", pdfSignatureJson);
                                    recordDoc.setKinggridSignature(kinggridSignatureJson.toString());
                                    process.doUpdate(recordDoc);
                                }
                            }
                        }
                        Document document = (Document)MemoryCacheUtil.getFromPrivateSpace(recordDoc.getId(), user);
                        document.setKinggridSignature(recordDoc.getKinggridSignature());
                        MemoryCacheUtil.putToPrivateSpace(recordDoc.getId(), document, user);
                    }
                } else {
                    //需要签章的按钮
                    FlowStateRT flowStateRT = doc.getState();
                    if(flowStateRT != null){
                        Collection<NodeRT> nodeRTs =  doc.getState().getNoderts();
                        FlowDiagram fd = flowStateRT.getFlowVO().toFlowDiagram();
                        for (NodeRT nodeRT : nodeRTs) {
                            Node currnode = fd.getNodeByID(nodeRT.getNodeid());

                            //当前节点没有需要签章的
                            String kinggridSignature = doc.getKinggridSignature();
                            if (!StringUtil.isBlank(kinggridSignature)) {
                                JSONObject kinggridSignatureJson = JSONObject.fromObject(kinggridSignature);
                                Object pdfSignature = kinggridSignatureJson.get("pdfSignature");
                                if (pdfSignature != null) {
                                    JSONObject pdfSignatureJson = (JSONObject) pdfSignature;
                                    Object signatures = pdfSignatureJson.get("signatures");
                                    if(signatures != null){
                                        JSONObject signaturesJson = (JSONObject) signatures;
                                        Object data = signaturesJson.get("data");
                                        if(data != null){
                                            JSONArray dataArr = (JSONArray) data;

                                            //获取最大的签章记录数
                                            int maxSignatureNum = 0;
                                            //是否已存在当前节点的信息
                                            boolean isExist = false;
                                            Iterator iterator = dataArr.iterator();
                                            while(iterator.hasNext()){
                                                JSONObject signature = (JSONObject) iterator.next();
                                                int signatureNum = signature.getInt("signatureNum");
                                                String nodeId = signature.getString("nodeId");
                                                if(signatureNum > maxSignatureNum){
                                                    maxSignatureNum = signatureNum;
                                                }
                                                if(nodeId.equalsIgnoreCase(currnode.id)){
                                                    isExist = true;
                                                }
                                            }
                                            if(!isExist){
                                                JSONObject signature = new JSONObject();
                                                signature.put("position", "ignore");
                                                signature.put("userId", "ignore");
                                                signature.put("isSignature", false);
                                                signature.put("signatureNum", ++maxSignatureNum);
                                                signature.put("nodeId", currnode.id);
                                                signature.put("statelabel", currnode.statelabel);
                                                dataArr.add(signature);
                                                signaturesJson.put("data", dataArr);
                                            }
                                        } else {
                                            JSONArray dataArr = new JSONArray();
                                            JSONObject signature = new JSONObject();
                                            signature.put("position", "ignore");
                                            signature.put("userId", "ignore");
                                            signature.put("isSignature", false);
                                            signature.put("signatureNum", 0);
                                            signature.put("nodeId", currnode.id);
                                            signature.put("statelabel", currnode.statelabel);
                                            dataArr.add(signature);
                                            signaturesJson.put("data", dataArr);
                                        }
                                        pdfSignatureJson.put("signatures", signaturesJson);
                                    } else {
                                        JSONObject signaturesJson = new JSONObject();
                                        JSONArray data = new JSONArray();
                                        JSONObject signature = new JSONObject();
                                        signature.put("position", "ignore");
                                        signature.put("userId", "ignore");
                                        signature.put("isSignature", false);
                                        signature.put("signatureNum", 0);
                                        signature.put("nodeId", currnode.id);
                                        signature.put("statelabel", currnode.statelabel);
                                        data.add(signature);
                                        signaturesJson.put("data", data);
                                        pdfSignatureJson.put("signatures", signaturesJson);
                                    }
                                    kinggridSignatureJson.put("pdfSignature", pdfSignatureJson);
                                    doc.setKinggridSignature(kinggridSignatureJson.toString());
                                    process.doUpdate(doc);
                                } else {
                                    JSONObject pdfSignatureJson = new JSONObject();
                                    JSONObject signaturesJson = new JSONObject();
                                    JSONArray dataArr = new JSONArray();
                                    JSONObject signature = new JSONObject();
                                    signature.put("position", "ignore");
                                    signature.put("userId", "ignore");
                                    signature.put("isSignature", false);
                                    signature.put("signatureNum", 0);
                                    signature.put("nodeId", currnode.id);
                                    signature.put("statelabel", currnode.statelabel);
                                    dataArr.add(signature);
                                    signaturesJson.put("data", dataArr);
                                    pdfSignatureJson.put("signatures", signaturesJson);
                                    kinggridSignatureJson.put("pdfSignature", pdfSignatureJson);
                                    doc.setKinggridSignature(kinggridSignatureJson.toString());
                                    process.doUpdate(doc);
                                }
                            } else {
                                JSONObject kinggridSignatureJson = new JSONObject();
                                JSONObject pdfSignatureJson = new JSONObject();
                                JSONObject signaturesJson = new JSONObject();
                                JSONArray dataArr = new JSONArray();
                                JSONObject signature = new JSONObject();
                                signature.put("position", "ignore");
                                signature.put("userId", "ignore");
                                signature.put("isSignature", false);
                                signature.put("signatureNum", 0);
                                signature.put("nodeId", currnode.id);
                                signature.put("statelabel", currnode.statelabel);
                                dataArr.add(signature);
                                signaturesJson.put("data", dataArr);
                                pdfSignatureJson.put("signatures", signaturesJson);
                                kinggridSignatureJson.put("pdfSignature", pdfSignatureJson);
                                doc.setKinggridSignature(kinggridSignatureJson.toString());
                                process.doUpdate(doc);
                            }
                        }
                    }
                    Document document = (Document)MemoryCacheUtil.getFromPrivateSpace(doc.getId(), user);
                    document.setKinggridSignature(doc.getKinggridSignature());
                    MemoryCacheUtil.putToPrivateSpace(doc.getId(), document, user);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 检查当前节点是否全部签章了
     *
     * @param applicationId
     * @param docId
     * @param params
     * @param user
     * @return
     */
    public boolean checkSignatureAmounts(String applicationId, String docId, ParamsTable params, WebUser user) {
        try {
            DocumentProcess process = (DocumentProcess) ProcessFactory.createRuntimeProcess(DocumentProcess.class, applicationId);
            Document doc = (Document) process.doView(docId);
            if (doc != null) {
                Form form = doc.getForm();
                doc = form.recalculateDocument(doc, params, user);
                int mySignatureActsCount = getSignatureAct(doc, form.getAllFields(), params, user, new ArrayList<Integer>());
                if(mySignatureActsCount == 0){
                    return true;
                } else {
                    return false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    /**
     * 根据传入的css路径地址获取css文件内容
     *
     * @param url
     * @return
     * @throws Exception
     */
    private String getCssContent(String url) throws Exception {
        StringBuffer content = new StringBuffer();
        content.append("<style>\n");
        String filePath = url;
        content.append(cn.myapps.util.file.FileOperate.getFileContentAsString(filePath));
        content.append("</style>\n");
        return content.toString();
    }

    /**
     * 获取当前节点
     *
     * @param doc
     * @param user
     * @return
     * @throws Exception
     */
    private Node getCurrentNode(Document doc, WebUser user) throws Exception {
        FlowStateRT instance = doc.getState();
        if (instance != null) {
            BillDefiVO flowVO = instance.getFlowVO();
            String currNodeId = null;
            FlowDiagram fd = null;
            if (flowVO != null) {
                NodeRT nodert = null;
                fd = flowVO.toFlowDiagram();
                if (instance.isTemp()) {
                    nodert = ((List<NodeRT>) instance.getNoderts()).get(0);
                    currNodeId = nodert.getNodeid();
                }

                if (currNodeId == null && nodert == null) {
                    nodert = StateMachine.getCurrUserNodeRT(doc, user, currNodeId);
                    if (nodert != null)
                        currNodeId = nodert.getNodeid();
                }
            }
            // 获取当前结点
            Node currnode = null;
            if (currNodeId != null) {
                currnode = (Node) fd.getElementByID(currNodeId);
            }
            return currnode;
        }
        return null;
    }

    /**
     * 获取签章按钮
     *
     * @param doc
     * @param fields
     * @param params
     * @param user
     * @return
     * @throws Exception
     */
    private int getSignatureAct(Document doc, Collection<FormField> fields, ParamsTable params, WebUser user, List<Integer> signatureActsCount) throws Exception {
        int mySignatureActsCount = 0;
        IRunner runner = JavaScriptFactory.getInstance(user.getSessionid(), doc.getApplicationid());
        runner.initBSFManager(doc, params, user, new ArrayList<ValidateMessage>());

        for (FormField formField : fields) {
            if (formField instanceof ButtonField && ((ButtonField) formField).getActType() == ActivityType.SIGNATURE && "PDF".equals(((ButtonField) formField).getSignatureType())) {
                String signatureAction = ((ButtonField) formField).getSignatureAction();
                if("date".equals(signatureAction)){
                    continue;
                }
                int displayType = formField.getDisplayType(doc, runner, user, PermissionType.MODIFY);
                if (displayType != PermissionType.HIDDEN) {
                    mySignatureActsCount++;
                    signatureActsCount.add(1);
                }
            }
        }
        return mySignatureActsCount;
    }

    /**
     * 删除回退节点内的签章（记录数比当前节点大的都删除）
     * @param applicationId
     * @param docId
     */
    public void deleteSignatures(String applicationId, String docId, String deleteDocId, WebUser user) {
        try {
            DocumentProcess process = (DocumentProcess) ProcessFactory.createRuntimeProcess(DocumentProcess.class, applicationId);
            Document doc = (Document) process.doView(docId);
            if (doc != null) {
                if(!StringUtil.isBlank(deleteDocId)){
                    Document deleteDoc = (Document) process.doView(deleteDocId);
                    if(deleteDoc != null){
                        if (!StringUtil.isBlank(deleteDoc.getKinggridSignature())) {
                            JSONObject kinggridSignature = JSONObject.fromObject(deleteDoc.getKinggridSignature());
                            Object pdfSignature = kinggridSignature.get("pdfSignature");
                            if (pdfSignature != null) {
                                JSONObject pdfSignatureJson = (JSONObject) pdfSignature;
                                Object signatures = pdfSignatureJson.get("signatures");
                                if (signatures != null) {
                                    JSONObject signaturesJson = (JSONObject) signatures;
                                    Object data = signaturesJson.get("data");
                                    if (data != null) {
                                        FlowStateRT flowStateRT = doc.getState();
                                        if(flowStateRT != null){
                                            Collection<NodeRT> nodeRTs = flowStateRT.getNoderts();
                                            FlowDiagram fd = flowStateRT.getFlowVO().toFlowDiagram();
                                            Node firstNode = fd.getFirstNode();
                                            //pdf路径
                                            String pdfUrl = pdfSignatureJson.getString("pdfUrl");
                                            //记录删除前全部签章数量
                                            int signatureCount = 0;
                                            JSONArray dataArr = (JSONArray) data;
                                            for (Iterator dataArrIterator = dataArr.iterator();dataArrIterator.hasNext();){
                                                JSONObject dataJson = (JSONObject) dataArrIterator.next();
                                                Object isSignatureObj = dataJson.get("isSignature");
                                                if(isSignatureObj != null){
                                                    boolean isSignature = dataJson.getBoolean("isSignature");
                                                    if(isSignature){
                                                        signatureCount++;
                                                    }
                                                } else {
                                                    signatureCount++;
                                                }
                                            }
                                            NodeRT nodeRT = nodeRTs.iterator().next();
                                            if(nodeRT != null){
                                                Node currnode = fd.getNodeByID(nodeRT.getNodeid());
                                                if(isFirstNode(fd, currnode)){
                                                    //删除pdf文件中的签章
                                                    for(int i=0; i<signatureCount; i++){
                                                        delElectronicSeal(pdfUrl);
                                                    }
                                                    //当前节点是第一个人工节点，删除全部信息
                                                    signaturesJson.put("data", new JSONArray());
                                                    pdfSignatureJson.put("signatures", signaturesJson);
                                                    kinggridSignature.put("pdfSignature", pdfSignatureJson);
                                                    deleteDoc.setKinggridSignature(kinggridSignature.toString());
                                                    process.doUpdate(deleteDoc);
                                                } else {
                                                    Iterator iterator = dataArr.iterator();
                                                    int countDeleteNum = 0;
                                                    //当前节点最小签章记录数
                                                    int minSignatureNum = 1000;
                                                    while (iterator.hasNext()) {
                                                        JSONObject signature = (JSONObject) iterator.next();
                                                        String nodeId = signature.getString("nodeId");
                                                        int signatureNum = signature.getInt("signatureNum");
                                                        if (currnode.id.equals(nodeId)) {
                                                            if (signatureNum < minSignatureNum) {
                                                                minSignatureNum = signatureNum;
                                                            }
                                                        }
                                                    }

                                                    //记录回退经过的哪些节点，除了当前节点
                                                    iterator = dataArr.iterator();
                                                    while (iterator.hasNext()) {
                                                        JSONObject signature = (JSONObject) iterator.next();
                                                        int signatureNum = signature.getInt("signatureNum");
                                                        //比当前节点签章记录大的都删除，除了不是签章的记录
                                                        if (signatureNum >= minSignatureNum) {
                                                            iterator.remove();
                                                        }
                                                    }

                                                    //给个节点定位，防止再次回退找不到
                                                    JSONObject signature = new JSONObject();
                                                    signature.put("position", "ignore");
                                                    signature.put("userId", "ignore");
                                                    signature.put("isSignature", false);
                                                    signature.put("signatureNum", minSignatureNum);
                                                    signature.put("nodeId", currnode.id);
                                                    signature.put("statelabel", currnode.statelabel);
                                                    dataArr.add(signature);

                                                    //记录删除签章后的数量
                                                    int afterSignatureCount = 0;
                                                    for (Iterator dataArrIterator = dataArr.iterator();dataArrIterator.hasNext();){
                                                        JSONObject dataJson = (JSONObject) dataArrIterator.next();
                                                        Object isSignatureObj = dataJson.get("isSignature");
                                                        if(isSignatureObj != null){
                                                            boolean isSignature = dataJson.getBoolean("isSignature");
                                                            if(isSignature){
                                                                afterSignatureCount++;
                                                            }
                                                        } else {
                                                            afterSignatureCount++;
                                                        }
                                                    }
                                                    //删除pdf文件中的签章
                                                    for(int i=0;i<(signatureCount-afterSignatureCount);i++){
                                                        delElectronicSeal(pdfUrl);
                                                    }

                                                    signaturesJson.put("data", dataArr);
                                                    pdfSignatureJson.put("signatures", signaturesJson);
                                                    kinggridSignature.put("pdfSignature", pdfSignatureJson);
                                                    deleteDoc.setKinggridSignature(kinggridSignature.toString());
                                                    process.doUpdate(deleteDoc);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        Document document = (Document)MemoryCacheUtil.getFromPrivateSpace(deleteDoc.getId(), user);
                        document.setKinggridSignature(deleteDoc.getKinggridSignature());
                        MemoryCacheUtil.putToPrivateSpace(deleteDoc.getId(), document, user);
                    }
                } else {
                    if (!StringUtil.isBlank(doc.getKinggridSignature())) {
                        JSONObject kinggridSignature = JSONObject.fromObject(doc.getKinggridSignature());
                        Object pdfSignature = kinggridSignature.get("pdfSignature");
                        if (pdfSignature != null) {
                            JSONObject pdfSignatureJson = (JSONObject) pdfSignature;
                            Object signatures = pdfSignatureJson.get("signatures");
                            if (signatures != null) {
                                JSONObject signaturesJson = (JSONObject) signatures;
                                Object data = signaturesJson.get("data");
                                if (data != null) {
                                    FlowStateRT flowStateRT = doc.getState();
                                    if(flowStateRT != null){
                                        Collection<NodeRT> nodeRTs = flowStateRT.getNoderts();
                                        FlowDiagram fd = flowStateRT.getFlowVO().toFlowDiagram();
                                        Node firstNode = fd.getFirstNode();

                                        //pdf路径
                                        String pdfUrl = pdfSignatureJson.getString("pdfUrl");
                                        //记录删除前全部签章数量
                                        int signatureCount = 0;
                                        JSONArray dataArr = (JSONArray) data;
                                        for (Iterator dataArrIterator = dataArr.iterator();dataArrIterator.hasNext();){
                                            JSONObject dataJson = (JSONObject) dataArrIterator.next();
                                            Object isSignatureObj = dataJson.get("isSignature");
                                            if(isSignatureObj != null){
                                                boolean isSignature = dataJson.getBoolean("isSignature");
                                                if(isSignature){
                                                    signatureCount++;
                                                }
                                            } else {
                                                signatureCount++;
                                            }
                                        }
                                        NodeRT nodeRT = nodeRTs.iterator().next();
                                        if(nodeRT != null) {
                                            Node currnode = fd.getNodeByID(nodeRT.getNodeid());
                                            if(isFirstNode(fd, currnode)){
                                                //删除pdf文件中的签章
                                                for(int i=0; i<signatureCount; i++){
                                                    delElectronicSeal(pdfUrl);
                                                }
                                                //当前节点是第一个人工节点，删除全部信息
                                                signaturesJson.put("data", new JSONArray());
                                                pdfSignatureJson.put("signatures", signaturesJson);
                                                kinggridSignature.put("pdfSignature", pdfSignatureJson);
                                                doc.setKinggridSignature(kinggridSignature.toString());
                                                process.doUpdate(doc);
                                            } else {
                                                Iterator iterator = dataArr.iterator();
                                                //当前节点最小签章记录数
                                                int minSignatureNum = 1000;
                                                while (iterator.hasNext()) {
                                                    JSONObject signature = (JSONObject) iterator.next();
                                                    String nodeId = signature.getString("nodeId");
                                                    int signatureNum = signature.getInt("signatureNum");
                                                    if (currnode.id.equals(nodeId)) {
                                                        if (signatureNum < minSignatureNum) {
                                                            minSignatureNum = signatureNum;
                                                        }
                                                    }
                                                }
                                                iterator = dataArr.iterator();
                                                while (iterator.hasNext()) {
                                                    JSONObject signature = (JSONObject) iterator.next();
                                                    int signatureNum = signature.getInt("signatureNum");

                                                    //比当前节点签章记录大的都删除，除了不是签章的记录
                                                    if (signatureNum >= minSignatureNum) {
                                                        iterator.remove();
                                                    }
                                                }

                                                //给个节点定位，防止再次回退找不到
                                                JSONObject signature = new JSONObject();
                                                signature.put("position", "ignore");
                                                signature.put("userId", "ignore");
                                                signature.put("isSignature", false);
                                                signature.put("signatureNum", minSignatureNum);
                                                signature.put("nodeId", currnode.id);
                                                signature.put("statelabel", currnode.statelabel);
                                                dataArr.add(signature);

                                                //记录删除签章后的数量
                                                int afterSignatureCount = 0;
                                                for (Iterator dataArrIterator = dataArr.iterator();dataArrIterator.hasNext();){
                                                    JSONObject dataJson = (JSONObject) dataArrIterator.next();
                                                    Object isSignatureObj = dataJson.get("isSignature");
                                                    if(isSignatureObj != null){
                                                        boolean isSignature = dataJson.getBoolean("isSignature");
                                                        if(isSignature){
                                                            afterSignatureCount++;
                                                        }
                                                    } else {
                                                        afterSignatureCount++;
                                                    }
                                                }
                                                //删除pdf文件中的签章
                                                for(int i=0;i<(signatureCount-afterSignatureCount);i++){
                                                    delElectronicSeal(pdfUrl);
                                                }

                                                signaturesJson.put("data", dataArr);
                                                pdfSignatureJson.put("signatures", signaturesJson);
                                                kinggridSignature.put("pdfSignature", pdfSignatureJson);
                                                doc.setKinggridSignature(kinggridSignature.toString());
                                                process.doUpdate(doc);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    Document document = (Document)MemoryCacheUtil.getFromPrivateSpace(doc.getId(), user);
                    document.setKinggridSignature(doc.getKinggridSignature());
                    MemoryCacheUtil.putToPrivateSpace(doc.getId(), document, user);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断是不是第一个人工节点
     * @param fd
     * @param currNode
     * @return
     */
    private boolean isFirstNode(FlowDiagram fd, Node currNode){
        Vector<Relation> relations = fd.getNodeNextRelation(fd.getFirstNode());

        boolean isFirstNode = false;
        for(Iterator<Relation> iterator = relations.iterator(); iterator.hasNext();){
            Relation relation = iterator.next();
            Node node = relation.getEndnode();
            if(currNode.id.equals(node.id)){
                isFirstNode = true;
            }
        }
        return isFirstNode;
    }

    /**
     * 删除签章方法
     * @param pdfPath
     * 		pdf文件路径
     */
    private static void delElectronicSeal(String pdfPath){
        KGPdfHummer hummer = null;
        FileOutputStream  fileOutputStream = null;
        String oldPdfUrl = "";
        String newPdfUrl = "";
        try {
            int num = pdfPath.lastIndexOf("/")+1;
            String fileName = pdfPath.substring(num, pdfPath.length());
            String path = PropertyUtil.getPath() + pdfPath.substring(0, num);

            oldPdfUrl = path + fileName;
            newPdfUrl = path + "tmp_" + fileName;

            fileOutputStream = new FileOutputStream(newPdfUrl);
            hummer = KGPdfHummer.createInstance(oldPdfUrl, null,
                    true, fileOutputStream, true);

            DeleteElectronicSeal deleteElectronicSeal = new DeleteElectronicSeal();
            deleteElectronicSeal.setDeleteLastOneSeal(true);
            hummer.addExecute(deleteElectronicSeal);

//            DeleteSignature deleteSignature = new DeleteSignature();
//            deleteSignature.deleteLastOne("keysn");
//            hummer.addExecute(deleteSignature);

            hummer.doExecute();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(fileOutputStream != null){
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(hummer != null) hummer.close();

            saveFile(oldPdfUrl, newPdfUrl);
        }
    }

    /**
     * 保存文件
     * @param oldPdfUrl
     * @param newPdfUrl
     */
    private static void saveFile(String oldPdfUrl, String newPdfUrl) {
        FileOutputStream fileOutputStream = null;
        FileInputStream in = null;
        File newFile = new File(newPdfUrl);
        try {
            in = new FileInputStream(newFile);
            fileOutputStream = new FileOutputStream(oldPdfUrl);
            IOUtils.copy(in, fileOutputStream);
        } catch (IOException var10) {
            throw new RuntimeException(var10.getMessage(), var10);
        } finally {
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(fileOutputStream);
            if (newFile.exists()) {
                newFile.delete();
            }

        }
    }
}
