package com.engine.htsc.collaboration.service;

import com.alibaba.fastjson.JSONObject;
import com.engine.common.util.ServiceUtil;
import com.engine.core.impl.Service;
import dm.jdbc.util.StringUtil;
import org.apache.commons.lang.StringUtils;
import weaver.conn.RecordSet;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.BaseBean;
import weaver.general.GCONST;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.resource.ResourceComInfo;
import weaver.interfaces.htsc.GlobatTools.JAVATools;
import weaver.interfaces.htsc.GlobatTools.Smstools;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.interfaces.htsc.cooperation.task.TaskTools;
import weaver.interfaces.htsc.util.HT_Util;
import weaver.soa.workflow.request.RequestInfo;

import java.util.*;

public class CoWorkService extends Service {

    /**
     * 创建协作事项
     * @param user
     * @return
     */
    public Map<String,Object> createCoWork(User user){
        BaseBean bs = new BaseBean();
        PropBean pb = new PropBean();
        RecordSet rs = new RecordSet();

        int userid = user.getUID();
        Map<String,Object> nodeMap = new HashMap<>();

        ResourceComInfo resourceComInfo = null;
        try {

            resourceComInfo = new ResourceComInfo();
            String uuid = UUID.randomUUID().toString();
            String modedatacreater = userid+"";
            String modedatacreatertype = "0";
            String modedatacreatedate = TimeUtil.getCurrentDateString();
            String modedatacreatetime = TimeUtil.getOnlyCurrentTimeString();
            String cjrq = TimeUtil.getCurrentDateString()+" "+TimeUtil.getOnlyCurrentTimeString().substring(0,5);
            String cjzt ="-1";

            String rwmodeid = pb.getPropName("UF_XZSY_CUBEUUIUD");
            JSONObject jsonObject_rw = pb.getModeInfoByUUID(rwmodeid);
            Integer formmodeid = Util.getIntValue(jsonObject_rw.getString("modeid"));

            Map<String,String> map = new HashMap<String,String>();
            map.put("formmodeid",formmodeid+"");
            map.put("modedatacreater",modedatacreater+"");
            map.put("modedatacreatertype",modedatacreatertype+"");
            map.put("modedatacreatedate",modedatacreatedate+"");
            map.put("modedatacreatetime",modedatacreatetime+"");
            map.put("modeuuid",uuid+"");
            HT_Util ht_util = new HT_Util();
            map.put("cjr",userid+"");
//            map.put("tzydr",userid+"");
            map.put("szbm",resourceComInfo.getDepartmentID(userid+""));
            map.put("szjg",ht_util.getszjg(userid+""));
            map.put("cjrq",cjrq+"");
            map.put("xzzt","0");
            map.put("yxj","1");
            map.put("cjzt",cjzt+"");


            String dttablename = "";
            String dttablenvalue = "";
            for (Map.Entry<String, String> entry : map.entrySet())
            {
                String fieldname = Util.null2String(entry.getKey());
                String fieldvalue = Util.null2String(entry.getValue());
                dttablename += dttablename == "" ? fieldname : "," + fieldname;
                dttablenvalue += dttablenvalue == "" ? "'" + fieldvalue + "'" : ",'" + fieldvalue + "'";
            }

            String sql = "insert into uf_xzsy("+dttablename+") values("+dttablenvalue+")";
            bs.writeLog("sql:"+sql);
            boolean bool = rs.executeUpdate(sql);
            if(bool){
                rs.executeQuery("select id from uf_xzsy where modeuuid='" + uuid + "'");
                if (rs.next()) {
                    int id = Util.getIntValue(rs.getString("id"));
                    bs.writeLog("id:"+id);
                    ModeRightInfo moderight = new ModeRightInfo();
                    moderight.editModeDataShare(userid, formmodeid, id);

                    int formid = 0 ;
                    rs.executeQuery("select formid from modeinfo where id= "+ formmodeid);
                    if(rs.next()){
                        formid = Util.getIntValue(Util.null2String(rs.getString("formid")));
                    }
                    bs.writeLog("formid:"+formid);

                    nodeMap.put("formmodeid",formmodeid);
                    nodeMap.put("formid",formid);
                    nodeMap.put("uuid",uuid);
                    nodeMap.put("billid",id);
                    nodeMap.put("status","1");
                    nodeMap.put("message","协作创建成功");
                }
            }else{
                nodeMap.put("billid","0");
                nodeMap.put("status","-1");
                nodeMap.put("message","新建协作异常，请联系系统管理员");
            }
        }catch (Exception e){
            nodeMap.put("billid","0");
            nodeMap.put("status","-2");
            nodeMap.put("message","系统错误,请联系系统管理员");
        }
        bs.writeLog("nodeMap:"+nodeMap.toString());
        return nodeMap;
    }

    /**
     * 根据关联流程id获取协作事项
     * @param requestid
     * @return
     */
    public List<Map<String,Object>> getCoWorkByRequestid(String requestid){
        BaseBean bs = new BaseBean();
        PropBean pb = new PropBean();
        String ecologyContentPath = GCONST.getContextPath();
        RecordSet rs = new RecordSet();
        List<Map<String,Object>> coWorkList = new ArrayList<>();

        String rwmodeid = pb.getPropName("UF_XZSY_CUBEUUIUD");
        JSONObject jsonObject_rw = pb.getModeInfoByUUID(rwmodeid);
        Integer modeid = Util.getIntValue(jsonObject_rw.getString("modeid"));
        int formid = 0 ;
        rs.executeQuery("select formid from modeinfo where id= "+ modeid);
        if(rs.next()){
            formid = Util.getIntValue(Util.null2String(rs.getString("formid")));
        }

        String sql = "select * from uf_xzsy where cjzt = '1' and gllc like '%"+requestid+"%'";
        bs.writeLog(sql);
        rs.executeQuery(sql);
        while(rs.next()){
            Map<String,Object> coWorkMap = new HashMap<>();
            coWorkMap.put("id",Util.null2String(rs.getString("id")));
            coWorkMap.put("bt",Util.null2String(rs.getString("bt")));
            coWorkMap.put("cjr",Util.null2String(rs.getString("cjr")));
            coWorkMap.put("jbr",Util.null2String(rs.getString("jbr")));
            coWorkMap.put("cjrq",Util.null2String(rs.getString("cjrq")));
            coWorkMap.put("xzzt",Util.null2String(rs.getString("xzzt")));
            coWorkList.add(coWorkMap);
        }
        for(Map<String,Object> coWorkMap:coWorkList){
            sql = "select lastname from HRMRESOURCE where id = '"+coWorkMap.get("cjr")+"'";
            bs.writeLog(sql);
            rs.executeQuery(sql);
            if(rs.next()){
                coWorkMap.put("name",Util.null2String(rs.getString("lastname")));
            }
            List<String> jbrList = new ArrayList<>();
            if(StringUtils.isNotEmpty(String.valueOf(coWorkMap.get("jbr")))){
                List<String> jbr = Arrays.asList(String.valueOf(coWorkMap.get("jbr")).split(","));
                for(String id:jbr){
                    sql = "select lastname from HRMRESOURCE where id = '"+id+"'";
                    bs.writeLog(sql);
                    rs.executeQuery(sql);
                    if(rs.next()){
                        jbrList.add(Util.null2String(rs.getString("lastname")));
                    }
                }
            }
            coWorkMap.put("jbrList",jbrList);


            String url = ecologyContentPath+"/spa/cube/index.html#/main/cube/card?type=2&modeId="+modeid+"&formId="+formid+"&billid="+coWorkMap.get("id");
            coWorkMap.put("url",url);
        }

        return coWorkList;
    }

    /**
     * 更新协作状态
     * @param user
     * @param billid
     * @param type
     * @return
     */
    public Map<String, Object> updateCoWorkState(User user, String billid, int type, String content, String fj){
        BaseBean bs = new BaseBean();
        RecordSet rs = new RecordSet();
        Map<String, Object> apidatas = new HashMap<String, Object>();

        String mainUserid = JAVATools.getmainhrmid(String.valueOf(user.getUID()));
        String title;
        //xzzt 0-草稿 1-已发布(废弃) 2-进行中 3-已完成
        int xzzt = 0;
        String sql = "select xzzt from uf_xzsy where id = '"+billid+"'";
        bs.writeLog(sql);
        rs.executeQuery(sql);
        if(rs.next()){
            xzzt = Util.getIntValue(rs.getString("xzzt"));
        }
        sql = "select id from uf_xzsy_dt3 where mainid = '"+billid+"' and ry = '"+mainUserid+"' and jd = '"+xzzt+"' and sfsh = '0'";
        bs.writeLog(sql);
        rs.executeQuery(sql);
        if(rs.next()){
            apidatas.put("api_status",false);
            apidatas.put("api_errormsg", "协作事项审核中，请在审核完成后操作");
            return apidatas;
        }

        if(2==type){
            title = "发布了协作事项";
            String now = TimeUtil.getCurrentTimeString();
            String updateSql = "update uf_xzsy set xzzt = '2',fbsj = '"+now+"' where id = '"+billid+"'";
            bs.writeLog(updateSql);
            rs.executeUpdate(updateSql);
            this.sendMessage(String.valueOf(user.getUID()),billid,"2");

            //发布协作事项，同时发布子任务，发送消息通知
            List<String> rwList = new ArrayList<>();
            sql = "select id from uf_rw where cjzt = '1' and rwzt = '0' and xzsy = '"+billid+"'";
            bs.writeLog(sql);
            rs.executeQuery(sql);
            while(rs.next()){
                rwList.add(Util.null2String(rs.getString("id")));
            }

            TaskService taskService = ServiceUtil.getService(TaskService.class);
            for(String rwid:rwList){
                updateSql = "update uf_rw set rwzt = '2', rwfbsj = '"+now+"' where id = '"+rwid+"'";
                bs.writeLog(updateSql);
                rs.executeUpdate(updateSql);
                taskService.sendMessage(String.valueOf(user.getUID()),rwid,"0");
            }
        }else if(3==type){
            title = "完成了协作事项";
            sql = "select id from uf_xzsy_dt2 where mainid = '"+billid+"' and ry = '"+mainUserid+"'";
            bs.writeLog(sql);
            rs.executeQuery(sql);
            if(rs.next()){
            }else{
                String rq = TimeUtil.getCurrentDateString();
                String sj = TimeUtil.getOnlyCurrentTimeString().substring(0,5);
                String insertSql = "insert into uf_xzsy_dt2(mainid,ry,rq,sj,ywc) values('"+billid+"','"+mainUserid+"','"+rq+"','"+sj+"','0')";
                bs.writeLog(insertSql);
                rs.executeUpdate(insertSql);
            }
            this.sendMessage(String.valueOf(user.getUID()),billid,"3");

            //完成协作事项，当全部人都完成，协作事项才完成
            String jbr = "";
            sql = "select jbr from uf_xzsy where id = '"+billid+"'";
            bs.writeLog(sql);
            rs.executeQuery(sql);
            if(rs.next()){
                jbr = Util.null2String(rs.getString("jbr"));
            }
            boolean flag = true;
            for(String jbrid:jbr.split(",")){
                String jbrMainid = JAVATools.getmainhrmid(jbrid);
                sql = "select id from uf_xzsy_dt2 where mainid = '"+billid+"' and ry = '"+jbrMainid+"'";
                bs.writeLog(sql);
                rs.executeQuery(sql);
                if(rs.next()){
                }else{
                    flag = false;
                    break;
                }
            }
            if(flag){
                String updateSql = "update uf_xzsy set xzzt = '3' where id = '"+billid+"'";
                bs.writeLog(updateSql);
                rs.executeUpdate(updateSql);
            }
        }else if(4==type){
            title = "重新打开了协作事项";
            String updateSql = "update uf_xzsy set xzzt = '2' where id = '"+billid+"'";
            bs.writeLog(updateSql);
            rs.executeUpdate(updateSql);

            String deleteSql = "delete from uf_xzsy_dt2 where mainid = '"+billid+"' and ry = '"+mainUserid+"'";
            bs.writeLog(deleteSql);
            rs.executeUpdate(deleteSql);
        }else{
            apidatas.put("api_status",false);
            apidatas.put("api_errormsg", "没有找到对应的协作状态:"+type);
            return apidatas;
        }

        TaskLogService taskLogService = ServiceUtil.getService(TaskLogService.class);
        taskLogService.createTaskLog(user,billid,fj,"0","0",content,title);
        apidatas.put("api_status",true);

        return apidatas;
    }

    /**
     * 创建人关闭协作事项
     * @param user
     * @param billid
     * @param type
     * @param content
     * @param fj
     * @return
     */
    public Map<String, Object> closeCoWorkState(User user, String billid, int type, String content, String fj){
        BaseBean bs = new BaseBean();
        PropBean pb = new PropBean();
        RecordSet rs = new RecordSet();
        RecordSet rs2 = new RecordSet();
        Map<String, Object> apidatas = new HashMap<String, Object>();

        try {
            ResourceComInfo resourceComInfo = new ResourceComInfo();
            String mainUserid = JAVATools.getmainhrmid(String.valueOf(user.getUID()));
            String cjrName = resourceComInfo.getLastname(mainUserid);

            String newXzzt = "";
            String newRwzt = "";
            if (1 == type) {//已完成
                newXzzt = "5";
                newRwzt = "6";
            } else if (2 == type) {
                newXzzt = "6";
                newRwzt = "7";
            } else {
                apidatas.put("api_status", false);
                apidatas.put("api_errormsg", "没有找到对应的协作状态:" + type);
                return apidatas;
            }

            //xzzt 0-草稿 1-已发布(废弃) 2-进行中 3-已完成 5-创建人已完成 6-终止
            int xzzt = 0;
            String xzjbr = "";
            String xzbt = "";
            String sql = "select xzzt,jbr,bt from uf_xzsy where id = '" + billid + "'";
            bs.writeLog(sql);
            rs.executeQuery(sql);
            if(rs.next()) {
                xzzt = Util.getIntValue(rs.getString("xzzt"));
                xzjbr = Util.null2String(rs.getString("jbr"));
                xzbt = Util.null2String(rs.getString("bt"));
            }else{
                apidatas.put("api_status", false);
                apidatas.put("api_errormsg", "没有找到对应的协作:" + billid);
                return apidatas;
            }

            //发送消息提醒
            Smstools smstools = new Smstools();
            int smstypeid = Integer.parseInt(Util.null2String(pb.getPropName("uf_ry_sms")));
            String xzurl = pb.getPropName("xz_mobile_url");
            String xzlink = xzurl + "&billid=" + billid;
            String messageTitle = "协作事项通知提醒";

            //未进行已阅操作的审核人
            Set<String> shrNoticeSet = new HashSet<>();
            sql = "select shr from uf_xzsy_dt3 where mainid = '"+billid+"' and jd = '"+xzzt+"' and sfsh = '0'";
            bs.writeLog(sql);
            rs.executeQuery(sql);
            while(rs.next()){
                shrNoticeSet.add(Util.null2String(rs.getString("shr")));
            }
            if(shrNoticeSet.size()>0){
                String context = "您审核的协作事项“"+xzbt+"”已由创建人"+cjrName+"关闭，关闭意见为“"+cutString(content,30)+"”。";
                smstools.sendMessage(smstypeid, shrNoticeSet, messageTitle, context, xzlink, xzlink);
            }

            if(2==xzzt){
                //未进行完成操作的执行人
                Set<String> xzjbrNoticeSet = new HashSet<>();
                if(StringUtils.isNotBlank(xzjbr)){
                    for(String jbrid:xzjbr.split(",")){
                        String jbrMainUserid = JAVATools.getmainhrmid(jbrid);
                        sql = "select id from uf_xzsy_dt2 where mainid = '"+billid+"' and ry = '"+jbrMainUserid+"'";
                        bs.writeLog(sql);
                        rs.executeQuery(sql);
                        if(rs.next()){
                        }else{
                            xzjbrNoticeSet.add(jbrid);
                        }
                    }
                }
                if(xzjbrNoticeSet.size()>0){
                    String context = "您执行的协作事项“"+xzbt+"”已由创建人"+cjrName+"关闭，关闭意见为“"+cutString(content,30)+"”。";
                    smstools.sendMessage(smstypeid, xzjbrNoticeSet, messageTitle, context, xzlink, xzlink);
                }
            }

            //更新协作状态
            String updateSql = "update uf_xzsy set xzzt = "+newXzzt+" where id = '" + billid + "'";
            bs.writeLog(updateSql);
            rs.executeUpdate(updateSql);

            //添加操作日志
            String title = "关闭了协作事项";
            TaskLogService taskLogService = ServiceUtil.getService(TaskLogService.class);
            taskLogService.createTaskLog(user,billid,fj,"0","0",content,title);
            apidatas.put("api_status",true);

            //如果有未完成的子任务，同时关闭
            String rwurl = pb.getPropName("rw_mobile_url");
            sql = "select id,cjr,jbr,rwbt from uf_rw where cjzt = '1' and rwzt = '2' and xzsy = '"+billid+"'";
            bs.writeLog(sql);
            rs.executeQuery(sql);
            while(rs.next()){
                String rwid = Util.null2String(rs.getString("id"));
                String rwcjr = Util.null2String(rs.getString("cjr"));
                String rwjbr = Util.null2String(rs.getString("jbr"));
                String rwbt = Util.null2String(rs.getString("rwbt"));
                String rwlink = rwurl + "&billid=" + rwid;

                //任务创建人和协作事项创建人不同
                if(!compareLoginid(mainUserid,rwcjr)){
                    String context = "您创建的协作任务“"+rwbt+"”已由其所属协作事项创建人"+cjrName+"关闭，关闭意见为“"+cutString(content,30)+"”。";
                    Set<String> sendSet = new HashSet<>();
                    sendSet.add(rwcjr);
                    smstools.sendMessage(smstypeid, sendSet, messageTitle, context, rwlink, rwlink);
                }

                //未进行完成操作的执行人
                Set<String> rwjbrNoticeSet = new HashSet<>();
                if(StringUtils.isNotBlank(rwjbr)){
                    for(String jbrid:rwjbr.split(",")){
                        String jbrMainUserid = JAVATools.getmainhrmid(jbrid);
                        sql = "select id from uf_rw_dt3 where mainid = '"+rwid+"' and ry = '"+jbrMainUserid+"'";
                        bs.writeLog(sql);
                        rs2.executeQuery(sql);
                        if(rs2.next()){
                        }else{
                            rwjbrNoticeSet.add(jbrid);
                        }
                    }
                }
                if(rwjbrNoticeSet.size()>0){
                    String context = "您执行的协作任务“"+rwbt+"”已由其所属协作事项创建人"+cjrName+"关闭，关闭意见为“"+cutString(content,30)+"”。";
                    smstools.sendMessage(smstypeid, rwjbrNoticeSet, messageTitle, context, rwlink, rwlink);
                }
            }

            //更新任务状态
            updateSql = "update uf_rw set rwzt = "+newRwzt+" where cjzt = '1' and rwzt in (0,2) and xzsy = '"+billid+"'";
            bs.writeLog(updateSql);
            rs.executeUpdate(updateSql);

        }catch (Exception e){
            e.printStackTrace();
            apidatas.put("api_status",false);
            apidatas.put("api_errormsg", "关闭协作事项失败");
            return apidatas;
        }

        return apidatas;
    }

    /**
     * 根据任务id获取关联的协作状态
     * @param billid
     * @return
     */
    public Map<String, Object> getCoWorkStatusByTaskid(String billid){
        BaseBean bs = new BaseBean();
        RecordSet rs = new RecordSet();
        Map<String, Object> apidatas = new HashMap<String, Object>();

        String xzbillid = "";
        String xzzt = "";
        String jbr = "";
        String sql = "select xzsy from uf_rw where id = '"+billid+"'";
        bs.writeLog(sql);
        rs.executeQuery(sql);
        if(rs.next()){
            xzbillid = Util.null2String(rs.getString("xzsy"));
        }
        if(StringUtil.isNotEmpty(xzbillid)){
            sql = "select xzzt,jbr from uf_xzsy where id = '"+xzbillid+"'";
            bs.writeLog(sql);
            rs.executeQuery(sql);
            if(rs.next()){
                xzzt = Util.null2String(rs.getString("xzzt"));
                jbr = Util.null2String(rs.getString("jbr"));
            }
        }
        Set<String> jbrAllid = new HashSet<>();
        if(StringUtils.isNotEmpty(jbr)){
            for(String id:jbr.split(",")){
                jbrAllid.addAll(getAllUserid(id));
            }
        }
        apidatas.put("billid",xzbillid);
        apidatas.put("xzzt",xzzt);
        apidatas.put("jbrAllId",jbrAllid);

        return apidatas;
    }

    /**
     * 转办
     * @param user
     * @param billid
     * @param forwardid
     * @return
     */
    public Map<String,Object> forwardTask(User user, String billid, String forwardid, String content, String fj){
        BaseBean bs = new BaseBean();
        PropBean pb = new PropBean();
        RecordSet rs = new RecordSet();
        Map<String, Object> apidatas = new HashMap<String, Object>();

        String userid = String.valueOf(user.getUID());
        String jbr = "";
        String tzydr = "";
        String bt = "";
        String sql = "select jbr,tzydr,bt from uf_xzsy where id = '"+billid+"'";
        bs.writeLog(sql);
        rs.executeQuery(sql);
        while(rs.next()){
            jbr = Util.null2String(rs.getString("jbr"));
            tzydr = Util.null2String(rs.getString("tzydr"));
            bt = Util.null2String(rs.getString("bt"));
        }

        List<String> tzydrList = new ArrayList<>();
        tzydrList.addAll(Arrays.asList(tzydr.split(",")));
        if(StringUtil.isNotEmpty(jbr)){
            List<String> jbrs = Arrays.asList(jbr.split(","));
            List<String> jbrList = new ArrayList<>(jbrs);
            for(int i=0;i<jbrList.size();i++){
                if(compareLoginid(userid,jbrList.get(i))){
                    //查询被转办人是否已经存在执行人中，如果已存在，仅删除当前操作人，不替换为被转办人
                    boolean flagExist = false;
                    for(String jbrid:jbrList){
                        if(compareLoginid(forwardid,jbrid)){
                            flagExist = true;
                            break;
                        }
                    }
                    if(!flagExist){
                        jbrList.set(i,forwardid);
                    }else{
                        jbrList.remove(i);
                    }

                    boolean flag1 = false;
                    for(String tzydrid:tzydrList){
                        if(compareLoginid(userid,tzydrid)){
                            flag1 = true;
                            break;
                        }
                    }
                    if(!flag1){
                        tzydrList.add(userid);
                    }
                    //A转办给B，仅A需要被带进参与人，B不需要
//                    boolean flag2 = false;
//                    for(String tzydrid:tzydrList){
//                        if(compareLoginid(forwardid,tzydrid)){
//                            flag2 = true;
//                            break;
//                        }
//                    }
//                    if(!flag2){
//                        tzydrList.add(forwardid);
//                    }
                    break;
                }
                if(i==jbrList.size()-1){
                    apidatas.put("status","-1");
                    apidatas.put("message","执行人中没有找到当前用户");
                    return apidatas;
                }
            }
            String newjbr = String.join(",",jbrList);
            String newtzydr = String.join(",",tzydrList);

            List<String> allidList = new ArrayList<>();
            for(String id:jbrList){
                allidList.addAll(getAllUserid(id));
            }
            String allidStr = String.join(",",allidList);

            List<String> allgzridList = new ArrayList<>();
            for(String id:tzydrList){
                allgzridList.addAll(getAllUserid(id));
            }
            String allgzridStr = String.join(",",allgzridList);

            String updateSql = "update uf_xzsy set jbr = '"+newjbr+"', jbrzzhyc = '"+allidStr+"', tzydr = '"+newtzydr+"', tzydzzhyc = '"+allgzridStr+"'  where id = '"+billid+"'";
            bs.writeLog(updateSql);
            boolean res = rs.executeUpdate(updateSql);

            if(res){
                String gxid = "";
                sql = "select id from uf_xzsy_dt1 where bgxr = '"+userid+"'";
                bs.writeLog(sql);
                rs.executeQuery(sql);
                if(rs.next()){
                    gxid = Util.null2String(rs.getString("id"));
                }
                if(StringUtil.isEmpty(gxid)){
                    String datetime = TimeUtil.getCurrentTimeString();
                    String insertSql = "insert into uf_xzsy_dt1(mainid,czr,bgxr,gxsj) values('"+billid+"','"+userid+"','"+userid+"','"+datetime+"')";
                    bs.writeLog(insertSql);
                    rs.executeUpdate(insertSql);
                }

                String rwmodeid = pb.getPropName("UF_XZSY_CUBEUUIUD");
                JSONObject jsonObject_rw = pb.getModeInfoByUUID(rwmodeid);
                int modeid = Util.getIntValue(jsonObject_rw.getString("modeid"));
                ModeRightInfo moderight = new ModeRightInfo();
                moderight.editModeDataShare(Integer.parseInt(userid), modeid, Integer.parseInt(billid));
                apidatas.put("status","1");
                apidatas.put("message","转办成功");

                try{
                    ResourceComInfo resourceComInfo = new ResourceComInfo();
                    String title = "将协作事项转办给"+resourceComInfo.getLastname(forwardid);
                    TaskLogService taskLogService = ServiceUtil.getService(TaskLogService.class);
                    taskLogService.createTaskLog(user,billid,fj,"0","0",content,title);

                    //发送消息提醒
                    Smstools smstools=new Smstools();
                    int smstypeid=Integer.parseInt(Util.null2String(pb.getPropName("uf_ry_sms")));
                    String url = pb.getPropName("xz_mobile_url");
                    String link = url+"&billid="+billid;
                    String messageTitle = "协作事项通知提醒";
                    String context = user.getLastname()+"将协作事项“"+bt+"”转办给您，";
                    if(StringUtils.isNotBlank(content)){
                        context += "转办意见为“"+cutString(content,30)+"”，";
                    }
                    context +="请您及时处理。";
                    Set<String> sendSet = new HashSet<>();
                    sendSet.add(forwardid);
                    if(sendSet.size()>0){
                        smstools.sendMessage(smstypeid,sendSet,messageTitle,context,link,link);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }


//                Map<String, Object> param = new HashMap<>();
//                param.put("user",user);
//                RequestInfo requestInfo = new RequestInfo();
//                requestInfo.setRequestid(billid);
//                param.put("RequestInfo",requestInfo);
//                TaskTools tasktools=new TaskTools();
//                tasktools.reloadUser(param);


            }else{
                apidatas.put("status","-1");
                apidatas.put("message","转办异常，请联系系统管理员");
            }
        }else{
            apidatas.put("status","-1");
            apidatas.put("message","没有找到当前执行人");
        }

        return apidatas;
    }

    /**
     * 审核人转办
     * @param user
     * @param billid
     * @param forwardid
     * @return
     */
    public Map<String,Object> forwardTaskApproval(User user, String billid, String forwardid, String content, String fj){
        BaseBean bs = new BaseBean();
        PropBean pb = new PropBean();
        RecordSet rs = new RecordSet();
        Map<String, Object> apidatas = new HashMap<String, Object>();

        String userid = String.valueOf(user.getUID());
        String shr = "";
        String tzydr = "";
        String bt = "";
        String sql = "select shr,tzydr,bt from uf_xzsy where id = '"+billid+"'";
        bs.writeLog(sql);
        rs.executeQuery(sql);
        while(rs.next()){
            shr = Util.null2String(rs.getString("shr"));
            tzydr = Util.null2String(rs.getString("tzydr"));
            bt = Util.null2String(rs.getString("bt"));
        }

        List<String> tzydrList = new ArrayList<>();
        tzydrList.addAll(Arrays.asList(tzydr.split(",")));
        if(StringUtil.isNotEmpty(shr)){
            List<String> shrList = Arrays.asList(shr.split(","));
            for(int i=0;i<shrList.size();i++){
                if(compareLoginid(userid,shrList.get(i))){
                    shrList.set(i,forwardid);
                    boolean flag1 = false;
                    for(String tzydrid:tzydrList){
                        if(compareLoginid(userid,tzydrid)){
                            flag1 = true;
                            break;
                        }
                    }
                    if(!flag1){
                        tzydrList.add(userid);
                    }
                    break;
                }
                if(i==shrList.size()-1){
                    apidatas.put("status","-1");
                    apidatas.put("message","执行人中没有找到当前用户");
                    return apidatas;
                }
            }
            String newshr = String.join(",",shrList);
            String newtzydr = String.join(",",tzydrList);

            List<String> allidList = new ArrayList<>();
            for(String id:shrList){
                allidList.addAll(getAllUserid(id));
            }
            String allidStr = String.join(",",allidList);

            List<String> allgzridList = new ArrayList<>();
            for(String id:tzydrList){
                allgzridList.addAll(getAllUserid(id));
            }
            String allgzridStr = String.join(",",allgzridList);

            String updateSql = "update uf_xzsy set shr = '"+newshr+"', shrzczhyc = '"+allidStr+"', tzydr = '"+newtzydr+"', tzydzzhyc = '"+allgzridStr+"'  where id = '"+billid+"'";
            bs.writeLog(updateSql);
            rs.executeUpdate(updateSql);

            String userMainUserid = JAVATools.getmainhrmid(userid);
            String shrMainUserid = JAVATools.getmainhrmid(forwardid);
            updateSql = "update uf_xzsy_dt3 set shr = '"+shrMainUserid+"' where mainid = '"+billid+"' and to_char(shr) = '"+userMainUserid+"' and sfsh = '0'";
            bs.writeLog(updateSql);
            rs.executeUpdate(updateSql);
            boolean res = rs.executeUpdate(updateSql);

            if(res){
//                String gxid = "";
//                sql = "select id from uf_xzsy_dt1 where bgxr = '"+userid+"'";
//                bs.writeLog(sql);
//                rs.executeQuery(sql);
//                if(rs.next()){
//                    gxid = Util.null2String(rs.getString("id"));
//                }
//                if(StringUtil.isEmpty(gxid)){
//                    String datetime = TimeUtil.getCurrentTimeString();
//                    String insertSql = "insert into uf_xzsy_dt1(mainid,czr,bgxr,gxsj) values('"+billid+"','"+userid+"','"+userid+"','"+datetime+"')";
//                    bs.writeLog(insertSql);
//                    rs.executeUpdate(insertSql);
//                }

                String rwmodeid = pb.getPropName("UF_XZSY_CUBEUUIUD");
                JSONObject jsonObject_rw = pb.getModeInfoByUUID(rwmodeid);
                int modeid = Util.getIntValue(jsonObject_rw.getString("modeid"));
                ModeRightInfo moderight = new ModeRightInfo();
                moderight.editModeDataShare(Integer.parseInt(userid), modeid, Integer.parseInt(billid));
                apidatas.put("status","1");
                apidatas.put("message","转办成功");

                try{
                    ResourceComInfo resourceComInfo =  new ResourceComInfo();
                    String title = "将协作事项转办给"+resourceComInfo.getLastname(forwardid);
                    TaskLogService taskLogService = ServiceUtil.getService(TaskLogService.class);
                    taskLogService.createTaskLog(user,billid,fj,"0","0",content,title);

                    //发送消息提醒
                    Smstools smstools=new Smstools();
                    int smstypeid=Integer.parseInt(Util.null2String(pb.getPropName("uf_ry_sms")));
                    String url = pb.getPropName("xz_mobile_url");
                    String link = url+"&billid="+billid;
                    String messageTitle = "协作事项通知提醒";
                    String context = user.getLastname()+"将协作事项“"+bt+"”转办给您审核，";
                    if(StringUtils.isNotBlank(content)){
                        context += "转办意见为“"+cutString(content,30)+"”，";
                    }
                    context +="请您及时处理。";
                    Set<String> sendSet = new HashSet<>();
                    sendSet.add(forwardid);
                    if(sendSet.size()>0){
                        smstools.sendMessage(smstypeid,sendSet,messageTitle,context,link,link);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }else{
                apidatas.put("status","-1");
                apidatas.put("message","转办异常，请联系系统管理员");
            }
        }else{
            apidatas.put("status","-1");
            apidatas.put("message","没有找到当前执行人");
        }

        return apidatas;
    }

    /**
     * 送审核
     * @param user
     * @param billid
     * @param approver
     */
    public Map<String,Object> sendApproval(User user, String billid, String approver){
        BaseBean bs = new BaseBean();
        PropBean pb = new PropBean();
        RecordSet rs = new RecordSet();
        Map<String, Object> apidatas = new HashMap<String, Object>();

        try {
            String rwmodeid = pb.getPropName("UF_XZSY_CUBEUUIUD");
            JSONObject jsonObject_rw = pb.getModeInfoByUUID(rwmodeid);
            Integer formmodeid = Util.getIntValue(jsonObject_rw.getString("modeid"));
            String mainUserid = JAVATools.getmainhrmid(String.valueOf(user.getUID()));
            ModeRightInfo moderight = new ModeRightInfo();

            int xzzt = 0;
            String bt = "";
            String shr = "";
            String tzydr = "";
            String sql = "select xzzt,bt,shr,tzydr from uf_xzsy where id = '" + billid + "'";
            bs.writeLog(sql);
            rs.executeQuery(sql);
            if (rs.next()) {
                xzzt = Util.getIntValue(rs.getString("xzzt"));
                bt = Util.null2String(rs.getString("bt"));
                shr = Util.null2String(rs.getString("shr"));
                tzydr = Util.null2String(rs.getString("tzydr"));
            }

            Set<String> shrSet = new LinkedHashSet<>();
            if(StringUtils.isNotEmpty(shr)){
                shrSet.addAll(Arrays.asList(shr.split(",")));
            }
//            Set<String> tzydrSet = new LinkedHashSet<>();
//            if(StringUtils.isNotEmpty(tzydr)){
//                tzydrSet.addAll(Arrays.asList(tzydr.split(",")));
//            }

            List<String> nameList = new ArrayList<>();
            for (String shrid : approver.split(",")) {
                shrSet.add(shrid);
//                tzydrSet.add(shrid);
                String shrMainUserid = JAVATools.getmainhrmid(shrid);
                String now = TimeUtil.getCurrentTimeString();
                String insertSql = "insert into uf_xzsy_dt3(mainid,ry,shr,sj,jd,sfsh) values('" + billid + "','" + mainUserid + "','" + shrMainUserid + "','" + now + "','" + xzzt + "','0')";
                bs.writeLog(insertSql);
                rs.executeUpdate(insertSql);

                moderight.editModeDataShare(Integer.parseInt(shrMainUserid), formmodeid, Integer.parseInt(billid));

                sql = "select lastname from HRMRESOURCE where id = '" + shrid + "'";
                bs.writeLog(sql);
                rs.executeQuery(sql);
                if (rs.next()) {
                    nameList.add(Util.null2String(rs.getString("lastname")));
                }
            }

            //审核人主次账号
            List<String> shrzczhycList = new ArrayList<>();
            for(String id:shrSet){
                shrzczhycList.addAll(getAllUserid(id));
            }
            String shrzczhycStr = String.join(",",shrzczhycList);
            String shrStr = String.join(",",shrSet);
//            String tzydrStr = String.join(",",tzydrSet);

            //更新主表中的审核人和参与人
            String updateSql = "update uf_xzsy set shzt = '0', shr = '"+shrStr+"', shrzczhyc = '"+shrzczhycStr+"' where id = '"+billid+"'";
            bs.writeLog(updateSql);
            rs.executeUpdate(updateSql);

            //添加日志
            String title = "提交了审核";
            String content = "提交" + String.join("、", nameList) + "审核";
            TaskLogService taskLogService = ServiceUtil.getService(TaskLogService.class);
            taskLogService.createTaskLog(user, billid, "", "0", "0", content, title);

            //发送消息提醒
            ResourceComInfo resourceComInfo = new ResourceComInfo();
            Smstools smstools=new Smstools();
            int smstypeid=Integer.parseInt(Util.null2String(pb.getPropName("uf_ry_sms")));
            String url = pb.getPropName("xz_mobile_url");
            String link = url+"&billid="+billid;
            String messageTitle = "协作事项通知提醒";
            String sendName = resourceComInfo.getLastname(mainUserid);
            String context = sendName+"将协作事项“"+bt+"”提交至您审核，请点击查看详情。";
            Set<String> sendSet = new HashSet<>();
            sendSet.addAll(Arrays.asList(approver.split(",")));
            if(sendSet.size()>0){
                smstools.sendMessage(smstypeid,sendSet,messageTitle,context,link,link);
            }

            apidatas.put("api_status", true);
        }catch (Exception e){
            e.printStackTrace();
            apidatas.put("api_status",false);
            apidatas.put("api_errormsg", "提交审核失败");
            return apidatas;
        }

        return apidatas;
    }

    /**
     * 审核
     * @param user
     * @param billid
     * @param content
     * @param fj
     */
    public Map<String,Object> approve(User user, String billid, String content, String fj){
        BaseBean bs = new BaseBean();
        PropBean pb = new PropBean();
        RecordSet rs = new RecordSet();
        Map<String, Object> apidatas = new HashMap<String, Object>();

        try{
            String mainUserid = JAVATools.getmainhrmid(String.valueOf(user.getUID()));
            int xzzt = 0;
            String bt = "";
            String sql = "select xzzt,bt from uf_xzsy where id = '"+billid+"'";
            bs.writeLog(sql);
            rs.executeQuery(sql);
            if(rs.next()){
                xzzt = Util.getIntValue(rs.getString("xzzt"));
                bt = Util.null2String(rs.getString("bt"));
            }

            Set<String> sendSet = new HashSet<>();
            sql = "select ry from uf_xzsy_dt3 where mainid = '"+billid+"' and to_char(shr) = '"+mainUserid+"' and jd = '"+xzzt+"' and sfsh = '0'";
            bs.writeLog(sql);
            rs.executeQuery(sql);
            while(rs.next()){
                sendSet.add(Util.null2String(rs.getString("ry")));
            }

            String update_sql = "update uf_xzsy_dt3 set sfsh = '1' where mainid = '"+billid+"' and to_char(shr) = '"+mainUserid+"' and jd = '"+xzzt+"'";
            bs.writeLog(update_sql);
            rs.executeUpdate(update_sql);

            //协作事项的审核状态
            boolean coWorkApproveState = true;
            sql = "select shr from uf_xzsy_dt3 where mainid = '"+billid+"' and jd = '"+xzzt+"' and sfsh = '0'";
            bs.writeLog(sql);
            rs.executeQuery(sql);
            while(rs.next()){
                coWorkApproveState = false;
            }
            if(coWorkApproveState){
                String updateSql = "update uf_xzsy set shzt = '1' where id = '"+billid+"'";
                bs.writeLog(updateSql);
                rs.executeUpdate(updateSql);
            }

            String title = "已审核协作事项";
            TaskLogService taskLogService = ServiceUtil.getService(TaskLogService.class);
            taskLogService.createTaskLog(user,billid,fj,"0","0",content,title);

            ResourceComInfo resourceComInfo = new ResourceComInfo();
            Smstools smstools=new Smstools();
            int smstypeid=Integer.parseInt(Util.null2String(pb.getPropName("uf_ry_sms")));
            String url = pb.getPropName("xz_mobile_url");
            String link = url+"&billid="+billid;
            String messageTitle = "协作事项通知提醒";
            String sendName = resourceComInfo.getLastname(mainUserid);
            String context = sendName+"针对协作事项“"+bt+"”审核意见为“"+cutString(content,30)+"”，请您及时处理。";
            if(sendSet.size()>0){
                smstools.sendMessage(smstypeid,sendSet,messageTitle,context,link,link);
            }

            apidatas.put("api_status",true);
        }catch (Exception e){
            apidatas.put("api_status",false);
            apidatas.put("api_errormsg", "提交审核失败");
            return apidatas;
        }


        return apidatas;
    }

    /**
     * 获取协作事项的审核状态
     * @param user
     * @param billid
     * @return
     */
    public Map<String,Object> getApproveInfo(User user, String billid){
        BaseBean bs = new BaseBean();
        RecordSet rs = new RecordSet();
        Map<String, Object> apidatas = new HashMap<String, Object>();

        String mainUserid = JAVATools.getmainhrmid(String.valueOf(user.getUID()));
        int xzzt = 0;
        String bt = "";
        String sql = "select xzzt from uf_xzsy where id = '"+billid+"'";
        bs.writeLog(sql);
        rs.executeQuery(sql);
        if(rs.next()){
            xzzt = Util.getIntValue(rs.getString("xzzt"));
        }

        //当前用户的审核状态
        boolean userApproveState = true;
        sql = "select * from uf_xzsy_dt3 where mainid = '"+billid+"' and to_char(shr) = '"+mainUserid+"' and jd = '"+xzzt+"' and sfsh = '0'";
        bs.writeLog(sql);
        rs.executeQuery(sql);
        while(rs.next()){
            userApproveState = false;
        }
        apidatas.put("userApproveState",userApproveState);

        //当前用户提交的审核状态
        boolean userSendApproveState = true;
        sql = "select * from uf_xzsy_dt3 where mainid = '"+billid+"' and ry = '"+mainUserid+"' and jd = '"+xzzt+"' and sfsh = '0'";
        bs.writeLog(sql);
        rs.executeQuery(sql);
        while(rs.next()){
            userSendApproveState = false;
        }
        apidatas.put("userSendApproveState",userSendApproveState);

        //协作事项的审核状态
        boolean coWorkApproveState = true;
        Set<String> approverNotFinish = new HashSet<>();
        sql = "select shr from uf_xzsy_dt3 where mainid = '"+billid+"' and jd = '"+xzzt+"' and sfsh = '0'";
        bs.writeLog(sql);
        rs.executeQuery(sql);
        while(rs.next()){
            coWorkApproveState = false;
            approverNotFinish.add(Util.null2String(rs.getString("shr")));
        }
        apidatas.put("coWorkApproveState",coWorkApproveState);

        //获取已完成的审核人
        Set<String> approverFinish = new HashSet<>();
        sql = "select shr from uf_xzsy_dt3 where mainid = '"+billid+"' and sfsh = '1'";
        bs.writeLog(sql);
        rs.executeQuery(sql);
        while(rs.next()){
            approverFinish.add(Util.null2String(rs.getString("shr")));
        }
        Set<String> finishIdSet = new HashSet<>();
        for(String approverId:approverFinish){
            if(!approverNotFinish.contains(approverId)){
                finishIdSet.addAll(getAllUserid(approverId));
            }
        }
        apidatas.put("finishIds",finishIdSet);


        return apidatas;
    }

    /**
     * 发送消息提醒
     * @param billid
     * @param type
     */
    public void sendMessage(String userid, String billid, String type){
        BaseBean bs = new BaseBean();
        PropBean pb = new PropBean();
        RecordSet rs = new RecordSet();

        try{
            ResourceComInfo resourceComInfo = new ResourceComInfo();
            Smstools smstools=new Smstools();
            int smstypeid=Integer.parseInt(Util.null2String(pb.getPropName("uf_ry_sms")));
            String url = pb.getPropName("xz_mobile_url");
            String link = url+"&billid="+billid;

            String cjr = "";
            String jbr = "";
            String tzydr = "";
            String bt = "";
            String sql = "select cjr,jbr,tzydr,bt from uf_xzsy where id = '"+billid+"'";
            bs.writeLog(sql);
            rs.executeQuery(sql);
            while(rs.next()){
                cjr = Util.null2String(rs.getString("cjr"));
                jbr = Util.null2String(rs.getString("jbr"));
                tzydr = Util.null2String(rs.getString("tzydr"));
                bt = Util.null2String(rs.getString("bt"));
            }
            String userName = resourceComInfo.getLastname(userid);
            String cjrName = resourceComInfo.getLastname(cjr);
            List<String> jbrList = Arrays.asList(jbr.split(","));
            List<String> tzydrList = Arrays.asList(tzydr.split(","));
            List<String> jbrNameList = new ArrayList<>();
            List<String> tzydrNameList = new ArrayList<>();
            List<String> cyrList = new ArrayList<>();
            for(String jbrid:jbrList){
                jbrNameList.add(resourceComInfo.getLastname(jbrid));
            }
            for(String tzydrid:tzydrList){
                if(!jbrList.contains(tzydrid)){
                    cyrList.add(tzydrid);
                }
                tzydrNameList.add(resourceComInfo.getLastname(tzydrid));
            }

            if("2".equals(type)){//发布
                String title = "协作事项发布提醒";
                String context1 = cjrName+"邀请您执行协作事项“"+bt+"”，请点击查看详情";
                Set<String> sendSet1 = new HashSet<>();
                sendSet1.addAll(jbrList);
                if(sendSet1.size()>0){
                    smstools.sendMessage(smstypeid,sendSet1,title,context1,link,link);
                }

                String tzydrNameStr = StringUtils.join(tzydrNameList,"、");
                String context2 = cjrName+"发布了协作事项“"+bt+"”，邀请"+tzydrNameStr+"共同参与，请点击查看详情";
                Set<String> sendSet2 = new HashSet<>();
                sendSet2.addAll(cyrList);
                if(sendSet2.size()>0){
                    smstools.sendMessage(smstypeid,sendSet2,title,context2,link,link);
                }
            }else if("3".equals(type)){//完成
                String title = "协作事项完成提醒";
                String context = "您创建的协作事项“"+bt+"”已由"+userName+"完成，请点击查看详情";
                Set<String> sendSet = new HashSet<>();
                sendSet.add(cjr);
                if(sendSet.size()>0){
                    smstools.sendMessage(smstypeid,sendSet,title,context,link,link);
                }
//                String title = "协作事项通知提醒";
//                String context = cjrName+"发起的协作事项“"+bt+"”已完成，请点击查看详情";
//                Set<String> sendSet = new HashSet<>();
//                sendSet.addAll(tzydrList);
//                if(sendSet.size()>0){
//                    smstools.sendMessage(smstypeid,sendSet,title,context,link,link);
//                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 比较工号
     * @param userid_1
     * @param userid_2
     * @return
     */
    private boolean compareLoginid(String userid_1,String userid_2){
        RecordSet rs = new RecordSet();
        BaseBean bs = new BaseBean();
        String loginid_1 = "";
        String loginid_2 = "";
        String sql = "select workcode from hrmresource where id = '"+userid_1+"'";
        rs.executeQuery(sql);
        if(rs.next()){
            loginid_1 = Util.null2String(rs.getString("workcode"));
        }
        sql = "select workcode from hrmresource where id = '"+userid_2+"'";
        rs.executeQuery(sql);
        if(rs.next()){
            loginid_2 = Util.null2String(rs.getString("workcode"));
        }
        if(StringUtils.isNotEmpty(loginid_1)&&StringUtils.isNotEmpty(loginid_2)&&loginid_1.equals(loginid_2)){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 获得全部工号
     * @param id
     * @return
     */
    private List<String> getAllUserid(String id){
        BaseBean bs = new BaseBean();
        RecordSet rs = new RecordSet();
        List<String> idList = new ArrayList<>();

        if(StringUtils.isNotBlank(id)){
            String mainUserid = JAVATools.getmainhrmid(id);
            idList.add(mainUserid);
            String sql="select id from hrmresource where belongto = '"+mainUserid+"'";
            bs.writeLog(sql);
            rs.executeQuery(sql);
            while(rs.next()){
                idList.add(Util.null2String(rs.getString("id")));
            }
        }
        return idList;
    }

    /**
     * 截取String
     * @param str
     * @param index
     * @return
     */
    private String cutString(String str,int index){
        if(str.length()>index){
            return str.substring(0, index)+"…";
        }else{
            return str;
        }
    }
}
