package com.engine.htsc.collaboration.service;

import com.alibaba.fastjson.JSONObject;
import com.engine.core.impl.Service;
import com.engine.htsc.collaboration.entity.FileLink;
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.Smstools;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.general.GCONST;
import java.text.SimpleDateFormat;
import java.util.*;

public class TaskLogService extends Service {

    /**
     * 创建任务日志
     * @param user
     * @param glid 关联id
     * @param fj 附件
     * @param jllx 关联类型 协作事项-0,任务-1,督办事项-2
     * @param sjlx 数据类型 反馈-0
     * @param content
     * @param title
     * @return
     */
    public boolean createTaskLog(User user, String glid, String fj, String jllx, String sjlx, String content, String title){
        BaseBean bs = new BaseBean();
        RecordSet rs = new RecordSet();
        ModeRightInfo modeRightInfo = new ModeRightInfo();
        boolean res = true ;
        try{
            int userid = user.getUID();
            String uuid = UUID.randomUUID().toString();
            String jlzt = "0";
            String cjsj = TimeUtil.getCurrentTimeString();
            String modedatacreatedate = TimeUtil.getCurrentDateString();
            String modedatacreatetime = TimeUtil.getOnlyCurrentTimeString();

            String formmodeid = " ";
            String sql =" select id from modeinfo where formid in(\n" +
                    " select id from workflow_bill where tablename='uf_xzrwfkpl'\n" +
                    " ) ";
            rs.execute(sql);
            if(rs.next()){
                formmodeid = Util.null2String(rs.getString("id"));
            }

            Map<String,String> map = new HashMap<String,String>();
            map.put("cjr",String.valueOf(userid));
            map.put("glid",glid);
            map.put("fj",fj);
            map.put("jllx",jllx);
            map.put("sjlx",sjlx);
            map.put("jlzt",jlzt);
            map.put("nr",content);
            map.put("bt",title);
            map.put("cjsj",cjsj);
            map.put("modeuuid",uuid);
            map.put("formmodeid",formmodeid);
            map.put("modedatacreatedate",modedatacreatedate);
            map.put("modedatacreatetime",modedatacreatetime);
            map.put("modedatacreater",String.valueOf(userid));
            map.put("modedatacreatertype","0");


            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 + "'";
            }
            int count = 0;
            sql = "insert into uf_xzrwfkpl("+dttablename+") values("+dttablenvalue+")";
            bs.writeLog(sql);
            res = rs.executeUpdate(sql);
            if(res)
            {
                count++;
            }
            if(count >0) {
                String dataid = "";
                sql = " select id from uf_xzrwfkpl where modeuuid='" + uuid + "'";
                rs.execute(sql);
                if (rs.next()) {
                    dataid = Util.null2String(rs.getString("id"));
                }
                if (!"".equals(dataid)) {
                    modeRightInfo.editModeDataShare(Integer.valueOf(userid), Util.getIntValue(formmodeid), Integer.parseInt(dataid));
                }
            }
        }catch (Exception e){
            res = false;
        }

        return res;
    }

    /**
     * 根据id获得日志
     * @param billid
     * @return
     */
    public List<Map<String,Object>> getTaskLog(String billid,String type){
        BaseBean bs = new BaseBean();
        RecordSet rs = new RecordSet();
        String ecologyContentPath = GCONST.getContextPath();
        List<Map<String,Object>> taskLogList = new ArrayList<>();
        String sql = "select * from uf_xzrwfkpl where jllx = '"+type+"' and glid = '"+billid+"'";
        bs.writeLog(sql);
        rs.executeQuery(sql);
        while(rs.next()){
            Map<String,Object> taskLogMap = new HashMap<>();
            taskLogMap.put("id",Util.null2String(rs.getString("id")));
            taskLogMap.put("cjr",Util.null2String(rs.getString("cjr")));
            taskLogMap.put("jllx",Util.null2String(rs.getString("jllx")));
            taskLogMap.put("glid",Util.null2String(rs.getString("glid")));
            taskLogMap.put("nr",Util.null2String(rs.getString("nr")));
            taskLogMap.put("bt",Util.null2String(rs.getString("bt")));
            taskLogMap.put("jlzt",Util.null2String(rs.getString("jlzt")));
            taskLogMap.put("fj",Util.null2String(rs.getString("fj")));
            taskLogMap.put("cjsj",Util.null2String(rs.getString("cjsj")));
            taskLogList.add(taskLogMap);
        }
        taskLogList.addAll(getUpdateLog(billid,type));

        if("0".equals(type)||"2".equals(type)){
            List<Map<String,String>> taskList = new ArrayList<>();
            if("0".equals(type)){//协作事项
                sql = "select id,rwbt from uf_rw where cjzt = '1' and xzsy = '"+billid+"'";
            }else if("2".equals(type)){//督办事项
                sql = "select id,rwbt from uf_rw where cjzt = '1' and dbsy = '"+billid+"'";
            }
            bs.writeLog(sql);
            rs.executeQuery(sql);
            while(rs.next()){
                Map<String,String> taskMap = new HashMap<>();
                taskMap.put("id",Util.null2String(rs.getString("id")));
                taskMap.put("rwbt",Util.null2String(rs.getString("rwbt")));
                taskList.add(taskMap);
            }

            for(Map<String,String> task:taskList){
                sql = "select * from uf_xzrwfkpl where jllx = '1' and glid = '"+task.get("id")+"'";
                bs.writeLog(sql);
                rs.executeQuery(sql);
                while(rs.next()){
                    Map<String,Object> taskLogMap = new HashMap<>();
                    taskLogMap.put("rwbt",task.get("rwbt"));
                    taskLogMap.put("id",Util.null2String(rs.getString("id")));
                    taskLogMap.put("cjr",Util.null2String(rs.getString("cjr")));
                    taskLogMap.put("jllx",Util.null2String(rs.getString("jllx")));
                    taskLogMap.put("glid",Util.null2String(rs.getString("glid")));
                    taskLogMap.put("nr",Util.null2String(rs.getString("nr")));
                    taskLogMap.put("bt",Util.null2String(rs.getString("bt")));
                    taskLogMap.put("jlzt",Util.null2String(rs.getString("jlzt")));
                    taskLogMap.put("fj",Util.null2String(rs.getString("fj")));
                    taskLogMap.put("cjsj",Util.null2String(rs.getString("cjsj")));
                    taskLogList.add(taskLogMap);
                }

                List<Map<String,Object>> updateLogList = getUpdateLog(task.get("id"),"1");
                for(Map<String,Object> updateLog:updateLogList){
                    updateLog.put("rwbt",task.get("rwbt"));
                }
                taskLogList.addAll(updateLogList);
            }
        }



        Collections.sort(taskLogList, new Comparator<Map<String,Object>>() {
            @Override
            public int compare(Map<String,Object> o1, Map<String,Object> o2) {
                try{
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy'-'MM'-'dd' 'HH:mm:ss");
                    Date d1 = sdf.parse(o1.get("cjsj").toString());
                    Date d2 = sdf.parse(o2.get("cjsj").toString());
                    if (d1.equals(d2)) {
                        return 0;
                    }else {
                        return d1.before(d2) ? 1 : -1 ;
                    }
                }catch(Exception e){
                    return 0;
                }
            }
        });

        for(Map<String,Object> taskLogMap:taskLogList){
            sql = "select t1.loginid,t1.lastname,t2.departmentname from HRMRESOURCE t1,HRMDEPARTMENT t2 where t2.id = t1.departmentid and t1.id = '"+taskLogMap.get("cjr")+"'";
            bs.writeLog(sql);
            rs.executeQuery(sql);
            if(rs.next()){
                taskLogMap.put("loginid",Util.null2String(rs.getString("loginid")));
                taskLogMap.put("name",Util.null2String(rs.getString("lastname")));
                taskLogMap.put("department",Util.null2String(rs.getString("departmentname")));
            }
            List<String> fileList = Arrays.asList(String.valueOf(taskLogMap.get("fj")).split(","));
            List<FileLink> fileLinkList = new ArrayList<>();
            for(String fileid:fileList){
                if(StringUtil.isNotEmpty(fileid)&&!"null".equals(fileid)){
                    FileLink fileLink = new FileLink();
                    fileLink.setFileid(fileid);
                    fileLink.setReviewLink(ecologyContentPath+"/spa/document/index2file.jsp?imagefileId="+fileid);
                    fileLink.setDownloadLink(ecologyContentPath+"/weaver/weaver.file.FileDownload?fileid="+fileid);
                    sql = "select imagefilename from IMAGEFILE  where imagefileid = '"+fileid+"'";
                    bs.writeLog(sql);
                    rs.executeQuery(sql);
                    if(rs.next()){
                        fileLink.setFilename(Util.null2String(rs.getString("imagefilename")));
                    }
                    fileLinkList.add(fileLink);
                }
            }
            taskLogMap.put("fileLinkList",fileLinkList);
        }
        return  taskLogList;
    }

    /**
     * 获得修改记录
     * @param taskid
     * @param type
     */
    public List<Map<String,Object>> getUpdateLog(String taskid,String type){
        BaseBean bs = new BaseBean();
        PropBean pb = new PropBean();
        RecordSet rs = new RecordSet();
        List<Map<String,Object>> taskLogList = new ArrayList<>();
        List<Map<String,Object>> taskLogReleaseList = new ArrayList<>();

        try{
            ResourceComInfo resourceComInfo = new ResourceComInfo();
            int modeid = 0;
            String rwms = "";
            String jzsj = "";
            String shrzczhyc = "";
            int state = 0;
            String fbsj = "";
            if("0".equals(type)){
                JSONObject jsonObject_xz = pb.getModeInfoByUUID(pb.getPropName("UF_XZSY_CUBEUUIUD"));
                modeid = Util.getIntValue(jsonObject_xz.getString("modeid"));
                rwms = "bz";
                jzsj = "jzsj";
                String sql = "select xzzt,fbsj,shrzczhyc from uf_xzsy where id = '"+taskid+"'";
                bs.writeLog(sql);
                rs.executeQuery(sql);
                if(rs.next()){
                    state = Integer.parseInt(Util.null2String(rs.getString("xzzt")));
                    fbsj = Util.null2String(rs.getString("fbsj"));
                    shrzczhyc = Util.null2String(rs.getString("shrzczhyc"));
                }
            }else if("1".equals(type)){
                JSONObject jsonObject_rw = pb.getModeInfoByUUID(pb.getPropName("UF_RW_CUBEUUIUD"));
                modeid = Util.getIntValue(jsonObject_rw.getString("modeid"));
                rwms = "rwgs";
                jzsj = "jzrq";
                String sql = "select rwzt,rwfbsj from uf_rw where id = '"+taskid+"'";
                bs.writeLog(sql);
                rs.executeQuery(sql);
                if(rs.next()){
                    state = Integer.parseInt(Util.null2String(rs.getString("rwzt")));
                    fbsj = Util.null2String(rs.getString("rwfbsj"));
                }
            }else if("2".equals(type)){
                JSONObject jsonObject_xz = pb.getModeInfoByUUID(pb.getPropName("DUBAN_XZ_UUID"));
                modeid = Util.getIntValue(jsonObject_xz.getString("modeid"));
                rwms = "bz";
                jzsj = "jzsj";
                String sql = "select xzzt,fbsj from uf_xzsx where id = '"+taskid+"'";
                bs.writeLog(sql);
                rs.executeQuery(sql);
                if(rs.next()){
                    state = Integer.parseInt(Util.null2String(rs.getString("xzzt")));
                    fbsj = Util.null2String(rs.getString("fbsj"));
                }
            }

            //优先级
            List<Map<String,Object>> yxlList = new ArrayList<>();
            String sql = "select t1.operateuserid,t1.operatedate,t1.operatetime,t2.fieldvalue,t2.prefieldvalue " +
                    "from modeviewlog_"+modeid+" t1,modelogfielddetail t2,workflow_billfield t3 " +
                    "where t2.viewlogid = t1.id and t3.id = t2.fieldid and t1.operatetype = 2 and t3.fieldname = 'yxj' and t1.relatedid = '"+taskid+"' " +
                    "order by t1.operatedate,t1.operatetime";
            bs.writeLog(sql);
            rs.executeQuery(sql);
            while(rs.next()){
                String prefieldvalue = Util.null2String(rs.getString("prefieldvalue"));
                String fieldvalue = Util.null2String(rs.getString("fieldvalue"));
                Map<String,String> map = new HashMap<>();
                map.put("0","高");
                map.put("1","中");
                map.put("2","低");
                Map<String,Object> taskLogMap = new HashMap<>();
                taskLogMap.put("glid",taskid);
                taskLogMap.put("jllx",type);
                taskLogMap.put("cjr",Util.null2String(rs.getString("operateuserid")));
                taskLogMap.put("bt","修改了优先级");
                taskLogMap.put("nr","将“"+map.get(prefieldvalue)+"”改为“"+map.get(fieldvalue)+"”");
                taskLogMap.put("cjsj",Util.null2String(rs.getString("operatedate"))+" "+Util.null2String(rs.getString("operatetime")));
                yxlList.add(taskLogMap);
            }
            if(yxlList.size()>0){
                taskLogList.addAll(yxlList);
            }

            //任务描述
            List<Map<String,Object>> rwmsList = new ArrayList<>();
            sql = "select t1.operateuserid,t1.operatedate,t1.operatetime " +
                    "from modeviewlog_"+modeid+" t1,modelogfielddetail t2,workflow_billfield t3 " +
                    "where t2.viewlogid = t1.id and t3.id = t2.fieldid and t1.operatetype = 2 and t3.fieldname = '"+rwms+"' and t1.relatedid = '"+taskid+"' " +
                    "order by t1.operatedate,t1.operatetime";
            bs.writeLog(sql);
            rs.executeQuery(sql);
            while(rs.next()){
                Map<String,Object> taskLogMap = new HashMap<>();
                taskLogMap.put("glid",taskid);
                taskLogMap.put("jllx",type);
                taskLogMap.put("bt","修改了任务描述");
                taskLogMap.put("cjr",Util.null2String(rs.getString("operateuserid")));
                taskLogMap.put("cjsj",Util.null2String(rs.getString("operatedate"))+" "+Util.null2String(rs.getString("operatetime")));
                rwmsList.add(taskLogMap);
            }
            if(rwmsList.size()>0){
                rwmsList.remove(0);
                taskLogList.addAll(rwmsList);
            }

            //截止时间
            List<Map<String,Object>> jzsjList = new ArrayList<>();
            sql = "select t1.operateuserid,t1.operatedate,t1.operatetime,t2.fieldvalue,t2.prefieldvalue " +
                    "from modeviewlog_"+modeid+" t1,modelogfielddetail t2,workflow_billfield t3 " +
                    "where t2.viewlogid = t1.id and t3.id = t2.fieldid and t1.operatetype = 2 and t3.fieldname = '"+jzsj+"' and t1.relatedid = '"+taskid+"' " +
                    "order by t1.operatedate,t1.operatetime";
            bs.writeLog(sql);
            rs.executeQuery(sql);
            while(rs.next()){
                String prefieldvalue = Util.null2String(rs.getString("prefieldvalue"));
                String fieldvalue = Util.null2String(rs.getString("fieldvalue"));
                Map<String,Object> taskLogMap = new HashMap<>();
                taskLogMap.put("glid",taskid);
                taskLogMap.put("jllx",type);
                taskLogMap.put("cjr",Util.null2String(rs.getString("operateuserid")));
                taskLogMap.put("bt","修改了截止时间");
                taskLogMap.put("nr","将“"+prefieldvalue+"”改为“"+fieldvalue+"”");
                taskLogMap.put("cjsj",Util.null2String(rs.getString("operatedate"))+" "+Util.null2String(rs.getString("operatetime")));
                jzsjList.add(taskLogMap);
            }
            if(jzsjList.size()>0){
                jzsjList.remove(0);
                taskLogList.addAll(jzsjList);
            }

            //执行人
            List<Map<String,Object>> jbrList = new ArrayList<>();
            sql = "select t1.operateuserid,t1.operatedate,t1.operatetime,t2.fieldvalue,t2.prefieldvalue " +
                    "from modeviewlog_"+modeid+" t1,modelogfielddetail t2,workflow_billfield t3 " +
                    "where t2.viewlogid = t1.id and t3.id = t2.fieldid and t1.operatetype = 2 and t3.fieldname = 'jbr' and t1.relatedid = '"+taskid+"' " +
                    "order by t1.operatedate,t1.operatetime";
            bs.writeLog(sql);
            rs.executeQuery(sql);
            while(rs.next()){
                String nr = "";
                List<String> beforeList = Arrays.asList(Util.null2String(rs.getString("prefieldvalue")).split(","));
                List<String> afterList = Arrays.asList(Util.null2String(rs.getString("fieldvalue")).split(","));
                List<String> addList = new ArrayList<>();
                List<String> deleteList = new ArrayList<>();
                for(String id:afterList){
                    if(StringUtils.isNotEmpty(id)&&!beforeList.contains(id)){
                        addList.add(resourceComInfo.getLastname(id));
                    }
                }
                for(String id:beforeList){
                    if(StringUtils.isNotEmpty(id)&&!afterList.contains(id)){
                        deleteList.add(resourceComInfo.getLastname(id));
                    }
                }
                if(addList.size()>0){
                    nr += "增加了"+ StringUtils.join(addList, "、");
                }
                if(deleteList.size()>0){
                    if(addList.size()>0){
                        nr += "，";
                    }
                    nr += "删除了"+StringUtils.join(deleteList, "、");
                }

                Map<String,Object> taskLogMap = new HashMap<>();
                taskLogMap.put("glid",taskid);
                taskLogMap.put("jllx",type);
                taskLogMap.put("cjr",Util.null2String(rs.getString("operateuserid")));
                taskLogMap.put("bt","修改了执行人");
                taskLogMap.put("nr",nr);
                taskLogMap.put("cjsj",Util.null2String(rs.getString("operatedate"))+" "+Util.null2String(rs.getString("operatetime")));
                jbrList.add(taskLogMap);
            }
            if(jbrList.size()>0){
                taskLogList.addAll(jbrList);
            }

            //参与人
            if("1".equals(type)){
                List<Map<String,Object>> gzrList = new ArrayList<>();
                sql = "select t1.operateuserid,t1.operatedate,t1.operatetime,t2.fieldvalue,t2.prefieldvalue " +
                        "from modeviewlog_"+modeid+" t1,modelogfielddetail t2,workflow_billfield t3 " +
                        "where t2.viewlogid = t1.id and t3.id = t2.fieldid and t1.operatetype = 2 and t3.fieldname = 'gzr' and t1.relatedid = '"+taskid+"' " +
                        "order by t1.operatedate,t1.operatetime";
                bs.writeLog(sql);
                rs.executeQuery(sql);
                while(rs.next()){
                    String nr = "";
                    List<String> beforeList = Arrays.asList(Util.null2String(rs.getString("prefieldvalue")).split(","));
                    List<String> afterList = Arrays.asList(Util.null2String(rs.getString("fieldvalue")).split(","));
                    List<String> addList = new ArrayList<>();
                    List<String> deleteList = new ArrayList<>();
                    for(String id:afterList){
                        if(StringUtils.isNotEmpty(id)&&!beforeList.contains(id)){
                            addList.add(resourceComInfo.getLastname(id));
                        }
                    }
                    for(String id:beforeList){
                        if(StringUtils.isNotEmpty(id)&&!afterList.contains(id)){
                            deleteList.add(resourceComInfo.getLastname(id));
                        }
                    }
                    if(addList.size()>0){
                        nr += "增加了"+ StringUtils.join(addList, "、");
                    }
                    if(deleteList.size()>0){
                        if(addList.size()>0){
                            nr += "，";
                        }
                        nr += "删除了"+StringUtils.join(deleteList, "、");
                    }

                    Map<String,Object> taskLogMap = new HashMap<>();
                    taskLogMap.put("glid",taskid);
                    taskLogMap.put("jllx",type);
                    taskLogMap.put("cjr",Util.null2String(rs.getString("operateuserid")));
                    taskLogMap.put("bt","修改了参与人");
                    taskLogMap.put("nr",nr);
                    taskLogMap.put("cjsj",Util.null2String(rs.getString("operatedate"))+" "+Util.null2String(rs.getString("operatetime")));
                    gzrList.add(taskLogMap);
                }
                if(gzrList.size()>0){
                    taskLogList.addAll(gzrList);
                }
            }

            //除审核人以外的修改记录值显示发布后的修改记录
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date fbTime = new Date();
            if(StringUtils.isNotEmpty(fbsj)){
                fbTime = sdf.parse(fbsj);
            }
            List<String> shridList = new ArrayList<>();
            if(StringUtils.isNotEmpty(shrzczhyc)){
                shridList.addAll(Arrays.asList(shrzczhyc.split(",")));
            }
            for(Map<String,Object> logMap:taskLogList){
                String cjr = (String)logMap.get("cjr");
                if(shridList.contains(cjr)){
                    taskLogReleaseList.add(logMap);
                }else if(0!=state){
                    if(StringUtils.isNotEmpty(fbsj)){
                        String cjsj = (String)logMap.get("cjsj");
                        Date cjTime = sdf.parse(cjsj);
                        if(fbTime.before(cjTime)){
                            taskLogReleaseList.add(logMap);
                        }
                    }else{
                        taskLogReleaseList.add(logMap);
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return taskLogReleaseList;
    }

    /**
     * 执行人创建动态发送消息提醒
     * @param user
     * @param taskid
     * @param jllx
     * @param content
     */
    public void sendTaskLogMessage(User user, String taskid, String jllx, String content){
        BaseBean bs = new BaseBean();
        PropBean pb = new PropBean();
        RecordSet rs = new RecordSet();

        try{
            Smstools smstools=new Smstools();
            int smstypeid=Integer.parseInt(Util.null2String(pb.getPropName("uf_ry_sms")));

            content = cutString(content,30);
            String cjr = "";
            String jbr = "";
            String bt = "";

            String tablename = "";
            String btField = "bt";
            String type = "";
            String url = "";
            //关联类型 协作事项-0,任务-1,督办任务-2
            if("0".equals(jllx)){
                tablename = "uf_xzsy";
                type = "协作事项";
                url = pb.getPropName("xz_mobile_url");
            }else if("1".equals(jllx)){
                tablename = "uf_rw";
                btField = "rwbt";
                type = "协作任务";
                url = pb.getPropName("rw_mobile_url");
            }else if("2".equals(jllx)){
                tablename = "uf_xzsx";
                type = "督办任务";
                url = pb.getPropName("dbrw_mobile_url");
            }
            String sql = "select cjr,jbr,"+btField+" as bt from "+tablename+" where id = '"+taskid+"'";
            bs.writeLog(sql);
            rs.executeQuery(sql);
            if(rs.next()){
                cjr = Util.null2String(rs.getString("cjr"));
                jbr = Util.null2String(rs.getString("jbr"));
                bt = Util.null2String(rs.getString("bt"));
            }

            if(Arrays.asList(jbr.split(",")).contains(String.valueOf(user.getUID()))){
                String title = type+"动态提醒";
                String message = user.getLastname()+"在"+type+"“"+bt+"”发布了动态“"+content+"”，请点击查看详情";
                String link = url+"&billid="+taskid;
                Set<String> sendSet = new HashSet<>();
                sendSet.add(cjr);
                if(sendSet.size()>0){
                    smstools.sendMessage(smstypeid,sendSet,title,message,link,link);
                }
            }


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

    /**
     * 截取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;
        }
    }
}
