/**
 * 待办审批
 */
var currentPage=1;//当前页
var totalpage=0;//总页数
var pageNum = 5;//最多显示页数
var pageSize = 0; //每页默认显示的数量100,lhy20181226修改,为了不显示分页
var projectId;
var taskIds;
var canSelfTurning = null;
var flowObjectName = null;
var task = null;
var activityid = null;
var canFinishFlow = false;
var searchInfo;
var startTimeconditionJson;
var overTimeconditionJson;
var statusJson;
var typeJson;
var userserver;
var checkboxState = "";
var listObject;
var listShowObject;
var flowList;
var linkList;
var roleIds;
$(function () {
	getRoleIds();
	curserver = CONF_BACK_SERVERURL;
	//获取列表按钮权
	getRoleChildrenPrivilege( window.parent.listName);

	getHoliday();//hyh  新增   获取假期,并且该方法设置为同步   2017、10、14
	getApproveList(1);
	btnEvent();
	meetSearchEvent();
	getSelectType();

	getLayerIdByKeyName("业务类型_图层");//ljy 2018-01-08 获取键值对


	$('#searchInput').bind('keypress', function (event) {
        if (event.keyCode == "13") {
    		var condition = $("#searchInput").val();
    		searchInfo = condition;
    		getApproveList(1,condition);
        }
    });
	//TODO 先注释lhy
	setListHeight();

	getUnhandledProjectCount();

});

window.onresize=setListHeight;//当窗口改变宽度时执行此函数,lhy20181226修改
function setListHeight() {
	var tableTop =  parseInt($("#workingsTabDiv").offset().top)-10;
//	var tableTop =  parseInt($("#tbodylist").offset().top)-10;
	var wh = $(window).height();
	var bodyPadding = parseInt($("body").css("padding"));
	var iframeTop = window.parent.$("#iframecontent").offset().top;
	//$("#workingsTabDiv").css("height",wh-iframeTop-tableTop-bodyPadding+"px");
	var height = wh-iframeTop-tableTop-bodyPadding -40;//50大概是tablehead的高度
	$("#tbodylist").css("height", height +"px");
	//$("#datalist").css("min-width",getTableInitWidth("datalist")+"px");//设置table的初始宽度
	setTableMinWidth();//设置表格的最小宽度
	setCellWidth();//设置单元格宽度
}


window.onload = function(){
	 setTimeout(function() {parent.window.NProgress.done()}, 500);
}

function getRoleIds() {
	userInfo=JSON.parse($.cookie('cookieuser'));
	var userdetail = getUserInfoByUserid(userInfo.user.id);
	var role = userdetail.roles;
	var roleidArray = new Array();
	for(var i=0;i<role.length;i++){
		roleidArray.push(role[i].id);
	}
	roleIds = roleidArray.join(',');
}

/**
 * 接件
 */
function openlayer_type(){
	parent.typeIndex = parent.layer.open({
		type: 2,
		title: '<img src="image/projecttask/type.png" style=\"width:25px;height:25px;\"/><span>选择接件类型</span>',
		shadeClose: true,
		shade: 0.3,
		area: ['80%', '80%'],
		content: "view/projecttask/selectHandl.html?createmethod=接件",
	});
}

/**
 * 批量发送
 */
/*function batchSendClick(){
	var checboxdata = [];
	var myDatatable = $('table.datatable').data('zui.datatable');
	var rowdata = myDatatable.data.rows;
	for(var i=0;i<rowdata.length;i++){
		if(rowdata[i].checked==true){
			var obj = rowdata[i];
			var tid = obj.data[2].text
			checboxdata.push(tid);
		}
	}
	taskIds = checboxdata.join(",");
	if(!taskIds){
		layer.msg('请选择需要发送的项目',{icon:2});
		return ;
	}
	var tid = taskIds.split(",")[0];
	//校验是否为同一流程同一环节

	$.ajax({
		type: "POST",
		url: curserver + global.modelctls.project.task.batchSend,
		headers:{
    		"token":$.cookie('ftoken')
		},
		data:{taskIds:taskIds},
		dataType: 'json',
		success:function(data){
			if(data.status=='ok'){
				//批量发送
				$.ajax({
					type: "POST",
					url: curserver + global.modelctls.project.task.resource,
					headers:{
			    		"token":$.cookie('ftoken')
					},
					data:{taskid : tid},
					dataType: 'json',
					success:function(data){
						canSelfTurning=data.activity.canSelfTurning;
						flowObjectName=data.activity.flowObjectName;
						task = data.task;
						activityid = data.activity.id;
					}
				});

				var index = layer.open({
					type : 2,
					title : '选择用户',
					shadeClose : true,
					shade : 0.3,
					area : [ '640px', '600px' ],
					offset : [ '50px' ],
					content : '../../view/userlist.jsp?taskId=' + tid,
					btn : [ '发送', '取消' ],
					yes : function(index, layero) {
						var iframeWin = window[layero.find('iframe')[0]['name']];
						var splabel = iframeWin.splabel();
						var toArray = [];
						for (var i = 0; i < splabel.length; i++) {
							var item = splabel[i];
							toArray.push({
								id : item.id,
								name : item.name,
								users : item.user
							});
						}
						var sendInfo = {
							from : {
								id : task.flowObjectId,
								name : task.name+",发送"
							},
							to : toArray
						};
						$.ajax({
							type: "POST",
							url: curserver + global.modelctls.flowEngine.task.batchComplete,
							headers:{
					    		"token":$.cookie('ftoken')
							},
							data:{
								taskIds : taskIds,
								activityId: activityid,
								sendObject : JSON.stringify(sendInfo)
							},
							dataType: 'json',
							success:function(result){
								if (result.status == 'ok') {
									//发送短信微信
								  	var tousers=iframeWin.users();
								  	var checkMessage=iframeWin.checkMessage();
								  	if(checkMessage!=""){
								  		var content = iframeWin.dWxWconContent();
								  		allSend(tousers,checkMessage,content);
								  	}



									layer.close(index);
								} else {
									console.info(result);
									layer.msg('发送失败!',{icon:2});
								}
							}
						});
					},
					end : function(index, layero) {

					}
				});

			}else
				layer.msg(data.message,{icon: 2});
		}
	});
}*/

function getdoctype() {
	return "batchsp";
}
function getcanSelfTurningData(){
	var data={canSelfTurning:canSelfTurning,
			flowObjectName:flowObjectName};
	return data;
}

/**
 * 批量结束流程
 *
 */
/*function finishFlow(){
	if(!taskIds){
		layer.msg('请选择需要结束的项目',{icon:2});
		return ;
	}
	if(!canFinishFlow){
		layer.msg('所选择的项目包含非退件项目,无法结束',{icon:2});
		return ;
	}
	layer.open({
		content: '确定结束该项目吗?',
		btn: ['确认', '取消'],
		shadeClose: true,
		icon: 3,
		yes: function(){
			var url = global.contextPath + global.modelctls.flowEngine.task.finishFlow;
			$.post(url,{taskIds:taskIds},function(data){
				if(data.status=='ok'){
					layer.msg(data.message,{icon: 1});
					getApproveList(1);
				}else
					layer.msg(data.message,{icon: 2});
			});
		}
	});

}*/

/**
 *显示流程日志
 */
function openlayer_flowlog(){
	parent.layer.open({
	    type: 2, //page层
	    area: ['700px', '400px'],
	    title: '流程日志',
	    shade: 0.6, //遮罩透明度
	    moveType: 1, //拖拽风格,0是默认,1是传统拖动
	    //shift: 1, //0-6的动画形式,-1不开启
	    content: 'ApprovalTask/Pages/flowlog.html'
	});
}

function newTask(){
	layer.closeAll();
	window.parent.iframeLoad('projecttask/detailproject.jsp', '办理项目', 'subMenuApprovalTask_4');
}


function sendToUsers(){
	parent.layer.open({
	    type: 2,
	    title: '选择人员',
	    shadeClose: true,
	    shade: 0.6,
	    area: ['200px', '400px'],
	    content: ['ApprovalTask/Pages/selectUsers.html'] //iframe的url
		,btn:['确定']
		,yes:function(index,layero){
			layer.closeAll();
		}
	});
}

/**
 * 已经不使用,下次没发现什么问题可删除 2018-01-08
 */
/*function opendetailproject(obj){
	var jqobj=$(obj);
	var tds = jqobj.find("td");
	var taskid = tds[3].innerText;
	var title = tds[6].innerText;
	var titleEncode = encodeURI(encodeURI(title));
	var stats = "projecting";
	var url = CONF_FRONT_SERVERURL + 'view/projecttask/detailproject.jsp?taskId=' + taskid+"&stats="+stats+"&titleEncode="+titleEncode;
	//打开后修改样式,修改未读样式
	var obj_div=$(obj).css("font-weight","");
	//window.open(url);
	parent.saveOpenNew(window.open(url)); //hyh 修改  2017/11/6
}*/


/**
 * 根据获取到的权限判断时候拥有列表显示的权限
 * hepo20171023
 */
function getListShowPrivilege(){
	var privilege=listPrivilege;
	var flag=false;
	if(privilege.length>0){
		for(var i=0;i<privilege.length;i++){
			if(privilege[i].name.indexOf("列表")!=-1){
				flag=true;
				break;
			}

		}
	}
	return flag;
}

/**
 * 获取列表
 */
function getApproveList(pageIndex,condition,starttimecondition,
		overtimecondition,statuscondition,typecondition){


	//若没有列表显示的权限 不加载
	if(!getListShowPrivilege()){
		parent.layer.msg('没有显示列表的权限',{icon: 2});
		return;
	}
	currentPage=pageIndex?pageIndex:1;
	if(searchInfo)
		condition = searchInfo;
	if(startTimeconditionJson)
		starttimecondition = startTimeconditionJson;
	if(overTimeconditionJson)
		overtimecondition = overTimeconditionJson
	if(statusJson)
		statuscondition = statusJson
	var documentType = $('#documentType').find("option:selected").val();
	var projectTypes = $('#projectTypes').val();
	$.ajax({
		type: "POST",
		url: curserver + global.modelctls.project.list.correctionWorkings,
		headers:{
    		"token":$.cookie('ftoken')
		},
		data:{pageIndex: pageIndex,
		 	   pageSize :pageSize,
		 	   condition:condition,
		 	   starttimecondition:starttimecondition,
			   overtimecondition:overtimecondition,
			   statuscondition:statuscondition,
			   typecondition:projectTypes,
			   documentType:documentType
			 },
		dataType: 'json',
		beforeSend: function(){
			parent.window.$.showLoading();
		},
		complete: function(){
			parent.window.$.hideLoading();
		},
		success:function(result){
			var totalre = result["total"];
			// layuiPage(totalre);
			dealingProjectDate(result);
			if (totalre == 0){
				$('#msg').css("display", "block");
				$('#nvaTab').css("visibility", "hidden");
			}else{
				$('#msg').css("display", "none");
				$("#page").text("共"+totalre+"条");
				$("#page").css("font-size","13px");
				$("#page").css("margin-right","25px");
				$("#page").css("margin-top","5px");
				$('#nvaTab').css("visibility", "visible");
			}
		}
	});
}

var nScrollTop=0;
function srollPage(pageIndex,nDivHight){
	  $("table tbody").scroll(function(){
	       var nScrollHight = $(this)[0].scrollHeight;
	       nScrollTop = $(this)[0].scrollTop;
	       if(nScrollTop + nDivHight >= nScrollHight){
	    		var pagenumber = pageIndex+1;
	    	   	if(pagenumber<=totalpage){
	    	   		parent.window.processBar.showBar();
	    	   		getApproveList(pagenumber);
	    	   		$("table tbody").scrollTop(nScrollTop);
	    	   	}else{
	    	   		layer.msg('没有更多数据加载', {
	    				  icon: 5
	    				  ,shade: 0.01
	    				});
	    	   	}
	       	}
	       });

}


/* hzw 2018/3/15 注释  不影响可以删除
 * var zuidate = {
	    	cols: [
	    	    {width: 'auto', text: '项目id', type: 'number', flex: false, colClass: 'hidden'},
	    	    {width: 'auto', text: '流程id', type: 'number', flex: false, colClass: 'hidden'},
	    	    {width: 'auto', text: '实例id', type: 'number', flex: false, colClass: 'hidden'},
	    	    {width: '40', text: '<img src="../../image/projecttask/projecttaskinfo.png "style="width:16px;">',type: 'string', flex: false,sort:false},//hyh 修改,给图标一栏的头部加个图标   2017/10/23
	            {width: '70', text: '状态', type: 'string', flex: false, colClass: '',sort:false},
	            {width: '100', text: '当前环节', type: 'string', flex: false, colClass: '',sort:false },
	            {width: 'auto', text: '项目类型', type: 'string', flex: false,colClass: '',sort:false},
	            {width: '200', text: '项目编号', type: 'number', flex: false, colClass: '',sort:false},
	            {width: 'auto', text: '项目名称', type: 'string', flex: false, colClass: '',sort:false },
	            {width: 'auto', text: '建设单位', type: 'string', flex: false,colClass: '',sort:false  },
	            {width: 'auto', text: '主办科室 ', type: 'string', flex: false,colClass: '',sort:false  },
	            {width: '100', text: '主办人', type: 'string', flex: false,colClass: '',sort:false },
	            {width: 'auto', text: '接件日期', type: 'date', flex: false,colClass: '',sort:true  },
	            {width: '100', text: '理论办结日期', type: 'date', flex: false,sort:false}
//	            {width: '180', text: '<img src="../assets/images/projecttask/operation.png" style="width:20px;height:20px;margin-right:10px;">操作', type: 'string',flex: false,sort:false}
//	            ,],
	       rows:[]
}*/


/* hzw 2018/3/15 注释  不影响可以删除
 * function zuitable(){
	$('table.datatable').datatable({
		checkable: true,
	    sortable: true,
	    checkByClickRow:false,
	    minFixedLeftWidth: 300,
	});
}*/

var dataTable = [];

function dealingProjectDate(result){
	//zuidate.rows = [];
	var data = [];

	var result_map=result["Data"];
	var listpath=[];
	listObject= [];
	listShowObject= [];
	for(var i=0;i<result_map.length;i++){
		var list_re = result_map[i];
		if(list_re.length>0){
			for(var j=0;j<list_re.length;j++){
				var map_result=list_re[j];
				var spListShowOrHidden = map_result["SPLISTSHOWORHIDDEN"];
				if(spListShowOrHidden && spListShowOrHidden == "hidden"){
					continue;
				}else{
					var lamp="";
					var bjqx="";
					var flowid = map_result["FLOWID"];
					var taskkey = map_result["TASK_DEF_KEY_"];
					var attachpath = map_result["ATTACHPATH"];
					//审批任务列表
					var description=map_result["DESCRIPTION"];
					var str="";

					var recevietime = new Date(map_result["CREATETIME"]);
					var projectcode = map_result["PROJECTCODE"]==null?"":map_result["PROJECTCODE"];
					var casecode = map_result["CASECODE"] == null ? ""
							: map_result["CASECODE"];
					var registertime = map_result["REGISTERTIME"] == null ? ""
							: new Date(map_result["REGISTERTIME"]);
					var buildadddress = map_result["BUILDADDRESS"] == null ? ""
							: map_result["BUILDADDRESS"];
					var projectname = map_result["PROJECTNAME"]==null?"":map_result["PROJECTNAME"];
					var projectflowtype = map_result["PROJECTFLOWTYPE"]==null?"":map_result["PROJECTFLOWTYPE"];
					var flowname = map_result["FLOWNAME"]==null?"":map_result["FLOWNAME"];

					var buildunit = map_result["BUILDUNIT"]==null?"":map_result["BUILDUNIT"];
					var bindingassignee = map_result["BINDINGASSIGNEE"]==null?"-":map_result["BINDINGASSIGNEE"];
					var meetingprojectstate=map_result["MEETINGPROJECTSTATE"]==null?"":map_result["MEETINGPROJECTSTATE"];
					var activityName = map_result["ACTIVITYNAME"]==null?"无":map_result["ACTIVITYNAME"];
					var status = map_result["PROJECTSTATUS"]==null?"-":map_result["PROJECTSTATUS"];
					var flowrevisionid = map_result["FLOWREVISIONID"]==null?"":map_result["FLOWREVISIONID"];
					var bindingunit = map_result["BINDINGUNIT"]==null?"-":map_result["BINDINGUNIT"];
	    			//根据流程版本获取总时限
	    			var timelimitDays = map_result["FINISHTIME"]==null?0:map_result["FINISHTIME"];
	    			var suptotaltime = map_result["SUPTOTALTIME"]==null?0:map_result["SUPTOTALTIME"];
	    			var officialdate =getAddDate(new Date(map_result["CREATETIME"]).format("yyyy-MM-dd hh:mm:ss"),timelimitDays,suptotaltime)//hyh 新增,根据办结天数算出办结时间  2017、10、13
	    			var flowItemType =  map_result["FLOWITEMTYPE"]?map_result["FLOWITEMTYPE"]:null;
	    			var correctionRecordId = map_result["RECORDID"]?map_result["RECORDID"]:null;
					//因为 审批列表使用的是zui组件,所以无法更换
	    			if (searchInfo) {  //搜索结果关键字变红  yyl 20180309
						projectcode = projectcode.replace(searchInfo,
								'<span style="color:red">' + searchInfo
										+ '</span>');
						projectname = projectname.replace(searchInfo,
								'<span style="color:red">' + searchInfo
										+ '</span>');
						buildunit = buildunit.replace(searchInfo,
								'<span style="color:red">' + searchInfo
										+ '</span>');
	                    bindingunit = bindingunit.replace(searchInfo,
								'<span style="color:red">' + searchInfo
										+ '</span>');
						buildadddress = buildadddress.replace(searchInfo,
								'<span style="color:red">' + searchInfo
										+ '</span>');
	                    bindingassignee = bindingassignee.replace(searchInfo,
								'<span style="color:red">' + searchInfo
										+ '</span>');
					}

	    			//续办图标
	    			var continueProject = "";
	    			var projectid = map_result["PROJECTID"]==null?"":map_result["PROJECTID"];
	    			bjqx=lefttime(new Date(),new Date(officialdate));
	    			var cqStr = "";
	    			// var color=changrowcolor(bjqx);
	    			if(status == "办结") {
	 					cqStr += '<div style=" display: inline-block; margin-right: 5px; "><img src="../../image/projecttask/over.png" title="办结" style="width:18px;height:18px;margin-top: 4px"></div>';
	    			}else if(status == "退件办结") {
	 					cqStr += '<div style=" display: inline-block; margin-right: 5px; "><img src="../../image/projecttask/over.png" title="退件办结" style="width:18px;height:18px;margin-top: 4px"></div>';
	 				}else if(status == "回退") {
	 					cqStr += '<div style=" display: inline-block; margin-right: 5px; "><img src="../../image/projecttask/rollback.png" title="回退" style="width:18px;height:18px;margin-top: 4px"></div>';
	 				}else if(status == "退件") {
	 					cqStr += '<div style=" display: inline-block; margin-right: 5px; "><img src="../../image/projecttask/return.png" title="退件" style="width:18px;height:18px;margin-top: 4px"></div>';
	 				}else if(bjqx=="超时"){
	 					cqStr += '<div style=" display: inline-block; margin-right: 5px;"><img src="../../image/projecttask/redhint.png" title="超时-'+officialdate+'" style="width:16px;height:16px;margin-top: 4px"></div>';//hyh 修改,谢文洲要求改审批图标    2017/10/23
	 					officialdate='<span style="color:red;font-weight:bold;">'+officialdate+'</span>';
	 				}else if(bjqx=="快超时") {
	 					cqStr += '<div style=" display: inline-block; margin-right: 5px;"><img src="../../image/projecttask/grayhint.png" title="快超时-'+officialdate+'" style="width:16px;height:16px;margin-top: 4px"></div>'//hyh 修改,谢文洲要求改审批图标    2017/10/23
	 				}else if(status == "在办") {
	 					cqStr += '<div style=" display: inline-block; margin-right: 5px; "><img src="../../image/projecttask/process.png" title="在办" style="width:18px;height:18px;margin-top: 4px"></div>';
	 				}
	    			//补正图标
					var getDays = function(day1,day2){
						var dateTime = 1000*60*60*24; //每一天的毫秒数
						var minusDays = Math.floor(((day2 - day1)/dateTime));
						var days = Math.abs(minusDays);
						return days;
					}
					var picturePath = "../../image/projecttask/buzheng.png";
					var pictureTitle = "补正中。。。";
					var correctionState = '<div style=" display: inline-block; margin-right: 5px; "><img src="'+ picturePath +'" title="'+ pictureTitle +'" style="width:20px;height:20px"></div>';
					var correctionCreatedTime = map_result["RECEIVETIME"];
					var nowTime = new Date().getTime();
					var days = getDays(correctionCreatedTime,nowTime);
					if(days < 1){
						days = "< 1";
					}
	 				var flowrevisionid = map_result["FLOWREVISIONID"] == null ? "":map_result["FLOWREVISIONID"];
	 				var instanceid = map_result["INSTANCEID"] == null ? "":map_result["INSTANCEID"];
	 				var taskid = 	map_result["TASKID"] == null ? "":map_result["TASKID"];
	 				listObject.push(map_result);
	 				listpath.push(attachpath);
					var row = {
							"PROJECTID": projectid,
							"INSTANCEID": instanceid,
							"TASKID": taskid,
							"BJQX": cqStr,
							"CORRECTIONSTATE":correctionState,
							"DURATION":days,
							"PROJECTSTATUS": status,
							"ACTIVITYNAME": activityName,
							"MEETINGPROJECTSTATE":meetingprojectstate,
							"FLOWNAME": flowname,
							"PROJECTCODE": projectcode,
							"CASECODE": casecode,
							"PROJECTNAME": projectname,
							"PROJECTFLOWTYPE": projectflowtype,
							"BUILDADDRESS": buildadddress,
							// "REGISTERTIME": registertime?registertime.format("yyyy-MM-dd hh:mm:ss").split("00:00:00")[0]:"",
							"REGISTERTIME": registertime ? registertime.format("yyyy-MM-dd") : "",
							"BUILDUNIT": buildunit,
							"BINDINGASSIGNEE": bindingassignee,
							"BINDINGUNIT": bindingunit,
							// "RECEIVETIME": recevietime?recevietime.format("yyyy-MM-dd hh:mm:ss"):"",
							"RECEIVETIME": recevietime ? recevietime.format("yyyy-MM-dd") : "",
							"FINISHTIME": officialdate,
							"FLOWREVISIONID": flowrevisionid,
							"DESCRIPTION": description,
							"ATTACHPATH":attachpath,
							"TASK_DEF_KEY_":taskkey,
							"FLOWITEMTYPE":flowItemType,
							"RECORDID":correctionRecordId
					}
					data.push(row);
					listShowObject.push(row);
				}
			}
		}
	}

	// // // TODO 获取数据后组装数据,新添加lhy20181225
	dynamicWorkingTable(data,"workingsTabDiv", 'searchtext');

    // setLayuiData(data);//注释掉,不以数据表格形式显示lhy20181226
    /*$.ajax({
        type: "POST",
        async: true,
        url: CONF_DOC_SERVERURL +"ftpfile/recordList.do",
        data: {pathList:JSON.stringify(listpath)},
        success: function(result) {
            var img = '<img class="img" src="../../image/home-content/fj.png" title="附件" style="width:18px;height:18px;margin-right: 5px;">';
            var htlist=$("#nvaTab tbody tr");
            var recordData=result.data;
            if(recordData) {
            for(var y=0;y<listObject.length;y++){
                var cupath = listObject[y].ATTACHPATH;
                var flowId= listObject[y].FLOWID;
                var flowObjectId=listObject[y].TASK_DEF_KEY_;
                var flowrevision=listObject[y].FLOWREVISIONID;
                var task1=listObject[y].TASKID;
                var flowlist1=flowList[flowId];
                var flowobject1=linkList[flowrevision+flowObjectId];
                if(task1 && flowobject1 && cupath!=null && cupath!="undefined") {
                    for(var l=0;l<flowobject1.length;l++){
                        for(var k=0;k<flowlist1.length;k++){
                            if(flowobject1[l].RESOURCEID==flowlist1[k].RESOURCEID) {
                                flowlist1.splice(k,1);
                            }

                        }

                    }
                    if(flowlist1.length>0) {
                        for(var v=0;v<flowlist1.length;v++){
                            var flowpath=cupath+"/"+flowlist1[v].MATERNAME;
                            for(var x=0;x<recordData.length;x++){
                                var filepath=recordData[x].slice(1,flowpath.length+1);
                                if(flowpath == filepath) {
                                    recordData.splice(x,1);
                                }
                            }
                        }
                    }
                    for(var j=0;j<recordData.length;j++){
                        var	compare=recordData[j].slice(1,cupath.length+1);
                        if(compare == cupath){
                            var data_show=layui.table.cache.tableRenderId;//这里应该是获取整张表的数据,lhy,原来的
                            for(var k=0;k<data_show.length;k++) {
                                if(data_show[k].ATTACHPATH==cupath) {
                                    $(htlist[k]).find(".img").remove();
                                    $(htlist[k]).find("td[data-field=\"PROJECTNAME\"] div").prepend(img);
                                    break;
                                }
                             }
                            break;
                           }
                        }
                }else if(task1 && !flowobject1 && cupath!=null && cupath!="undefined") {
                    if(cupath!=null && flowlist1) {
                    for(var v=0;v<flowlist1.length;v++){
                        for(var x=0;x<recordData.length;x++){
                            var flowpath=cupath+"/"+flowlist1[v].MATERNAME;
                            var filepath=recordData[x].slice(1,flowpath.length+1);
                            if(flowpath == filepath) {
                                recordData.splice(x,1);
                            }
                        }
                    }

                    for(var j=0;j<recordData.length;j++){
                        var	compare=recordData[j].slice(1,cupath.length+1);
                        if(compare == cupath){
                            var data_show=layui.table.cache.tableRenderId;
                            for(var k=0;k<data_show.length;k++) {
                                if(data_show[k].ATTACHPATH==cupath) {
                                    $(htlist[k]).find(".img").remove();
                                    $(htlist[k]).find("td[data-field=\"PROJECTNAME\"] div").prepend(img);
                                    break;
                                }
                             }
                            break;
                           }
                        }
                    }else if(cupath!=null && cupath!="undefined"){
                        for(var j=0;j<recordData.length;j++){
                            var	compare=recordData[j].slice(1,cupath.length+1);
                            if(compare == cupath){
                                var data_show=layui.table.cache.tableRenderId;
                                for(var k=0;k<data_show.length;k++) {
                                    if(data_show[k].ATTACHPATH==cupath) {
                                        $(htlist[k]).find(".img").remove();
                                        $(htlist[k]).find("td[data-field=\"PROJECTNAME\"] div").prepend(img);
                                        break;
                                    }
                                 }
                                break;
                               }
                            }
                    }
                }else if(!task1 && cupath!=null && cupath!="undefined"){
                    for(var j=0;j<recordData.length;j++){
                        var	compare=recordData[j].slice(1,cupath.length+1);
                        if(compare == cupath){
                            var data_show=layui.table.cache.tableRenderId;
                            for(var k=0;k<data_show.length;k++) {
                                if(data_show[k].ATTACHPATH==cupath) {
                                    $(htlist[k]).find(".img").remove();
                                    $(htlist[k]).find("td[data-field=\"PROJECTNAME\"] div").prepend(img);
                                    break;
                                }
                             }
                            break;
                           }
                        }
                   }
              }
          }
        },
        error: function(e) {
            console.log(e);
        }

    })*/

}

/* hzw 2018/3/15 注释  不影响可以删除
 * function openRefreshList(){
	zuidate.rows = [];
	$('table.datatable').datatable('load',getApproveList(1));
}*/


//check box 勾选事件
function CheckItem(obj){
//	$("input[type='checkbox']:checked").each(function(i){
//		$(this).prop('checked','');
//	});
	canFinishFlow = true;
	var checkBoxs = $("input[type='checkbox']:checked");
	var tds = checkBoxs.parent().parent().find("td");
	if(checkBoxs.length==0){
		projectId = null;
		taskIds = null;
		canFinishFlow = false;
		$("#continueProject").attr("disabled","disabled");
		return ;
	}
	if(checkBoxs.length>1){
		$("#continueProject").attr("disabled","disabled");
		projectId = '';
		var i = 0;
		taskIds = '';
		$("#continueProject").attr("disabled","disabled");
		$("input[type='checkbox']:checked").each(function(i){
			var tds = $(this).parent().parent().find("td");
			if(tds[4].innerText!="退件")
				canFinishFlow = false;
			if(i==0){
				projectId += tds[1].innerText;
				taskIds += tds[3].innerText;
			}else{
				projectId += ','+tds[1].innerText;
				taskIds += ','+tds[3].innerText;
			}
			i++;
		});
		i = 0;
	}else{
		$("#continueProject").attr("disabled",null);
		projectId = tds[1].innerText;
		taskIds = tds[3].innerText;
		if(tds[4].innerText!="退件")
			canFinishFlow = false;
	}
}
/**
 * 动态分页按钮
 * @param tatalre
 * @param totalpa
 */
/* hzw 2018/3/15 注释  不影响可以删除
 * function dynamicPage(totalre,totalpa,currentPage){
	$("#total_records").html(totalre);
	$("#total_page").html(totalpa);
	var pageStart = "";
	var pageEnd = "";
	if(currentPage<=Math.round(pageNum/2)+1){
		pageStart = 1;
		pageEnd = pageNum;
	}
	if(currentPage>Math.round(pageNum/2)+1){
		pageStart = currentPage-Math.round(pageNum/2);
		pageEnd = currentPage+Math.round(pageNum/2)-2;
	}
	if(pageEnd>totalpa){
		pageEnd = totalpa;
	}
	var ulcontent = $(".pagination");
	ulcontent.children().filter('li').remove();
	ulcontent.append("<li> <a onclick=\"jumpPage(0)\" aria-label=\"Previous\">" +
	"<span aria-hidden=\"true\">上一页</span></a></li> ");
	for(var i=pageStart;i<=pageEnd;i++){
		if(i==currentPage){
			ulcontent.append("<li class=\"active\"><a onclick=\"getApproveList("+i+")\">"+i+"</a></li>");
		}else{
			ulcontent.append("<li><a onclick=\"getApproveList("+i+")\">"+i+"</a></li>");
		}

	}
	ulcontent.append("<li> <a onclick=\"jumpPage(1)\" aria-label=\"Next\">" +
			"<span aria-hidden=\"true\">下一页</span></a></li> ");
	pagging.modifyPagging(totalre, totalpa,currentPage);
}*/
pagging.config.list=getApproveList;
/**
 * 上一页、下一页调转
 * @param index
 */
/* hzw 2018/3/15 注释  不影响可以删除
 * function jumpPage(index){
	var pageindex=1;
	if(index==0){//上一页
		pageindex = currentPage-1<=1?1:currentPage-1;
	}else {
		pageindex= currentPage+1>=totalpage?totalpage:currentPage+1;
	}
	getApproveList(pageindex);
}

function newTab(url, tabname, tabid){
	window.parent.iframeLoad(url, tabname, tabid);
}

function refreshTable(){
	zuidate.rows = [];
	$('table.datatable').datatable('load',getApproveList(1));
}
function checkboxStop(){
	$("input[type='checkbox']").click(function(e){
	    e.stopPropagation();
	});
}*/

/**
 * 上会
 * @param obj
 */
function openProject(obj){

//	var tid = $(obj).parents().parents().children("td:nth-child(3)").text();
//	var projectId = $(obj).parents().parents().children("td:nth-child(1)").text();
//	window.open(global.contextPath+'/mvc/meetingProject/findSpProject.do?projectId='+projectId+"&spParameter="+tid);
//
//
	var checboxnumber=0;
	var checboxdata = [];
	var myDatatable = $('table.datatable').data('zui.datatable');
	var rowdata = myDatatable.data.rows;
	for(var i=0;i<rowdata.length;i++){
		if(rowdata[i].checked==true){
			checboxnumber++;
			var obj = rowdata[i];
			checboxdata.push(obj);
		}
	}
	if(checboxnumber==0){
		alert("请选择项目")
	}
	if(checboxnumber>1){
		alert("只能选择一个项目上会")
	}

	if(checboxdata.length==1){
		var data = checboxdata[0];
		var projectId = data.data[0].text;
		var tid = data.data[2].text;
		var state = data.data[4].text;
		if(state=="上会"){
			alert("项目已经上会");
			return;
		}
		//window.open(global.contextPath+'/mvc/meetingProject/findSpProject.do?projectId='+projectId+"&spParameter="+tid);
		parent.saveOpenNew(window.open(window.open(global.contextPath+'/mvc/meetingProject/findSpProject.do?projectId='+projectId+"&spParameter="+tid))); //hyh 修改  2017/11/6
	}



}
/**
 * 撤会
 */
function closeProject(obj){
	var projectId = $(obj).parents().parents().children("td:nth-child(1)").text();
	$.post(global.contextPath + '/mvc/meetingProject/closeProject.do', {
		projectId : projectId
	}, function(result) {
		if (result.status == 'ok') {
			action="撤会";
			updateStatus(projectId);
			layer.msg("撤会成功", {
				   icon: 1,
				   time: 1500,
				   offset: '300px'
				 },function(){
					 getApproveList(currentPage,"");
				 });
		}else{
			layer.msg(result.message,{icon: 2});
		}
	}).error(function(e) {
		$.messager.alert('错误', 'HTTP请求失败,请检查网络!');
	});
	event.stopPropagation();
}

/**
 * 回退
 */
function mbFallBack(obj){
	var taskId = $(obj).parents().parents().children("td:nth-child(3)").text();
	var projectId = $(obj).parents().parents().children("td:nth-child(1)").text();
	action="回退";
	$.ajax({
		type: "POST",
		url: curserver + global.modelctls.flowEngine.task.fallback,
		headers:{
    		"token":$.cookie('ftoken')
		},
		data:{taskid : taskId},
		dataType: 'json',
		success:function(result){
			if (result.status == 'ok') {
				console.debug(result);
				global.main.closeTab('taskId_' + taskId);
				action = "回退";
				updateStatus(projectId);
				layer.msg("回退成功", {
					   icon: 1,
					   time: 1500,
					   offset: '300px'
					 },function(){
						 getApproveList(currentPage,"");
					 });
			} else {
				console.info(result);
				layer.msg("回退失败", {
					   icon: 2,
					   time: 1500,
					   offset: '300px'
					 },function(){
					 });
			}
		},
		error:function(e){
			$.messager.alert('错误', 'HTTP请求失败,请检查网络!');
		}
	});
	event.stopPropagation();
}

/**
 * 退件
 */
function mbReject(obj) {
	var taskId = $(obj).parents().parents().children("td:nth-child(3)").text();
	var projectId = $(obj).parents().parents().children("td:nth-child(1)").text();
	parent.layer.confirm(
			'确认退件吗?',
			{icon: 3, title:'提示'},
			function(index){
				action="退件";
				$.ajax({
					type: "POST",
					url: curserver + global.modelctls.flowEngine.task.reject,
					headers:{
			    		"token":$.cookie('ftoken')
					},
					data:{taskid : taskId},
					dataType: 'json',
					success:function(result){
						if (result.status == 'ok') {
							console.debug(result);
							global.main.closeTab('taskId_' + taskId);
							updateStatus(projectId);
							parent.layer.msg("退件成功", {
								   icon: 1,
								   time: 1500,
								   offset: '300px'
								 },function(){
									 getApproveList(currentPage,"");
								 });
						} else {
							console.info(result);
							layer.msg("退件失败", {
								   icon: 2,
								   time: 1500,
								   offset: '300px'
								 },function(){

								 });
						}
					},
					error:function(e){
						$.messager.alert('错误', 'HTTP请求失败,请检查网络!');
					}

				});
			});
	event.stopPropagation();
}


/**
 * 续办
 */
/* hzw 2018/3/15 注释  提取到layuiDataList.js作为通用方法 不影响可以删除
 * function openlayer_continue(obj){
	var checboxnumber=0;
	var checboxdata = [];
	var myDatatable = $('table.datatable').data('zui.datatable');
	var rowdata = myDatatable.data.rows;
	for(var i=0;i<rowdata.length;i++){
		if(rowdata[i].checked==true){
			checboxnumber++;
			var obj = rowdata[i];
			checboxdata.push(obj);
		}
	}
	if(checboxnumber==0){
		parent.layer.msg("请选择项目!", {icon : 2});
	}
	if(checboxnumber>1){
		parent.layer.msg("只能选择一个项目!", {icon : 2});
	}
	if(checboxdata.length==1){
		var data = checboxdata[0];
		var projectId = data.data[0].text;
		$.ajax({
			type: "POST",
			url: curserver + global.modelctls.project.getProjectCasecode,
			headers:{
	    		"token":$.cookie('ftoken')
			},
			data:{projectId:projectId},
			dataType: 'json',
			success:function(data){
				if(data.status=='ok'){
					layer.open({
						  type: 2,
						  title: '审批类型',
						  shadeClose: true,
						  shade: 0.6,
						  offset:'20px',
						  area: ['80%', '80%'],
						  content: 'selecttype.jsp?projectId='+projectId //iframe的url
					});
				}else
					layer.msg(data.message,{icon: 2});
			}
		});
		event.stopPropagation();
	}
}
*/

function changeStatus(){
	var selectStatus = $('#selectStatus').find("option:selected").val();
	statusJson = selectStatus;
	getApproveList(1);
}
function changeType(){
	if($('#documentType').val()!="所有") {
		$('#projectTypes').val("");
	}
	if($('#projectTypes').val().replace(/(^\s*)|(\s*$)/g, "")==""&& $('#optionType').find(".remove").length!=0) {
		$("#optionType").find(".remove").remove();
	}
	nScrollTop = 0;
	getApproveList(1);
}

//根据操作更新当前公文的动作状态
function updateStatus(projectId){
	$.post(global.contextPath + global.modelctls.flowEngine.updateActionStatus, {
		action : action,
		pid: projectId
	}, function(data) {

	});
}

function allSend(tousers,checkMessage,content){
	$.post(global.contextPath + global.modelctls.sms.sendAll,{
		jsonUserId:tousers,
		content:content,
		checkMessage:checkMessage
	},function(result){
		var dXmsg = "";
		var wXmsg = "";
		if(result[0]!=""){
			result[0]=(result[0].substring(result[0].length-1)==',')?result[0].substring(0,result[0].length-1):result[0];
			dXmsg = result[0]+"号码不存在";
		}
		if(result[1]!=""){
			result[1]=(result[1].substring(result[1].length-1)==',')?result[1].substring(0,result[1].length-1):result[1];
			wXmsg += result[1]+"微信号未绑定"
		}
		if(checkMessage=="message"){
			if(dXmsg=="")
				layer.msg("已发送短信提醒",{icon: 1});
			else
				layer.msg(dXmsg,{icon: 2});
		}else if(checkMessage=="wechat"){
			if(wXmsg=="")
				layer.msg("已发送微信提醒",{icon: 1});
			else
				layer.msg(wXmsg,{icon: 2});
		}else{
			var msg = dXmsg+","+wXmsg;
			if(msg==",")
				layer.msg("提醒成功",{icon: 1});
			else{
				msg = (msg.substr(0,1)==',')?msg.substr(1):msg;
				layer.msg(msg,{icon: 2});
			}
		}
	});
}

function btnEvent(){
	$('input[type="text"]').keydown( function(e) {
		if(event.keyCode == 13){
			currentPage=1;
		}else{
			currentPage=$(".layui-input").val();
		}

	});
	$(document).keyup(function (e) {//捕获文档对象的按键弹起事件
	    if (e.keyCode == 13) {//按键信息对象以参数的形式传递进来了
	    	var condition = $("#searchInput").val();
    		searchInfo = condition;
    		getApproveList(currentPage,condition);
	    }
	});
	$("#searchBtn").click(function(){
		var condition = $("#searchInput").val();
		searchInfo = condition;
		nScrollTop = 0;
		getApproveList(currentPage,condition);
	});

	$("#searchInput").on('input',function(e){
		searchInfo = $("#searchInput").val();
		if(searchInfo==''){
			nScrollTop = 0;
			getApproveList(1,"");
		}
	});

//	$('table.datatable').datatable().on("sort.zui.datatable", function(event) {
//	    alert("111");
//	});

}
function searQuery(){
	var condition = $("#searchInput").val();
	searchInfo = condition;
	zuidate.rows = [];
	nScrollTop = 0;
	getApproveList(1,condition);
}

function supendTack(obj){
	var taskId = $(obj).parents().parents().children("td:nth-child(3)").text();
//	 $.post(global.contextPath + global.modelctls.flowEngine.task.suspend,{taskid: taskId}, function (result) {
//         if (result.status == 'ok') {
//        	alert("111");
//         }
//	 });
	event.stopPropagation();
}

function activation(obj){
	var taskId = $(obj).parents().parents().children("td:nth-child(3)").text();
//	 $.post(global.contextPath + global.modelctls.flowEngine.task.activation,{taskid: taskId}, function (result) {
//         if (result.status == 'ok') {
//        	alert("111");
//         }
//	 });
	event.stopPropagation();
}


/**
 * 项目树
 */
function openlayer_tree(){
	//var checkboxData = getCheckStatus().data;//改为如下,因为待办项目不是使用layui的数据表格显示的
	var checkboxData;
	if (window.parent.listName == "待办项目") {
		checkboxData =  getCheckedProjectData();

	} else {
		checkboxData =  getCheckStatus().data;
	}
	if(checkboxData.length == 0){
		parent.layer.msg("请选择项目!", {icon : 2});
	}else
	if(checkboxData.length > 1){
		parent.layer.msg("只能选择一个项目!", {icon : 2});
	}else
	if(checkboxData.length==1){
		var projectid = checkboxData[0].PROJECTID;
		var url = CONF_FRONT_SERVERURL
		+ 'view/projecttask/projectTree.jsp'+'?projectId='+projectid;
		layer.open({
			type : 2, //page层
			area : [ '50%', '90%' ],
			offset : '10px',
			title : '项目一棵树',
			shadeClose : true,
			shade : 0.6, //遮罩透明度
			moveType : 1, //拖拽风格,0是默认,1是传统拖动
			moveOut : true,
			maxmin: true,//最大化最小化
			//shift: 1, //0-6的动画形式,-1不开启
			content : url
		});
	}

}


/**
 * 结束流程
 */
/*function openlayer_endtask(){
	var taskArray=[];
	var projectids =[];
	var myDatatable = $('table.datatable').data('zui.datatable');
	var rowdata = myDatatable.data.rows;
	for(var i=0;i<rowdata.length;i++){
		if(rowdata[i].checked==true){
			var obj = rowdata[i];
			var taskid = obj.data[2].text
			if(obj.data[4].text != '退件'){
				parent.layer.msg("结束失败!只有状态为'退件'的案件才可以结束!", {icon : 2});
				return false ;
			}else{
				taskArray.push(taskid);
				projectids.push(obj.data[0].text);
			}
		}
	}
	if(taskArray!=null && taskArray.length>0){
		parent.layer.open({
			content: '确定结束选中流程吗?',
			btn: ['确认', '取消'],
			shadeClose: true,
			icon: 3,
			yes: function(){
				var taskString = taskArray.join();
				$.ajax({
				type: "POST",
				url: curserver + global.modelctls.flowEngine.task.finishFlow,
				headers:{
    				"token":$.cookie('ftoken')
				},
				data:{
					taskIds : taskString,
				},
				success:function(result){
					if(result.status == 'ok') {
						action = "退件办结";
						for(var i=0;i<projectids.length;i++){
							projectid = projectids[i];
							updateActionStatus();
						}
						var taskListArray=[];
						var taskList=result.data;
						for(var i=0;i<taskList.length;i++){
							taskListArray.push(taskList[i].instanceId);

						}
						if(taskListArray!=null){
							$.ajax({
								type: "POST",
								url: curserver + global.modelctls.project.updateProjectTwo,
								headers:{
				    				"token":$.cookie('ftoken')
								},
								data:{
									taskList : taskListArray.join()
								},
								dataType: 'json',
								success:function(msg){
									}
								});
						}
						parent.layer.msg(result.message,{icon: 1});
						//openRefreshList();
					}
				}
			});
			parent.layer.closeAll();
		}
	});
	}else{
		parent.layer.msg("请选择项目!", {icon : 2});
	}
}*/




/**
 * 日志
 */
function openJournal(){
	var checboxnumber=0;
	var checboxdata = [];
	var myDatatable = $('table.datatable').data('zui.datatable');
	var rowdata = myDatatable.data.rows;
	for(var i=0;i<rowdata.length;i++){
		if(rowdata[i].checked==true){
			checboxnumber++;
			var obj = rowdata[i];
			checboxdata.push(obj);
		}
	}
	if(checboxnumber==0){
		parent.layer.msg("请选择项目!", {icon : 2});
	}
	if(checboxnumber>1){
		parent.layer.msg("只能选择一个项目!", {icon : 2});
	}

	if(checboxdata.length==1){
		var data = checboxdata[0];
		var flowInstanceId = data.data[1].text;
		var url = CONF_FRONT_SERVERURL + 'view/projecttask/flowlog.jsp?flowInstanceId='
		+ flowInstanceId;

		layer.open({
			type : 2, //page层
			area : [ '70%', '90%' ],
			offset : '10px',
			title : '流程日志',
			shadeClose : true,
			shade : 0.6, //遮罩透明度
			moveType : 1, //拖拽风格,0是默认,1是传统拖动
			moveOut : true,
			//shift: 1, //0-6的动画形式,-1不开启
			content : url
		});
	}
}
function updateActionStatus(){
	$.ajax({
		type: "POST",
		url: curserver + global.modelctls.flowEngine.updateActionStatus,
		headers:{
    		"token":$.cookie('ftoken')
		},
		data:{action : action,pid: projectid},
		success:function(data){
		}
	});
}
function selectProjecType(){
	var index = layer.open({
		type : 2,
		title : '选择业务类型',
		shadeClose : true,
		shade : 0.3,
		area : [ '650px', '630px' ],
		content : '../../view/userlist.jsp?name=projectType',
		btn : [ '确定', '取消' ],
		yes : function(index, layero) {
			var iframeWin = window[layero.find('iframe')[0]['name']];
			var username = iframeWin.selectSearchUser();
			//获取主办人搜索    yyl  2018.01.05
			$('#projectTypes').val(username);
			layer.close(index);
			if($('#projectTypes').val()!="") {
				$('#documentType').val("所有");
			}
			if($('#projectTypes').val().replace(/(^\s*)|(\s*$)/g, "")!=""&& $('#optionType').find(".remove").length==0) {
				$("#optionType").append('<span class="glyphicon glyphicon-remove remove" title="移除内容" onclick="remove(this)" ></span>');
			}
			nScrollTop = 0;
			getApproveList(1);
		},
		end : function(index, layero) {
			
		}
	});
}
function remove(e) {
	$(e.parentElement).find("input[type='text']").val("");
	getApproveList(1);
	$(e).remove();
}

function valchange(e){
	if($(e).val().replace(/(^\s*)|(\s*$)/g, "")!=""&& $(e.parentElement).find(".remove").length==0) {
		$(e.parentElement).append('<span class="glyphicon glyphicon-remove remove" title="移除内容" onclick="remove(this)" ></span>');
	}else if($(e).val().replace(/(^\s*)|(\s*$)/g, "")==""&& $(e.parentElement).find(".remove").length!=0) {
		$(e.parentElement).find(".remove").remove();
	}
}

function getMaterialverifyData(){
	$.ajax({
		type: "POST",
		async: true,
		headers:{
    		"token":$.cookie('ftoken')
		},
		url: curserver+"/mvc/project/getMaterialverify.do",
		success: function(result) {
			var instance=result.instance;//流程数据
			var link=result.link;//节点数据
			flowList= {};
			linkList= {};
			var dest;
			for(var i=0;i<instance.length;i++) {
				var a=instance[i];
				if(!flowList[a.FLOWID]) {
					dest=[];
					dest.push(a);
					flowList[a.FLOWID]=dest;
				}else {
					flowList[a.FLOWID].push(a);
				}
			}
			for(var i=0;i<link.length;i++) {
				var b=link[i];
				if(!linkList[b.FLOWREVISIONID+b.FLOWOBJECTID]) {
					dest=[];
					dest.push(b);
					linkList[b.FLOWREVISIONID+b.FLOWOBJECTID]=dest;
				}else {
					linkList[b.FLOWREVISIONID+b.FLOWOBJECTID].push(b);
				}
			}
		}
	});
}

var showDataList;//按顺序存放显示的表格行数据
/**
 * 组装数据
 * hzw 2018/4/27 修改 lhy
 * @param result		数据
 * @param tbodyid		列表ID
 * @param searchtext	搜索关键字
 */
function dynamicWorkingTable(result,tbodyid, searchtext){
	showDataList = [];
	var data = result;
	if(data==null){return;}
	//先分组归类项目信息
	var groupData = groupByFlowType(data);


	var str = JSON.stringify(result);
	$("#"+tbodyid).children().remove();
	var htmlTable = "";
	if(groupData.length>0){//如果有分组数据
		//添加表头
		htmlTable  += "<table  class=\"striped\" id=\"datalist\" style=\"table-layout: fixed;width: 100%;\">" +
		"<thead><tr class=\"tabletitle\"> " +
		"<th width=\"1%\" class=\"checkboxCls\">"+'<input class="parent_check" type="checkbox" name="" lay-skin="primary" title="" >'+"</th>"+
		"<th width=\"3%\" class=\"statusIcon\"></th>"+
		"<th width=\"6%\"><div class=\"tableCell\">历时(天)</div></th> " +
		"<th width=\"12%\"><div class=\"tableCell\">业务类型</div></th>" +
		"<th width=\"10%\"><div class=\"tableCell\">项目编号</div></th>" +
		"<th width=\"10%\"><div class=\"tableCell\">报建编号</div></th>" +
		"<th width=\"20%\"><div class=\"tableCell\">项目名称</div></th>"+
		"<th width=\"8%\"><div class=\"tableCell\">建设位置</div></th>" +
		"<th width=\"8%\"><div class=\"tableCell\">建设单位</div></th>" +
		"<th width=\"8%\"><div class=\"tableCell\">接收时间</div></th>" +
		"<th width=\"5%\"><div class=\"tableCell\">经办人</div></th>" +
		"<th width=\"10%\"><div class=\"tableCell\">所属部门</div></th>" +
		"</tr>" +
		"</thead>" +
		"<tbody id=\"tbodylist\">"


		for(var i=0; i<groupData.length; i++){//遍历分组数据
			/*if(i>0){//TODO 测试
				break;
			}*/
			var flowType = groupData[i]["type"];
			var flowTypeName = groupData[i]["name"];
			var sum = 0 ;//统计属于该类型的项目个数
			var htmlTableBodyTr = "";//归类项目内容
				for( var j=0; j<data.length;j++){//遍历所有项目数据
					var flowTypeStr = data[j]["PROJECTFLOWTYPE"];
					var obj = JSON.stringify(data[j]);
					var fontweight = "";
					var descrption = data[j]["DESCRIPTION"];
					if(descrption != "read"){
						fontweight = ' style=\"font-weight: 600;color: blue;\" ';
					}
					if(flowType == flowTypeStr){
						htmlTableBodyTr += "<tr id=\""+data[j]["PROJECTID"]+"\" "+fontweight+' class=\"group'+ i +'\">'+
						"<td width=\"1%\" class=\"checkboxCls\" >"+'<input class="son_check" type="checkbox" name="layTableCheckbox" lay-skin="primary" title="" >'+"</td>"+
						"<td width=\"3%\" onclick=\'workingSeeDetail(this)\' class=\"statusIcon\">"+data[j]["CORRECTIONSTATE"]+"</td>"+
						"<td width=\"6%\" onclick=\'workingSeeDetail(this)\'><div class=\"tableCell\">"+data[j]["DURATION"]+"</div></td>"+
						"<td width=\"10%\"  onclick=\'workingSeeDetail(this)\'><div class=\"tableCell\">"+data[j]["FLOWNAME"]+"</div></td>"+
						"<td width=\"10%\" onclick=\'workingSeeDetail(this)\'><div class=\"tableCell\">"+data[j]["PROJECTCODE"]+"</div></td>"+
						"<td width=\"10%\" onclick=\'workingSeeDetail(this)\'><div class=\"tableCell\">"+data[j]["CASECODE"]+"</div></td>"+
						"<td width=\"20%\" onclick=\'workingSeeDetail(this)\' data-field=\"PROJECTNAME\"><div class=\"tableCell\">"+data[j]["PROJECTNAME"]+"</div></td>"+
						"<td width=\"8%\" onclick=\'workingSeeDetail(this)\'><div class=\"tableCell\">"+data[j]["BUILDADDRESS"]+"</div></td>"+
						"<td width=\"8%\" onclick=\'workingSeeDetail(this)\'><div class=\"tableCell\">"+data[j]["BUILDUNIT"]+"</div></td>"+
						"<td width=\"10%\" onclick=\'workingSeeDetail(this)\'><div class=\"tableCell\">"+data[j]["REGISTERTIME"]+"</div></td>"+
						"<td width=\"5%\" onclick=\'workingSeeDetail(this)\'><div class=\"tableCell\">"+data[j]["BINDINGASSIGNEE"]+"</div></td>"+
						"<td width=\"10%\">"+data[j]["BINDINGUNIT"]+"</td>"+
						"</tr>";
						sum++;
						showDataList.push(data[j]);//将显示的数据保存
					}
				}
				//往表格中添加一行用于提示分类的标志行
				var htmlTableHeadTr = "<tr class=\"flowtypeParent\" id=\""+"group"+ i +"\">"+
				"<td width=\"1%\" class=\"iconTd\">"+"<span class=\"glyphicon glyphicon-minus\"></span>"+"</td>"+
				 "<td width=\"3%\">"+flowTypeName+"("+sum+")"+"</td>"+
				 "<td width=\"5%\">"+""+"</td>"+
				 "<td width=\"10%\">"+""+"</td>"+
				 "<td width=\"10%\">"+""+"</td>"+
				 "<td width=\"10%\">"+""+"</td>"+
				 "<td width=\"20%\">"+""+"</td>"+
				 "<td width=\"8%\">"+""+"</td>"+
				 "<td width=\"8%\">"+""+"</td>"+
				 "<td width=\"10%\">"+""+"</td>"+
				 "<td width=\"5%\">"+""+"</td>"+
				 "<td width=\"10%\">"+""+"</td>"+
				 "</tr>";
				htmlTable += htmlTableHeadTr + htmlTableBodyTr;
		}
		 htmlTable += "</tbody></table>";

		 //TODO 先注释	 $("#"+tbodyid).append(contentstr);
		 $("#"+tbodyid).append(htmlTable);
		 //设置未读加粗和鼠标悬停显示内容
		 setCell(showDataList);
		 setListHeight();//设置table高度适应
		//复选框的点击事件
		chexboxClickEvent();
		//隐藏或显示按钮点击事件
		ShowHideClickEvent();
		tabSize.init('datalist');
		setTableMinWidth();//设置表格的最小宽度
		setCellWidth();//设置单元格宽度

	}

}
/**
 * 以projectflowtype分组归类项目信息
 */
function groupByFlowType(result){
	var groupData = [];
	var returnData = [];
	for(var i=0; i<result.length; i++){
		var flowType = result[i]["PROJECTFLOWTYPE"];
		if(groupData.indexOf(flowType)==-1){
			for( var j=0; j<optionFlowData.length;j++){
				var flowTypeStr = optionFlowData[j]["value"];
				if(flowType == flowTypeStr){
					var flowTypeName = optionFlowData[j]["text"];
					break;
				}
			}

			var obj = {
					"type" : flowType,
					"name" : flowTypeName,
			}
			groupData.push(flowType);
			returnData.push(obj);
		     }
	}
	return returnData;

}

/**
 * 查看项目详情
 */
function workingSeeDetail(td){
	var data;
	//如果这个复选框被选中,则获取这行tr的id(项目id)
    var trProjectId = $(td).parent().attr("id");
    console.log("选中的项目id="+trProjectId);
    for(var i=0;i<listShowObject.length;i++){
    	var listProjectId = listShowObject[i].PROJECTID
    	if(trProjectId.trim() == listProjectId){
    		data = listShowObject[i];
    		break;
    	}
    }
    //不再验证会议状态
    openApproveDetail(data);
	/*if(data.MEETINGPROJECTSTATE!=null && data.MEETINGPROJECTSTATE!="" && parent.listName!="项目查询" && parent.listName!="已办项目"){
		parent.layer?parent.layer.msg("项目正在"+data.MEETINGPROJECTSTATE, {icon : 7}):opener.parent.layer.msg("项目正在"+data.MEETINGPROJECTSTATE, {icon : 7});
		return;
	}else{
		openApproveDetail(data);
	}*/
}


/**
 * 鼠标悬停显示title 这是修改过的代办项目显示页面使用,lhy修改20181227
 * 待办项目未读加粗
 */
/*function setCell(data) {
	$("#workingsTabDiv tbody td,#workingsTabDiv thead th").each(function() {
		var text = $(this).first()[0].innerText.trim();
		if(text == "") text = "";
		$(this).attr("title", text);
	})
	if(window.parent.listName == "待办项目") {
		$("#datalist tbody tr").not(".flowtypeParent").each(function(index) {//筛选不为分类行的tr,lhy20181227
			if(data[index].DESCRIPTION != "read") {
				$(this).css("font-weight", "600");
			}
		})
	}*/

/*	$(".layui-table-header th").each(function(index) {
		var field = $(this).attr("data-field");
		fields.push(field);
	}) */
/*	$(".laytable-cell-1-BJQX").each(function() {
		$(this).removeClass("laytable-cell-1-BJQX");
	})*/

/**
 * 复选框的点击事件
 */
function chexboxClickEvent(){
	//全局的checkbox选中和未选中的样式
    $parentChexbox = $('.parent_check'), //全选
    $dataBox = $('#tbodylist'),           //用于判断全局与子类的关系
    $sonCheckBox = $('.son_check');      //单个子类选中

    //全局全选与单个的关系
    $parentChexbox.click(function () {
        var $checkboxs = $dataBox.find('input[type="checkbox"]');
        if ($(this).is(':checked')) {
            $checkboxs.prop("checked", true);
        } else {
            $checkboxs.prop("checked", false);
        }

      //判断:所有子复选框个数
        var len = $sonCheckBox.length;
        var num = 0;
      //判断子复选框选了几个
        $sonCheckBox.each(function () {
            if ($(this).is(':checked')) {
                num++;
            }
        });
      //续办,日志,删除按钮状态
		buttonStyle(getCheckedProjectData().length, num == len);
    });

    $sonCheckBox.each(function () {
        $(this).click(function () {
            if ($(this).is(':checked')) {
                //判断:所有单个是否勾选
                var len = $sonCheckBox.length;
                var num = 0;
                //判断子复选框选了几个
                $sonCheckBox.each(function () {
                    if ($(this).is(':checked')) {
                    	//如果这个复选框被选中,则获取这行tr的id(项目id)
                    var projectId = $(this).parent().parent().attr("id");
                        num++;
                    }
                });
                if (num == len) {
                    $parentChexbox.prop("checked", true);
                   /* console.log("全选了共"+num+"个复选框");*/
                }
            } else {
                //单个取消勾选,全局全选取消勾选
                $parentChexbox.prop("checked", false);
            }

            //续办,日志,删除按钮状态
            buttonStyle(getCheckedProjectData().length, num == len);
        })

    })

}

/**
 * 获取复选框选中的项目信息
 */
function getCheckedProjectData(){
    //存放已选择的项目信息
   var checkedProjectList = [];
   //判断子复选框选了几个
   $("input[name='layTableCheckbox']").each(function () {
       if ($(this).is(':checked')) {
       //如果这个复选框被选中,则获取这行tr的id(项目id)
       var trProjectId = $(this).parent().parent().attr("id");
       /!*console.log("选中的项目id="+trProjectId);*!/
       for(var i=0;i<listShowObject.length;i++){//通过项目id获取当前行的数据
           var listProjectId = listShowObject[i].PROJECTID
           if(trProjectId == listProjectId){
               checkedProjectList.push(listShowObject[i]);
           }
       }

       }

   });
    return checkedProjectList;
}

/**
 * 隐藏或显示按钮的点击事件
 */
function ShowHideClickEvent(){
    $iconTd = $('.iconTd');
	$iconTd.each(function () {
    $(this).click(function () {
    	 var trId = $(this).parent().attr("id");
    		$(this).parent().nextAll("."+ trId ).toggle();
    		var display =$(this).parent().nextAll("."+ trId ).css('display');
    		if(display == 'none'){
    			//如果是隐藏的就改变图标
    			$(this).html('<span class="glyphicon glyphicon-plus"></span>');//显示加号
    		}else{
    			 $(this).html('<span class="glyphicon glyphicon-minus"></span>');//显示减号
    		}

    })

})
$flowtypeParent = $('.flowtypeParent');
	$flowtypeParent.each(function () {
		$(this).dblclick(function () {//双击事件
			var trId = $(this).attr("id");
			$(this).nextAll("."+ trId ).toggle();
			var display =$(this).nextAll("."+ trId ).css('display');
			if(display == 'none'){
				//如果是隐藏的就改变图标
				$(this).children(".iconTd").html('<span class="glyphicon glyphicon-plus"></span>');//显示加号
			}else{
				$(this).children(".iconTd").html('<span class="glyphicon glyphicon-minus"></span>');//显示减号
			}

		})

	})

}


	var tabSize = tabSize || {};
	//表头拖动事件
	tabSize.init = function (id) {
	    var i,
	        self,
	        table = document.getElementById(id),
	        header = table.rows[0],
	        tableX = header.clientWidth,
	        length = header.cells.length;

	    for (i = 0; i < length; i++) {
	        header.cells[i].onmousedown = function () {
	            self = this;
	            if (event.offsetX > self.offsetWidth - 10) {
	                self.mouseDown = true;
	                self.oldX = event.x;
	                self.oldWidth = self.offsetWidth;
	            }
	        };
	        header.cells[i].onmousemove = function () {
	        	setCellWidth();//设置单元格宽度
	            if (event.offsetX > this.offsetWidth - 10) {
	                this.style.cursor = 'col-resize';
	            } else {
	                this.style.cursor = 'default';
	            }
	            if (self == undefined) {
	                self = this;
	            }
	            if (self.mouseDown != null && self.mouseDown == true) {
	                self.style.cursor = 'default';
	                if (self.oldWidth + (event.x - self.oldX) > 0) {
	                    self.width = self.oldWidth + (event.x - self.oldX);
	                }
	                self.style.width = self.width;
	                table.style.width = tableX + (event.x - self.oldX) + 'px';
	                self.style.cursor = 'col-resize';

	            }
	        };
	        table.onmouseup = function () {
	            if (self == undefined) {
	                self = this;
	            }
	            self.mouseDown = false;
	            self.style.cursor = 'default';
	            tableX = header.clientWidth;
	          //  setCellWidth();//设置单元格宽度
	        };
	    }

	};

	/**
	 * 设置表格的th和td宽度一致
	 */
	function setCellWidth(){
		 var thHeader = $("#datalist").find("th");//获取表头对象
		 var trBody = $('#tbodylist').find("tr");//获取表格tr
		 $("#tbodylist tr").each(function(){
			//var t = $(this).nextAll("td");
			var t = $(this).children("td");
			$(this).children("td").each(function(index){
				var td_width = thHeader.eq(index).width();
				$(this).width(td_width);

				/*var td_width1 = $(this).width();
				if(index != thHeader.length-1){

					$(this).width(thHeader.eq(index).width());
				}else{
					// TO需要判断是否出现了滚动条
					$(this).width(thHeader.eq(index).width() - 10);//最后一个td减去滚动条的宽度
				}*/


			 });
		 });


	}

/**
 * 获取表格的初始宽度
 */
 function getTableInitWidth(id){
	var table = document.getElementById(id);
    var header = table.rows[0];
    var tableX = header.clientWidth;
    return tableX;
 }
 /**
  * 设置表格的最小宽度
  */
 function setTableMinWidth(){
	 var minWidth = $("#workingsTabDiv").width();
	 if(minWidth < 1000) minWidth = 1000;//设置最小宽度是为了出现X向滚动条
	 $("#datalist").css("min-width",minWidth+"px");//设置table的初始宽度
 }


function WaitingToStart() {
	layer.open({
		id: '_id_',
		type: 1,
		maxmin: true,
		area: ['80%', '80%'],
		content: '<div><table id="waitingprocessinglist" lay-filter="test"></table></div>',
		success: function (layero, index) {
			layui.use('table', function(){
				var table = layui.table;
				var tableObj = table.render({
					page: true
					,elem: '#waitingprocessinglist'
					,height: 'full-' + (($("body").height() - ($("#_id_").offset().top + $("#_id_").height()-65))+$("#_id_").offset().top+40)
					,url: CONF_DOCKINGSYSTEM_SERVERURL + '/xiangj/resource/getUnhandledItems'
					,where: {roleid: roleIds}
					,cols: [[ //表头
						{field: 'flowname', title: '业务类型'}
						,{field: 'xmmc', title: '项目名称'}
						,{field: 'jsdd', title: '建设地点'}
						,{field: 'sxmc', title: '事项名称'}
						,{field: 'sxbm', title: '事项编码'}
					]]
					,parseData: function(res){ //res 即为原始返回的数据
						// 如果只有一页,则隐藏页码。
						var pageelm = $('[lay-id='+tableObj.config.id+']').find('.layui-table-page');
						if (res.total < tableObj.config.limit) {
							pageelm.css('display', 'none');
						} else {
							pageelm.css('display', 'block');
						}
						return {
							'code': 0, //解析接口状态
							'msg': '获取数据成功', //解析提示文本
							'count': res.total, //解析数据长度
							'data': res.records //解析数据列表
						};
					}
					,done: function(res, curr, count){
						// 点击行打开详情页。鼠标按下到放开间隔超过半秒,不打开详情页(避免复制文字的时候也打开详情页)
						this.elem.parent().find('tr[data-index]').mousedown(function() {
							var stop, flag = true;
							stop = setTimeout(function() { flag = false; }, 500);
							$(this).one('mouseup', function() {
								if (flag) {
									clearTimeout(stop);
									// 获取参数
									var data = res.data;
									var dataIndex = this.getAttribute('data-index');
									var rowdata = dataIndex && data[dataIndex];
									var flowid = rowdata && rowdata.flowid;
									var dockingid = rowdata && rowdata.sxslbm;
									if (!flowid) {
										return layer.msg('没有绑定启动流程!');
									}
									if (!dockingid) {
										return layer.msg('获取实例编码失败!');
									}
									// 项目文件夹ID
									$.cookie('uuid',uuid(), {path: '/frontweb/view/projecttask'});
									// 打开页面
									var url = CONF_FRONT_SERVERURL + 'view/projecttask/detailproject.jsp?dockingid='+ dockingid +'&flowid=' + flowid + '&create=0&stats=create';
									window.open(handleJumpUrl(url));
								}
							});
						});
					}
				});
			});
		}
	});
}


function getUnhandledProjectCount() {
 	$.ajax({
		url: CONF_DOCKINGSYSTEM_SERVERURL + '/xiangj/resource/getUnhandledItemCount',
		data: {roleid: roleIds},
		success: function (result) {
			if (result) {
				$('.w-badge').text(result).css('display', 'inline-block');
			} else {
				$('.w-badge').css('display', 'none');
			}
		},
		error: function (error) {

		}
	})
}

function uuid() {
	function S4() {
		return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
	}
	return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}