<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ include file="/common/context.jsp"%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<title>合同信息管理</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="<%=path%>/common/script/context.js" type="text/javascript"></script>
<script src="<%=path%>/common/script/context_table.js" type="text/javascript"></script>
<script type="text/javascript">
var _table;
var contractWorkflow="${contractWorkflow}";
var className;
$(function (){
	var $wrapper = $('#div-table-container');
	var $table = $('#table-general');
	
	_table = $table.dataTable($.extend(true,{
	},CONSTANT.DATA_TABLES.DEFAULT_OPTION, {
		ajax : function(data, callback, settings) {//ajax配置为function,手动调用异步查询
			//手动控制遮罩
			$wrapper.spinModal();
			//封装请求参数
			var param = GeneralManage.getQueryCondition(data);
			$.ajax({
		            type: "POST",
		            url: "findContractInfo_contractInfo.action",
		            cache : false,	//禁用缓存
		            data: param,	//传入已封装的参数
		            dataType: "json",
		            success: function(result) {
		            	//setTimeout仅为测试遮罩效果
		            	setTimeout(function(){
		            		//异常判断与处理
		            		if (result.errorCode) {
		            			showMsg("error","查询失败。错误码："+result.errorCode);
		            			return;
							}
		            		
		            		//封装返回数据，这里仅修改属性名
		            		var returnData = {};
			            	returnData.draw = data.draw;//这里直接自行返回了draw计数器,应该由后台返回
			            	returnData.recordsTotal = result.total;
			            	returnData.recordsFiltered = result.total;//后台不实现过滤功能，每次查询均视作全部结果
			            	returnData.data = result.pageData;
			            	//关闭遮罩
			            	$wrapper.spinModal(false);
			            	//调用DataTables提供的callback方法，代表数据已封装完成并传回DataTables进行渲染
			            	//此时的数据需确保正确无误，异常判断应在执行此回调前自行处理完毕
			            	callback(returnData);
		            	},200);
		            },
		            error: function(XMLHttpRequest, textStatus, errorThrown) {
		               
		                $wrapper.spinModal(false);
		            }
		        });
		},
        columns: [
            CONSTANT.DATA_TABLES.COLUMN.CHECKBOX, 
            {	
            	className : "ellipsis",
				orderable : false,
            	render: function(data,type, row, meta) {
					
					if(row.orderStateName=="流程审批中")
					{
					    var action="display_workflow.action?param=view&processId="+row.processId+"&orderId=";
						return "<img src=\"<%=path%>/images/msg_1.jpg\" title=\"流程催办\" onclick=\"openWorkFlowWindow('"+action+"',"+row.ciId+",'"+row.processId+"')\" style=\"cursor:pointer\">";
					}else
					{
						return "";
					}
                },         	
            	width : "30px"
            }
            ,{
            	className : "ellipsis",
            	data: "projectName",
            	render: CONSTANT.DATA_TABLES.RENDER.ELLIPSIS,
            	width : "15%"
             }
            ,{
            	className : "ellipsis",
            	data: "contractCode",
            	render: CONSTANT.DATA_TABLES.RENDER.ELLIPSIS,
            	width : "10%"
             }
            ,{
            	className : "ellipsis",
            	data: "contractName",
            	render: viewContractInfoDetail,
            	width : "15%"
             }
            ,{
            	className : "ellipsis",
            	data: "framework",
            	render: viewFrameWork,
            	width : "5%",
				orderable : false
             }
            ,{
            	className : "ellipsis",
            	data: "contractNameB",
            	render: CONSTANT.DATA_TABLES.RENDER.ELLIPSIS,
            	width : "15%"
             }
            ,{
            	className : "ellipsis",
            	data: "contractPersonB",
            	render: CONSTANT.DATA_TABLES.RENDER.ELLIPSIS,
            	width : "8%",
				orderable : false
             }
            ,{
            	className : "ellipsis",
            	data: "contractTelB",
            	render: CONSTANT.DATA_TABLES.RENDER.ELLIPSIS,
            	width : "8%",
				orderable : false
             }
            ,{
            	className : "numPrice",
            	data: "contractMoney",
            	render: CONSTANT.DATA_TABLES.RENDER.NUMBER_PRICE,
            	width : "8%"
             }
            ,{
            	className : "ellipsis",
            	data: "writeDate",
            	render: CONSTANT.DATA_TABLES.RENDER.ELLIPSIS,
            	width : "8%"
             }
            ,{
            	className : "ellipsis",
            	data: "signDate",
            	render: CONSTANT.DATA_TABLES.RENDER.ELLIPSIS,
            	width : "8%"
             }
            ,{
            	className : "ellipsis",
            	data: "statusCn",
            	width : "8%",
				orderable : false
             }
        ],
        "createdRow": function ( row, data, index ) {
        	//行渲染回调,在这里可以对该行dom元素进行任何操作
        	//给当前行加样式
        	if (data.role) {
        		$(row).addClass("info");
			}
        	 //给当前行某列加样式
        	$('td', row).eq(12).addClass("light-red");
            
        },
        "drawCallback": function( settings ) {
        	//渲染完毕后的回调
        	//清空全选状态
			$(":checkbox[name='cb-check-all']",$wrapper).prop('checked', false);
        	//默认选中第一行
        	$("tbody tr",$table).eq(0).click();
        }
	})).api();//此处需调用api()方法,否则返回的是JQuery对象而不是DataTables的API对象

    
    
	
	
	$("#btn-advanced-search").click(function(){
		_table.draw();
	});
		
	$("#btn-add").click(function(){
		GeneralManage.addItemInit();
	});
	
	$("#btn-edit").click(function(){
		var arrItemId = [];
        $("tbody :checkbox:checked",$table).each(function(i) {
        	var item = _table.row($(this).closest('tr')).data();
        	arrItemId.push(item);
        });
		GeneralManage.editItemInit(arrItemId);
	});
	
	$("#btn-del").click(function(){
		var arrItemId = [];
        $("tbody :checkbox:checked",$table).each(function(i) {
        	var item = _table.row($(this).closest('tr')).data();
        	arrItemId.push(item);
        });
		GeneralManage.deleteItem(arrItemId);
	});
	
	//撤销确认流程
	$("#btn-processCancel").click(function(){
		var arrItemId = [];
        $("tbody :checkbox:checked",$table).each(function(i) {
        	var item = _table.row($(this).closest('tr')).data();
        	arrItemId.push(item);
        });
		GeneralManage.pCancelItem(arrItemId);
	});
	//提交确认流程
	$("#btn-processSubmit").click(function(){
  		var arrItemId = [];
        $("tbody :checkbox:checked",$table).each(function(i) {
        	var item = _table.row($(this).closest('tr')).data();
        	arrItemId.push(item);
        });
		GeneralManage.pSubmitItem(arrItemId);
	});
	$("#btn-send").click(function(){
		var arrItemId = [];
        $("tbody :checkbox:checked",$table).each(function(i) {
        	var item = _table.row($(this).closest('tr')).data();
        	arrItemId.push(item);
        });
		GeneralManage.sendItemInit(arrItemId);
	});
	
	$("#btn-sign").click(function(){
		var arrItemId = [];
        $("tbody :checkbox:checked",$table).each(function(i) {
        	var item = _table.row($(this).closest('tr')).data();
        	arrItemId.push(item);
        });
		GeneralManage.signItemInit(arrItemId);
	});
	
	//提交合同
	$("#btn-Submit").click(function(){
		var arrItemId = [];
        $("tbody :checkbox:checked",$table).each(function(i) {
        	var item = _table.row($(this).closest('tr')).data();
        	arrItemId.push(item);
        });
		GeneralManage.btnSubmitItem(arrItemId);
	});
	//合同终止
	$("#btn-term").click(function(){
		var arrItemId = [];
        $("tbody :checkbox:checked",$table).each(function(i) {
        	var item = _table.row($(this).closest('tr')).data();
        	arrItemId.push(item);
        });
		GeneralManage.termItem(arrItemId);
	});
	//行点击事件
	$("tbody",$table).on("click","tr",function(event) {
		$(this).addClass("active").siblings().removeClass("active");
		//获取该行对应的数据
		//var item = _table.row($(this).closest('tr')).data();
		//GeneralManage.currentItem = item;
    });
	
	$table.colResizable();$table.on("change",":checkbox",function() {
		if ($(this).is("[name='cb-check-all']")) {
			//全选
			$(":checkbox",$table).prop("checked",$(this).prop("checked"));
		}else{
			//一般复选
			var checkbox = $("tbody :checkbox",$table);
			$(":checkbox[name='cb-check-all']",$table).prop('checked', checkbox.length == checkbox.filter(':checked').length);
		}
    }).on("click",".td-checkbox",function(event) {
    	//点击单元格即点击复选框
    	!$(event.target).is(":checkbox") && $(":checkbox",this).trigger("click");
    })
	
	$("#toggle-advanced-search").click(function(){
		$("i",this).toggleClass("icon-search icon-circle-arrow-up");
		$("#div-advanced-search").slideToggle("fast");
	});
	
	$("#btn-info-content-collapse").click(function(){
		$("i",this).toggleClass("fa-minus fa-plus");
		$("span",this).toggle();
	});
	
});
		

var GeneralManage = {
	currentItem : null,
	getQueryCondition : function(data) {
		var param = {};

		//组装排序参数 
		//默认进入的排序
		 param.orderColumn="de.ciId";
		if (data.order&&data.order.length&&data.order[0]) {
			switch (data.order[0].column) {
            case 2:
				param.orderColumn = "de.projectName";
				break;
            case 3:
				param.orderColumn = "de.contractCode";
				break;
            case 4:
				param.orderColumn = "de.contractName";
				break;
            case 6:
				param.orderColumn = "de.contractNameB";
				break;
            case 9:
				param.orderColumn = "de.contractMoney";
				break;
            case 10:
				param.orderColumn = "de.writeDate";
				break;
            case 11:
				param.orderColumn = "de.signDate";
				break;
			}
			param.orderDir = data.order[0].dir;
		}
		
		//组装查询参数  ***按需修改****
		param.contractCode = $("#contractCode").val();
		param.contractName = $("#contractName").val();
		param.contractNameB = $("#contractNameB").val();
		//组装分页参数
		param.startIndex = data.start;
		param.pageSize = data.length;
		
		param.draw = data.draw;
		
		return param;
	},
	// 新增
	addItemInit: function()  {
		
	   window.location.href="saveContractInfoInit_contractInfo.action?type=0";	    
	},
	//修改
	editItemInit: function(selectedItems)  {
	   var v = selectedItems;
	   if(v.length==0){
           showMsg("alert","请选择信息");
       }else if(v.length > 1){
   	      showMsg("alert","温馨提示：只能选择一条信息修改！");
       }else{
	  		var ids = v[0].ciId;
	  		var runStatus=v[0].runStatus;
	  		if(runStatus=="01"){
		      window.location.href="updateContractInfoInit_contractInfo.action?contractInfo.ciId="+ids;	    
		    }else{
		     showMsg("alert","温馨提示：该合同不是起草状态，不能修改！");
		    }
		    
      }
	 },
	//合同发送至供应商
	sendItemInit: function(selectedItems)  {
	   var v = selectedItems;
		if(v!=0){
	          	var ids = "";
	          	var falg=true;
		        for(var i=0;i<v.length;i++){
		     		if(i == (v.length-1)){
						ids += v[i].ciId;
				    }else{
	 			     	ids += v[i].ciId + ",";
			        }
			        if(v[i].runStatus!="0"){
			          falg=false;
			        }
				}
				if(falg){		        
					$.dialog.confirm("温馨提示：你确定要发送选中的合同信息至供应商么！",function(){
						   result = ajaxGeneral("saveSendContractInfo_contractInfo.action","ids="+ids);
							   showMsg('success',''+result+'',function(){
							   		doQuery();							
				   					});
						   	 	}); 
				   }else{
				     showMsg("alert","温馨提示：只有提交的合同才能发送至供应商进行确认操作");
				   }
	    }else{
        	showMsg("alert","请选择信息！");
        }
	 }, 
	//合同签订
	signItemInit: function(selectedItems)  {
	   var v = selectedItems;
	   if(v.length==0){
           showMsg("alert","请选择信息");
       }else if(v.length > 1){
   	      showMsg("alert","温馨提示：只能选择一条信息修改！");
       }else{
	  		var ids = v[0].ciId;
	  		var runStatus=v[0].runStatus;
	  		if(runStatus=="5"){
		       createdetailwindow("签订合同信息","updateSignContractInfoInit_contractInfo.action?contractInfo.ciId="+ids,2);	    
		    }else{
		     showMsg("alert","温馨提示：只有经过供应商确认的合同才能进行合同签订操作，请通知供应商进行合同确认操作！");
		    }
		    
      }
	 },
	//删除
	deleteItem : function(selectedItems) {
		var v = selectedItems;
		if(v!=0){
	          	var ids = "";
	          	var falg=true;
		        for(var i=0;i<v.length;i++){
		     		if(i == (v.length-1)){
						ids += v[i].ciId;
				    }else{
	 			     	ids += v[i].ciId + ",";
			        }
			        if(v[i].runStatus!="01"&&v[i].runStatus!="3"){
			          falg=false;
			        }
				}
				if(falg){		        
					$.dialog.confirm("温馨提示：你确定要删除选中的信息！",function(){
						   result = ajaxGeneral("deleteContractInfo_contractInfo.action","ids="+ids);
							   showMsg('success',''+result+'',function(){
							   		doQuery();							
				   					});
						   	 	}); 
				   }else{
				     showMsg("alert","温馨提示：非起草状态的合同不能删除！");
				   }
	    }else{
        	showMsg("alert","请选择信息！");
        } 
    },
    //撤销确认流程
	pCancelItem:function(selectedItems){
		var v = selectedItems;
		if(v.length < 1){
      		showMsg("alert","温馨提示：请选择将要撤销的信息！");
      	}else if(v.length > 1){
	    	showMsg("alert","温馨提示：只能选择一条信息撤销！");
	    }else{
	    	var orderState = v[0].orderState;
	    	if(orderState == "0"){
    	    		showMsg("alert","温馨提示:此项目流程已结束,不能撤销!");
    	    		return false;
   	    	}else{
   	    		var action = "deleteCancelContractInfoProcess_bidworkflow.action";
				var param = "contractInfo.ciId="+v[0].ciId;
				var result = ajaxGeneral(action,param,"text");
				if(parseInt(result)==0){
					showMsg("alert","温馨提示：流程撤销成功！",function(){
					 window.location.href= window.location.href;
					});
				}else if(parseInt(result)==1){
					showMsg("alert","温馨提示：流程编号不存在！");
					return ;
				}else if(parseInt(result)==2){
					showMsg("alert","温馨提示：没有提交流程，不能撤销！");
					return ;
				}else{
				    showMsg("alert","温馨提示：流程已经处理，不能撤回");
					return ;				
				}
    		}
	    }
	},
	//提交确认流程
	pSubmitItem:function(selectedItems){
  		var v = selectedItems;
  		if(v.length < 1){
	  		showMsg("alert","温馨提示：请选择将要提交的信息！");
	  	}else if(v.length > 1){
	  		showMsg("alert","温馨提示：请选择一条将要提交的信息的信息！");
	    }else{
	    	var ciId = v[0].ciId;
	    	var processId = v[0].processId;
	    	var orderId = v[0].orderId;
	    	var orderState = v[0].orderState;
	    	var instanceUrl = v[0].instanceUrl;
	    	var contractAppFile = v[0].contractAppFile;
	    	if(contractAppFile==""){
	    	  showMsg("alert","温馨提示:请上传合同审批附件信息再提交审批!");
	    	}else{
	    	if(orderState == "0"){
	    		showMsg("alert","温馨提示:此项目流程已结束,请选择将要提交的信息!");
	    	}else if(orderState == "1"){
	    		showMsg("alert","温馨提示:此项目流程正在运行,请选择将要提交的信息!");
	    	}else{
	    		 var orderNo="${work_flow_type}"+ciId;
					createdetailwindow("提交合同审批","<%=path%>"+instanceUrl+"?processId="+processId+"&orderId="+orderId+"&orderNo="+orderNo,1);
			}
			}
	    }
	},
	//提交为合同
	btnSubmitItem:function(selectedItems){
	  var v = selectedItems;
		if(v.length < 1){
      		showMsg("alert","温馨提示：请选择将要提交的合同信息！");
      	}else{
      	        var f=0;
    	    	var ids = "";
      	   		var orderIds = "";
      	   		var noFile=0;
    			for(var i=0;i<v.length;i++){
    			var orderState = v[i].orderState;
	    	    var contractAppFile = v[0].contractAppFile;
				    if(orderState != "01") f=1;	 
				    if(contractAppFile=="")	noFile=1;		   
    				if(i == (v.length-1)){
    					ids += v[i].ciId;
    					orderIds = v[i].orderId;
    				}else{
    					ids += v[i].ciId + ",";
    					orderIds += v[i].orderId + ",";
    				}
    			}
    			if(f==1){
	    	    	showMsg("alert","温馨提示:您选择的合同中存在已提交的合同,不能提交!");
	    	    	return false;
		    	 }
		    	 if(noFile==1){
		    	    showMsg("alert","温馨提示:请上传合同审批附件信息再提交合同!");
	    	    	return false;
		    	  }
	    			$.dialog.confirm("温馨提示：你确定要提交选中的信息！",function(){
	 				  var result = ajaxGeneral("updateProcessContractInfo_contractInfo.action","ids="+ids);
	 					   showMsg('success',''+result+'',function(){
	 					   		doQuery();							
	 		   					});
	 				   	 	});
	    }
	},
	//合同终止
	termItem : function(selectedItems) {
		var v = selectedItems;
		 if(v.length>0){
			  if(v.length>1)
			  {
			  	showMsg("alert",'温馨提示：只能选择一条信息！');
			  }else
			  {
				  if(v[0].runStatus=="8")
				  {
				  	showMsg("alert",'温馨提示：该合同已经终止！');
				  }else
				  {
				  	createdetailwindow('合同终止','saveContractTerminationInit_contractTermination.action?contractInfo.ciId='+v[0].ciId,2);
				  }
		    	 
	
			  }
	    }else{
	    	showMsg("alert",'温馨提示：请选择要终止的信息！');
	    }
	}   				 
		
   };
   
    //查看
    function viewContractInfoDetail(data, type, row,   meta){
       return "<a href='#' onClick='createdetailwindow(\"查看合同信息明细\",\"viewContractInfoDetail_contractInfo.action?contractInfo.ciId=" + row.ciId + "\",1)' title='"+data+"'>"+data+"</a>"; 
    }
    //框架协议
    function viewFrameWork(data, type, row,   meta){
       if(data==0)  return "<span class=\"light-red\">协议</span>";
       else  return "<span class=\"light-green\">合同</span>";
    }
    //查看流程审批信息
	
      function viewWorkflowProcess(data, type, row,   meta ){
        if(contractWorkflow=="0"){
    	  if(row.orderState != ""){
	    		  var action="display_workflow.action?param=view&processId="+row.processId+"&orderId=";
	    		  return "<a href='#' onclick='openWorkFlowWindow(\""+action+"\","+row.ciId+",\""+row.processId+"\")'>"+data+"</a>";
    	  }else{
    		  return "起草状态";
    	  }
    	  }else{
    	    if(row.orderState=="01")  return "起草状态";
    	    else  if(row.orderState=="0")  return "已完成";
    	  }
    	  
      }
      
	//弹出一个新窗口
	function openWorkFlowWindow(action, ciId, processId){
	    ciId="${work_flow_type}"+ciId;
		$.ajax({
			url:"<%=path%>/findWfOrder_workflow.action",
			type:"POST",
			dataType: 'json',
			async:false, 
			data:{orderNo:ciId, processId:processId},
			success:function(msg){
				var rsb = msg;
				var rs = rsb.order;
				if(rs.length > 0){
					createdetailwindow("查看流程",action+rs[0].id,0);
				}else{
					return false;
				}
			},
			error:function(){
			}
		});
		
	}
    function doQuery(){
     _table.draw();
    }

</script>
</head>
<body >
<div class="container-fluid">
		<div class="row-fluid">
			<div class="span12" id="content">
				<div class="row-fluid">
					<div class="span12">
						<div class="btn-toolbar">
							<div class="pull-right">
								<div class="input-append">
									<div class="btn-group">
									    <button type="button" class="btn btn-warning" title="查询区域" id="toggle-advanced-search">
											<i class="icon-white icon-search"></i>
										</button> 
										<button type="button" class="btn btn-warning" title="刷新" id="toggle-advanced-refresh" onclick="doQuery()">
											 <i class="icon-white icon-refresh"></i>
										</button>
									</div>
								</div>
							</div>
							<button type="button" class="btn btn-info" id="btn-add"><i class="icon-white icon-plus-sign"></i> 新建合同</button>
							<button type="button" class="btn btn-info" id="btn-edit"><i class="icon-white icon-edit"></i> 修改</button>
							<button type="button" class="btn btn-danger" id="btn-del"><i class="icon-white icon-trash"></i> 删除</button>
							<c:if test="${contractWorkflow=='0'}">
							<button type="button" class="btn btn-info" id="btn-processSubmit"><i class="icon-white icon-resize-small"></i> 提交流程</button>  <!--fa fa-chain-broken icon-resize-full -->
							<button type="button" class="btn btn-warning" id="btn-processCancel"><i class="icon-white icon-resize-full"></i> 撤销流程</button>
							</c:if>
							<c:if test="${contractWorkflow=='1'}">
							<button type="button" class="btn btn-info" id="btn-Submit"><i class="icon-white icon-resize-small"></i> 提交合同信息</button>  <!--fa fa-chain-broken icon-resize-full -->
							</c:if>
							<button type="button" class="btn  btn-warning" id="btn-send"><i class="icon-white icon-file"></i> 发送至供应商</button>
							<button type="button" class="btn  btn-primary" id="btn-sign"><i class="icon-white icon-lock"></i> 合同签订</button>
							<button type="button" class="btn  btn-warning" id="btn-term"><i class="icon-white icon-remove-sign"></i> 合同终止</button>
						   </div>
					</div>
				</div>
				<div class="row-fluid" style="display:none;" id="div-advanced-search">
					<form class="form-inline well">
					<input type="hidden" id="returnValues" name="returnValues"/>
					  <!--***按需修改****-->
					          合同编号：
						<input class="input-medium" placeholder="合同编号" type="text" id="contractCode" name="contractCode" value="" />
						合同名称：
						<input class="input-medium" placeholder="合同名称" type="text" id="contractName" name="contractName" value="" />
						乙方名称：
						<input class="input-medium" placeholder="乙方名称" type="text" id="contractNameB" name="contractNameB" value="" />
						<button type="button" class="btn btn-info" id="btn-advanced-search"  ><i class="icon-white icon-search"></i> 查询</button>
						<button type="button" class="btn btn-cacel" id="btn-advanced-cacel" onclick="doReset();"><i class="icon-info-sign"></i> 重置</button>
					</form>
				</div>
				<div class="row-fluid">
					<div class="span12" id="div-table-container">
						<table class="table table-striped table-bordered table-hover table-condensed" id="table-general" cellspacing="0" width="100%">
							<thead>
								<tr>
									<th>
										<input type="checkbox"  name="cb-check-all"/>
									</th>
									<th>操作</th>
						            <th>项目名称</th>
						            <th>合同编号</th>
						            <th>合同名称</th>
						            <th>类别</th>
						            <th>乙方名称</th>
						            <th>乙方联系人</th>
						            <th>乙方电话</th>
						            <th>合同金额</th>
						            <th>起草日期</th>
						            <th>签订日期</th>
						            <th>合同状态</th>
								</tr>
							</thead>
							<tbody>
							</tbody>							
						</table>
					</div>
				</div>
			</div>
		</div>
	</div>
</body>
</html>