package com.engine.custom.archives.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.api.workflow.service.RequestAuthenticationService;
import com.api.workflow.util.ServiceUtil;
import com.engine.custom.archives.action.WorkflowToDocCus;
import com.engine.custom.archives.entity.PushArchivesBean;
import com.engine.workflow.biz.RobotNode.RobotNodeBiz;
import com.engine.workflow.biz.RobotNode.RobotNodeServiceBiz;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import weaver.conn.RecordSet;
import weaver.crm.Maint.CustomerInfoComInfo;
import weaver.docs.docs.DocRecycleManager;
import weaver.general.StringUtil;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.resource.ResourceComInfo;
import weaver.soa.workflow.request.RequestInfo;
import weaver.soa.workflow.request.RequestService;
import weaver.workflow.monitor.Monitor;
import weaver.workflow.workflow.WorkflowConfigComInfo;

import java.io.*;
import java.lang.reflect.Field;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalTime;
import java.util.*;
import java.util.concurrent.TimeUnit;


public class ArchivesUtil {
    public static Logger log = LoggerFactory.getLogger("Archives");
    public static final String SQL = "select request from uf_pushArchivesLog where  ddsj <= ? " +
            " and type = ? and ( zt is null or zt = 1 ) group by REQUEST";

    /**
     * 获取前一天的date
     *
     * @return
     */
    public static Date getDate() {
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        //把日期往后增加一天.整数往后推,负数往前移动(1:表示明天、-1：表示昨天，0：表示今天)
        calendar.add(Calendar.DATE, -1);
        date = calendar.getTime();
        return date;
    }


    /**
     * 获取指定日期的第一秒
     *
     * @param date
     * @return
     */
    public static Date getFirstSecondOfDate(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }


    /**
     * 获取指定日期的最后一秒
     *
     * @param date
     * @return
     */
    public static Date getLastSecondOfDate(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        return calendar.getTime();
    }


    /**
     * 获取推送档案的bean
     *
     * @param beginTime
     * @param endTime
     * @param type
     * @return
     */

    public static List<PushArchivesBean> getResultList(RecordSet rs, String beginTime, String endTime, int type) {

        rs.executeQuery(SQL, endTime, type);
        // Field[] fields = PushArchivesBean.class.getDeclaredFields();
        log.info("getResultListSQL:{}?{}?{}",SQL,endTime,type);
        LinkedList<PushArchivesBean> result = new LinkedList<>();
        while (rs.next()) {
            PushArchivesBean pushArchivesBean = new PushArchivesBean();
            // pushArchivesBean.setId(Util.getIntValue(rs.getString("id")));
            pushArchivesBean.setRequest(Util.getIntValue(rs.getString("request")));
            result.add(pushArchivesBean);
        }
        return result;
    }

    /**
     * 获取流程自动发起的节点
     *
     * @param workflowid
     * @return
     */
    public static List<String> getAutoInitNodeIds(String workflowid) {
        RecordSet recordSet = new RecordSet();
        ArrayList<String> nodeids = new ArrayList<>();
        //String sql = "select node.NODEID nodeid ,  nodegroup.GROUPNAME from  workflow_flownode node " +
        //        "                     left join workflow_nodegroup nodegroup " +
        //        "                               on node.nodeid = nodegroup.nodeid " +
        //        "                                            left join workflow_groupdetail detail " +
        //        "on nodegroup.id = detail.GROUPID " +
        //        "where node.WORKFLOWID in (select distinct WORKFLOWID from WORKFLOW_REQUESTBASE where REQUESTID in ( " + mainAndSubRequestId + " ) ) and detail.id is null";
        //recordSet.executeQuery(sql);

        String sql = "select * from uf_ArchivesSet where mainwfid = ? ";
        recordSet.executeQuery(sql,workflowid);
        String exclusenodeid= "";
        if (recordSet.next()){
            exclusenodeid = recordSet.getString("exclusenodeid");
        }
        return Arrays.asList(exclusenodeid.split(","));
    }


    /**
     * @param TemplatePath     模版存放目录
     * @param TemplateName     模版名
     * @param root             填充的数据
     * @param GenerateFilename 生成文件名
     * @throws Exception
     */

    public static String generate(String TemplatePath, String TemplateName, Map<String, Object> root, String GenerateFilename) throws Exception {
        Configuration cfg = new Configuration();
        //指定模板文件的来源目录
        cfg.setDirectoryForTemplateLoading(new File(TemplatePath));
        cfg.setDefaultEncoding("UTF-8");
        //设置错误的显示方式（日志）
        //在生产系统中：TemplateExceptionHandler.RETHROW_HANDLER 默认值
        //在开发HTML模板期间：TemplateExceptionHandler.HTML_DEBUG_HANDLER
        //在开发非HTML模板期间：TemplateExceptionHandler.DEBUG_HANDLER
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);

        //获取模板文件
        Template temp = cfg.getTemplate(TemplateName);
        //合并模板和数据模型
        // File file = new File(TemplatePath + "new-built");
        //如果文件夹不存在，则创建文件夹
        // if (!file.exists()) {
        //     //file.mkdirs();//多级目录
        //     file.mkdir();//只创建一级目录
        // }
        //Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(TemplatePath + "new-built/" + GenerateFilename)));//输出文件
        // FileWriter out = new FileWriter(TemplatePath + "new-built/" + GenerateFilename);
        //Writer out = new OutputStreamWriter(System.out);//输出控制台
        //StringWriter out = new StringWriter();//输出为字符串,可作为接口动态返回
        File file = new File(GenerateFilename);
        File parentDir = file.getParentFile();

        // 检查父目录是否存在
        if (!parentDir.exists()) {
            // 父目录不存在，创建所有必需的父目录
            boolean dirsCreated = parentDir.mkdirs();
            if (dirsCreated) {
                System.out.println("所有必需的父目录已创建.");
            } else {
                System.out.println("无法创建目录，请检查权限或路径是否正确.");
            }
        } else {
            System.out.println("父目录已存在，无需创建.");
        }

        // FileOutputStream fos = new FileOutputStream(GenerateFilename);
        // Writer out = new OutputStreamWriter(fos, StandardCharsets.UTF_8);
        // temp.process(root, out);
        // out.flush();//可不手动调用
        // 使用 try-with-resources 确保流被正确关闭
        try (FileOutputStream fos = new FileOutputStream(GenerateFilename);
             Writer out = new OutputStreamWriter(fos, StandardCharsets.UTF_8)) {
            temp.process(root, out);
            out.flush();
        }
        return GenerateFilename;
    }

    /**
     * 写入txt
     *
     * @param path
     * @param title
     * @param content
     * @param append
     */
    public static void writeToTxt(String path, String title, String content, Boolean append) {
        try {
            System.out.println(111);
            /* 写入Txt文件 */
            File mkdirsName = new File(path);
            // 相对路径
            if (!mkdirsName.exists()) {
                mkdirsName.mkdirs();
            }
            File writename = new File(path + "/" + title + ".txt");
            // 存在即根据操作系统添加换行符
            if (!writename.exists() && append == true) {
                // 创建新文件
                writename.createNewFile();
            } else if ("del".equals(content) && append == false) {
                writename.delete();
                return;
            } else if (!writename.exists() && append == false) {
                writename.createNewFile();
            } else {
                String osName = System.getProperties().getProperty("os.name");
                System.out.println(osName);
                if ("Linux".equals(osName)) {
                    content = "\r" + content;
                } else {
                    content = "\r\n" + content;
                }
            }
            // 如果是在原有基础上写入则append属性为true，默认为false
            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(writename, append), StandardCharsets.UTF_8));
            // 写入TXT
            out.write(content);
            // 把缓存区内容压入文件
            out.flush();
            // 最后记得关闭文件
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(222);
    }


    /**
     * 创建文件夹
     *
     * @param pathName
     * @return
     */
    public static File crFile(String pathName) {
        // bean.writeLog("创建文件夹==="+pathName);
        File file = new File(pathName);
        try {
            // bean.writeLog("创建文件夹==="+file.exists());
            if (!file.exists()) {
                file.mkdir();
            }
        } catch (Exception E) {
            // bean.writeLog("Exception"+E.getMessage());
        }
        return file;
    }


    /**
     * 生成流转意见  意见
     *
     * @param requestid
     * @param dirName
     * @param requestName
     * @return
     */
    public static String getSignLog(int requestid, String dirName, String requestName, String TemplatePath, String filePath, boolean isSubReq ,String workflowid) {
        List<String> subRequestIds = getSubRequestIds(requestid, isSubReq);
        ArrayList<Map<String, Object>> lists = new ArrayList<>();
        List<String> autoInitNodeIds = getAutoInitNodeIds(workflowid);
        RecordSet recordSet = new RecordSet();
        String getWFNameByReqId = "select WORKFLOWNAME from WORKFLOW_REQUESTBASE req " +
                " left join WORKFLOW_BASE wf on req.WORKFLOWID = wf.ID " +
                " where REQUESTID = ? ";
        for (String reqid : subRequestIds) {
            recordSet.executeQuery(getWFNameByReqId, reqid);
            String wfName = "";
            if (recordSet.next()) {
                wfName = recordSet.getString("WORKFLOWNAME");
            }
            HashMap<String, Object> params = new HashMap<>();
            params.put("requestid", reqid);
            params.put("desremark", "all");
            params.put("pageSize", "9999");
            params.put("isfirst", "true");
            // params.put("request", request);
            Map<String, Object> data = ArchivesUtil.getSignLogCmd(params, new User(1));
            log.info("流转信息:{}", data);
            log.error(JSONObject.toJSONString(data));
            Map<String, Object> datas = (Map<String, Object>) data.get("datas");
            List<Map.Entry<String, Object>> entries = new ArrayList<>(datas.entrySet());
            entries.sort(new Comparator<Map.Entry<String, Object>>() {
                @Override
                public int compare(Map.Entry<String, Object> o1, Map.Entry<String, Object> o2) {
                    Integer key1 = Util.getIntValue((Util.null2String(o1.getKey())).replace("key", ""));
                    Integer key2 = Util.getIntValue((Util.null2String(o2.getKey())).replace("key", ""));
                    return key1 - key2;
                }
            }); // 自然顺序

            ArrayList<Map<String, String>> results = new ArrayList<>();
            // log.error(JSONObject.toJSONString(entries));
            for (Map.Entry<String, Object> entry : entries) {

                Map value = (Map) entry.getValue();
                List<Map<String, Object>> list = (List) value.get("list");
                String nodeid = Util.null2String(value.get("nodeid"));
                if (autoInitNodeIds.contains(nodeid)) {
                    continue;
                }
                for (Map<String, Object> item : list) {
                    String operator = (String) item.get("operator");
                    String operatorid = (String) item.get("operatorid");
                    if ("6771".equals(operatorid)) {
                        operator = "子流程处理";
                    }
                    String operatortype = (String) item.get("operatortype");
                    String operatedate = (String) item.get("operatedate");
                    String receivedate = (String) item.get("receivedate");
                    String nodename = (String) value.get("nodename");
                    String statuscode = (String) item.get("statuscode");
                    HashMap<String, String> itemMap = new HashMap<>();
                    itemMap.put("operator", operator);
                    itemMap.put("operatorid", operatorid);
                    itemMap.put("operatortype", operatortype);
                    itemMap.put("operatedate", StringUtil.isEmpty(operatedate) ? receivedate : operatedate);
                    itemMap.put("nodename", nodename);
                    itemMap.put("nodename", nodename);
                    itemMap.put("requestName", (String) value.get("requestName"));
                    //1:未查看， 2：:以查看， 3：已提交， 4:暂停， 5:撤销, 6:启用 7:已查阅 8:退回 9:被撤回
                    String action = "";
                    if ("1".equals(statuscode)) {
                        action = "未查看";
                    } else if ("2".equals(statuscode)) {
                        action = "已查看";
                    } else if ("3".equals(statuscode)) {
                        action = "已提交";
                    } else if ("4".equals(statuscode)) {
                        action = "暂停";
                    } else if ("5".equals(statuscode)) {
                        action = "撤销";
                    } else if ("6".equals(statuscode)) {
                        action = "启用";
                    } else if ("7".equals(statuscode)) {
                        action = "已查阅";
                    } else if ("8".equals(statuscode)) {
                        action = "退回";
                    } else if ("9".equals(statuscode)) {
                        action = "被撤回";
                    }
                    itemMap.put("statuscode", "3".equals(statuscode) ? "提交" : "查看");
                    itemMap.put("action", action);

                    results.add(itemMap);
                }
            }
            log.error("排序结果:{}", JSONObject.toJSONString(results));
            HashMap<String, Object> records = new HashMap<>();
            records.put("results", results);
            String requestName1 = (String) data.get("requestName");
            records.put("requestName", "【" + wfName + "】-" + requestName1);
            log.error("requestName1:{}", requestName1);
            log.error("records:{}", JSONObject.toJSONString(records));
            lists.add(records);
        }

        try {
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("lists", lists); // 将用户列表添加到数据映射中
            log.error("dataMap:{}", JSONObject.toJSONString(dataMap));
            // String TemplatePath = "/opt/weaver/filesys/";
            //String TemplateName = "html模版.ftl";
            String TemplateName = "temp.ftl";
            // 加载模板并填充数据
            log.error("模板路径:{}", TemplatePath);
            // 导出Word文档
            String outputPath = filePath + File.separator + "togd" +requestid + File.separator + dirName + File.separator + "文件流转信息" + ".docx"; // 输出文件路径
            log.error("生成文件路径:{}", TemplatePath);

            return generate(TemplatePath, TemplateName, dataMap, outputPath);
        } catch (Exception e) {
            log.error("errorerrorerror");
            log.error(e.getMessage());
            e.printStackTrace();
        }
        return Util.null2String(requestid);
    }


    public static Map<String, Object> getSignLogCmd(Map<String, Object> params, User user) {
        Map<String, Object> result = new HashMap<String, Object>();
        RequestAuthenticationService authService = new RequestAuthenticationService();
        authService.setUser(user);

        long date1 = new Date().getTime();
        try {
            RecordSet rs = new RecordSet();
            RecordSet rs1 = new RecordSet();
            int pageSize = Util.getIntValue(Util.null2String(params.get("pageSize")), 30);
            int desrequestid = Util.getIntValue(Util.null2String(params.get("desrequestid")), 0);
            String isfirst = Util.null2String(params.get("isfirst"));
            String isurger = Util.null2String(params.get("isurger"));
            String desremark = Util.null2String(params.get("desremark"));
            int desremarkIndex = desremark.indexOf("_");
            boolean isAdSearch = false;//是否有过滤条件
            if (desremarkIndex > -1) {
                isAdSearch = true;
                desremark = desremark.substring(0, desremarkIndex);
            }
            String parameter = Util.null2String(params.get("parameter"));
            int selectedNode = Util.getIntValue(Util.null2String(params.get("selectedNode")), -1);//选中的节点
            String selectedOperator = Util.null2String(params.get("selectedOperator"));//选中的操作者
            int requestid = Util.getIntValue(Util.null2String(params.get("requestid")), 0);
            int workflowid = -1;
            String requestName = "";
            rs.executeQuery("select workflowid , REQUESTNAMENEW  from workflow_requestbase where requestid=" + requestid);
            if (rs.next()) {
                workflowid = Util.getIntValue(rs.getString("workflowid"));
                requestName = Util.null2String(rs.getString("REQUESTNAMENEW"));
            }
            // 将json字符串转换成jsonObject
            int currentMaxId = 0;
            int currentMinId = 0;
            int currentId = 0;
            int currentId2 = 0;
            int lastNodeId = 0;
            String viewlogids = "";
            int index = 0;
            try {
                if (!"true".equals(isfirst)) {
                    Map<String, String> parameterMap = JSON.parseObject(parameter, Map.class);//Weibo类在下边定义
                    currentMaxId = Util.getIntValue(parameterMap.get("currentMaxId"), 0);
                    currentMinId = Util.getIntValue(parameterMap.get("currentMinId"), 0);
                    String currentId12 = Util.null2String(parameterMap.get("currentId"));
                    if (currentId12.contains("_")) {
                        String[] currentId12Arr = currentId12.split("_");
                        currentId = Util.getIntValue(currentId12Arr[0]);
                        currentId2 = Util.getIntValue(currentId12Arr[1]);
                    } else {
                        currentId = Util.getIntValue(currentId12);
                    }
                    viewlogids = Util.null2String(parameterMap.get("viewlogids"));
                    index = Util.getIntValue(parameterMap.get("nodeindex"), 0);
                    lastNodeId = Util.getIntValue(parameterMap.get("lastNodeId"), 0);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            Map<String, String> putpara = new HashMap<String, String>();

            Monitor monitor = new Monitor();
//			String joinStr = ("oracle".equalsIgnoreCase(rs.getDBType()) || "mysql".equalsIgnoreCase(rs.getDBType())) ? " left join " : " left hash join ";
            String joinStr = " left join ";
//        if (isurger.equals("true") || monitor.hasMonitor(requestid+"", user.getUID() + "")) {
//            StringBuffer sqlsb = new StringBuffer();
//            sqlsb.append(" select a.id,a.nodeid, ");
//            sqlsb.append("                 b.nodename, ");
//            sqlsb.append("              a.userid, ");
//            sqlsb.append("              a.isremark, ");
//            sqlsb.append("              a.lastisremark, ");
//            sqlsb.append("              a.usertype, ");
//            sqlsb.append("             a.agentorbyagentid, ");
//            sqlsb.append("             a.agenttype, ");
//            sqlsb.append("             a.receivedate, ");
//            sqlsb.append("             a.receivetime, ");
//            sqlsb.append("             a.operatedate, ");
//            sqlsb.append("             a.operatetime, ");
//            sqlsb.append("             a.viewtype, ");
//            sqlsb.append("             a.nodetype ");
//            sqlsb.append("             ,a.operator ");
//            sqlsb.append("        from (SELECT distinct top ").append(pageSize);
//            sqlsb.append("				o.id, " );
//            sqlsb.append("				o.requestid, " );
//            sqlsb.append("                              o.userid, ");
//            sqlsb.append("                              o.workflowid, ");
//            sqlsb.append("                              o.workflowtype, ");
//            sqlsb.append("                              o.isremark, ");
//            sqlsb.append("                              o.lastisremark, ");
//            sqlsb.append("                              o.usertype, ");
//            sqlsb.append("                              o.nodeid, ");
//            sqlsb.append("                              o.agentorbyagentid, ");
//            sqlsb.append("                              o.agenttype, ");
//            sqlsb.append("                              o.receivedate, ");
//            sqlsb.append("                              o.receivetime, ");
//            sqlsb.append("                              o.viewtype, ");
//            sqlsb.append("                              o.iscomplete, ");
//            sqlsb.append("                              o.operatedate, ");
//            sqlsb.append("                              o.operatetime, ");
//            sqlsb.append("                              nodetype ");
//            sqlsb.append("                              ,wr.operator ");
//            sqlsb.append("                FROM workflow_currentoperator o ");
//
//            sqlsb.append("                left join workflow_requestlog wr");
//            sqlsb.append("                on wr.requestid=o.requestid");
//            sqlsb.append("                and wr.nodeid=o.nodeid");
//            sqlsb.append("                and wr.operator = o.userid");
//            sqlsb.append("                and wr.logtype <> '1'");
//
//            sqlsb.append("                , workflow_flownode ");
//
//            sqlsb.append("               where o.nodeid = ");
//            sqlsb.append("                     workflow_flownode.nodeid ");
//            if(desremark ==1){//1:已提交
//            	sqlsb.append(" AND o.isremark='2' AND wr.operator IS NOT null ");
//            }else if(desremark == 2){//2：未提交
//            	sqlsb.append(" and ((o.isremark = '0' and (o.takisremark is null or o.takisremark=0)) or o.isremark in ('1','5','7','8','9') )");
//            }else if(desremark == 3){//3:已查看
//            	sqlsb.append(" and (((o.isremark = '2' AND wr.operator IS NULL) or o.isremark in ('0','1','4','5','7','8','9')) AND o.viewtype IN (-1,-2)) ");
//            }else if(desremark == 4){//4:未查看
//            	sqlsb.append(" AND o.viewtype = 0 ");
//            }
//            sqlsb.append(" 			and o.id > ").append(currentId);
//            sqlsb.append("                 and o.requestid = " + requestid + ") a, ");
//            sqlsb.append("             workflow_nodebase b ");
//            sqlsb.append("       where a.nodeid = b.id ");
//            sqlsb.append("         and a.requestid = " + requestid + " ");
//            sqlsb.append("         and a.agenttype <> 1 ");
//            sqlsb.append("         order by  a.id ");
//            //log.error("20170309 =====> sqlsb.toString() = "+sqlsb.toString());
//            rs.executeSql(sqlsb.toString());
//
//        } else {
            // 处理相关流程的查看权限
//            if ("".equals(viewlogids)) {
//            	viewlogids = this.getViewLogids();
//            }
            StringBuffer sqlsb = new StringBuffer();
            if ("sqlserver".equalsIgnoreCase(rs.getDBType())) {    // sqlserver 排序提到这里
                sqlsb.append("		select top ").append(pageSize).append(" a.id,a.nodeid, ");
            } else {
                sqlsb.append("		select a.id,a.nodeid, ");
            }
            sqlsb.append("(CASE WHEN a.nodeid < -1 THEN (SELECT nodename FROM workflow_freenode t WHERE t.id = a.nodeid) ELSE (SELECT nodename FROM workflow_nodebase t1 WHERE t1.id = a.nodeid) END) AS nodename,");
            sqlsb.append("             a.userid, ");
            sqlsb.append("             a.isremark, ");
            sqlsb.append("             a.preisremark, ");
            sqlsb.append("             a.lastisremark, ");
            sqlsb.append("             a.usertype, ");
            sqlsb.append("             a.agentorbyagentid, ");
            sqlsb.append("             a.agenttype, ");
            sqlsb.append("             a.receivedate, ");
            sqlsb.append("             a.receivetime, ");
            sqlsb.append("             a.operatedate, ");
            sqlsb.append("             a.operatetime, ");
            sqlsb.append("             a.processuser, ");
            sqlsb.append("             a.viewtype, ");
            sqlsb.append("             a.nodetype ");
            sqlsb.append("             ,a.operator ");
            sqlsb.append("             ,a.tab ");
            //if("true".equals(isfirst)){
			    /*if("oracle".equals(rs.getDBType()) || "mysql".equals(rs.getDBType())){
			    	sqlsb.append("        from (SELECT distinct ");
			    }else{
			    	sqlsb.append("        from (SELECT distinct top ").append(pageSize);		// sqlserver排序提到外层查询
			    }*/
            sqlsb.append("        from (SELECT distinct ");
//            }else{
//            	sqlsb.append("        from (SELECT distinct ");
//            }
            sqlsb.append("				o.id, ");
            sqlsb.append("				o.requestid, ");
            sqlsb.append("                              o.userid, ");
            sqlsb.append("                              o.workflowid, ");
            sqlsb.append("                              o.workflowtype, ");
            //workflow_otheroperator表中isremark为字符型，这里转下字符
            if (rs.getDBType().toLowerCase().equals("oracle") || rs.getDBType().toLowerCase().equals("postgresql")) {
                sqlsb.append("                              to_char(o.isremark) as isremark, ");
                sqlsb.append("                              to_char(o.preisremark) AS preisremark, ");
                sqlsb.append("                              to_char(o.lastisremark) AS lastisremark, ");
            } else if (rs.getDBType().toLowerCase().equals("mysql")) {
                sqlsb.append("                              o.isremark, ");
                sqlsb.append("                              o.preisremark, ");
                sqlsb.append("                              o.lastisremark, ");
            } else {
                sqlsb.append("                              cast(o.isremark as varchar) as isremark, ");
                sqlsb.append("                              cast(o.preisremark as varchar) as preisremark, ");
                sqlsb.append("                              cast(o.lastisremark as varchar) as lastisremark, ");
            }
            sqlsb.append("                              o.usertype, ");
            sqlsb.append("                              o.nodeid, ");
            sqlsb.append("                              o.agentorbyagentid, ");
            sqlsb.append("                              o.agenttype, ");
            sqlsb.append("                              o.receivedate, ");
            sqlsb.append("                              o.receivetime, ");
            sqlsb.append("                              o.viewtype, ");
            sqlsb.append("                              o.iscomplete, ");
            sqlsb.append("                              o.operatedate, ");
            sqlsb.append("                              o.operatetime, ");
            sqlsb.append("                              o.processuser, ");
            sqlsb.append("(case when o.nodeid < -1 then (select nodetype from workflow_freenode t where t.id = o.nodeid) else (select nodetype from workflow_flownode t1 where t1.nodeid = o.nodeid) end) as nodetype ");
            sqlsb.append("                              ,wr.operator ");
            sqlsb.append("                              ,1 as tab ");
            sqlsb.append("                FROM workflow_currentoperator o ");
            sqlsb.append("  " + joinStr + "      workflow_requestlog wr");
            sqlsb.append("                on wr.requestid=o.requestid");
            sqlsb.append("                and wr.nodeid=o.nodeid");
            sqlsb.append("                and wr.operator = o.userid");
            sqlsb.append("                and wr.logtype <> '1'");
            sqlsb.append("                and o.operatedate = wr.operatedate");
            sqlsb.append("                and o.operatetime = wr.operatetime");//再通过时间关联一下，防止流程状态操作状态显示错误
            sqlsb.append(" where o.id > ").append(currentId);
            if ("submit".equals(desremark)) {//1:已提交----isremark等于4，preisremark=11实际对应已提交数据
                sqlsb.append(" AND (o.isremark='2' or (o.isremark=4 and o.preisremark=11)) AND (wr.operator IS NOT null or o.userid  = o.processuser)");
            } else if ("nosubmit".equals(desremark)) {//2：未提交
                sqlsb.append(" AND( (o.isremark != '2' AND o.isremark != '4') OR (o.isremark = '4' AND o.viewtype = 0 and o.preisremark != 11) ) ");
            } else if ("view".equals(desremark)) {//3:已查看
                sqlsb.append(" and ((o.isremark = '2' AND wr.operator IS NULL) or o.isremark in ('0','1','5','7','8','9','11') or (o.isremark=4 and o.preisremark!=11)) AND o.viewtype IN (-1,-2) ");
            } else if ("noview".equals(desremark)) {//4:未查看
                sqlsb.append(" AND o.viewtype=0 AND (o.isremark IN ('0','1','5','7','8','9','11') or (o.isremark = '2' AND wr.operator IS NULL) or (o.isremark=4 and o.preisremark!=11))  ");
            }
            sqlsb.append("                 and o.requestid = " + requestid);
            sqlsb.append(" union ");
            sqlsb.append(" SELECT DISTINCT ");
            sqlsb.append(" o.id, ");
            sqlsb.append(" o.requestid, ");
            sqlsb.append(" o.userid, ");
            sqlsb.append(" o.workflowid, ");
            sqlsb.append(" 0 as workflowtype, ");
            sqlsb.append(" o.isremark, ");
            sqlsb.append(" o.isremark as preisremark, ");
            sqlsb.append(" o.isremark as lastisremark, ");
            sqlsb.append(" o.usertype, ");
            sqlsb.append(" o.nodeid, ");
            sqlsb.append(" 0 as agentorbyagentid, ");
            sqlsb.append(" '0' as agenttype, ");
            sqlsb.append(" o.receivedate, ");
            sqlsb.append(" o.receivetime, ");
            sqlsb.append(" o.viewtype, ");
            sqlsb.append(" 1 as iscomplete, ");
            sqlsb.append(" o.operatedate, ");
            sqlsb.append(" o.operatetime, ");
            sqlsb.append(" wr.operator as processuser, ");
            sqlsb.append("(case when o.nodeid < -1 then (select nodetype from workflow_freenode t where t.id = o.nodeid) else (select nodetype from workflow_flownode t1 where t1.nodeid = o.nodeid) end) as nodetype, ");
            sqlsb.append(" wr.operator ");
            sqlsb.append(" ,2 as tab ");
            sqlsb.append(" FROM workflow_otheroperator o LEFT JOIN workflow_requestlog wr ON wr.requestid = o.requestid ");
            sqlsb.append(" AND wr.nodeid = o.nodeid ");
            sqlsb.append(" AND wr.operator = o.userid ");
            sqlsb.append(" AND wr.logtype <> '1' ");
            sqlsb.append(" WHERE o.requestid = " + requestid + " ");
            sqlsb.append(" and o.id > ").append(currentId2);
            sqlsb.append(" ) a ");
            sqlsb.append("         where a.requestid = " + requestid + " ");
            sqlsb.append("         and a.agenttype <> 1 ");
            if (!"".equals(viewlogids)) {
                sqlsb.append("         and a.nodeid in (" + viewlogids + ") ");
            }
            if (selectedNode != -1) {
                sqlsb.append(" AND  a.nodeid = " + selectedNode + " ");
            }
            if (!"".equals(selectedOperator)) {
                sqlsb.append(" AND  a.userid = " + selectedOperator + " ");
            }

            WorkflowConfigComInfo configComInfo = new WorkflowConfigComInfo();
            boolean showdelFreeNodeInfo = "1".equals(configComInfo.getValue("showdelete_freenode_info"));

            sqlsb.append(" and (a.nodeid > -1 or (a.nodeid < -1 and exists (select id from workflow_freenode where id = a.nodeid and requestid  = " + requestid + (showdelFreeNodeInfo ? "" : " and groupid > 0 ") + " ))) ");

            //搜索时返回状态
            if (isAdSearch && "true".equals(isfirst)) {
                rs.executeQuery("select count(id) as count from (" + sqlsb.toString().replace("top " + pageSize, "") + ") t");
                result.put("countTime", new Date().getTime() - date1);
                if (rs.next()) {
                    result.put("count", Util.null2String(rs.getString("count")));
                }
            }

            sqlsb.append("         order by a.receivedate, a.receivetime,a.id , a.nodetype");

            //log.error("20170309 =====> sqlsb.toString() = "+sqlsb.toString());
            if ("oracle".equals(rs.getDBType())) {    //必须排序后再限制rownum
                String sql_oracle = sqlsb.toString();
                sqlsb.setLength(0);
                sqlsb.append("select * from (" + sql_oracle + ") where rownum < ").append(pageSize);
            } else if ("mysql".equals(rs.getDBType())) {
                sqlsb.append(" LIMIT " + pageSize);
            } else if ("postgresql".equals(rs.getDBType())) {
                sqlsb.append(" LIMIT " + pageSize);
            }
            if (requestid > 0) {
                rs.executeSql(sqlsb.toString());
            }
            result.put("dataTime", new Date().getTime() - date1);
//        }
            List<Map<String, String>> statuslist = new ArrayList<Map<String, String>>();
            int tmpnodeid = 0;
            while (rs.next()) {
                int tab = rs.getInt("tab");
                if (tab == 1) {
                    currentId = rs.getInt("id");
                } else {
                    currentId2 = rs.getInt("id");
                }
                tmpnodeid = rs.getInt("nodeid");
                String tmpnodename = rs.getString("nodename");
                Map<String, String> nodekv = null;
                if (statuslist.size() == 0) {
                    currentMinId = currentId;
                    nodekv = new HashMap<String, String>();
                    statuslist.add(nodekv);
                } else {
                    Map<String, String> temmap = statuslist.get(statuslist.size() - 1);
                    int tnodeid = Util.getIntValue(temmap.get("nodeid"), 0);
                    if (tnodeid == tmpnodeid) {
                        nodekv = temmap;
                    } else {
                        currentMinId = currentId;
                        nodekv = new HashMap<String, String>();
                        statuslist.add(nodekv);
                    }
                }
                nodekv.put("nodeid", tmpnodeid + "");
                nodekv.put("nodename", tmpnodename + "");
            }
            int nextlistcount = 0;
            int nextsubmitCount = 0;
            int nextviewCount = 0;
            int nextnoviewCount = 0;
            if ("all".equals(desremark) && !isAdSearch) {
                currentMaxId = currentId;
                String maxsql = " select a.id,a.nodeid from workflow_currentoperator a where a.id > " + currentId + " and a.requestid=" + requestid + " order by a.id ,a.receivedate, a.receivetime";
                rs1.executeSql(maxsql);
                while (rs1.next()) {
                    int currentid = rs1.getInt("id");
                    int currentnodeid = rs1.getInt("nodeid");
                    if (currentnodeid == tmpnodeid) {
                        currentMaxId = currentid;
                    } else {
                        break;
                    }
                }
                String listcountsql = " select count(id) num from workflow_currentoperator where id > " + currentId + " and id <= " + currentMaxId + " and requestid=" + requestid + " and nodeid=" + tmpnodeid + " and agenttype <> 1 and usertype <> 1 ";
                //String submitCountsql = " select count(id) num from workflow_currentoperator where id > "+currentId +" and id <= "+currentMaxId+" and requestid="+requestid +" and nodeid="+tmpnodeid +" and agenttype <> 1 and usertype <> 1 and isremark = 2 and exists (select 1 from workflow_requestlog where workflow_requestlog.requestid = workflow_currentoperator.requestid and workflow_currentoperator.nodeid=workflow_requestlog.nodeid and workflow_requestlog.operator=workflow_currentoperator.userid )";
                //String viewCountsql = " select count(id) num from workflow_currentoperator where id > "+currentId +" and id <= "+currentMaxId+" and requestid="+requestid +" and nodeid="+tmpnodeid + " and agenttype <> 1 and usertype <> 1 and (viewtype = -1 or viewtype=-2) and ((isremark = '0' and (takisremark is null or takisremark=0)) or isremark in ('1','5','7','8','9') or (isremark = '2' and not exists (select 1 from workflow_requestlog where workflow_requestlog.requestid = workflow_currentoperator.requestid and workflow_currentoperator.nodeid=workflow_requestlog.nodeid and (workflow_requestlog.operator is null or workflow_requestlog.operator ='' )))) ";
                //String noviewCountsql = " select count(id) num from workflow_currentoperator where id > "+currentId +" and id <= "+currentMaxId+" and requestid="+requestid +" and nodeid="+tmpnodeid + " and agenttype <> 1 and usertype <> 1 AND viewtype=0 AND (isremark IN ('0','1','4','5','7','8','9') or (isremark = '2' and not exists (select 1 from workflow_requestlog where workflow_requestlog.requestid = workflow_currentoperator.requestid and workflow_currentoperator.nodeid=workflow_requestlog.nodeid and (workflow_requestlog.operator is null or workflow_requestlog.operator ='' )))) ";
                String submitCountsql = " SELECT Count(distinct wc.id) num FROM workflow_currentoperator wc " + joinStr + " workflow_requestlog wr ON  wr.requestid = wc.requestid AND wc.nodeid = wr.nodeid AND wr.operator = wc.userid WHERE wc.id > " + currentId + " AND wc.id <= " + currentMaxId + " AND wc.requestid = " + requestid + " AND wc.nodeid = " + tmpnodeid + " AND wc.agenttype <> 1 AND wc.usertype <> 1 AND wc.isremark = 2 and wr.operator is NOT null ";
                String viewCountsql = " SELECT Count(distinct wc.id) num FROM workflow_currentoperator wc " + joinStr + " workflow_requestlog wr ON  wr.requestid = wc.requestid AND wc.nodeid = wr.nodeid AND wr.operator = wc.userid WHERE wc.id > " + currentId + " AND wc.id <= " + currentMaxId + " AND wc.requestid = " + requestid + " AND wc.nodeid = " + tmpnodeid + " AND wc.agenttype <> 1 AND wc.usertype <> 1 AND wc.viewtype IN (-1,-2) and ((wc.isremark = '2' AND wr.operator IS NULL) or wc.isremark in ('0','1','4','5','7','8','9'))  ";
                String noviewCountsql = " SELECT Count(distinct wc.id) num FROM workflow_currentoperator wc " + joinStr + " workflow_requestlog wr ON  wr.requestid = wc.requestid AND wc.nodeid = wr.nodeid AND wr.operator = wc.userid WHERE wc.id > " + currentId + " AND wc.id <= " + currentMaxId + " AND wc.requestid = " + requestid + " AND wc.nodeid = " + tmpnodeid + " AND wc.agenttype <> 1 AND wc.usertype <> 1  AND wc.viewtype=0 AND (wc.isremark IN ('0','1','4','5','7','8','9','11') or (wc.isremark = '2' and wr.operator is null ))  ";
                rs1.executeSql(listcountsql);
                while (rs1.next()) {
                    nextlistcount = rs1.getInt("num");
                }
                rs1.executeSql(submitCountsql);
                while (rs1.next()) {
                    nextsubmitCount = rs1.getInt("num");
                }
                rs1.executeSql(viewCountsql);
                while (rs1.next()) {
                    nextviewCount = rs1.getInt("num");
                }
                rs1.executeSql(noviewCountsql);
                while (rs1.next()) {
                    nextnoviewCount = rs1.getInt("num");
                }
            }

            Map<String, Object> allstatusmap = new HashMap<String, Object>();
            Map<String, Object> submitstatusmap = new HashMap<String, Object>();
            Map<String, Object> nosubmitstatusmap = new HashMap<String, Object>();
            Map<String, Object> viewstatusmap = new HashMap<String, Object>();
            Map<String, Object> noviewstatusmap = new HashMap<String, Object>();
            //提交节点信息--滚动加载到当前currentoperator对应最大id

            //数字统计转到新接口count中
            ResourceComInfo resourceComInfo = new ResourceComInfo();
            CustomerInfoComInfo customerInfoComInfo = new CustomerInfoComInfo();
            Map<String, Object> all_nodemap = new HashMap<String, Object>();
            Map<String, Object> submit_nodemap = new HashMap<String, Object>();
            Map<String, Object> nosubmit_nodemap = new HashMap<String, Object>();
            Map<String, Object> view_nodemap = new HashMap<String, Object>();
            Map<String, Object> noview_nodemap = new HashMap<String, Object>();

            rs.beforFirst();
            int currentnum = 0;
            for (Iterator<Map<String, String>> it = statuslist.iterator(); it.hasNext(); index++) {

                Map<String, String> nodekv = it.next();
                int fnodeid = Util.getIntValue(nodekv.get("nodeid"));
                String namename = nodekv.get("nodename");
                int submitCount = 0;
                int viewCount = 0;
                int noviewCount = 0;
                int listcount = 0;
                if ("false".equals(isfirst) && currentnum == 0 && lastNodeId == fnodeid) {
                    index -= 1;
                }
                if (tmpnodeid == fnodeid && currentnum == (statuslist.size() - 1)) {
                    submitCount = nextsubmitCount;
                    viewCount = nextviewCount;
                    noviewCount = nextnoviewCount;
                    listcount = nextlistcount;
                }
                currentnum++;
                Map<String, Object> all_nodemap_in = new HashMap<String, Object>();
                all_nodemap_in.put("nodeid", fnodeid);
                all_nodemap_in.put("nodename", namename);
                Map<String, Object> submit_nodemap_in = new HashMap<String, Object>();
                Map<String, Object> nosubmit_nodemap_in = new HashMap<String, Object>();
                Map<String, Object> view_nodemap_in = new HashMap<String, Object>();
                Map<String, Object> noview_nodemap_in = new HashMap<String, Object>();

                List<Map<String, String>> nodeallstatuslist = new ArrayList<Map<String, String>>();
                List<Map<String, String>> nodesubmitstatuslist = new ArrayList<Map<String, String>>();
                List<Map<String, String>> nodenosubmitstatuslist = new ArrayList<Map<String, String>>();
                List<Map<String, String>> nodeviewstatuslist = new ArrayList<Map<String, String>>();
                List<Map<String, String>> nodenoviewstatuslist = new ArrayList<Map<String, String>>();

                if ("submit".equals(desremark)) {//1:已提交
                    //提交节点信息
                    submit_nodemap_in.putAll(all_nodemap_in);
                    submitstatusmap.put("datas", submit_nodemap);
                    submit_nodemap.put("key" + index, submit_nodemap_in);
                    submit_nodemap_in.put("list", nodesubmitstatuslist);
                } else if ("nosubmit".equals(desremark)) {//2：未提交
                    nosubmit_nodemap_in.putAll(all_nodemap_in);
                    nosubmitstatusmap.put("datas", nosubmit_nodemap);
                    nosubmit_nodemap.put("key" + index, nosubmit_nodemap_in);
                    nosubmit_nodemap_in.put("list", nodenosubmitstatuslist);
                } else if ("view".equals(desremark)) {//3:已查看
                    view_nodemap_in.putAll(all_nodemap_in);
                    viewstatusmap.put("datas", view_nodemap);
                    view_nodemap.put("key" + index, view_nodemap_in);
                    view_nodemap_in.put("list", nodeviewstatuslist);
                } else if ("noview".equals(desremark)) {//4:未查看
                    noview_nodemap_in.putAll(all_nodemap_in);
                    noviewstatusmap.put("datas", noview_nodemap);
                    noview_nodemap.put("key" + index, noview_nodemap_in);
                    noview_nodemap_in.put("list", nodenoviewstatuslist);
                } else {
                    //所有节点信息
                    allstatusmap.put("datas", all_nodemap);
                    all_nodemap.put("key" + index, all_nodemap_in);
                    all_nodemap_in.put("list", nodeallstatuslist);
                }

                boolean islight = false;
                RobotNodeServiceBiz robotNodeServiceBiz = new RobotNodeServiceBiz();
                while (rs.next()) {
                    int tmpnodeid1 = rs.getInt("nodeid");

                    if (tmpnodeid1 != fnodeid) {
                        rs.previous();
                        break;
                    }

                    //String tmpnodename = rs.getString("nodename");
                    int tmpcurrid = rs.getInt("id");
                    String tmpuserid = rs.getString("userid");
                    String tmpisremark = Util.null2String(rs.getString("isremark"));
                    if (tmpisremark.equals("")) {
                        tmpisremark = Util.null2String(rs.getString("lastisremark"));
                    }
                    int tmpusertype = rs.getInt("usertype");
                    String tmpagentorbyagentid = rs.getString("agentorbyagentid");
                    int tmpagenttype = rs.getInt("agenttype");
                    String tmpreceivedate = rs.getString("receivedate");
                    String tmpreceivetime = rs.getString("receivetime");
                    String tmpoperatedate = rs.getString("operatedate");
                    String tmpoperatetime = rs.getString("operatetime");
                    String viewtype = rs.getString("viewtype");
                    String nodetype = rs.getString("nodetype");
                    int preisremark = rs.getInt("preisremark");
                    String processuser = rs.getString("processuser");
                    boolean flags = false;
                    String tmpIntervel = "";
                    // 如果tmpisremark=2 判断时候在日志表里有该人（确定是否是由非会签得到的isremark=2）

                    String operator = rs.getString("operator");
                    if (operator != null && !"".equals(operator)) {
                        flags = true;
                    }
                    if ((tmpisremark.equals("2") || (tmpisremark.equals("4") && preisremark == 11)) && tmpoperatedate != null && !tmpoperatedate.equals("")) {
                        tmpIntervel = TimeUtil.timeInterval2(tmpreceivedate + " " + tmpreceivetime, tmpoperatedate + " " + tmpoperatetime, user.getLanguage());
                    }
                    islight = !islight;
                    Map<String, String> _statusmap = new HashMap<String, String>();
                    // 操作人
                    String _statususername = "";
                    String _operatorid = "";
                    String _beagentid = "";
                    String _beagentname = "";
                    String _operatortype = "0";
                    if (tmpusertype == 0) {
                        _operatorid = tmpuserid;
                        _statususername = ServiceUtil.convertChar(resourceComInfo.getResourcename(tmpuserid));
                        if (tmpagenttype == 2) {    //代理情况
                            _beagentid = tmpagentorbyagentid;
                            _beagentname = ServiceUtil.convertChar(resourceComInfo.getResourcename(tmpagentorbyagentid));
                        }
                        _statusmap.put("operatorImg", resourceComInfo.getMessagerUrls(tmpuserid));
                        _statusmap.put("operatorImgDefName", _statususername);
                    } else if (RobotNodeBiz.operatortype.equals(tmpusertype + "")) {
                        _statususername = Util.formatMultiLang(robotNodeServiceBiz.getRobotNodeSet(tmpnodeid1).getOperatorName());
                        _operatorid = tmpuserid;
                        _operatortype = "2";
                    } else {
                        _operatorid = tmpuserid;
                        _operatortype = "1";
                        _statususername = ServiceUtil.convertChar(customerInfoComInfo.getCustomerInfoname(tmpuserid));
                    }

                    // 查看状态 1:未查看， 2：:以查看， 3：已提交， 4:暂停， 5:撤销, 6:启用 7:已查阅 8:退回 9:被撤回
                    int _statusCode = 0;

                    if (preisremark != 8 && (tmpisremark.equals("2") || (tmpisremark.equals("4") && preisremark == 11)) && (flags || tmpuserid.equals(processuser))) {
                        _statusCode = 3;
                        submitCount++;
                        if ("4".equals(nodetype) && preisremark == 0) {
                            _statusCode = 7;
                        }
                    } else if (tmpisremark.equals("0") || tmpisremark.equals("1") || tmpisremark.equals("5") || tmpisremark.equals("4") || tmpisremark.equals("8") || tmpisremark.equals("9") || tmpisremark.equals("7") || tmpisremark.equals("11") || (tmpisremark.equals("2") && !flags)) {
                        if (viewtype.equals("-2") || (viewtype.equals("-1") && !tmpoperatedate.equals(""))) {
                            _statusCode = 2;
                            viewCount++;
                        } else {
                            _statusCode = 1;
                            noviewCount++;
                        }
                    } else if ("s".equals(tmpisremark)) {
                        _statusCode = 4;
                    } else if ("r".equals(tmpisremark)) {
                        _statusCode = 6;
                    } else if ("c".equals(tmpisremark)) {
                        _statusCode = 5;
                    } else if (preisremark == 8 && viewtype.equals("-2") && tmpisremark.equals("2")) {
                        _statusCode = 2;
                        viewCount++;
                    }
                    RecordSet recordSet = new RecordSet();
                    recordSet.executeQuery("select operatetype from workflow_currentoperator where id=?", tmpcurrid);
                    if (recordSet.next()) {
                        int operatetype = recordSet.getInt(1);
                        if (operatetype == 3) {//退回
                            _statusCode = 8;
                        } else if (operatetype == 4) {//被撤回
                            _statusCode = 9;
                        }
                    }


                    listcount++;
                    if ("view".equals(desremark)) {//3:已查看
                        if (processuser.equals(tmpuserid) && ("2".equals(tmpisremark) || "4".equals(tmpisremark))) {
                            listcount--;
                        }
                    }
                    String _receivedate = "";
                    String _operatedate = "";
                    String _intervel = "";

                    if (!tmpisremark.equals("s") && !tmpisremark.equals("c") && !tmpisremark.equals("r")) {
                        _receivedate = Util.toScreen(tmpreceivedate, user.getLanguage()) + " " + Util.toScreen(tmpreceivetime, user.getLanguage());
                    }
                    _operatedate = Util.toScreen(tmpoperatedate, user.getLanguage()) + " " + Util.toScreen(tmpoperatetime, user.getLanguage());

                    _intervel = Util.toScreen(tmpIntervel, user.getLanguage());

                    _statusmap.put("statuscode", String.valueOf(_statusCode));
                    _statusmap.put("operator", _statususername);
                    _statusmap.put("receivedate", _receivedate);
                    _statusmap.put("operatedate", _operatedate);
                    _statusmap.put("intervel", _intervel);
                    _statusmap.put("operatorid", _operatorid);
                    _statusmap.put("operatortype", _operatortype);
                    _statusmap.put("beagentid", _beagentid);
                    _statusmap.put("beagentname", _beagentname);
                    _statusmap.put("nodetype", nodetype);


                    //所有节点
                    nodeallstatuslist.add(_statusmap);
                    //查看状态 1:未查看， 2：:以查看， 3：已提交， 4:暂停， 5:撤销, 6:启用 7:已查阅
                    if ((tmpisremark.equals("2") || (tmpisremark.equals("4") && preisremark == 11)) && (flags || tmpuserid.equals(processuser))) {
                        nodesubmitstatuslist.add(_statusmap);
                    } else if (tmpisremark.equals("0") || tmpisremark.equals("1") || tmpisremark.equals("5") || tmpisremark.equals("4") || tmpisremark.equals("8") || tmpisremark.equals("9") || tmpisremark.equals("7") || tmpisremark.equals("11") || (tmpisremark.equals("2") && !flags)) {
                        if (viewtype.equals("-2") || (viewtype.equals("-1") && !tmpoperatedate.equals(""))) {
                            nodeviewstatuslist.add(_statusmap);
                        } else if (viewtype.equals("0")) {
                            nodenoviewstatuslist.add(_statusmap);
                        }
                    }

                    if ((!tmpisremark.equals("2") && !tmpisremark.equals("4")) || (tmpisremark.equals("4") && viewtype.equals("0"))) {
                        if (!tmpisremark.equals("s") && !tmpisremark.equals("s") && !tmpisremark.equals("c") && !tmpisremark.equals("r")) {
                            nodenosubmitstatuslist.add(_statusmap);
                        }
                    }
                }
                //--已提交、已查看、未查看
                all_nodemap_in.put("submitCount", submitCount);//--已提交
                all_nodemap_in.put("viewCount", viewCount);//--已查看
                all_nodemap_in.put("noviewCount", noviewCount);//--未查看
                if ("submit".equals(desremark)) {//1:已提交
                    //提交节点信息
                    submit_nodemap_in.put("listcount", listcount);
                    result.putAll(submitstatusmap);
                } else if ("nosubmit".equals(desremark)) {//2：未提交
                    nosubmit_nodemap_in.put("listcount", listcount);
                    result.putAll(nosubmitstatusmap);
                } else if ("view".equals(desremark)) {//3:已查看
                    view_nodemap_in.put("listcount", listcount);
                    result.putAll(viewstatusmap);
                } else if ("noview".equals(desremark)) {//4:未查看
                    noview_nodemap_in.put("listcount", listcount);
                    result.putAll(noviewstatusmap);
                } else {
                    //所有节点信息
                    all_nodemap_in.put("listcount", listcount);
                    result.putAll(allstatusmap);
                }
                lastNodeId = fnodeid;
            }
//        if(maxid == currentMaxId){
//        	isfinish = 1;
//        }
            putpara.put("nodeindex", index + "");
            putpara.put("currentMaxId", currentMaxId + "");
            putpara.put("currentMinId", currentMinId + "");
            putpara.put("currentId", currentId + "_" + currentId2);
            putpara.put("lastNodeId", lastNodeId + "");
            putpara.put("viewlogids", viewlogids + "");
            putpara.put("requestName", requestName);
            result.put("parameter", putpara);
            result.put("otherTime", new Date().getTime() - date1);
            result.put("requestName", requestName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    /**
     * 获取当前流程下的所有子流程
     *
     * @param requestid 主流程id
     * @param max 遍历次数
     * @return
     */
    public static Map<String, String> getSubRequest(String requestid,int max) {
        HashMap<String, String> records = new HashMap<>();
        RecordSet rs = new RecordSet();
        String ids = requestid;
        for (int i = 0; i < max; i++) {
            ArrayList<String> idList = new ArrayList<>();
            String sql = "select requestid , workflowid from workflow_requestbase where mainrequestid in ( " + ids + " )";
            rs.executeQuery(sql);
            while (rs.next()) {
                String subrequestid = Util.null2String(rs.getString("requestid"));
                String workflowid = Util.null2String(rs.getString("workflowid"));
                idList.add(subrequestid);
                // 使用map自动去重,一种流程类型只取一个requestid
                records.put(subrequestid, workflowid);
            }
            ids = String.join(",", idList);
        }


        // String sql = "select requestid from workflow_requestbase where mainrequestid = ?";
        // RecordSet rs = new RecordSet();
        // rs.executeQuery(sql, requestid);
        // if (rs.next()) {
        //     String subrequestid = Util.null2String(rs.getString("requestid"));
        //     records.add(subrequestid);
        // }
        return records;
    }

    public static List<String> getSubRequestIds(int requestid, boolean isSubReq) {
        List<String> reqids = new ArrayList<>();
        String mainwfid = "";
        String subwfid = "";
        if (!isSubReq) {
            RecordSet recordSet = new RecordSet();
            recordSet.executeQuery("select * from WORKFLOW_REQUESTBASE where REQUESTID = ?", requestid);
            String wfid = "";
            if (recordSet.next()) {
                wfid = Util.null2String(recordSet.getString("WORKFLOWID"));
            }
            recordSet.executeQuery("select * from uf_ArchivesSet where mainwfid = ? ", wfid);

            if (recordSet.next()) {
                mainwfid = Util.null2String(recordSet.getString("mainwfid"));
                subwfid = Util.null2String(recordSet.getString("subwfid"));
            } else {
                reqids.add(requestid + "");
                return reqids;
            }
        }
        RecordSet rs = new RecordSet();
        String ids = requestid + "";
        reqids.add(requestid + "");
        for (int i = 0; i < 5; i++) {
            ArrayList<String> idList = new ArrayList<>();
            String sql;
            if (isSubReq) {
                sql = "select requestid , workflowid from workflow_requestbase where mainrequestid in ( " + ids + " )";
            } else {
                sql = "select requestid , workflowid from workflow_requestbase where mainrequestid in ( " + ids + " ) and workflowid in ( " + subwfid + " ) ";
            }
            log.error("subrequestSql:{}", sql);
            rs.executeQuery(sql);
            while (rs.next()) {
                String subrequestid = Util.null2String(rs.getString("requestid"));
                // String workflowid = Util.null2String(rs.getString("workflowid"));
                idList.add(subrequestid);
                reqids.add(subrequestid);
                // 使用map自动去重,一种流程类型只取一个requestid

            }
            ids = String.join(",", idList);
            if (ids.length() == 0) {
                break;
            }
        }


        // String sql = "select requestid from workflow_requestbase where mainrequestid = ?";
        // RecordSet rs = new RecordSet();
        // rs.executeQuery(sql, requestid);
        // if (rs.next()) {
        //     String subrequestid = Util.null2String(rs.getString("requestid"));
        //     records.add(subrequestid);
        // }
        return reqids;
    }


    /**
     * 获取imageid  Map<imageid,docid>
     *
     * @param ids
     * @return
     */
    public static Map<String, String> getFileIdByDocId(String ids) {
        HashMap<String, String> records = new HashMap<>();

        String sql = "select docid,df.imagefileid imgid  from   docimagefile df left join imagefile imf on df.imagefileid = imf.imagefileid where DOCID in (" + ids + ")";
        RecordSet recordSet = new RecordSet();
        recordSet.execute(sql);
        while (recordSet.next()) {
            String docid = Util.null2String(recordSet.getString("docid"));
            String imgid = Util.null2String(recordSet.getString("imgid"));
            records.put(docid, imgid);
        }
        return records;
    }

    /**
     * 将InputStream写入本地文件
     *
     * @param inputStream   输入流
     * @param localFilePath 本地文件路径
     * @return
     * @throws IOException 如果发生输入输出异常
     */
    public static File saveInputStreamToFile(InputStream inputStream, String localFilePath) throws IOException {
        File targetFile = new File(localFilePath);

        // 确保目标文件的父目录存在
        File parentDir = targetFile.getParentFile();
        if (parentDir != null && !parentDir.exists()) {
            parentDir.mkdirs();
        }


        // 使用try-with-resources语句确保流的正确关闭
        try (InputStream in = inputStream;
             OutputStream outputStream = new FileOutputStream(targetFile)) {
            int read;
            byte[] bytes = new byte[1024];
            while ((read = in.read(bytes)) != -1) {
                outputStream.write(bytes, 0, read);
            }
        } // 自动关闭 in 和 outputStream
        return targetFile;
    }


    /**
     * 根据链接下载文件
     *
     * @param fileURL
     * @param saveDir
     */
    public static void downloadFile(String fileURL, String saveDir) {
        log.info("文件下载地址:{}", fileURL);
        log.info("文件保存地址:{}", saveDir);

        try {
            saveDir = codeUtf8(saveDir);
            URL url = new URL(fileURL);
            File file = new File(saveDir);
            FileUtils.copyURLToFile(url, file);
            log.error("Download completed successfully.");
        } catch (IOException e) {
            e.printStackTrace();
            log.error("Download failed.");
        }
    }


    /**
     * 调用永中接口
     *
     * @param BASE_URL
     * @param file
     * @return
     * @throws IOException
     */
    public static String callApi(String BASE_URL, File file) {
        // OkHttpClient client = new OkHttpClient();
        //增加设置超时时间

        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(150, TimeUnit.SECONDS)
                .readTimeout(150, TimeUnit.SECONDS)
                .writeTimeout(150, TimeUnit.SECONDS)
                .build();

        // Debugging: Check if the file exists and can be read
        if (file.exists() && file.canRead()) {
            log.error("File exists and is readable. File path: " + file.getAbsolutePath());
        } else {
            log.error("File does not exist or cannot be read. File path: " + file.getAbsolutePath());
        }
        RequestBody requestBody = null;
        String code = getCodeByFileType(file.getName());
        // if (StringUtil.isEmpty(code)){
        //     return "";
        // }
        String fileName = null;
        String extName = "";
        try {
            fileName = URLEncoder.encode(file.getName(), StandardCharsets.UTF_8.toString());
            extName = fileName.substring(fileName.lastIndexOf("."));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (Exception e){
            e.printStackTrace();
        }
        try {
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            requestBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("convertType", code)
                    .addFormDataPart("file", uuid + extName , RequestBody.create(MediaType.parse("application/zip"), file))
                    .build();
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }

        Request request = new Request.Builder()
                .url(BASE_URL)
                .post(requestBody)
                .build();

        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 根据文件类型获取转为pdf的编码
     *
     * @param FileName
     * @return
     */

    public static String getCodeByFileType(String FileName) {
        if (!FileName.contains(".")){
            return "";
        }
        String extName = FileName.substring(FileName.lastIndexOf(".") + 1);
        String convertType = "";
        if (extName.matches("(doc|dot|dtd|docx|docm|dotx|ppt|pptx|ppsx|potx|xlsx|xlsm|wps|dps|et|wpt|xls|xlc|xlt|xlm|xlw|DOC|DOT|DTD|DOCX|DOCM|DOTX|PPT|PPTX|PPSX|POTX|XLSX|XLSM|WPS|DPS|ET|WPT|XLS|XLC|XLT|XLM|XLW)")) {
            convertType = "3";
        } else if (extName.matches("(ofd|OFD)")) {
            convertType = "57";
        } else if (extName.matches("(GIF|JPEG|JPG|BMP|PNG|gif|jpeg|jpg|bmp|png)")) {
            convertType = "32";
        } else if (extName.matches("(PDF|pdf)")) {
            convertType = "34";
        }
        return convertType;
    }


    /***
     * 获取关键词
     * @param id
     * @return
     */
    public static String getKeyword(String id) {
        String sql = "select * from uf_test where id = ?";
        RecordSet rs = new RecordSet();
        rs.executeQuery(sql, id);
        rs.next();
        return Util.null2String(rs.getString("label"));
    }

    /**
     * 删除文档及附件,调用移到回收站,再从回收站删除
     *
     * @param docid
     */
    public static void deleteDocByid(String docid) {
        DocRecycleManager docRecycleManager = new DocRecycleManager();
        User user = new User(1);
        docRecycleManager.moveDocToRecycle(user.getUID(), user.getLogintype(), Util.getIntValue(docid), "127.0.0.1");
        docRecycleManager.deleteDocFromRecycle(user.getUID(), user.getLogintype(), weaver.general.Util.getIntValue(docid), "127.0.0.1");
    }

    /**
     * 获取流程类型名称
     *
     * @param wfid
     * @return
     */

    public static String getWfNameByid(String wfid) {
        String sql = "select WORKFLOWNAME from WORKFLOW_BASE where id = ?";
        RecordSet rs = new RecordSet();
        rs.executeQuery(sql, wfid);
        rs.next();
        return Util.null2String(rs.getString("WORKFLOWNAME"));
    }

    public static String[] getDeptNameAndCode(String ngbm) {
        String sql = "select DEPARTMENTNAME , DAPYBH  from hrmdepartment a left join hrmdepartmentdefined b " +
                " on a.ID = b.DEPTID " +
                " where a.ID = ? ";
        RecordSet recordSet = new RecordSet();
        recordSet.executeQuery(sql, ngbm);
        recordSet.next();
        return new String[]{recordSet.getString("DAPYBH"), recordSet.getString("DEPARTMENTNAME")};
    }

    /**
     * 将gbk转为UTF-8,创建ISO-8859-1编码的字符串，
     * ISO-8859-1编码是一个字节对应一个字符，因此不会使最后一个字节错误。
     *
     * @param text
     * @return
     */
    public static String codeUtf8(String text) {
        String ISOtext = null;
        ISOtext = new String(text.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        return new String(ISOtext.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);

    }

    public static String getAssociatedPersons(int requestid, boolean isSubReq) {
        List<String> subRequest = getSubRequestIds(requestid, isSubReq);
        String sql = "select distinct b.LOGINID loginid from WORKFLOW_REQUESTLOG a left join HRMRESOURCE b " +
                " on a.OPERATOR = b.ID " +
                " where a.OPERATOR is not null   and a.OPERATOR != 1 and a.REQUESTID in ( " + String.join(",", subRequest) + " )";
        RecordSet recordSet = new RecordSet();
        HashSet<String> set = new HashSet<>();
        recordSet.executeQuery(sql);
        while (recordSet.next()) {
            String loginid = Util.null2String(recordSet.getString("loginid"));
            if (StringUtil.isEmpty(loginid)) {
                continue;
            }
            //处理下子账号
            if (loginid.length() > 8) {
                loginid = loginid.substring(0, 8);
            }
            if ("fenfa".equals(loginid)){
                continue;
            }
            set.add(loginid);
        }
        return String.join("&&", set);
    }


    public static Map<String, String> getSignFiles(int requestid, boolean isSubReq) {
        RecordSet recordSet = new RecordSet();
        ArrayList<String> docids = new ArrayList<>();
        List<String> subRequest = ArchivesUtil.getSubRequestIds(requestid, isSubReq);
        String sql = "select * from WORKFLOW_REQUESTLOG where REQUESTID in ( " +
                String.join(",", subRequest) + " )" +
                "and logtype != '1' and (annexdocids is not null or annexdocids <> '' ) ";
        log.error("getSignFilessql:{}",sql);
        recordSet.executeQuery(sql);
        while (recordSet.next()) {
            String annexdocids = Util.null2String(recordSet.getString("annexdocids"));
            if (annexdocids.length() > 0) {
                if (annexdocids.contains(",")) {
                    // annexdocids.split(",")
                    docids.addAll(Arrays.asList(annexdocids.split(",")));
                } else {
                    docids.add(annexdocids);
                }
            }
        }
        return ArchivesUtil.getFileIdByDocId(String.join(",", docids));
    }

    /**
     * 生成子流程承办单
     *
     * @param requestid 主流程id
     */
    public static List<String> generaSubRequestFormPdf(String requestid) {
        log.error("generaSubRequestFormPdf,requestid:{}", requestid);
        Map<String, String> subRequest = ArchivesUtil.getSubRequest(requestid,5);
        for (String s : subRequest.keySet()) {
            requestid = subRequest.get(s);
            break;
        }
        List<String> docids = new ArrayList<>();
        // for (String wfid : subRequest.keySet()) {
        RequestService requestService = new RequestService();
        RequestInfo requestInfo = requestService.getRequest(Util.getIntValue(requestid), 100);
        WorkflowToDocCus workflowToDoc = new WorkflowToDocCus();
        requestInfo.setLastoperator("1");
        requestInfo.setDescription(ArchivesUtil.getWfNameByid(requestInfo.getWorkflowid()) + "-" + requestInfo.getDescription());
        log.error("generaSubRequestFormPdf,requestInfo:{}", JSON.toJSONString(requestInfo));

        List<String> subDocids = workflowToDoc.execute(requestInfo, 1);
        docids.addAll(subDocids);
        log.error("generaSubRequestFormPdf,requestInfo:{}", JSON.toJSONString(subDocids));

        // }
        return docids;
    }

    /**
     * 生成主流程承办单
     *
     * @param requestid 生成表单时的签字意见是否需要子流程的签字意见
     */
    public static List<String> generaRequestFormPdf(int requestid, int reqType) {
        log.error("generaRequestFormPdf,requestid:{}", requestid);
        RequestService requestService = new RequestService();
        RequestInfo requestInfo = requestService.getRequest(Util.getIntValue(requestid), 100);
        WorkflowToDocCus workflowToDoc = new WorkflowToDocCus();
        requestInfo.setLastoperator("1");
        requestInfo.setDescription(ArchivesUtil.getWfNameByid(requestInfo.getWorkflowid()) + "-" + requestInfo.getDescription());
        log.error("generaRequestFormPdf,requestInfo:{}", JSON.toJSONString(requestInfo));
        return workflowToDoc.execute(requestInfo, reqType);
    }

    //
    public static int findMaxValue(String commaSeparatedValues) {
        try {
// 分割字符串
            String[] numbers = commaSeparatedValues.split(",");
            // 初始化最大值为整数的最小值
            int max = 0;

            // 遍历字符串数组
            for (String number : numbers) {
                // 转换为整数
                int value = Integer.parseInt(number.trim()); // 使用trim()移除可能的空格
                // 检查是否为最大值
                if (value > max) {
                    max = value;
                }
            }
            return max;
        }catch (NumberFormatException  e){
            log.error("ConversionException:"+commaSeparatedValues);
            return 0;
        }


    }



    public static String[] getSubCom(String ngbm) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select sub.id subid , SUBCOMPANYNAME from HRMDEPARTMENT dept left join HRMSUBCOMPANY sub " +
                " on dept.SUBCOMPANYID1 = sub.ID " +
                " where dept.id = ? ",ngbm);
        rs.next();
        String subcompanyname = rs.getString("SUBCOMPANYNAME");
        String subid = rs.getString("subid");
        if ("总行".equals(subcompanyname)){
            subcompanyname = "总行机关";
        }
        rs.executeQuery("select DAPYBH from HRMSUBCOMPANYDEFINED where SUBCOMID = ?",subid);
        rs.next();
        String DAPYBH = rs.getString("DAPYBH");
        return new String[]{DAPYBH,subcompanyname};
    }



    public static void deleteDirectory( String directoryPath ){
        // 创建File对象
        File directory = new File(directoryPath);

        try {
            // 使用FileUtils.deleteDirectory删除目录及其子目录和文件
            FileUtils.deleteDirectory(directory);
            log.info("目录删除成功:{}",directory);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("目录删除失败:{}",directory);
            log.error("失败原因:{}",e.getMessage());
        }
    }

    public static boolean isAfterSevenAM(int time) {
        // 获取当前时间
        LocalTime currentTime = LocalTime.now();

        // 定义早上7点的时间
        LocalTime sevenAM = LocalTime.of(time, 0);

        // 比较当前时间和早上7点
        return currentTime.isAfter(sevenAM);
    }

    public static void main(String[] args) {
        String fileName = "11111";
        System.out.println( fileName.substring(fileName.lastIndexOf(".")));

    }
}
