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.soa.workflow.request.RequestInfo;

import java.util.*;

public class TaskService extends Service {

    /**
     * 创建任务
     * @param user
     * @param sxbillid
     * @param rwlx 0-协作 1-督办
     * @return
     */
    public Map<String,Object> createTask(User user, String sxbillid, String rwlx){
        BaseBean bs = new BaseBean();
        PropBean pb = new PropBean();
        RecordSet rs = new RecordSet();

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

        try {
            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_RW_CUBEUUIUD");
            JSONObject jsonObject_rw = pb.getModeInfoByUUID(rwmodeid);
            Integer formmodeid = Util.getIntValue(jsonObject_rw.getString("modeid"));
            String modelableid = getTab(sxbillid,rwlx);

            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+"");
            map.put("cjr",userid+"");
//            map.put("gzr",userid+"");
            map.put("rwlx",rwlx);
            map.put("cjrq",cjrq);
            map.put("rwzt","0");
            map.put("zqtx","0");
            map.put("cjzt",cjzt);
            map.put("modelableid",modelableid);
            map.put("mrbq",modelableid);

            if("0".equals(rwlx)){//协作事项创建
                map.put("xzsy",sxbillid);
                String sql = "select bt,jzsj,yxj,gllc,xgwj from uf_xzsy where id = '"+sxbillid+"'";
                bs.writeLog(sql);
                rs.executeQuery(sql);
                if(rs.next()){
                    map.put("rwbt",Util.null2String(rs.getString("bt"))+"-子任务");
                    map.put("jzrq",Util.null2String(rs.getString("jzsj")));
                    map.put("yxj",Util.null2String(rs.getString("yxj")));
                    map.put("gllc",Util.null2String(rs.getString("gllc")));
                    map.put("xgwj",Util.null2String(rs.getString("xgwj")));
                }
            }else if("1".equals(rwlx)){//督办事项创建
                map.put("dbsy",sxbillid);
                String sql = "select bt,jzsj,yxj,gllc,xgwj from uf_xzsx where id = '"+sxbillid+"'";
                bs.writeLog(sql);
                rs.executeQuery(sql);
                if(rs.next()){
                    map.put("rwbt",Util.null2String(rs.getString("bt"))+"-子任务");
                    map.put("jzrq",Util.null2String(rs.getString("jzsj")));
                    map.put("yxj",Util.null2String(rs.getString("yxj")));
                    map.put("gllc",Util.null2String(rs.getString("gllc")));
                    map.put("xgwj",Util.null2String(rs.getString("xgwj")));
                }
            }

            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_rw("+dttablename+") values("+dttablenvalue+")";
            bs.writeLog("sql:"+sql);
            boolean bool = rs.executeUpdate(sql);
            if(bool){
                rs.executeQuery("select id from uf_rw 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;
    }

    /**
     * 根据事项添加任务标签
     * @param sxbillid
     * @return
     */
    private String getTab(String sxbillid, String rwlx){
        BaseBean bs = new BaseBean();
        PropBean pb = new PropBean();
        RecordSet rs = new RecordSet();
        String rwTab = "";

        if(StringUtil.isNotEmpty(sxbillid)){
            String modelableid = "";
            String sql = "";
            if("0".equals(rwlx)){
                sql = "select modelableid from uf_xzsy where id = '"+sxbillid+"'";
            }else if("1".equals(rwlx)){
                sql = "select modelableid from uf_xzsx where id = '"+sxbillid+"'";
            }
            bs.writeLog(sql);
            rs.executeQuery(sql);
            if(rs.next()){
                modelableid = Util.null2String(rs.getString("modelableid"));
            }
            bs.writeLog("modelableid:"+modelableid);
            if(StringUtil.isNotEmpty(modelableid)){
                JSONObject jsonObject_xz = pb.getModeInfoByUUID(pb.getPropName("UF_XZSY_CUBEUUIUD"));
                Integer xzmodeid = Util.getIntValue(jsonObject_xz.getString("modeid"));
                JSONObject jsonObject_db = pb.getModeInfoByUUID(pb.getPropName("DUBAN_XZ_UUID"));
                Integer dbmodeid = Util.getIntValue(jsonObject_db.getString("modeid"));
                JSONObject jsonObject_rw = pb.getModeInfoByUUID(pb.getPropName("UF_RW_CUBEUUIUD"));
                Integer rwmodeid = Util.getIntValue(jsonObject_rw.getString("modeid"));

                List<String> xzTabList = Arrays.asList(modelableid.split(","));
                List<String> rwTabList = new ArrayList<>();
                for(String xzTab:xzTabList){
                    String tabname = "";
                    String id = "";
                    if("0".equals(rwlx)){
                        sql = "select tabname from modeTabs_"+xzmodeid+" where id = '"+xzTab+"'";
                    }else if("1".equals(rwlx)){
                        sql = "select tabname from modeTabs_"+dbmodeid+" where id = '"+xzTab+"'";
                    }
                    bs.writeLog(sql);
                    rs.executeQuery(sql);
                    if(rs.next()){
                        tabname = Util.null2String(rs.getString("tabname"));
                    }

                    sql = "select id from modeTabs_"+rwmodeid+" where tabname = '"+tabname+"'";
                    bs.writeLog(sql);
                    rs.executeQuery(sql);
                    if(rs.next()){
                        id = Util.null2String(rs.getString("id"));
                    }else{
                        Map<String,String> map = new HashMap<String,String>();
                        if("0".equals(rwlx)){
                            sql = "select * from modeTabs_"+xzmodeid+" where id = '"+xzTab+"'";
                        }else if("1".equals(rwlx)){
                            sql = "select * from modeTabs_"+dbmodeid+" where id = '"+xzTab+"'";
                        }
                        bs.writeLog(sql);
                        rs.executeQuery(sql);
                        if(rs.next()){
                            map.put("tabname",Util.null2String(rs.getString("tabname")));
                            map.put("color",Util.null2String(rs.getString("color")));
                            map.put("bgcolor",Util.null2String(rs.getString("bgcolor")));
                            map.put("bdcolor",Util.null2String(rs.getString("bdcolor")));
                            map.put("type",Util.null2String(rs.getString("type")));
                            map.put("creator",Util.null2String(rs.getString("creator")));
                        }

                        sql = "select max(orderid) from modeTabs_"+rwmodeid;
                        bs.writeLog(sql);
                        rs.executeQuery(sql);
                        if(rs.next()){
                            int orderid = Util.getIntValue(rs.getString("max(orderid)"));
                            orderid++;
                            map.put("orderid",String.valueOf(orderid));
                        }

                        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 insertSql = "insert into modeTabs_"+rwmodeid+" ("+dttablename+") values("+dttablenvalue+")";
                        bs.writeLog(insertSql);
                        rs.executeUpdate(insertSql);

                        sql = "select id from modeTabs_"+rwmodeid+" where tabname = '"+tabname+"'";
                        bs.writeLog(sql);
                        rs.executeQuery(sql);
                        if(rs.next()){
                            id = Util.null2String(rs.getString("id"));
                        }
                    }
                    rwTabList.add(id);
                }
                rwTab = StringUtils.join(rwTabList, ",");
            }
        }

        return rwTab;
    }

    /**
     * 根据事项id获取任务
     * @param sxbillid
     * @return
     */
    public List<Map<String,Object>> getTaskList(String sxbillid, String rwlx){
        BaseBean bs = new BaseBean();
        PropBean pb = new PropBean();
        RecordSet rs = new RecordSet();
        List<Map<String,Object>> taskList = new ArrayList<Map<String,Object>>();

        String rwmodeid = pb.getPropName("UF_RW_CUBEUUIUD");
        JSONObject jsonObject_rw = pb.getModeInfoByUUID(rwmodeid);
        int 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 = "";
        if("0".equals(rwlx)){//协作事项
            sql = "select * from uf_rw where cjzt = '1' and xzsy = '"+sxbillid+"' order by modedatacreatedate,modedatacreatetime";
        }else if("1".equals(rwlx)){//督办事项
            sql = "select * from uf_rw where cjzt = '1' and dbsy = '"+sxbillid+"' order by modedatacreatedate,modedatacreatetime";
        }
        bs.writeLog(sql);
        rs.executeQuery(sql);
        while(rs.next()){
            Map<String,Object> taskMap = new HashMap<String,Object>();
            taskMap.put("id",Util.null2String(rs.getString("id")));
            taskMap.put("cjr",Util.null2String(rs.getString("cjr")));
            taskMap.put("cjrq",Util.null2String(rs.getString("cjrq")));
            taskMap.put("rwbt",Util.null2String(rs.getString("rwbt")));
            taskMap.put("rwbh",Util.null2String(rs.getString("rwbh")));
            taskMap.put("jbr",Util.null2String(rs.getString("jbr")));
            taskMap.put("gzr",Util.null2String(rs.getString("gzr")));
            taskMap.put("rwzt",Util.null2String(rs.getString("rwzt")));
            taskMap.put("formid",formid);
            taskMap.put("formmodeid",modeid);
            taskList.add(taskMap);
        }
        for(Map<String,Object> taskMap:taskList){
            sql = "select t1.loginid,t1.lastname,t2.departmentname from HRMRESOURCE t1,HRMDEPARTMENT t2 where t2.id = t1.departmentid and t1.id = '"+taskMap.get("cjr")+"'";
            bs.writeLog(sql);
            rs.executeQuery(sql);
            if(rs.next()){
                taskMap.put("loginid",Util.null2String(rs.getString("loginid")));
                taskMap.put("name",Util.null2String(rs.getString("lastname")));
                taskMap.put("department",Util.null2String(rs.getString("departmentname")));
            }
            if(StringUtils.isNotEmpty(String.valueOf(taskMap.get("jbr")))){
                List<String> jbr = Arrays.asList(String.valueOf(taskMap.get("jbr")).split(","));
                List<Map<String,Object>> jbrList = new ArrayList<Map<String,Object>>();
                Set<String> jbrAllid = new HashSet<>();
                int complete = 0;
                for(String id:jbr){
                    sql = "select t1.loginid,t1.lastname,t2.departmentname from HRMRESOURCE t1,HRMDEPARTMENT t2 where t2.id = t1.departmentid and t1.id = '"+id+"'";
                    bs.writeLog(sql);
                    rs.executeQuery(sql);
                    if(rs.next()){
                        Map<String,Object> jbrMap = new HashMap<String,Object>();
                        jbrMap.put("id",(Util.null2String(rs.getString("id"))));
                        jbrMap.put("loginid",(Util.null2String(rs.getString("loginid"))));
                        jbrMap.put("name",(Util.null2String(rs.getString("lastname"))));
                        jbrMap.put("department",(Util.null2String(rs.getString("departmentname"))));
                        jbrList.add(jbrMap);
                    }

                    String jbrMainid = JAVATools.getmainhrmid(id);
                    sql = "select id from uf_rw_dt3 where mainid = '"+taskMap.get("id")+"' and ry = '"+jbrMainid+"'";
                    bs.writeLog(sql);
                    rs.executeQuery(sql);
                    if(rs.next()){
                        complete++;
                    }
                    jbrAllid.addAll(getAllUserid(id));
                }
                taskMap.put("jbrList",jbrList);
                taskMap.put("jbrAllNum",jbrList.size());
                taskMap.put("jbrCompleteNum",complete);
                taskMap.put("jbrAllId",jbrAllid);
//                sql = "select count(*) num from uf_rw_dt3 t where mainid = '"+taskMap.get("id")+"'";
//                bs.writeLog(sql);
//                rs.executeQuery(sql);
//                if(rs.next()){
//                    taskMap.put("jbrCompleteNum",Util.null2String(rs.getString("num")));
//                }
            }
            if(StringUtils.isNotEmpty(String.valueOf(taskMap.get("gzr")))){
                List<String> gzr = Arrays.asList(String.valueOf(taskMap.get("gzr")).split(","));
                List<Map<String,Object>> gzrList = new ArrayList<Map<String,Object>>();
                for(String id:gzr){
                    sql = "select t1.loginid,t1.lastname,t2.departmentname from HRMRESOURCE t1,HRMDEPARTMENT t2 where t2.id = t1.departmentid and t1.id = '"+id+"'";
                    bs.writeLog(sql);
                    rs.executeQuery(sql);
                    if(rs.next()){
                        Map<String,Object> gzrMap = new HashMap<String,Object>();
                        gzrMap.put("id",(Util.null2String(rs.getString("id"))));
                        gzrMap.put("loginid",(Util.null2String(rs.getString("loginid"))));
                        gzrMap.put("name",(Util.null2String(rs.getString("lastname"))));
                        gzrMap.put("department",(Util.null2String(rs.getString("departmentname"))));
                        gzrList.add(gzrMap);
                    }
                }
                taskMap.put("gzrList",gzrList);
            }
        }
        return taskList;
    }

    /**
     * 更新任务状态
     * @param user
     * @param billid
     * @param type
     */
    public Map<String, Object> updateTaskState(User user, String billid, String rwlx, 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;
        //rwzt 0-草稿 1-已发布(废弃) 2-进行中 3-已完成 4-被退回(废弃) 5-终止(废弃)
        if(2==type){
            title = "发布了任务";
            String now = TimeUtil.getCurrentTimeString();
            String updateSql = "update uf_rw set rwzt = '2',rwfbsj = '"+now+"' where id = '"+billid+"'";
            bs.writeLog(updateSql);
            rs.executeUpdate(updateSql);
            sendMessage(String.valueOf(user.getUID()),billid,"1");
        }else if(3==type){
            title = "完成了任务";
            String sql = "select id from uf_rw_dt3 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_rw_dt3(mainid,ry,rq,sj,ywc) values('"+billid+"','"+mainUserid+"','"+rq+"','"+sj+"','0')";
                bs.writeLog(insertSql);
                rs.executeUpdate(insertSql);
            }
            sendMessage(String.valueOf(user.getUID()),billid,"3");

            //完成任务，当全部人都完成，任务才完成
            String jbr = "";
            sql = "select jbr from uf_rw 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_rw_dt3 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_rw set rwzt = '3' where id = '"+billid+"'";
                bs.writeLog(updateSql);
                rs.executeUpdate(updateSql);
            }
        }else if(4==type){
            title = "重新打开了任务";
            String updateSql = "update uf_rw set rwzt = '2' where id = '"+billid+"'";
            bs.writeLog(updateSql);
            rs.executeUpdate(updateSql);

            String deleteSql = "delete from uf_rw_dt3 where mainid = '"+billid+"' and ry = '"+mainUserid+"'";
            bs.writeLog(deleteSql);
            rs.executeUpdate(deleteSql);

//            //子任务重新打开，同时打开父任务
//            if("0".equals(rwlx)){//协作事项
//                String xzsy = "";
//                String sql = "select xzsy from uf_rw where id = '"+billid+"'";
//                bs.writeLog(sql);
//                rs.executeQuery(sql);
//                if(rs.next()){
//                    xzsy = Util.null2String(rs.getString("xzsy"));
//                }
//                if(StringUtil.isNotEmpty(xzsy)){
//                    int xzzt=0;
//                    sql = "select xzzt from uf_xzsy where id = '"+xzsy+"'";
//                    bs.writeLog(sql);
//                    rs.executeQuery(sql);
//                    if(rs.next()){
//                        xzzt = Util.getIntValue(rs.getString("xzzt"));
//                    }
//                    if(3==xzzt){
//                        updateSql = "update uf_xzsy set xzzt = '"+2+"' where id = '"+xzsy+"'";
//                        bs.writeLog(updateSql);
//                        rs.executeUpdate(updateSql);
//                    }
//                }
//            }else if("1".equals(rwlx)){//督办事项
//                String dbsy = "";
//                String sql = "select dbsy from uf_rw where id = '"+billid+"'";
//                bs.writeLog(sql);
//                rs.executeQuery(sql);
//                if(rs.next()){
//                    dbsy = Util.null2String(rs.getString("dbsy"));
//                }
//                if(StringUtil.isNotEmpty(dbsy)){
//                    int xzzt=0;
//                    sql = "select xzzt from uf_xzsx where id = '"+dbsy+"'";
//                    bs.writeLog(sql);
//                    rs.executeQuery(sql);
//                    if(rs.next()){
//                        xzzt = Util.getIntValue(rs.getString("xzzt"));
//                    }
//                    if(3==xzzt){
//                        updateSql = "update uf_xzsx set xzzt = '"+2+"' where id = '"+dbsy+"'";
//                        bs.writeLog(updateSql);
//                        rs.executeUpdate(updateSql);
//                    }
//                }
//            }
        }else{
            apidatas.put("api_status",false);
            apidatas.put("api_errormsg", "没有找到对应的任务状态:"+type);
            return apidatas;
        }

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

        return apidatas;
    }

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

        String rwmodeid = pb.getPropName("UF_RW_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_rw where cjzt = '1' and gllc like '%"+requestid+"%'";
        bs.writeLog(sql);
        rs.executeQuery(sql);
        while(rs.next()){
            Map<String,Object> taskMap = new HashMap<String,Object>();
            taskMap.put("id",Util.null2String(rs.getString("id")));
            taskMap.put("rwbt",Util.null2String(rs.getString("rwbt")));
            taskMap.put("cjr",Util.null2String(rs.getString("cjr")));
            taskMap.put("jbr",Util.null2String(rs.getString("jbr")));
            taskMap.put("cjrq",Util.null2String(rs.getString("cjrq")));
            taskMap.put("rwzt",Util.null2String(rs.getString("rwzt")));
            taskList.add(taskMap);
        }
        for(Map<String,Object> taskMap:taskList){
            sql = "select lastname from HRMRESOURCE where id = '"+taskMap.get("cjr")+"'";
            bs.writeLog(sql);
            rs.executeQuery(sql);
            if(rs.next()){
                taskMap.put("name",Util.null2String(rs.getString("lastname")));
            }
            List<String> jbrList = new ArrayList<>();
            if(StringUtils.isNotEmpty(String.valueOf(taskMap.get("jbr")))){
                List<String> jbr = Arrays.asList(String.valueOf(taskMap.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")));
                    }
                }
            }
            taskMap.put("jbrList",jbrList);
            String url = ecologyContentPath+"/spa/cube/index.html#/main/cube/card?type=0&modeId="+modeid+"&formId="+formid+"&billid="+taskMap.get("id");
            taskMap.put("url",url);
        }

        return taskList;
    }

    /**
     * 任务转办
     * @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 gzr = "";
        String rwbt = "";
        String sql = "select jbr,gzr,rwbt from uf_rw where id = '"+billid+"'";
        bs.writeLog(sql);
        rs.executeQuery(sql);
        if(rs.next()){
            jbr = Util.null2String(rs.getString("jbr"));
            gzr = Util.null2String(rs.getString("gzr"));
            rwbt = Util.null2String(rs.getString("rwbt"));
        }

        List<String> gzrList = new ArrayList<>();
        gzrList.addAll(Arrays.asList(gzr.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 gzrid:gzrList){
                        if(compareLoginid(userid,gzrid)){
                            flag1 = true;
                            break;
                        }
                    }
                    if(!flag1){
                        gzrList.add(userid);
                    }
                    //A转办给B，仅A需要被带进参与人，B不需要
//                    boolean flag2 = false;
//                    for(String gzrid:gzrList){
//                        if(compareLoginid(forwardid,gzrid)){
//                            flag2 = true;
//                            break;
//                        }
//                    }
//                    if(!flag2){
//                        gzrList.add(forwardid);
//                    }
                    break;
                }
                if(i==jbrList.size()-1){
                    apidatas.put("status","-1");
                    apidatas.put("message","执行人中没有找到当前用户");
                    return apidatas;
                }
            }
            String newjbr = String.join(",",jbrList);
            String newgzr = String.join(",",gzrList);

            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:gzrList){
                allgzridList.addAll(getAllUserid(id));
            }
            String allgzridStr = String.join(",",allgzridList);

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

            if(res){
                String gxid = "";
                sql = "select id from uf_rw_dt2 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_rw_dt2(mainid,czr,bgxr,gxsj) values('"+billid+"','"+userid+"','"+userid+"','"+datetime+"')";
                    bs.writeLog(insertSql);
                    rs.executeUpdate(insertSql);
                }

                String rwmodeid = pb.getPropName("UF_RW_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,"1","0",content,title);

                    //发送消息提醒
                    Smstools smstools=new Smstools();
                    int smstypeid=Integer.parseInt(Util.null2String(pb.getPropName("uf_ry_sms")));
                    String url = pb.getPropName("rw_mobile_url");
                    String link = url+"&billid="+billid;
                    String messageTitle = "协作任务通知提醒";
                    String context = user.getLastname()+"将协作任务“"+rwbt+"”转办给您，";
                    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 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("rw_mobile_url");
            String link = url+"&billid="+billid;

            String cjr = "";
            String jbr = "";
            String gzr = "";
            String rwbt = "";
            String sql = "select cjr,jbr,gzr,rwbt from uf_rw where id = '"+billid+"'";
            bs.writeLog(sql);
            rs.executeQuery(sql);
            while(rs.next()){
                cjr = Util.null2String(rs.getString("cjr"));
                jbr = Util.null2String(rs.getString("jbr"));
                gzr = Util.null2String(rs.getString("gzr"));
                rwbt = Util.null2String(rs.getString("rwbt"));
            }
            String cjrName = resourceComInfo.getLastname(cjr);
            String currentUserName = resourceComInfo.getLastname(userid);
            List<String> jbrList = Arrays.asList(jbr.split(","));
            List<String> gzrList = Arrays.asList(gzr.split(","));
            List<String> jbrNameList = new ArrayList<>();
            List<String> gzrNameList = new ArrayList<>();
            List<String> cyrList = new ArrayList<>();
            for(String jbrid:jbrList){
                jbrNameList.add(resourceComInfo.getLastname(jbrid));
            }
            for(String gzrid:gzrList){
                if(!jbrList.contains(gzrid)){
                    cyrList.add(gzrid);
                }
                gzrNameList.add(resourceComInfo.getLastname(gzrid));
            }

            if("0".equals(type)||"1".equals(type)){//协作发布触发任务发布
                String title = "协作任务发布提醒";
                String context = cjrName+"邀请您执行协作任务“"+rwbt+"”，请点击查看详情";
                Set<String> sendSet = new HashSet<>();
                sendSet.addAll(jbrList);
                if(sendSet.size()>0){
                    smstools.sendMessage(smstypeid,sendSet,title,context,link,link);
                }
            }
            if("1".equals(type)){//直接发布
                String title = "协作任务发布提醒";
                String jbrNameStr = StringUtils.join(jbrNameList,"、");
                String context = cjrName+"发布了协作任务“"+rwbt+"”，邀请"+jbrNameStr+"共同参与，请点击查看详情";
                Set<String> sendSet = new HashSet<>();
                sendSet.addAll(cyrList);
                if(sendSet.size()>0){
                    smstools.sendMessage(smstypeid,sendSet,title,context,link,link);
                }
            }else if("3".equals(type)){//完成
                String title = "协作任务完成提醒";
                String context1 = "您创建的任务“"+rwbt+"”已由"+currentUserName+"完成，请点击查看详情";
                Set<String> sendSet1 = new HashSet<>();
                sendSet1.add(cjr);
                if(sendSet1.size()>0){
                    smstools.sendMessage(smstypeid,sendSet1,title,context1,link,link);
                }

//                String context2 = "协作任务“"+rwbt+"”已由"+currentUserName+"完成，请点击查看详情";
//                Set<String> sendSet2 = new HashSet<>();
//                sendSet2.addAll(gzrList);
//                if(sendSet2.size()>0){
//                    smstools.sendMessage(smstypeid,sendSet2,title,context2,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<>();

        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;
        }
    }
}
