package com.engine.htsc.workflow.web;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.engine.htsc.workflow.util.WorkflowTodoUtil;
import com.engine.htsc.workflow.util.WorkflowUtil;
import org.apache.commons.lang.StringUtils;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.general.BaseBean;
import weaver.general.GCONST;
import weaver.general.Util;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.resource.ResourceComInfo;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.workflow.request.RequestLogOperateName;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.time.LocalDate;
import java.util.*;

/**
 * @Title: ecology-9
 * @Company: 泛微软件
 * @author: weaver.K1810007
 * @version: 1.0
 * @CreateDate: 2022-08-22
 * @Description: PC待办、在办接口
 * * @ModifyLog:
 *
 **/
public class WorkflowTodoAction {


    /**
     * 查询人员待办
     * @param request
     * @param response
     * @return
     */
    @GET
    @Path("/todos")
    @Produces({MediaType.TEXT_PLAIN})
    public String getPortalTodoData(@Context HttpServletRequest request, @Context HttpServletResponse response){
        BaseBean bb = new BaseBean();
        Map<String, Object> apidatas = new HashMap<String, Object>();
        //获取用户
        String userCode = Util.null2String(request.getHeader("iv-user"));
        int num = Util.getIntValue(request.getParameter("num"));
        String type = Util.null2String(request.getParameter("type"));
        String callback = Util.null2String(request.getParameter("callback"));
        bb.infoLog("WorkflowTodoAction","iv-user======"+userCode+" type:"+type);

        RecordSet rs = new RecordSet();
        try {
            if(!"".equals(userCode) && !"null".equals(userCode) && userCode !=null && userCode !="")
            {
                List<Map<String,String>> dataList = getWorkflowDataSql(userCode,type,num);

                String userName = "" ;
                String sql = " select id,lastname from hrmresource where workcode=? and nvl(belongto,0) = 0 ";
                rs.executeQuery(sql,new Object[]{userCode});
                if(rs.next()){
                    userName = Util.null2String(rs.getString("lastname"));
                }
                apidatas.put("userCode",userCode);
                apidatas.put("userName",userName);
                apidatas.put("dataList",dataList);
                apidatas.put("success", true);
            }else{
                apidatas.put("success", false);
            }
        } catch (Exception e) {
            e.printStackTrace();
            apidatas.put("success", false);
        }

        String dataString = callback+"("+JSONObject.toJSONString(apidatas)+")";
        return dataString;
    }


    /**
     * 获取流程签字意见分类数据
     * @param request
     * @param response
     * @return
     */
    @GET
    @Path("/signs/all")
    @Produces({MediaType.TEXT_PLAIN})
    public String getWfSigns(@Context HttpServletRequest request, @Context HttpServletResponse response){

        Map<String, Object> apidatas = new HashMap<String, Object>();
        PropBean propBean = new PropBean();
        String requestid = Util.null2String(request.getParameter("requestid"));
        String workflowid = Util.null2String(request.getParameter("workflowid"));
        String ismobile = Util.null2String(request.getParameter("ismobile"));
        String authSignatureStr = Util.null2String(request.getParameter("authSignatureStr"));
        String authStr = Util.null2String(request.getParameter("authStr"));
        String f_weaver_belongto_userid = Util.null2String(request.getParameter("f_weaver_belongto_userid"));
        if("".equals(requestid) || "-1".equals(requestid)){
            apidatas.put("datas", new ArrayList());
            apidatas.put("success", true);
            return JSONObject.toJSONString(apidatas);
        }

        RequestLogOperateName requestLogOperateName = new RequestLogOperateName();
        try {

            ResourceComInfo resourceComInfo = new ResourceComInfo();
            DepartmentComInfo deptComInfo = new DepartmentComInfo();

            List<Map<String,String>> dataList = new ArrayList<Map<String,String>>();

            RecordSet rs = new RecordSet();
            RecordSet rs2 = new RecordSet();
            RecordSet rs3 = new RecordSet();

            //判断是否是子流程
            String mainReqSql = " select a.mainrequestid,b.workflowid from workflow_subwfrequest a, workflow_requestbase b " +
                    "  where a.subrequestid=? and a.mainrequestid = b.requestid ";
            rs.executeQuery(mainReqSql,new Object[]{requestid});
            if(rs.next()){
                requestid = Util.null2String(rs.getString("mainrequestid"));
                workflowid = Util.null2String(rs.getString("workflowid"));

            }

            //判断签字意见中部门是否要显示一级部门名称
            boolean showTopDept = false;
            String mainWfUnnumber = propBean.getWorkflowUnNumberByid(workflowid);
            String configUnnumber = propBean.getPropName("signShowTopDept");
            if(configUnnumber.indexOf(mainWfUnnumber)>-1){
                showTopDept = true;
            }

            rs.executeQuery(" select lc,jd,hbxs,jdfl,jdlx,flmc,sx from uf_qzyjpzb a,uf_jdfl b ,workflow_base c " +
                    " where a.jdfl=b.id and a.lc=c.unnumber and c.id=? order by sx ",workflowid);
            while(rs.next()){
                String jdnum = Util.null2String(rs.getString("jd"));
                String hbxs = Util.null2String(rs.getString("hbxs"));
                String flmc = Util.null2String(rs.getString("flmc"));
                String jdfl = Util.null2String(rs.getString("jdfl"));
                String jdlx = Util.null2String(rs.getString("jdlx"));

                if("".equals(jdnum) && !"1".equals(jdlx) && !"4".equals(jdlx) ){
                    continue;
                }
                String jd = "";
                if(!"".equals(jdnum)){
                    jdnum = "'"+String.join("','",jdnum.split(","))+"'" ;
                    rs2.execute(" select wm_concat_old(id) jd from  workflow_nodebase where unnumber in ("+jdnum+") ");
                    rs2.next();
                    jd = Util.null2String(rs2.getString("jd"));
                }

                String orderStr = getDeptOrderStr(requestid,jd,jdfl);
                String signSql = " select t1.*,t2.nodename from workflow_requestLog t1,workflow_nodebase t2 " +
                        " where t1.requestid="+requestid +" and t1.nodeid=t2.id and t1.nodeid in("+jd+") " +
                        " and logtype in('0','2','3','a','b','h','j','w','m','u','z','k','n') " +
                        " order by instr('"+orderStr+"', operatordept||','),operatedate,operatetime ";


                //会签节点单独处理
                if("1".equals(jdlx)){
                    rs2.executeQuery(" select wm_concat_old(freenode) freenode from uf_qzyjhqb where id in (select id from uf_qzyjhqb where lcid=? and jdfl=? ) ",new Object[]{requestid,jdfl});
                    rs2.next();
                    String freenode = Util.null2String(rs2.getString("freenode"));
                    if("".equals(freenode)){
                        continue;
                    }
                    orderStr = getDeptOrderStr(requestid,freenode,jdfl);
                    signSql = " select t1.*,t2.nodename from workflow_requestLog t1,workflow_freenode t2 " +
                            " where t1.requestid="+requestid+" and t1.nodeid=t2.id and t1.nodeid in("+freenode+") " +
                            " and logtype in('0','2','3','a','b','h','j','w','m','u','z','k','n') " +
                            " order by instr('"+orderStr+"', operatordept||','),operatedate,operatetime ";
                }

                //子流程节点单独处理
                if("3".equals(jdlx)){
                    rs2.executeQuery(" select wm_concat_old(subrequestid) subrequestids from workflow_subwfrequest where mainrequestid=? ",new Object[]{requestid});
                    rs2.next();
                    String subrequestids = Util.null2String(rs2.getString("subrequestids"));
                    if("".equals(subrequestids)){
                        continue;
                    }
                    orderStr = getDeptOrderStr(subrequestids,jd,jdfl);
                    signSql = " select t1.*,t2.nodename from workflow_requestLog t1,workflow_nodebase t2 " +
                            " where t1.requestid in("+subrequestids +") and t1.nodeid=t2.id and t1.nodeid in("+jd+") " +
                            " and logtype in('0','2','3','a','b','h','j','w','m','u','z','k','n') " +
                            " order by instr('"+orderStr+"', operatordept||','),operatedate,operatetime ";
                }

                //看阅回复意见(含子流程)
                if("4".equals(jdlx)){
                    rs2.executeQuery(" select wm_concat_old(requestid) allrequestids from workflow_requestbase where requestid=? or mainrequestid=? ",new Object[]{requestid,requestid});
                    rs2.next();
                    String allrequestids = Util.null2String(rs2.getString("allrequestids"));
                    if(!"".equals(allrequestids)){
                        continue;
                    }
                    orderStr = getDeptOrderStr(allrequestids,jd,jdfl);
                    signSql = " select t1.*,t2.nodename from workflow_requestLog t1,workflow_nodebase t2 " +
                            " where t1.requestid in("+allrequestids +") and t1.nodeid=t2.id  and logtype='9' " +
                            " order by instr('"+orderStr+"', operatordept||','),operatedate,operatetime ";

                }


                String lastlogtype = "";
                rs2.execute(signSql);
                while(rs2.next()){
                    String currentRequestid = Util.null2String(rs2.getString("requestid"));
                    String currentWorkflowid = Util.null2String(rs2.getString("workflowid"));
                    String nodeid = Util.null2String(rs2.getString("nodeid"));
                    String nodename = Util.null2String(rs2.getString("nodename"));
                    String historyDeptName = Util.null2String(rs2.getString("historydeptname"));

                    String operator = Util.null2String(rs2.getString("operator"));
                    String operatorName = resourceComInfo.getResourcename(operator);
                    String workcode = resourceComInfo.getWorkcode(operator);
                    operatorName = operatorName+"("+workcode+")";

                    //如果当前操作是代理操作，展示代理关系
                    int agentorbyagentid = Util.getIntValue(rs2.getString("agentorbyagentid"));
                    if(agentorbyagentid>0){
                        String agentorName = resourceComInfo.getResourcename(agentorbyagentid+"");
                        String agentWorkcode = resourceComInfo.getWorkcode(agentorbyagentid+"");
                        //operatorName = agentorName+"("+agentWorkcode+")"+"->"+operatorName;
                        operatorName = operatorName+"("+agentorName+"授权)";
                    }

                    int seclevel = Util.getIntValue(resourceComInfo.getSeclevel(operator));
                    String deptid = Util.null2String(rs2.getString("operatordept"));
                    String deptname = getDeptShowName(deptid,showTopDept,historyDeptName);

                    String operatedate = Util.null2String(rs2.getString("operatedate"));
                    String operatetime = Util.null2String(rs2.getString("operatetime"));
                    if(!"".equals(operatetime)){//时间保留到分钟
                        operatetime = operatetime.substring(0,5);
                    }

                    String logtype = Util.null2String(rs2.getString("logtype"));


                    //特殊需求，韩总提交的流程2022-04-09日期之前的需要显示为提交
                    LocalDate optdate = LocalDate.parse(operatedate);
                    LocalDate comparedate = LocalDate.parse("2022-04-09");
                    String operationName = requestLogOperateName.getOperateName(currentWorkflowid,currentRequestid,nodeid,logtype,operator,7,operatedate,operatetime);
                    if("13723".equals(operator) && optdate.isBefore(comparedate)){
                        if("同意".equals(operationName) || "不同意".equals(operationName)){
                            operationName = "提交";
                        }
                    }

                    //String remark = Util.HTMLtoTxt(Util.null2String(rs2.getString("remark")));
                    String remark = Util.null2String(rs2.getString("remark"));
                    String nullRemark = "{\"remark\":\"\",\"remarkquote\":\"\"}";
                    if(remark.equals(nullRemark)){
                        remark = "";
                        continue;
                    }

                    String annexdocids = Util.null2String(rs2.getString("annexdocids"));//意见相关附件
                    if(!"".equals(annexdocids)){
                        String docFileHtml =  WorkflowUtil.getDocFileHtml(ismobile,annexdocids,requestid,authStr,authSignatureStr,f_weaver_belongto_userid);
                        remark += docFileHtml;
                    }

                    Map<String,String> requestLogMap = new HashMap<>();

                    if("11".equals(jdfl)){
                        String deptShortName = WorkflowUtil.getTopDeptShortName(deptid);
                        requestLogMap.put("type",deptShortName+"会签");

                    }else{
                        requestLogMap.put("type",flmc);
                    }

                    requestLogMap.put("deptname",deptname);
                    requestLogMap.put("deptid",deptid);
                    requestLogMap.put("deptcode",deptid+"_"+deptname);
                    if(("a".equals(lastlogtype) || "b".equals(logtype) || "z".equals(logtype)) && seclevel<50 ){//意见征询显示节点名称内部审核其他显示节点名称
                        requestLogMap.put("nodename","内部审核");
                    }else if("m".equals(logtype) || "w".equals(logtype) || "u".equals(logtype)){

                        rs3.executeQuery(" select * from workflow_currentoperator " +
                                "where requestid=? and userid=? and nodeid=? ",new Object[]{currentRequestid,operator,nodeid});
                        if(rs3.next()){
                            String takisremark = Util.null2String(rs3.getString("takisremark"));
                            if("2".equals(takisremark)  && seclevel<50){
                                requestLogMap.put("nodename","内部审核");
                            }else{
                                requestLogMap.put("nodename",nodename);
                            }
                        }
                    }else{
                        requestLogMap.put("nodename",nodename);
                    }

                    if(Integer.parseInt(nodeid)<0 && "指定人员".equals(nodename)){
                        requestLogMap.put("nodename","指定处理人");
                    }



                    requestLogMap.put("operator",operatorName);
                    requestLogMap.put("operatename",operationName);
                    requestLogMap.put("remark",remark);
                    requestLogMap.put("operatedatetime",operatedate+" "+operatetime);
                    requestLogMap.put("hbxs",hbxs);

                    dataList.add(requestLogMap);

                    lastlogtype = logtype;
                }
            }
            apidatas.put("datas", dataList);
            apidatas.put("success", true);
        } catch (Exception e) {
            e.printStackTrace();
            apidatas.put("success", false);
        }
        return JSONObject.toJSONString(apidatas);
    }


    /**
     * 获取流程签字意见分类数据
     * @param request
     * @param response
     * @return
     */
    @GET
    @Path("/historySigns/sort")
    @Produces({MediaType.TEXT_PLAIN})
    public String getHistoryWfSigns(@Context HttpServletRequest request, @Context HttpServletResponse response){
        Map<String, Object> apidatas = new HashMap<String, Object>();
        String requestid = Util.null2String(request.getParameter("requestid"));
        if("".equals(requestid) || "-1".equals(requestid)){
            apidatas.put("datas", new ArrayList());
            apidatas.put("success", true);
            return JSONObject.toJSONString(apidatas);
        }


        try {
            List<Map<String,String>> dataList = new ArrayList<Map<String,String>>();
            String tablename = WorkflowUtil.getTableName(requestid);
            if(!"".equals(tablename)){
                String dataSql = " select b.yjfl,b.bmmc,b.bz,b.clr,b.spjg,b.spyj,b.clsj from "+tablename+" a,"+tablename+"_dt1 b \n" +
                        "where a.id=b.mainid and requestid=?  order by b.yjfl,b.clsj  ";
                RecordSet rs = new RecordSet();
                rs.executeQuery(dataSql,requestid);
                while (rs.next()){
                    String type = Util.null2String(rs.getString("yjfl"));
                    String nodename = Util.null2String(rs.getString("bz"));
                    String operatedatetime = Util.null2String(rs.getString("clsj"));
                    String deptname = Util.null2String(rs.getString("bmmc"));
                    String operator = Util.null2String(rs.getString("clr"));
                    String operatename = Util.null2String(rs.getString("spjg"));
                    String remark = Util.null2String(rs.getString("spyj"));


                    Map<String,String> logMap = new HashMap<>();
                    logMap.put("type",type);
                    logMap.put("nodename",nodename);
                    logMap.put("operatedatetime",operatedatetime);
                    logMap.put("deptname",deptname);
                    logMap.put("operator",operator);
                    logMap.put("operatename",operatename);
                    logMap.put("remark",remark);

                    dataList.add(logMap);
                }
            }
            apidatas.put("datas", dataList);
            apidatas.put("success", true);
        } catch (Exception e) {
            e.printStackTrace();
            apidatas.put("success", false);
        }



        return JSONObject.toJSONString(apidatas);
    }


    /**
     * 更新流程数据
     * @param request
     * @param response
     * @return
     */
    @POST
    @Path("/paService/doUpdateRequest")
    @Produces({MediaType.TEXT_PLAIN})
    public String doUpdateRequest(@Context HttpServletRequest request, @Context HttpServletResponse response){

        Map<String, Object> apidatas = new HashMap<String, Object>();
        RecordSetTrans rts = new RecordSetTrans();
        rts.setAutoCommit(false);
        try {
            String requestid = Util.null2String(request.getParameter("requestid"));

            RecordSet rs = new RecordSet();
            rs.executeQuery(" select tablename from workflow_base a,workflow_bill b,workflow_requestbase c where " +
                    " a.formid=b.id and a.id=c.workflowid and c.requestid=?",new Object[]{requestid});
            if(rs.next()){
                String mainTableName = Util.null2String(rs.getString("tablename"));

                //更新主表数据
                String mainData = Util.null2String(request.getParameter("mainData"));
                if(!"".equals(mainData)){
                    JSONArray mainDataArray = JSONArray.parseArray(mainData);
                    String sqlWhere = " where requestid="+requestid;
                    Map<String, Object> resultMap = WorkflowUtil.getUpdateExcuteSql(mainTableName,sqlWhere,mainDataArray);
                    String updateSql = (String) resultMap.get("updateSql");
                    List<String> valueList = (List<String>) resultMap.get("fieldValue");

                    try{
                        rts.executeUpdate(updateSql,valueList.toArray());
                    }catch (Exception e){
                        rts.rollback();
                        apidatas.put("success", false);
                        apidatas.put("msg", "主表字段参数无效");
                        return JSONObject.toJSONString(apidatas);
                    }
                }

                //更新明细表数据
                String detailData = Util.null2String(request.getParameter("detailData"));
                if(!"".equals(detailData)){
                    //明细插入需要加上mainid字段
                    rs.executeQuery(" select id from "+mainTableName+" where requestid=? ",new Object[]{requestid});
                    rs.next();
                    int mainid = rs.getInt("id");
                    JSONObject keyValueJson = new JSONObject();
                    keyValueJson.put("fieldName","mainid");
                    keyValueJson.put("fieldValue",mainid);

                    JSONArray detailDataArray = JSONArray.parseArray(detailData);
                    for(int i=0;i<detailDataArray.size();i++){
                        JSONObject detailItemJson = detailDataArray.getJSONObject(i);
                        String detailTableName = detailItemJson.getString("detailTableName");
                        //明细表的数据更新数据，没有明细标识只能删除原有明细后重新添加
                        rts.executeUpdate("delete from "+detailTableName+" where mainid=?",new Object[]{mainid});

                        //遍历当前明细表的所有明细记录
                        JSONArray records = detailItemJson.getJSONArray("records");
                        for(int j=0;j<records.size();j++){
                            JSONArray rowFieldDatas = records.getJSONObject(j).getJSONArray("rowFieldDatas");
                            rowFieldDatas.add(keyValueJson);

                            //生成插入sql
                            Map<String, List<String>> fieldKeyValueMap = WorkflowUtil.getFiledKeyValueMap(rowFieldDatas);
                            List<String> keyList = fieldKeyValueMap.get("fieldName");
                            List<String> valueList = fieldKeyValueMap.get("fieldValue");
                            String sqlPlaceHolder = WorkflowUtil.createPlaceHolder(keyList.size());
                            String keyStrs = StringUtils.join(keyList, ",");
                            String insertSql = " insert into "+detailTableName+"("+ keyStrs +") values("+sqlPlaceHolder+")";

                            try{
                                rts.executeUpdate(insertSql,valueList.toArray());
                            }catch (Exception e){
                                rts.rollback();
                                apidatas.put("success", false);
                                apidatas.put("msg", "明细表字段参数无效");
                                return JSONObject.toJSONString(apidatas);
                            }
                        }
                    }
                }


            }else{
                apidatas.put("success", false);
                apidatas.put("msg", "更新数据不存在");
                return JSONObject.toJSONString(apidatas);
            }

            rts.commit();
            apidatas.put("success", true);
            apidatas.put("msg", "数据更新成功");
        } catch (Exception e) {
            rts.rollback();
            e.printStackTrace();
            apidatas.put("success", false);
            apidatas.put("msg", "系统内部错误");
        }

        return JSONObject.toJSONString(apidatas);
    }


    /***
     *
     * @param userCode
     * @param type
     * @param num
     * @return
     */
    public List<Map<String,String>> getWorkflowDataSql(String userCode,String type,int num){

        WorkflowTodoUtil workflowTodoUtil = new WorkflowTodoUtil();

        RecordSet rs = new RecordSet();
        BaseBean bb = new BaseBean();
        PropBean pb = new PropBean();
        List<Map<String,String>> dataList = new ArrayList<Map<String,String>>();
        ResourceComInfo resourceComInfo = null;
        try {
             resourceComInfo = new ResourceComInfo();

            String excludeFlow = pb.getPropName("noSendWorkflowId");
            String excludeSqlWhere = "";
            if (StringUtils.isNotEmpty(excludeFlow)) {
                excludeSqlWhere = " and t3.id not in(" + excludeFlow + ") ";
            }

            String oahost = pb.getPropName("OAHOST");  //pc地址

            String useridAll = "" ;
            rs.executeQuery(" select id from hrmresource where workcode=? and status=1 ",new Object[]{userCode});
            while(rs.next())
            {
                String id = Util.null2String(rs.getString("id"));
                useridAll += useridAll == "" ? id :","+id ;
            }

            bb.infoLog("WorkflowTodoAction","useridAll:"+useridAll);

            if(!"".equals(useridAll)){

                List<String> bqList = workflowTodoUtil.queryLabelData(useridAll);

                List<String> dzyyList = workflowTodoUtil.queryElectPrintData(useridAll);

                List<String> yjList = workflowTodoUtil.queryMailData(useridAll);

                //type 1、待阅  2、待办 3、在办 4、搁置 5、草稿  6、在阅 7、已阅
                //type 11、待阅(排除特定流程) 12、待办(增加特定流程) 13、在办(增加特殊流程) 16、在阅（排除特殊流程） 17、已阅(排除特定流程)   (唐老师需求)

                String sql = "" ;
                if ("1".equals(type)) {  //1、通知阅读  待阅

                    sql = workflowTodoUtil.queryNoticeUnReadData(useridAll,excludeSqlWhere,num);

                } else if ("2".equals(type)) {  //2、待办事宜   待办
                    String todoUnViewsql = workflowTodoUtil.getWorkflowTodoUnView(useridAll,excludeSqlWhere);

                    sql =   " select w.* from (\n" +
                            " select l.* from ("+
                            todoUnViewsql +
                            " ) l"+
                            "   where 1=1  " +
                            "   order by l.receivetime desc " +
                            " ) w where rownum<=" + num;

                } else if ("3".equals(type)) { //3、待办事宜  在办

                    String todoViewsql = workflowTodoUtil.getWorkflowTodoView(useridAll,excludeSqlWhere);

                    sql =   " select w.* from (\n" +
                            " select l.* from ("+
                            todoViewsql +
                            " ) l"+
                            " where 1 = 1 " +
                            " order by l.receivetime desc " +
                            " ) w where rownum<=" + num;

                }else if("4".equals(type)){//搁置

                    sql = workflowTodoUtil.queryWorkflowShelveData(useridAll,excludeSqlWhere,num);

                }else if("5".equals(type)){//草稿

                    sql =  workflowTodoUtil.queryWorkflowDraftData(useridAll,excludeSqlWhere,num);

                }else if ("6".equals(type)) { //6、通知阅读  在阅

                    sql = workflowTodoUtil.queryNoticeReadingData(useridAll,excludeSqlWhere,num);

                } else if ("7".equals(type)) { //通知阅读 已阅

                    sql = workflowTodoUtil.queryNoticeReadedData(useridAll,excludeSqlWhere,num);

                }
//                System.out.println(sql);
                rs.execute(sql);
                while(rs.next())
                {
                    String title = Util.null2String(rs.getString("requestname"));
                    String requestid = Util.null2String(rs.getString("requestid"));
                    if("2".equals(type)){
                        if(bqList.contains(requestid)){
                            continue;
                        }
                    }

                    if(dzyyList.contains(requestid)){
                        title = "[E]"+title ;
                    }
                    if(yjList.contains(requestid)){
                        title = "[邮]"+title ;
                    }

                    String userid = Util.null2String(rs.getString("userid"));
                    String creater = Util.null2String(rs.getString("creater"));

                    String workcode = "";
                    String lastname = "";
                    try {
                        workcode = resourceComInfo.getWorkcode(creater);
                        lastname = resourceComInfo.getLastname(creater);
                    } catch (Exception e) {
                    }

                    String priority = Util.null2String(rs.getString("requestlevel"));

                    if("0".equals(priority)){
                        priority = "一般";
                    }else if("1".equals(priority)){
                        priority = "紧急";
                    }else if("2".equals(priority)){
                        priority = "特急";
                    }else{
                        priority = "一般";
                    }

                    String workflowname = Util.null2String(rs.getString("workflowname"));
                    String action = WorkflowUtil.getNodeName(Util.null2String(rs.getString("currentnodeid"))) ;
                    String createTime = Util.null2String(rs.getString("createtime"));
                    String createDate = Util.null2String(rs.getString("createdate"));
                    String referencenumber = Util.null2String(rs.getString("requestmark"));
                    String workflowid = Util.null2String(rs.getString("workflowid"));
                    String receiveTime = Util.null2String(rs.getString("receiveTime"));

                    Map<String,String> itemMap = new HashMap<String,String>();
                    itemMap.put("createrCode",workcode);
                    itemMap.put("priority",priority);
                    itemMap.put("title",title);

                    itemMap.put("receiveTime",receiveTime);
                    itemMap.put("requestid",requestid);
                    itemMap.put("type",workflowname);
                    itemMap.put("createrName",lastname);
                    itemMap.put("action",action);
                    itemMap.put("createTime",createTime);
                    itemMap.put("createDate",createDate);
                    itemMap.put("referencenumber",referencenumber);
                    itemMap.put("fromSystem","数字办公平台");

                    long sjc = System.currentTimeMillis();
                    //&_workflowid=4024&_workflowtype=&isovertime=0&preloadkey=1615367484147&timestamp=1615367484147&_key=w3aabh
                    itemMap.put("url",oahost+"workflow/request/ViewRequestForwardSPA.jsp?requestid="+requestid+"" +
                            "&_workflowid="+workflowid+"&f_weaver_belongto_userid="+userid+"&isovertime=0&preloadkey="+sjc+"&timestamp="+sjc);

                    dataList.add(itemMap);
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }

        return dataList;
    }

    /**
     * 根据签字意见时间返回部门排序顺序
     * @param requestid
     * @param nodeids
     * @return
     */
    public String getDeptOrderStr(String requestid,String nodeids){
        String orderStr = "";
        String nodeSqlWhere = "";
        if(nodeids!=null && !"".equals(nodeids)){
            nodeSqlWhere = " and nodeid in("+nodeids+") ";
        }

        String sql = "select operatordept " +
                " from (select ROW_NUMBER() OVER(PARTITION BY operatordept ORDER BY operatedate,operatetime ) rn,operatordept,operatedate,operatetime " +
                " from workflow_requestLog where requestid in ("+requestid+") "+nodeSqlWhere+"  ) " +
                " where rn = 1 order by operatedate,operatetime";
        RecordSet rs = new RecordSet();
        rs.execute(sql);
        while(rs.next()){
            orderStr += Util.null2String(rs.getString("operatordept"))+",";
        }
        if(orderStr.length()>0){
            orderStr = orderStr.substring(0,orderStr.length()-1);
        }

        return orderStr;
    }


    /**
     * 根据节点分类返回排序方式
     * @param requestid
     * @param nodeids
     * @return
     */
    public String getDeptOrderStr(String requestid,String nodeids,String jdfl){
        String orderStr = "";
        String nodeSqlWhere = "";
        if(nodeids!=null && !"".equals(nodeids)){
            nodeSqlWhere = " and nodeid in("+nodeids+") ";
        }

        String sql = "select operatordept " +
                " from (select ROW_NUMBER() OVER(PARTITION BY operatordept ORDER BY operatedate,operatetime ) rn,operatordept,operatedate,operatetime " +
                " from workflow_requestLog where requestid in ("+requestid+") "+nodeSqlWhere+"  ) " +
                " where rn = 1 order by operatedate,operatetime";
        if("10".equals(jdfl) || "14".equals(jdfl) ){
            sql = "select operatordept from workflow_requestLog a,hrmdepartment b " +
                    " where requestid in ("+requestid+") " +nodeSqlWhere+
                    "   and a.operatordept=b.id order by b.showorder";
        }


        RecordSet rs = new RecordSet();
        rs.execute(sql);
        while(rs.next()){
            orderStr += Util.null2String(rs.getString("operatordept"))+",";
        }

        return orderStr;
    }

    /**
     * 获取签字意见部门显示名称
     * @param deptid
     * @param showTopDept
     * @return
     */
    public String getDeptShowName(String deptid,boolean showTopDept,String historyDeptName){
        String deptname = "";
        DepartmentComInfo deptComInfo = new DepartmentComInfo();
        try {
            if (StringUtils.isNotBlank(historyDeptName)){
                deptname = historyDeptName;
            }else {
                deptname = deptComInfo.getDepartmentName(deptid);
            }
            if(!"28".equals(deptid) && !"655".equals(deptid)){//紫金和创投不加简称
                if(showTopDept){
                    String shortname = WorkflowUtil.getTopDeptShortName(deptid);
                    if(!"".equals(shortname)){
                        deptname += "("+shortname+")";
                    }
                }

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return deptname;
    }


    public static void main(String[] args) {
        GCONST.setRootPath("WEB-INF/");
        GCONST.setServerName("ecology");
        String userCode = "012901" ;
        WorkflowTodoAction workflowTodoAction = new WorkflowTodoAction();
        workflowTodoAction.getWorkflowDataSql(userCode,"1",500);
    }

}
