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.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 DubanCoWorkService extends Service {

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

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

        try {
            ResourceComInfo 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("DUBAN_XZ_UUID");
            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_xzsx("+dttablename+") values("+dttablenvalue+")";
            bs.writeLog("sql:"+sql);
            boolean bool = rs.executeUpdate(sql);
            if(bool){
                rs.executeQuery("select id from uf_xzsx 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 user
     * @param billid
     * @param type
     * @return
     */
    public Map<String, Object> updateDubanCoWorkState(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-已完成
        if(2==type){
            title = "发布了督办任务";
            String now = TimeUtil.getCurrentTimeString();
            String updateSql = "update uf_xzsx 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<>();
            String sql = "select id from uf_rw where cjzt = '1' and rwzt = '0' and dbsy = '"+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 = "完成了督办任务";
            String sql = "select id from uf_xzsx_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_xzsx_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_xzsx 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_xzsx_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_xzsx set xzzt = '3' where id = '"+billid+"'";
                bs.writeLog(updateSql);
                rs.executeUpdate(updateSql);
            }
        }else if(4==type){
            title = "重新打开了督办任务";
            String updateSql = "update uf_xzsx set xzzt = '2' where id = '"+billid+"'";
            bs.writeLog(updateSql);
            rs.executeUpdate(updateSql);

            String deleteSql = "delete from uf_xzsx_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,"2","0",content,title);
        apidatas.put("api_status",true);

        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 dbbillid = "";
        String xzzt = "";
        String jbr = "";
        String sql = "select dbsy from uf_rw where id = '"+billid+"'";
        bs.writeLog(sql);
        rs.executeQuery(sql);
        if(rs.next()){
            dbbillid = Util.null2String(rs.getString("dbsy"));
        }
        if(StringUtil.isNotEmpty(dbbillid)){
            sql = "select xzzt,jbr from uf_xzsx where id = '"+dbbillid+"'";
            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",dbbillid);
        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_xzsx 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_xzsx 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_xzsx_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_xzsx_dt1(mainid,czr,bgxr,gxsj) values('"+billid+"','"+userid+"','"+userid+"','"+datetime+"')";
                    bs.writeLog(insertSql);
                    rs.executeUpdate(insertSql);
                }

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

                    //发送消息提醒
                    Smstools smstools=new Smstools();
                    int smstypeid=Integer.parseInt(Util.null2String(pb.getPropName("uf_ry_sms")));
                    String url = pb.getPropName("dbrw_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 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("dbrw_mobile_url");
            String link = url+"&billid="+billid;

            String cjr = "";
            String jbr = "";
            String tzydr = "";
            String bt = "";
            String sql = "select cjr,jbr,tzydr,bt from uf_xzsx 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<>();

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