<%@page
        import="com.blueland.bpm.engine.core.model.ProcessDefinitionModel"%>
<%@page import="com.blueland.bpm.engine.config.model.ProcessInfoConfig"%>
<%@page import="com.blueland.bpm.common.page.*"%>
<%@page import="com.blueland.bpm.common.util.*"%>
<%@page import="java.util.*"%>
<%@ page contentType="text/html;charset=UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib tagdir="/WEB-INF/tags/simpletable" prefix="simpletable"%>
<%@ include file="/commons/taglibs.jsp"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>流程监控图</title>
    <%@ include file="/commons/meta.jsp"%>
    <link rel="stylesheet" href="${ctx}/resource/js/plugins/bpmn/css/diagram-js.css" />
</head>
<body class="white-page">
<div class="main-container" id="main-container">
    <input type="hidden" name="userId" id="userId" value='${bpm_login_session_user.userCode}'></input>
    <input type="hidden" id="processInstanceId" name ="processInstanceId" value="${processInstanceId}"/>
    <div class="hjjd-box">
        <div class="jd-list"><span class="jd-wzx"></span><span class="text">未执行</span></div>
        <div class="jd-list"><span class="jd-yzx"></span><span class="text">已执行</span></div>
        <div class="jd-list"><span class="jd-dqjd"></span><span class="text">当前节点</span></div>
        <div class="jd-list"><span class="jd-yzf"></span><span class="text">已作废</span></div>
    </div><!--hjjd-box 流程节点-->
    <div class="lct-box_act">
        <div class="canvas">
            <div id="js-canvas"></div>
        </div>
        <div class="lct-btn">
            <a class="btn-ico" onclick="getCurrAct()">
                <span class="link-icon"><img src="${ctx}/resource/css/images/ico-dqhj.png" /></span>
                <span class="link-text">当前环节</span>
                <span class="hover-link">当前<br>环节</span>
            </a>
            <a class="btn-ico" onclick="getMyDealed()">
                <span class="link-icon"><img src="${ctx}/resource/css/images/ico-wdjb.png" /></span>
                <span class="link-text">我的经办</span>
                <span class="hover-link">我的<br>经办</span>
            </a>
        </div><!---lct-btn 悬浮按钮--->
    </div><!---lct-box--->


</div>
<!-- viewer -->
<script  type='text/javascript'src="${ctx}/resource/js/plugins/bpmn/bpmn-navigated-viewer.development.js"></script>
<script type="text/javascript">
    var height1 = window.parent.document.documentElement.clientHeight;
    var windowHeight = (parseInt(height1)-200)
    var viewer = new BpmnJS({
        container: document.querySelector('#js-canvas'),
        height: windowHeight
    });
    var procDefId,
        processTrace,//处理的环节
        processDetailLogs;//流程处理的信息
    var arrayActId=[];
    $(function(){
        getProcessInfo();

    })
    function filters(startdate){
        var date = new Date(startdate);
        return formatDate("yyyy-MM-dd hh:mm:ss",date);
    }
    function differByDay(startTime,endTime){
        var start = new Date(startTime);
        var end = new Date(endTime);
        if(start==null||end==null){
            return 0;
        }
        return Math.round(end.getTime() / 86400000 - start.getTime() / 86400000);
    }
    function formatDate(format, date) {
        var o = {
            "M+": date.getMonth() + 1, //month
            "d+": date.getDate(), //day
            "h+": date.getHours(), //hour
            "m+": date.getMinutes(), //minute
            "s+": date.getSeconds(), //second
            "q+": Math.floor((date.getMonth() + 3) / 3), //quarter
            "S": date.getMilliseconds() //millisecond
        }
        if (/(y+)/.test(format)) format = format.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(format)) format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        return format;
    }
    //获取流程处理信息
    function getProcessInfo(){
        var url="${ctx}/workflow/trace/traceNewByImage.do";
        $.ajax({
            url : url,
            data:{"processInstanceId":$("#processInstanceId").val()},
            cache : false,
            async : false,
            type : "POST",
            success : function (data){
                procDefId = data.processInstance.processDefinitionId;
                processTrace = data.processTrace;
                processDetailLogs = data.hisTaskLog.processDetailLogs;
                try{
                    $("#headingSpan",window.parent.document).html("<b>流程标题：</b>"+data.processInstance.procTitle+"，<b>流程状态：</b>"+(data.processInstance.procState==1?'运行中':(data.processInstance.procState==5?'已结束':'已作废'))+"，<b>流程定义名称：</b>"+data.processInstance.processDefinitionName);
                }catch(e){}
                getXmlContent();

            }
        });
    }
    //获取xml数据
    function getXmlContent(){
        var url="${ctx}/procDefModelMgr/showProcessXml.do";
        $.ajax({
            url : url,
            data:{"procDefId":procDefId},
            cache : false,
            async : false,
            type : "POST",
            success : function (data){
                createNewDiagram(data.bpmnXml);
            }
        });
    }
    function createNewDiagram (bpmnXmlStr) {
        viewer.importXML(bpmnXmlStr, function (err) {
            if (err) {
                console.error(err)
            }else{
                var canvas = viewer.get('canvas');
                //canvas.zoom('fit-viewport');
                setNodeColor(processTrace, canvas)
                appendHtml();
                addActNum();
                dealLine(canvas);
            }
        })
    }
    // 给已经走过的流程添加颜色
    function setNodeColor(nodeCodes, canvas) {
        var colorClass = "";
        for (var i = 0; i < nodeCodes.length; i++) {
            console.log(i,nodeCodes[i])
            if(nodeCodes[i].status=='1'){
                colorClass = "highlight-run";
            }else if(nodeCodes[i].status=='2'){
                colorClass = "highlight";
            }else{
                colorClass = "highlight-cancle";
            }
            if(nodeCodes[i].type =='SEQ'){
                colorClass =  "highlight-line";
                canvas.addMarker(nodeCodes[i].activityId, colorClass);
            }else{
                canvas.addMarker(nodeCodes[i].activityId, colorClass);
            }
        }
    }
    function hidenDiv(id){
        document.getElementById(id).style="display:none";
        document.querySelectorAll("[signDiv]").forEach(function(item) {
            if(document.getElementById(item.id) !=null){//去掉所有的环节详细数据，防止页面延迟，没有消失显示的详情信息
                document.getElementById(item.id).style="display:none";
            }
        });
    }
    function showLineDiv(id){
        document.getElementById(id).style="display:block";
    }
    function hidenLineDiv(id){
        document.getElementById(id).style="display:none";
        document.querySelectorAll("[lineDiv]").forEach(function(item) {
            if(document.getElementById(item.id) !=null){//去掉所有的环节详细数据，防止页面延迟，没有消失显示的详情信息
                document.getElementById(item.id).style="display:none";
            }
        });
    }
    function showDiv(id){
        document.getElementById(id).style="display:block";
    }
    //拼接环节详细信息
    function appendHtml(){
        var eventBus =  viewer.get('eventBus');
        var events = [
            'element.hover',
            'element.out',
        ];
        var overlays =  viewer.get('overlays');
        events.forEach(function(event) {
            eventBus.on(event, function(e) {

                var thisNode=document.getElementById('div_'+e.element.id);
                var id = e.element.id.split("_")[0];
                var thisLinkNode=document.getElementById('line_'+id);

                if(e.element.type =='bpmn:UserTask' || e.element.type=='multi'){
                    if(event=='element.hover'){
                        var temp= processTrace.filter(function(item){//是否已处理
                            return item.activityId == e.element.id;
                        })
                        if(temp.length>0){//历史记录环节详细数据
                            appendHistoryHtml(overlays,event,e);
                        }else{//流程环节信息
                            dealActHtml(overlays,event,e);
                        }
                    }
                    if(event=='element.out' && thisNode != null){
                        document.getElementById('div_'+e.element.id).style="display:none";
                        document.querySelectorAll("[signDiv]").forEach(function(item) {
                            if(document.getElementById(item.id) !=null){//去掉所有的环节详细数据，防止页面延迟，没有消失显示的详情信息
                                document.getElementById(item.id).style="display:none";
                            }
                        });
                    }
                }else if(e.element.type =='label'){//处理输出线的名称
                    var listLine= viewer._getLineName.filter(function(item){//判断这个输出线是否是截取的输出线名称
                        return item.id == id;
                    })
                    if(listLine.length>0){
                        if(event=='element.hover'){
                            if(thisLinkNode!=null){
                                document.getElementById("line_"+id).style="display:block";
                            }else{
                                appendLineHtml(overlays,event,id);
                            }

                        }
                    }
                    if(event=='element.out'){
                        if(document.getElementById('line_'+id) !=null){//去掉输出线的显示
                            document.getElementById('line_'+id).style="display:none";
                        }
                        document.querySelectorAll("[lineDiv]").forEach(function(item) {
                            if(document.getElementById(item.id) !=null){//去掉所有的输出线显示
                                document.getElementById(item.id).style="display:none";
                            }
                        });
                    }

                }

            });
        });
    }
    //拼接环节详细信息
    function appendHistoryHtml(overlays,event,e){
        var thisNode=document.getElementById('div_'+e.element.id);
        var listAct= arrayActId.filter(function(item){//判断这个节点是否
            return item == e.element.id;
        })
        if(listAct.length==0){
            arrayActId.push('div_'+e.element.id);
        }
        if(thisNode!=null && listAct.length==0){
            document.getElementById('div_'+e.element.id).style="display:block";
            return;
        }
        var list= processDetailLogs.filter(function(item){//获取处理记录信息
            return item.historicTaskInstance.taskDefinitionKey == e.element.id;
        })
        var html = new Array();
        //onmouseout="javascript:document.getElementById(\'div_'+e.element.id+'\').style.display=\'none\';" <a class="link">流程梳理环节详情</a>
        html.push('<div class="lchj-box" signDiv="flag"  onmouseover="showDiv(\'div_'+e.element.id+'\')" onmouseleave="hidenDiv(\'div_'+e.element.id+'\')" id="div_'+e.element.id+'"><div class="box-head"><span class="title">任务执行情况</span></div><div class="box-body">');
        list.forEach(function(item){
            var limitTimeStr = "";
            var endDate=new Date();
            if (item.historicTaskInstance.endTime != null) {
                endDate=item.historicTaskInstance.endTime;
            }

            var t = differByDay(item.historicTaskInstance.startTime,endDate);

            limitTimeStr = "耗时" + t + "天";
            html.push('<table  cellpadding="0" cellspacing="0" class="lchj-table">');
            html.push('<tbody><tr>');
            html.push('<td class="clum" width="100">接收环节: </td>');
            html.push('<td>'+item.historicTaskInstance.name+'</td>');
            html.push('</tr>');
            html.push('<tr>');
            html.push('<td class="clum">发送环节: </td>');
            if(item.historicTaskInstance.preTaskDefName!=null){
                html.push('<td>'+item.historicTaskInstance.preTaskDefName+'</td>');
            }else{
                html.push('<td></td>');
            }

            html.push('</tr>');
            html.push('<tr>');
            html.push('<td class="clum">发送人: </td>');
            html.push('<td>'+item.sendUserName+'</td>');
            html.push('</tr>');
            html.push('<tr>');
            html.push('<td class="clum" title="'+item.assigneeInfo+'">接收人: </td>');
            if(item.reiceiveUserName != null
                || item.receiveOrgName != null){
                html.push('<td>'+item.reiceiveUserName +'（'+item.receiveOrgName+'）'+'</td>');
            }else{
                html.push('<td></td>');
            }
            html.push('</tr>');
            if(item.ownerName != undefined ){
                html.push('<tr>');
                html.push('<td class="clum">委托人: </td>');
                html.push('<td>'+item.ownerName+'</td>');
                html.push('</tr>');
            }
            html.push('<tr>');
            html.push('<td class="clum">审批意见: </td>');
            var fullCommentMsg = item.comment!=null&&item.comment.fullMessage!=null? item.comment.fullMessage : "";
            var shortCommentMsg="";
            if(item.historicTaskInstance.deleteReason!=null&&"cancel_process"==item.historicTaskInstance.actionType){
                var cancelCommentMsg="当前流程已作废,作废意见为:"+item.historicTaskInstance.deleteReason;
                fullCommentMsg=fullCommentMsg==""?cancelCommentMsg:(cancelCommentMsg+",发送环节意见为:"+fullCommentMsg);
                if(fullCommentMsg.length>7){
                    shortCommentMsg=fullCommentMsg.substring(0,7)+"...";
                    html.push('<td title="'+fullCommentMsg+'" style="white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">');
                    html.push('<a href="#" style="text-decoration:none;">'+shortCommentMsg+'</a></td>');
                }else{
                    html.push('<td>'+fullCommentMsg+'</td>');
                }
            }else{
                if(fullCommentMsg.length>7){
                    shortCommentMsg= fullCommentMsg.substring(0,7)+"...";
                    html.push('<td title="'+fullCommentMsg+'" style="white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">');
                    html.push('<a href="#" style="text-decoration:none;">'+shortCommentMsg+'</a></td>');
                }else{
                    html.push('<td class="qTipmessage">'+fullCommentMsg+'</td>');
                }
            }
            html.push('</tr>');
            html.push('<tr>');
            html.push('<td class="clum">开始时间: </td>');
            html.push('<td>'+filters(item.historicTaskInstance.startTime)+'</td>');
            html.push('</tr>');
            if(item.historicTaskInstance.endTime!=null){
                html.push('<tr>');
                html.push('<td class="clum">结束时间: </td>');
                html.push('<td>'+filters(item.historicTaskInstance.endTime)+'</td>');
                html.push('</tr>');
            }
            html.push('<tr>');
            html.push('<td class="clum">持续时间: </td>');
            html.push('<td>'+limitTimeStr+'</td>');
            html.push('</tr>');
            html.push('<tr>');
            html.push('<td class="clum">任务状态: </td>');
            if(item.historicTaskInstance.actionType=='cancel_process'){
                html.push('<td><font color="red">作废</font></td>');
            }else{
                if(item.historicTaskInstance.endTime != null){
                    html.push('<td>已完成</td>');
                }else{
                    html.push('<td><font color="red">正在审批</font></td>');
                }

            }
            html.push('</tr></tbody>');
            html.push('</table> <br>');
        })
        html.push('</div>');
        var content = html.join('');
        if(event=='element.hover'){
            overlays.add(e.element.id, 'note', {
                position: {
                    bottom: 0,
                    right: 0
                },
                html: content
            });
        }
    }
    //环节信息
    function dealActHtml(overlays,event,e){
        var html = new Array();
        var thisNode=document.getElementById('div_'+e.element.id);
        var listAct= arrayActId.filter(function(item){//判断这个节点是否
            return item == ('div_'+e.element.id);
        })
        if(listAct.length==0){
            arrayActId.push('div_'+e.element.id);
        }
        if(listAct.length>0){
            if(thisNode!=null){
                document.getElementById('div_'+e.element.id).style="display:block";
            }
            return;
        }
        var url="${ctx}/procDefMgr/getActivityDefModel.do";
        $.ajax({
            url : url,
            data:{"procDefId":procDefId,"actDefId":e.element.id},
            cache : false,
            async : false,
            type : "POST",
            success : function (data){
                var actDefObject = eval(data);
                html.push('<div class="lchj-box" signDiv="flag" onmouseover="showDiv(\'div_'+e.element.id+'\')" onmouseleave="hidenDiv(\'div_'+e.element.id+'\')" id="div_'+e.element.id+'"><div class="box-head"><span class="title">任务执行情况</span></div><div class="box-body">');
                html.push('<table cellpadding="0" cellspacing="0" class="lchj-table">');
                html.push('<tbody><tr>');
                html.push('<td class="clum" width="100">任务名称: </td>');
                html.push('<td>'+actDefObject.actDefName+'</td>');
                html.push('</tr>');
                html.push('<tr>');
                html.push('<td class="clum">任务资源: </td>');
                html.push('<td>');
                var roleStrs="";
                var orgStrs="";
                var userStrs="";
                var activityResources = eval(actDefObject.activityResources);
                activityResources.forEach(function(item){
                    // alert(activityResource.name);
                    if(item.type=="ROLE"){
                        roleStrs+=item.name+",";
                    }else if(item.type=="ORG"){
                        orgStrs+=item.name+",";
                    }else if(item.type=="USER"){
                        userStrs+=item.name+",";
                    }
                })
                roleStrs=roleStrs.substring(0,roleStrs.lastIndexOf(","));
                orgStrs=orgStrs.substring(0,orgStrs.lastIndexOf(","));
                userStrs=userStrs.substring(0,userStrs.lastIndexOf(","));
                if(roleStrs.length>0){
                    html.push("角色:"+roleStrs+"<br/>");
                }
                if(orgStrs.length>0){
                    html.push("组织:"+orgStrs+"<br/>");
                }
                if(userStrs.length>0){
                    html.push("人员:"+userStrs+"<br/>");
                }
                html.push('</td>');
                html.push('</tr>');
                html.push('<tr>');
                html.push('<td class="clum">任务类型: </td>');
                html.push('<td>单人处理</td>');
                html.push('</tr>');
                html.push('<tr>');
                html.push('<td class="clum">任务状态: </td>');
                html.push('<td>未执行</td>');
                html.push('</tr></tbody>');
                html.push('</table>');
                html.push('</div>');
                var content = html.join('');
                if(event=='element.hover'){
                    overlays.add(e.element.id, 'note', {
                        position: {
                            bottom: 0,
                            right: 0
                        },
                        html: content
                    });
                }
            }
        });
    }
    function appendLineHtml(overlays,event,id){//拼写输出线名称
        var html = new Array();
        var hash = {};//数组去重
        var lineList = viewer._getLineName.reduce(function(item, next) {
            hash[next.id] ? '' : hash[next.id] = true && item.push(next);
            return item;
        }, []);
        var thisNode=document.getElementById('line_'+id);
        var list= lineList.filter(function(item){//判断这个输出线是否是截取的输出线名称
            return item.id == id;
        })
        var listAct= arrayActId.filter(function(item){//判断这个节点是否
            return item == id;
        })
        if(listAct.length==0){
            arrayActId.push('line_'+id);
        }
        if(thisNode!=null && listAct.length==0){
            document.getElementById('line_'+id).style="display:block";
            return;
        }
        html.push('<div class="lchj-box" lineDiv="flag" onmouseover="showLineDiv(\'line_'+id+'\')" onmouseleave="hidenLineDiv(\'line_'+id+'\')" id="line_'+list[0].id+'"><div class="box-body">'+list[0].name);
        html.push('</div></div>');
        var content = html.join('');
        //alert(list[0].name)
        if(event=='element.hover'){
            overlays.add(id, {
                position: {
                    bottom: 0,
                    right: 0
                },
                html: content
            });
        }
    }
    //处理线的名称样式
    function dealLine(canvas){
        var hash = {};//数组去重
        var lineList = viewer._getLineId.reduce(function(item, next) {
            hash[next] ? '' : hash[next] = true && item.push(next);
            return item;
        }, []);
        var colorClass =  "highlight-label";
        lineList.forEach(function(item){
            canvas.addMarker(item+"_label", colorClass)
        })
    }
    //添加环节处理次数
    function addActNum(){
        var overlays = viewer.get('overlays');
        processTrace.forEach(function(item){
            if(item.type=='multi' || item.type=='call'){
                var list= processDetailLogs.filter(function(it){//获取处理记录信息
                    return it.historicTaskInstance.taskDefinitionKey == item.activityId;
                })
                overlays.add(item.activityId, 'note', {
                    position: {
                        bottom: 10,
                        right: 10
                    },
                    html: "<span class='num-color'>"+list.length+"</span>"
                });
            }

        })

    }
    //渲染当前节点
    function getCurrAct(){
        processTrace.forEach(function(item){
            viewer.get('canvas').removeMarker(item.activityId, "highlight_deal");
            if(item.status=="1"){ //是否是当前环节
                viewer.get('canvas').addMarker(item.activityId, "highlight_curr");
                getPosition(item.activityId);
            }
        })
    }
    //渲染已处理的节点
    function getMyDealed(){
        processDetailLogs.forEach(function(item){
            viewer.get('canvas').removeMarker(item.historicTaskInstance.taskDefinitionKey, "highlight_curr");
            if(item.reiceiveUserId==$("#userId").val()){//是否等于当前登录人
                viewer.get('canvas').addMarker(item.historicTaskInstance.taskDefinitionKey, "highlight_deal");
            }
        })
    }
    //定位
    function getPosition(id){
        var containerWidth = $('.bjs-container').width();
        var containerHeight = $('.bjs-container').height();
        var element = null;
        var element = viewer.get('elementRegistry')._elements[id].element;

        var x, y;
        x = element.x + element.width;
        y = element.y + element.height;
        viewer.get('canvas').viewbox({
            x: x- containerWidth/2,
            y: y- containerHeight/2,
            width: containerWidth,
            height: containerHeight
        });
    }
</script>
</body>
</html>
