package com.engine.workflow.cmd.requestForm;

import com.api.workflow.util.ServiceUtil;
import com.cloudstore.dev.api.util.Util_TableMap;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.workflow.biz.WorkflowTestBiz;
import com.engine.workflow.biz.publicApi.RequestOperateBiz;
import com.engine.workflow.biz.requestForm.RequestRemindBiz;
import com.engine.workflow.biz.requestForm.SubmitErrorMsgBiz;
import com.engine.workflow.biz.requestForm.TestWorkflowCheckBiz;
import com.engine.workflow.biz.requestList.RequestAttentionBiz;
import com.engine.workflow.biz.workflowOvertime.OvertimeBiz;
import com.engine.workflow.constant.RemindTypeEnum;
import com.engine.workflow.constant.requestForm.RequestExecuteType;
import com.engine.workflow.entity.requestForm.RequestOperationResultBean;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.file.FileUpload;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.meeting.MeetingUtil;
import weaver.systeminfo.SystemEnv;
import weaver.workflow.agent.AgentManager;
import weaver.workflow.msg.MsgPushUtil;
import weaver.workflow.msg.entity.MsgEntity;
import weaver.workflow.report.RequestDeleteLog;
import weaver.workflow.request.RequestAnnexUpload;
import weaver.workflow.request.RequestDeleteUtils;
import weaver.workflow.request.RequestOperationMsgManager;
import weaver.workflow.request.WFUrgerManager;
import weaver.workflow.workflow.*;
import weaver.workflow.workflow.RequestForceDrawBack;
import weaver.workflow.workflow.WFManager;
import weaver.workflow.workflow.WfForceDrawBack;
import weaver.workflow.workflow.WfForceOver;
import weaver.workflow.workflow.WfFunctionManageUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 功能管理
 * @author liuzy 2018/5/4
 */
public class FunctionManageCmd extends AbstractCommonCommand<Map<String,Object>>{

    private HttpServletRequest request;
    private HttpServletResponse response;

    public FunctionManageCmd(HttpServletRequest request, HttpServletResponse response, User user){
        this.request = request;
        this.response = response;
        this.user = user;
    }

    //判断是否为空，可能已分配空间有值为 "" (空串)，也可能未分配空间没有值为 null
    private boolean isEmpty(String str) {
        if ("".equals(str) || str == null) {
            return true;
        } else {
            return false;
        }
    }

    public Map<String,Object> execute(CommandContext commandContext){
        Map<String, Object> apidatas = new HashMap<String, Object>();

        Map<String, String> resultmap = new HashMap<String, String>();
        int logintype = Util.getIntValue(user.getLogintype());
        int requestid = Util.getIntValue(request.getParameter("requestid"), 0);
        String flag = Util.null2String(request.getParameter("flag"));
        WfFunctionManageUtil wffmu = new WfFunctionManageUtil();
        ArrayList<String> requestidlist = new ArrayList<String>();

        int formid = Util.getIntValue(request.getParameter("formid"), 0);
        int requestLogId = Util.getIntValue(request.getParameter("workflowRequestLogId"), 0);
        String signdocids = Util.null2String(request.getParameter("signdocids"));
        String signworkflowids = Util.null2String(request.getParameter("signworkflowids"));
        String remark = Util.null2String(request.getParameter("remark"));
        int workflowid = Util.getIntValue(request.getParameter("workflowid"), 0);
        int nodeid = -1;


        String isnew = new BaseBean().getPropValue("WorkflowOvertimeIsNew" , "isNew");
        boolean isnewFlag = "1".equals(isnew);
        // 流程暂停
        if ("stop".equals(flag)) {
            wffmu.setStopOperation(requestid, user);
//			this.pushOperationMsg(requestid,user,flag);
            if(isnewFlag)
                OvertimeBiz.getInstance().cancelOvertimeTask(requestid, nodeid);//取消超时任务
        }

        // 流程撤销
        if ("cancel".equals(flag)) {
            wffmu.setCancelOperation(requestid, user);
//			this.pushOperationMsg(requestid,user,flag);
            if(isnewFlag)
                OvertimeBiz.getInstance().cancelOvertimeTask(requestid, nodeid);//取消超时任务
        }

        // 流程启用
        if ("restart".equals(flag)) {
            wffmu.setRestartOperation(requestid, user);
//			this.pushOperationMsg(requestid,user,flag);
            if(isnewFlag)
                OvertimeBiz.getInstance().addOvertimeTaskThread(requestid, workflowid, nodeid);//添加超时任务
        }


        // 强制归档
        if ("ov".equals(flag)) {
            WfForceOver wfo = new WfForceOver();
            String annexdocids = "";
            String fromflow = Util.null2String(request.getParameter("fromflow"));
            String remarkLocation = Util.null2String(request.getParameter("remarkLocation"));

            int agentType = Util.getIntValue(Util.null2String(request.getParameter("agentType")));
            int agentorByAgentId = Util.getIntValue(Util.null2String(request.getParameter("agentorByAgentId")));
            if (agentType == 1) {//流程代理出去，本人强制归档，需先收回代理
                AgentManager agentManager = new AgentManager(user);
                agentManager.agentBackRequest(agentorByAgentId, user.getUID(), workflowid + "", requestid);
                Date currentDate = new Date();
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd");
                SimpleDateFormat timeForamt = new SimpleDateFormat("HH:mm:ss");
                new RecordSet().executeUpdate("update workflow_currentoperator set operatedate = ? , operatetime = ? where userid = ? and requestid = ? and (operatedate is null or operatedate < ' ' ) ",
                        dateFormat.format(currentDate), timeForamt.format(currentDate), user.getUID(), requestid);
            }

            if (fromflow.equals("1")) {
                FileUpload fu = new FileUpload(request);
                remark = Util.null2String(fu.getParameter("remark"));
                workflowid = Util.getIntValue(fu.getParameter("workflowid"), -1);
                nodeid = Util.getIntValue(fu.getParameter("nodeid"), -1);

                // 获取签字意见相关文档，相关流程

                signdocids = Util.null2String(fu.getParameter("signdocids"));
                signworkflowids = Util.null2String(fu.getParameter("signworkflowids"));
                String ismode = Util.null2String(request.getParameter("ismode"));
                if (!ismode.equals("1")) {
                    RequestAnnexUpload rau = new RequestAnnexUpload();
                    rau.setRequest(fu);
                    rau.setUser(user);
                    annexdocids = rau.AnnexUpload();
                } else {
                    String hasSign = "0";// 模板中是否设置了签字
                    RecordSet rs = new RecordSet();
                    rs.executeSql("select * from workflow_modeview where formid=" + formid + " and nodeid=" + nodeid + " and fieldid=-4");
                    if (rs.next())
                        hasSign = "1";
                    if ("1".equals(hasSign)) {// 模板中设置了签字
                        annexdocids = Util.null2String(fu.getParameter("qianzi"));
                    } else {// 模板中没有设置签字，按普通方式上传签字意见的附件
                        RequestAnnexUpload rau = new RequestAnnexUpload();
                        rau.setRequest(fu);
                        rau.setUser(user);
                        annexdocids = rau.AnnexUpload();
                    }
                }


                WFManager wfManager = new WFManager();
                wfManager.setWfid(workflowid);
                try {
                    wfManager.getWfInfo();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                String isShowChart = Util.null2s(wfManager.getIsShowChart().trim(),"0");
                apidatas.put("isShowChart", isShowChart);
            }

            wfo.setRemark(remark);
            wfo.setAnnexdocids(annexdocids);
            wfo.setSigndocids(signdocids);
            wfo.setSignworkflowids(signworkflowids);
            wfo.setRequestLogId(requestLogId);
            wfo.setRemarkLocation(remarkLocation);

            WFUrgerManager wfum = new WFUrgerManager();
            if (wffmu.haveOtherOperationRight(requestid) && !wfo.isOver(requestid) && (wfo.isNodeOperator(requestid, user.getUID()) || wfum.getMonitorViewRight(requestid, user.getUID()))) {
                requestidlist.add("" + requestid);
                wfo.doForceOver(requestidlist, request, response, user);
                apidatas.put("success",1);
                if(isnewFlag)
                    OvertimeBiz.getInstance().cancelOvertimeTask(requestid, nodeid);//取消超时任务
            }else{
                apidatas.put("success",0);
            }
            //判断是否属于流程测试
            TestWorkflowCheckBiz testBiz = new TestWorkflowCheckBiz();
            boolean belongTest = testBiz.judgeBelongTest(request, false);
            if(belongTest) {
                RecordSet rs = new RecordSet();
                rs.executeQuery("select nodeid from workflow_flownode where workflowid = ? and nodetype = 3",workflowid);
                rs.next();
                WorkflowTestBiz.setWorkflowTestInfo(flag, requestid, nodeid, "", null,rs.getInt("nodeid"));
            }

            this.doArchiveRemind(workflowid,requestid);

            new weaver.cpt.util.CptWfUtil().releaseFrozenCptnum(requestid+""); //清除资产冻结
        }

        // 强制收回
        if ("rb".equals(flag)) {

				/*
		    TODO 流程强制收回
		    //先查询workflowid在建模表中是否存在如果存在查询nodeid下
		     1. 先根据requestids查workflowid和nodeid看有没有在配置表里
		     有:有没有子流程数据一并删除
		     没有:不做处理
		    */
            BaseBean bb = new BaseBean();
            RecordSet rs = new RecordSet();
            String lcWorkflowid="";
            String lcCurrentnodeid="";
            String currentnodeid="";
            //requestid,workflowid,currentnodeid
            String query="select * from workflow_requestbase where requestid ="+requestid;
            bb.writeLog("querysql-->"+query);
            try {
                rs.execute(query);
                bb.writeLog("查询数据-->");
                if (rs.next()){
                    lcWorkflowid = Util.null2String(rs.getString("workflowid"));
                    lcCurrentnodeid = Util.null2String(rs.getString("lastnodeid"));
                    currentnodeid = Util.null2String(rs.getString("currentnodeid"));
                }
            }catch (Exception e){
                e.printStackTrace();
            }
            bb.writeLog("lcWorkflowid-->"+lcWorkflowid);
            bb.writeLog("lcCurrentnodeid-->"+lcCurrentnodeid);
            bb.writeLog("currentnodeid-->"+currentnodeid);
            if (!isEmpty(lcWorkflowid) && !isEmpty(lcCurrentnodeid)) {
                bb.writeLog("查询出的workflowid和currentnodeid不为空");
                int cnt = 0;
                int touchnodeid = 0;
                List<Integer> touchnodeids = new ArrayList<>();
                //查询配置表
                String sczlc = "select COUNT(1) as cnt,touchnodeid,workflowid from uf_sczlc where workflowid=" + lcWorkflowid + " and nodeid=" + lcCurrentnodeid + " group by touchnodeid,workflowid";

                bb.writeLog("sczlc-->" + sczlc);
                try {
                    rs.execute(sczlc);
                    bb.writeLog("sczlc查询数据-->");
                    while (rs.next()) {
                        int workflowid1 =  rs.getInt("workflowid");
                        if(workflowid==workflowid1) {
                            int node =  rs.getInt("touchnodeid");
                            bb.writeLog("node =-->"+node);
                            if(currentnodeid.equals(node+"")){
                                touchnodeid = node;
                                cnt++;
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                bb.writeLog("workflowid-->" + workflowid);
                bb.writeLog("touchnodeid-->" + touchnodeid);
                bb.writeLog("cnt结果-->" + cnt);
                if (cnt>0){
//						 select requestid,workflowid,currentnodeid from workflow_requestbase where mainrequestid=239239
//						 select COUNT(*) as cnt from workflow_requestbase where mainrequestid=239239
                    List<Map<String, String>> subList = new ArrayList<>();
//					String subWorkflowSql="select * from Workflow_SubwfSet where mainWorkflowId="+lcWorkflowid+" and triggerNodeId="+lcCurrentnodeid;
                    String subworkflowsql1 = "select workflowid subWorkflowId from workflow_requestbase  where requestid in (select subrequestid  from workflow_subwfrequest where subrequestid in (select requestid from workflow_requestbase where mainrequestid="+requestid+" and triggernode = "+touchnodeid+"))";
                    //String subWorkflowSql="select subWorkflowId from Workflow_SubwfSet where mainWorkflowId="+lcWorkflowid+" and triggerNodeId="+touchnodeid;
                    bb.writeLog("subWorkflowSql-->"+subworkflowsql1);
                    try {
                        rs.executeQuery(subworkflowsql1);
                        bb.writeLog("查询数据子流程id-->");
                        while (rs.next()){
                            Map<String, String> subMap = new HashMap<String, String>();
                            String subWorkflowId = Util.null2String(rs.getString(1));
                            bb.writeLog("subWorkflowId-->"+subWorkflowId);
                            subMap.put("subWorkflowId",subWorkflowId);
                            subList.add(subMap);
                        }
                        bb.writeLog("查询数据subList-->"+subList);
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                    if (subList.size()>0){
                        bb.writeLog("进入subList>0-->");
                        String subWorkid="";
                        for (int s = 0; s < subList.size(); s++) {
                            String subWorkflowId = subList.get(s).get("subWorkflowId").toString();
                            if(s+1 == subList.size()){
                                subWorkid = subWorkid + subWorkflowId;
                            }else{
                                subWorkid = subWorkid + subWorkflowId+",";
                            }
                        }
                        bb.writeLog("subWorkid-->"+subWorkid);

                        List<Map<String, String>> zlcList = new ArrayList<>();
                        String zlc=" select * from workflow_requestbase where mainrequestid="+requestid+" and workflowid in ("+subWorkid+")";
                        bb.writeLog("zlc-->"+zlc);
                        try {
                            rs.execute(zlc);
                            bb.writeLog("zlc查询数据-->");
                            while (rs.next()){
                                Map<String, String> zlcMap = new HashMap<String, String>();
                                String zlcRequestid = Util.null2String(rs.getString("requestid"));
                                String zlcWorkflowid = Util.null2String(rs.getString("workflowid"));
                                String zlcCurrentnodeid = Util.null2String(rs.getString("currentnodeid"));
                                zlcMap.put("zlcRequestid",zlcRequestid);
                                zlcMap.put("zlcWorkflowid",zlcWorkflowid);
                                zlcMap.put("zlcCurrentnodeid",zlcCurrentnodeid);
                                zlcList.add(zlcMap);
                            }
                            bb.writeLog("zlc查询数据zlcList-->"+zlcList);
                        }catch (Exception e){
                            e.printStackTrace();
                        }

                        if (zlcList.size()>0){
                            bb.writeLog("进入zlcList.size()>0-->");
                            String idResult="";
                            for (int s = 0; s < zlcList.size(); s++) {
                                String id = zlcList.get(s).get("zlcRequestid").toString();
                                if(s+1 == zlcList.size()){
                                    idResult = idResult + id;
                                }else{
                                    idResult = idResult + id+",";
                                }
                            }
                            bb.writeLog("idResult-->"+idResult);

                            ArrayList<Map> ResultList = new ArrayList<>();
                            String selectbaseSql="select * from workflow_requestbase where requestid in ("+idResult+")";
                            try {
                                rs.execute(selectbaseSql);
                                while (rs.next()){
                                    HashMap<String, String> map = new HashMap<>();
                                    map.put("requestid",Util.null2String(rs.getString("requestid")));
                                    map.put("workflowid",Util.null2String(rs.getString("workflowid")));
                                    ResultList.add(map);
                                }
                            }catch (Exception e){
                                e.printStackTrace();
                            }

                            bb.writeLog("ResultList-->"+ResultList);

                            for (int i = 0; i < ResultList.size(); i++) {
                                bb.writeLog("进入删除子流程方法-->["+i+"]");
                                boolean requestid1 = deleteWF(ResultList.get(i).get("requestid").toString(), user, "");
                                bb.writeLog("删除返回值-->"+requestid1);
                            }


//							if (zlcList.size()>0){
//							bb.writeLog("进入zlcList.size()>0-->");
//							String idResult="";
//							for (int s = 0; s < zlcList.size(); s++) {
//								String id = zlcList.get(s).get("zlcRequestid").toString();
//								if(s+1 == zlcList.size()){
//									idResult = idResult + id;
//								}else{
//									idResult = idResult + id+",";
//								}
//							}
//							bb.writeLog("idResult-->"+idResult);
//


							/*if (!isEmpty(idResult) && !isEmpty(subWorkid)){
								List<Map<String, String>> selectbaseList = new ArrayList<>();
								String selectbaseSql="select * from workflow_requestbase where requestid in ("+idResult+") and workflowid in ("+subWorkid+")";
								bb.writeLog("selectbaseSql-->"+selectbaseSql);
								try {
									rs.execute(selectbaseSql);
									bb.writeLog("查询待删除的子流程数据base-->");
									while (rs.next()){
										Map<String, String> selectbaseMap = new HashMap<String, String>();
										selectbaseMap.put("requestid",Util.null2String(rs.getString("requestid")));
										selectbaseMap.put("workflowid",Util.null2String(rs.getString("workflowid")));
										selectbaseMap.put("lastnodeid",Util.null2String(rs.getString("lastnodeid")));
										selectbaseMap.put("lastnodetype",Util.null2String(rs.getString("lastnodetype")));
										selectbaseMap.put("currentnodeid",Util.null2String(rs.getString("currentnodeid")));
										selectbaseMap.put("currentnodetype",Util.null2String(rs.getString("currentnodetype")));
										selectbaseMap.put("status",Util.null2String(rs.getString("status")));
										selectbaseMap.put("passedgroups",Util.null2String(rs.getString("passedgroups")));
										selectbaseMap.put("totalgroups",Util.null2String(rs.getString("totalgroups")));
										selectbaseMap.put("requestname",Util.null2String(rs.getString("requestname")));
										selectbaseMap.put("creater",Util.null2String(rs.getString("creater")));
										selectbaseMap.put("createdate",Util.null2String(rs.getString("createdate")));
										selectbaseMap.put("createtime",Util.null2String(rs.getString("createtime")));
										selectbaseMap.put("lastoperator",Util.null2String(rs.getString("lastoperator")));
										selectbaseMap.put("lastoperatedate",Util.null2String(rs.getString("lastoperatedate")));
										selectbaseMap.put("lastoperatetime",Util.null2String(rs.getString("lastoperatetime")));
										selectbaseMap.put("deleted",Util.null2String(rs.getString("deleted")));
										selectbaseMap.put("creatertype",Util.null2String(rs.getString("creatertype")));
										selectbaseMap.put("lastoperatortype",Util.null2String(rs.getString("lastoperatortype")));
										selectbaseMap.put("nodepasstime",Util.null2String(rs.getString("nodepasstime")));
										selectbaseMap.put("nodelefttime",Util.null2String(rs.getString("nodelefttime")));
										selectbaseMap.put("docids",Util.null2String(rs.getString("docids")));
										selectbaseMap.put("crmids",Util.null2String(rs.getString("crmids")));
										selectbaseMap.put("hrmids",Util.null2String(rs.getString("hrmids")));
										selectbaseMap.put("prjids",Util.null2String(rs.getString("prjids")));
										selectbaseMap.put("cptids",Util.null2String(rs.getString("cptids")));
										selectbaseMap.put("requestlevel",Util.null2String(rs.getString("requestlevel")));
										selectbaseMap.put("requestmark",Util.null2String(rs.getString("requestmark")));
										selectbaseMap.put("messageType",Util.null2String(rs.getString("messageType")));
										selectbaseMap.put("mainRequestId",Util.null2String(rs.getString("mainRequestId")));
										selectbaseMap.put("currentstatus",Util.null2String(rs.getString("currentstatus")));
										selectbaseMap.put("laststatus",Util.null2String(rs.getString("laststatus")));
										selectbaseMap.put("ismultiprint",Util.null2String(rs.getString("ismultiprint")));
										selectbaseMap.put("chatsType",Util.null2String(rs.getString("chatsType")));
										selectbaseMap.put("ecology_pinyin_search",Util.null2String(rs.getString("ecology_pinyin_search")));
										selectbaseMap.put("requestnamenew",Util.null2String(rs.getString("requestnamenew")));
										selectbaseMap.put("formsignaturemd5",Util.null2String(rs.getString("formsignaturemd5")));
										selectbaseMap.put("dataaggregated",Util.null2String(rs.getString("dataaggregated")));
										selectbaseMap.put("secLevel",Util.null2String(rs.getString("secLevel")));
										selectbaseMap.put("secdocid",Util.null2String(rs.getString("secdocid")));
										selectbaseMap.put("remindTypes",Util.null2String(rs.getString("remindTypes")));
										selectbaseMap.put("lastFeedBackDate",Util.null2String(rs.getString("lastFeedBackDate")));
										selectbaseMap.put("lastFeedBackTime",Util.null2String(rs.getString("lastFeedBackTime")));
										selectbaseMap.put("lastfeedbackoperator",Util.null2String(rs.getString("lastfeedbackoperator")));
										selectbaseMap.put("requestnamehtmlnew",Util.null2String(rs.getString("requestnamehtmlnew")));
										selectbaseMap.put("secvalidity",Util.null2String(rs.getString("secvalidity")));
										selectbaseList.add(selectbaseMap);
									}
									bb.writeLog("查询数据selectbaseList-->"+selectbaseList);
								}catch (Exception e){
									e.printStackTrace();
								}

								for (int i = 0; i < selectbaseList.size(); i++) {
									String baseInsert="insert into deleteworkflow_requestbase (requestid,workflowid,lastnodeid,lastnodetype,currentnodeid,currentnodetype,status,passedgroups,totalgroups,requestname,creater,createdate,createtime,lastoperator,lastoperatedate,lastoperatetime,deleted,creatertype,lastoperatortype,nodepasstime,nodelefttime,docids,crmids,hrmids,prjids,cptids,requestlevel,requestmark,messageType,mainRequestId,currentstatus,laststatus,ismultiprint,chatsType,ecology_pinyin_search,requestnamenew,formsignaturemd5,dataaggregated,secLevel,secdocid,remindTypes,lastFeedBackDate,lastFeedBackTime,lastfeedbackoperator,requestnamehtmlnew,secvalidity) ";
									String baseValues="values ('"
											 +selectbaseList.get(i).get("requestid")+ "'," +
											"'"+selectbaseList.get(i).get("workflowid")+"',"+
											"'"+selectbaseList.get(i).get("lastnodeid")+"',"+
											"'"+selectbaseList.get(i).get("lastnodetype")+"',"+
											"'"+selectbaseList.get(i).get("currentnodeid")+"',"+
											"'"+selectbaseList.get(i).get("currentnodetype")+"',"+
											"'"+selectbaseList.get(i).get("status")+"',"+
											"'"+selectbaseList.get(i).get("passedgroups")+"',"+
											"'"+selectbaseList.get(i).get("totalgroups")+"',"+
											"'"+selectbaseList.get(i).get("requestname")+"',"+
											"'"+selectbaseList.get(i).get("creater")+"',"+
											"'"+selectbaseList.get(i).get("createdate")+"',"+
											"'"+selectbaseList.get(i).get("createtime")+"',"+
											"'"+selectbaseList.get(i).get("lastoperator")+"',"+
											"'"+selectbaseList.get(i).get("lastoperatedate")+"',"+
											"'"+selectbaseList.get(i).get("lastoperatetime")+"',"+
											"'"+selectbaseList.get(i).get("deleted")+"',"+
											"'"+selectbaseList.get(i).get("creatertype")+"',"+
											"'"+selectbaseList.get(i).get("lastoperatortype")+"',"+
											"'"+selectbaseList.get(i).get("nodepasstime")+"',"+
											"'"+selectbaseList.get(i).get("nodelefttime")+"',"+
											"'"+selectbaseList.get(i).get("docids")+"',"+
											"'"+selectbaseList.get(i).get("crmids")+"',"+
											"'"+selectbaseList.get(i).get("hrmids")+"',"+
											"'"+selectbaseList.get(i).get("prjids")+"',"+
											"'"+selectbaseList.get(i).get("cptids")+"',"+
											"'"+selectbaseList.get(i).get("requestlevel")+"',"+
											"'"+selectbaseList.get(i).get("requestmark")+"',"+
											"'"+selectbaseList.get(i).get("messageType")+"',"+
											"'"+selectbaseList.get(i).get("mainRequestId")+"',"+
											"'"+selectbaseList.get(i).get("currentstatus")+"',"+
											"'"+selectbaseList.get(i).get("laststatus")+"',"+
											"'"+selectbaseList.get(i).get("ismultiprint")+"',"+
											"'"+selectbaseList.get(i).get("chatsType")+"',"+
											"'"+selectbaseList.get(i).get("ecology_pinyin_search")+"',"+
											"'"+selectbaseList.get(i).get("requestnamenew")+"',"+
											"'"+selectbaseList.get(i).get("formsignaturemd5")+"',"+
											"'"+selectbaseList.get(i).get("dataaggregated")+"',"+
											"'"+selectbaseList.get(i).get("secLevel")+"',"+
											"'"+selectbaseList.get(i).get("secdocid")+"',"+
											"'"+selectbaseList.get(i).get("remindTypes")+"',"+
											"'"+selectbaseList.get(i).get("lastFeedBackDate")+"',"+
											"'"+selectbaseList.get(i).get("lastFeedBackTime")+"',"+
											"'"+selectbaseList.get(i).get("lastfeedbackoperator")+"',"+
											"'"+selectbaseList.get(i).get("requestnamehtmlnew")+"',"+
											"'"+selectbaseList.get(i).get("secvalidity")+"')";
                                      String baseInsertSql=baseInsert+baseValues;
									  boolean execute = rs.execute(baseInsertSql);
									  bb.writeLog("baseInsertSql-->"+baseInsertSql);
									  bb.writeLog("baseInsert-->"+execute);
								}



								List<Map<String, String>> selectlogList = new ArrayList<>();
								String selectlogSql="select * from workflow_requestlog where requestid in ("+idResult+") and workflowid in ("+subWorkid+")";
								bb.writeLog("selectlogSql-->"+selectlogSql);
								try {
									rs.execute(selectlogSql);
									bb.writeLog("查询待删除的子流程数据log-->");
									while (rs.next()){
										Map<String, String> selectlogMap = new HashMap<String, String>();
										selectlogMap.put("requestid",Util.null2String(rs.getString("requestid")));
										selectlogMap.put("workflowid",Util.null2String(rs.getString("workflowid")));
										selectlogMap.put("nodeid",Util.null2String(rs.getString("nodeid")));
										selectlogMap.put("logtype",Util.null2String(rs.getString("logtype")));
										selectlogMap.put("operatedate",Util.null2String(rs.getString("operatedate")));
										selectlogMap.put("operatetime",Util.null2String(rs.getString("operatetime")));
										selectlogMap.put("operator",Util.null2String(rs.getString("operator")));
										selectlogMap.put("remark",Util.null2String(rs.getString("remark")));
										selectlogMap.put("clientip",Util.null2String(rs.getString("clientip")));
										selectlogMap.put("operatortype",Util.null2String(rs.getString("operatortype")));
										selectlogMap.put("destnodeid",Util.null2String(rs.getString("destnodeid")));
										selectlogMap.put("receivedPersons",Util.null2String(rs.getString("receivedPersons")));
										selectlogMap.put("showorder",Util.null2String(rs.getString("showorder")));
										selectlogMap.put("agentorbyagentid",Util.null2String(rs.getString("agentorbyagentid")));
										selectlogMap.put("agenttype",Util.null2String(rs.getString("agenttype")));
										selectlogMap.put("annexdocids",Util.null2String(rs.getString("annexdocids")));
										selectlogMap.put("requestLogId",Util.null2String(rs.getString("requestLogId")));
										selectlogMap.put("operatorDept",Util.null2String(rs.getString("operatorDept")));
										selectlogMap.put("signdocids",Util.null2String(rs.getString("signdocids")));
										selectlogMap.put("signworkflowids",Util.null2String(rs.getString("signworkflowids")));
										selectlogMap.put("isMobile",Util.null2String(rs.getString("isMobile")));
										selectlogMap.put("HandWrittenSign",Util.null2String(rs.getString("HandWrittenSign")));
										selectlogMap.put("SpeechAttachment",Util.null2String(rs.getString("SpeechAttachment")));
										selectlogMap.put("receivedpersonids",Util.null2String(rs.getString("receivedpersonids")));
										selectlogMap.put("remarklocation",Util.null2String(rs.getString("remarklocation")));
										selectlogMap.put("isSubmitDirect",Util.null2String(rs.getString("isSubmitDirect")));
										selectlogMap.put("remarkquote",Util.null2String(rs.getString("remarkquote")));
										selectlogMap.put("fulltextannotation",Util.null2String(rs.getString("fulltextannotation")));
										selectlogMap.put("speechattachmente9",Util.null2String(rs.getString("speechattachmente9")));
										selectlogMap.put("uuid",Util.null2String(rs.getString("uuid")));
										selectlogMap.put("operatorSub",Util.null2String(rs.getString("operatorSub")));
										selectlogMap.put("operatorJob",Util.null2String(rs.getString("operatorJob")));
										selectlogList.add(selectlogMap);
									}
									bb.writeLog("查询数据selectlogList-->"+selectlogList);
								}catch (Exception e){
									e.printStackTrace();
								}

								for (int i = 0; i < selectlogList.size(); i++) {
									String logInsert="insert into deleteworkflow_requestlog (requestid,workflowid,nodeid,logtype,operatedate,operatetime,operator,remark,clientip,operatortype,destnodeid,receivedPersons,showorder,agentorbyagentid,agenttype,annexdocids,requestLogId,operatorDept,signdocids,signworkflowids,isMobile,HandWrittenSign,SpeechAttachment,receivedpersonids,remarklocation,isSubmitDirect,remarkquote,fulltextannotation,speechattachmente9,uuid,operatorSub,operatorJob) ";
									String logValues="values ('"
											  + selectlogList.get(i).get("requestid")+ "'," +
											"'"+selectlogList.get(i).get("workflowid")+"',"+
											"'"+selectlogList.get(i).get("nodeid")+"',"+
											"'"+selectlogList.get(i).get("logtype")+"',"+
											"'"+selectlogList.get(i).get("operatedate")+"',"+
											"'"+selectlogList.get(i).get("operatetime")+"',"+
											"'"+selectlogList.get(i).get("operator")+"',"+
											"'"+selectlogList.get(i).get("remark")+"',"+
											"'"+selectlogList.get(i).get("clientip")+"',"+
											"'"+selectlogList.get(i).get("operatortype")+"',"+
											"'"+selectlogList.get(i).get("destnodeid")+"',"+
											"'"+selectlogList.get(i).get("receivedPersons")+"',"+
											"'"+selectlogList.get(i).get("showorder")+"',"+
											"'"+selectlogList.get(i).get("agentorbyagentid")+"',"+
											"'"+selectlogList.get(i).get("agenttype")+"',"+
											"'"+selectlogList.get(i).get("annexdocids")+"',"+
											"'"+selectlogList.get(i).get("requestLogId")+"',"+
											"'"+selectlogList.get(i).get("operatorDept")+"',"+
											"'"+selectlogList.get(i).get("signdocids")+"',"+
											"'"+selectlogList.get(i).get("signworkflowids")+"',"+
											"'"+selectlogList.get(i).get("isMobile")+"',"+
											"'"+selectlogList.get(i).get("HandWrittenSign")+"',"+
											"'"+selectlogList.get(i).get("SpeechAttachment")+"',"+
											"'"+selectlogList.get(i).get("receivedpersonids")+"',"+
											"'"+selectlogList.get(i).get("remarklocation")+"',"+
											"'"+selectlogList.get(i).get("isSubmitDirect")+"',"+
											"'"+selectlogList.get(i).get("remarkquote")+"',"+
											"'"+selectlogList.get(i).get("fulltextannotation")+"',"+
											"'"+selectlogList.get(i).get("speechattachmente9")+"',"+
											"'"+selectlogList.get(i).get("uuid")+"',"+
											"'"+selectlogList.get(i).get("operatorSub")+"',"+
											"'"+selectlogList.get(i).get("operatorJob")+"')";
									String logInsertSql=logInsert+logValues;
									boolean execute = rs.execute(logInsertSql);
									bb.writeLog("logInsertSql-->"+logInsertSql);
									bb.writeLog("logInsert-->"+execute);
								}

								String baseSql="delete from workflow_requestbase where requestid in ("+idResult+") and workflowid in ("+subWorkid+")";
								String logSql="delete from workflow_requestlog where requestid in ("+idResult+") and workflowid in ("+subWorkid+")";
								bb.writeLog("进入删除子流程-->");
								bb.writeLog("baseSql-->"+baseSql);
								bb.writeLog("logSql-->"+logSql);
								rs.execute(baseSql);
								rs.execute(logSql);
							}*/
                            //子流程数量
                            int size= ResultList.size();
                            bb.writeLog("子流程数量-->"+size);
                            apidatas.put("zlcCount",size);
                            bb.writeLog("子流程添加成功");
                        }
                    }
                }
            }


            WfForceDrawBack wfdb = new WfForceDrawBack();
            RequestForceDrawBack requestForceDrawBack = new RequestForceDrawBack();
            RequestOperationResultBean resultBean = new  RequestOperationResultBean();


            if (wffmu.haveOtherOperationRight(requestid) && wfdb.isHavePurview(requestid, user.getUID(), logintype, -1, -1)) {
                requestidlist.add("" + requestid);
                // WfForceDrawBack.doForceDrawBack(requestidsArr, request,
                // response, -1, -1);
                // 使用新的收回方式
                String sessionkey = workflowid + "_" + nodeid + "_" + user.getUID() + "_" + System.currentTimeMillis();
                int result = requestForceDrawBack.foreceDrawBack(user, requestid, false, -1, -1);
                if (!requestForceDrawBack.isAddInOperateSuccess()) {//强制收回附加操作执行失败，返回错误信息
                    String message = requestForceDrawBack.getMessage();
                    String messagecontent = requestForceDrawBack.getMessageContent();
                    if("".equals(message) || requestid <= 0) {
                        message = "1";
                    }
                    resultBean.setMessageInfo(SubmitErrorMsgBiz.getMsgInfo(request,user,message,messagecontent));
                    resultBean.setType(RequestExecuteType.FAILD);
                    Util_TableMap.setObjVal(Util.null2String(sessionkey), resultBean);
                    apidatas.put("success",false);
                    apidatas.put("msg",SystemEnv.getHtmlLabelNames("506175,83071",user.getLanguage()));
                    return apidatas;
                }
                if (result == RequestForceDrawBack.OLDDATA) {
                    wfdb.doForceDrawBack(requestidlist, request, response, -1, -1);
                }
                RequestOperateBiz.drawBackSpecialTreatment(formid, workflowid);

                /*E9打印登录超时报错(QC:527424)*/
                if(user == null) {
                    try {
                        response.sendRedirect(weaver.general.GCONST.getContextPath()+"/wui/index.html");
                        return null;
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                //判断是否可以跳转到新的页面
                boolean reqRoute = ServiceUtil.isReqRoute(String.valueOf(requestid),user);
                apidatas.put("reqRoute", reqRoute);
                apidatas.put("success",result == RequestForceDrawBack.SUCCESS);
                if(result == RequestForceDrawBack.SUCCESS){
                    apidatas.put("msg",SystemEnv.getHtmlLabelName(83585,user.getLanguage()));
                }else if(result == RequestForceDrawBack.FAIL){
                    apidatas.put("msg",SystemEnv.getHtmlLabelName(389102,user.getLanguage()));
                }else if(result == RequestForceDrawBack.NORIGHT){
                    apidatas.put("msg",SystemEnv.getHtmlLabelName(18567,user.getLanguage()));
                }
                apidatas.put("sessionkey", sessionkey);
            }else {
                apidatas.put("success",false);
                apidatas.put("msg",SystemEnv.getHtmlLabelName(18567,user.getLanguage()));
            }

        }
        //自动取消 流程关注
        new RequestAttentionBiz().cancelAttention(requestid,flag);
        return apidatas;
    }

    /**
     * 删除流程
     * @param requestid
     */
    public static boolean deleteWF(String requestid, User user, String from){
        RequestDeleteUtils rdu = new RequestDeleteUtils();
        RecordSetTrans trst = new RecordSetTrans();
        trst.setAutoCommit(false);
        RequestDeleteLog log = rdu.initRequestDeleteLog(user, from, String.valueOf(requestid));
        RequestDeleteUtils rdu1 = new RequestDeleteUtils(Util.getIntValue(requestid),trst,log);
        try {
            rdu1.executeDeleteRequest();
            trst.commit();
        } catch (Exception e) {
            new BaseBean().writeLog(e);
            trst.rollback();
            return false;
        }
        return true;
    }


    @Override
    public BizLogContext getLogContext() {
        return null;
    }


    /**
     * 暂停、撤销、启用消息数据
     * @param requestId
     * @param user
     * @param flag
     */
    private boolean pushOperationMsg(int requestId,User user,String flag){

        RequestOperationMsgManager romm = new RequestOperationMsgManager();
        List<MsgEntity> requestMsgEntity = romm.getOperateMsgByReqId(String.valueOf(requestId),user,flag);
        new MsgPushUtil().pushMsg(requestMsgEntity);
        return true;
    }


    private void doArchiveRemind(int workflowid,int requestid){
        String src = Util.null2String(request.getParameter("src"));
        String remindTypes = Util.null2String(request.getParameter("remindTypes"));   //表单上提醒方式
        RequestRemindBiz requestRemindBiz = new RequestRemindBiz(user);
        //默认提醒
        WFManager wfManager = new WFManager();
        try{
            wfManager.setWfid(workflowid);
            wfManager.getWfInfo();
        }catch (Exception e){}

        if("-1".equals(remindTypes)){ //老数据
            int messageType = Util.getIntValue(Util.null2String(request.getParameter("messageType")),-1); // 老短信提醒
            int mailMessageType = Util.getIntValue(Util.null2String(request.getParameter("chatsType")),-1); // 老邮件提醒
            if(messageType >=1) requestRemindBiz.requestRemind(requestid,workflowid,src, RemindTypeEnum.SMS,messageType);
            //历史数据可能只有短信提醒，但是其实也开启了邮件提醒
            int _mailMessageType = Util.getIntValue(wfManager.getMailMessageType(),-1);
            if(mailMessageType == 1 || _mailMessageType == 1) requestRemindBiz.requestRemind(requestid,workflowid,src,RemindTypeEnum.EMAIL,0);
            Set<String> remindType = new HashSet<>();
            if(messageType >=1) {
                requestRemindBiz.requestRemind(requestid,workflowid,src,RemindTypeEnum.SMS,messageType);
            }
            if(mailMessageType == 1 || _mailMessageType == 1) {
                requestRemindBiz.requestRemind(requestid,workflowid,src,RemindTypeEnum.EMAIL,0);
            }
        }else{

            String isSmsRemind = remindTypes.indexOf(RemindTypeEnum.SMS.getCode()) > -1 ? "1" : "0";
            String isEmailRemind = remindTypes.indexOf(RemindTypeEnum.EMAIL.getCode()) > -1 ? "1" : "0";
            if("1".equals(isSmsRemind)) requestRemindBiz.requestRemind(requestid,workflowid,src,RemindTypeEnum.SMS,0);
            if("1".equals(isEmailRemind)) requestRemindBiz.requestRemind(requestid,workflowid,src,RemindTypeEnum.EMAIL,0);
        }
        requestRemindBiz.requestEmailApproveRemind(String.valueOf(workflowid),String.valueOf(requestid),src);
    }

    public HttpServletRequest getRequest() {
        return request;
    }
}
