<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags"%>
<%@page import="com.fadu.app.util.SystemCache"%>
<c:set var="contextPath" value="${pageContext.request.contextPath}"></c:set>
<!-- 协助出函 -->
<link rel="stylesheet"
	href="${contextPath}/static/assets/css/jquery-ui.css" />
<link rel="stylesheet"
	href="${contextPath}/static/assets/css/datepicker.css" />
<link rel="stylesheet"
	href="${contextPath}/static/assets/css/ui.jqgrid.css" />
	
<style>
.hr-line-dashed {
	background-color: #ffffff;
	border-top: 1px dashed #e7eaec;
	color: #ffffff;
	height: 1px;
	margin: 20px 0;
}
</style>
<script>  
function setCity(obj){  
    var val = obj.value;  
    var sec = document.getElementById('cityId');
    sec.innerHTML = "<option value=''>全部</option>"; 
    if(val != ''){  
    	//ajax
    	$.getJSON("${contextPath}/util/getCitysByProvince?provinceId="+val,function(result){
    		$.each(result, function(i, v){
    			sec.innerHTML+="<option value='"+v.name+"'>"+v.name+"</option>";
    		});
  		});
    }     
}  
</script>

<div class="well well-sm">	
	<input type="text" class="input-sm" placeholder="搜索关键字" id="keyword" />
	<select class="select" id="orderState">
		<option value="" selected="selected">状态</option>
		<option value="0">待补单</option>
		<option value="1">已补单</option>
		<option value="2">无需求</option>
	</select>
		<input type="text" class="input-sm" placeholder="选择开始时间" id="sendStart" /> 
		<input type="text" class="input-sm"	placeholder="选择结束时间" id="sendEnd" />
	<button type="button" class="btn btn-primary btn-sm" id="searchd">
		筛选
	</button>
</div>

<div class="row">
	<div class="col-xs-12">
		<div id ="calc-result" class="bg-info" style="display:none">test</div>
		<table id="grid-table"></table>
		<div id="grid-pager"></div>
		<script type="text/javascript">
			var $path_base = "${contextPath}/static";//in Ace demo this will be used for editurl parameter
		</script>
		<!-- PAGE CONTENT ENDS -->
	</div>
	<!-- /.col -->
</div>
<!-- /.row -->
<%@include file="/WEB-INF/page/back/auth.jsp"%>
<div id="modal-edit-order" class="modal fade" tabindex="-1"
   data-backdrop="static">
   <div class="modal-dialog" style="min-width: 400px;">
      <div class="modal-content">
         <div class="modal-header no-padding">
            <div class="table-header">
               <button type="button" class="close" data-dismiss="modal"
                  aria-hidden="true">
                  <span class="white">&times;</span>
               </button>
               修改订单
            </div>
         </div>
         <div class="modal-body" id="modal-edit-order-body">
            <form id="editOrderForm" class="form-horizontal">
               <input type="hidden" name="orderId" id="mod-edit-orderId" />
               
               <div class="form-group" id="mod-edit-state-div">
                  <label class="col-sm-2 control-label">状态:</label>
                  <div class="col-sm-10 text-left">
                     <select class="select" id="mod-edit-state">
						      <option value="0">待补单</option>
						      <option value="1">已补单</option>
						      <option value="2">无需求</option>
                     </select>
                  </div>
               </div>
            </form>
         </div>
         <div class="modal-footer no-margin-top">
            <div class="text-center">
               <button id="modal-edit-order-submit" type="button"
                  class="btn btn-sm btn-primary">
                  <i class="ace-icon fa fa-floppy-o bigger-160"></i> 保存
               </button>
               <button class="btn btn-sm" data-dismiss="modal">
                  <i class="ace-icon fa fa-share bigger-160"></i> 取消
               </button>
            </div>
         </div>
      </div>
   </div>
</div>
<!-- page specific plugin scripts -->
<script type="text/javascript">
		var hiddenModalBody = null;
		var myGrid = null;
			 			 
		var scripts = [ null, "${contextPath}/static/assets/js/date-time/bootstrap-datepicker.js",
		                "${contextPath}/static/assets/js/date-time/locales/bootstrap-datepicker.zh-CN.js",
		                "${contextPath}/static/assets/js/jqGrid/jquery.jqGrid.js", 
		                "${contextPath}/static/assets/js/jqGrid/i18n/grid.locale-cn.js",
		                "${contextPath}/static/assets/js/lazyload/jquery.lazyload.js",
		                null ]
		
        $('.page-content-area').ace_ajax('loadScripts', scripts, function() {
        	// inline scripts related to this page
        	jQuery(function($) {
        		var grid_selector = "#grid-table";
        		var pager_selector = "#grid-pager";

        		// resize to fit page size
        		$(window).on('resize.jqGrid', function() {
        			$(grid_selector).jqGrid('setGridWidth', $(".page-content").width());
        		});
        		// resize on sidebar collapse/expand
        		var parent_column = $(grid_selector).closest('[class*="col-"]');
        		$(document).on('settings.ace.jqGrid', function(ev, event_name, collapsed) {
        			if (event_name === 'sidebar_collapsed' || event_name === 'main_container_fixed') {
        				// setTimeout is for webkit only to give time for DOM changes and then redraw!!!
        				setTimeout(function() {
        					$(grid_selector).jqGrid('setGridWidth', parent_column.width());
        				}, 0);
        			}
        		});
        		
			$("#searchd").click(function(){
				var keyword =$("#keyword").val();
				var state = $("#orderState").val();
				var sendStart = $("#sendStart").val();
				var sendEnd = $("#sendEnd").val();
				
		    	myGrid.setGridParam({postData:{'keyword':keyword,'state':state,'sendStart':sendStart,'sendEnd':sendEnd},
		    		url : '${contextPath}/sys/ssdbOrderrep/getOrder'}).trigger('reloadGrid');
			});
        	myGrid = jQuery(grid_selector).jqGrid({
        			subGrid : false,
        			url : "${contextPath}/sys/ssdbOrderrep/getOrder",
        			datatype : "json",
        			height : "auto",
        			mtype: 'POST',
        			
        			colModel : [ {
        				name : 'createDate',//1449829970000
        				index : 'createDate',
        				label : '订单时间',
        				width : 120,
        				search : false,
        				editable : false,
        				formatter : formatCreateDate
        		    },{
                   name : 'orderId',
                   index : 'orderId',
                   label : '订单号',
                   width : 140,
                   editable : false,
                   hidden : true
                },{
                  name : 'lawyerName',
                  index :'lawyerName',
                  label : '律师',
                  width :80,
               },{
                  name : 'contactNumber',
                  index :'contactNumber',
                  label : '电话',
                  width :120,
               },{
        				name : 'loginName',
        				label : '公司登录名',
        				width : 120,
        			},{
        				name : 'companyName',
        				label : '公司',
        				width : 120,
        			},{
        				name : 'courtName',
        				index :'courtName',
        				label : '法院',
        				width :180,
        			},{
        				name : 'bd',
        				label : '标的',
        				width :100,
        				search : false
        			},{
        				name : 'fee',
        				label : '保费',
        				width :100,
        				search : false,
        			},{
        				name : 'commision',
        				label : '返现比例',
        				width :100,
        				search : false,
        			},{
                  name : 'orderServiceType',
                  label : '订单类型',
                  width : 110,
               },{
                   name : 'orderShippingType',
                   label : '订单配送方式',
                   width : 110,
                },{
        				name : 'stateName',
        				label : '订单状态',
        				width : 110,
        			},{
        				name : 'id',
        				index : '',
        				label : '操作',
        				width : 150,
        				editable : false,
        				search : false,
        				sortable : false,
          			fixed:true,
        				formatter : optionFormatter
        			}],
        			//scroll : 1, // set the scroll property to 1 to enable paging with scrollbar - virtual loading of records
        			sortname : "createDate",
        			sortorder : "desc",
        			viewrecords : true,
        			rowNum : 30,
        			rowList : [ 30, 100, 500 ],
        			pager : pager_selector,
        			altRows : true,
        			//toppager : true,
        			//multiselect : true,
        			//multikey : "ctrlKey",
        	        //multiboxonly : true,
        			loadComplete : function() {
        				var table = this;
        				setTimeout(function(){
        					styleCheckbox(table);
        					updateActionIcons(table);
        					updatePagerIcons(table);
        					enableTooltips(table);
        				}, 0);
        			},
        			//caption : "用户管理列表",
        			//autowidth : true,
        			/**
        			grouping : true, 
        			groupingView : { 
        				 groupField : ['name'],
        				 groupDataSorted : true,
        				 plusicon : 'fa fa-chevron-down bigger-110',
        				 minusicon : 'fa fa-chevron-up bigger-110'
        			},
        			*/
        		});
        	
	        	function formatCommentFlag(cellvalue, options, rowObject){
	     			if(cellvalue==1)
						return "已评论";
	     			if(cellvalue==1)
						return "未评论";
					return "";
				}
	        	
	        	function formatCreateDate(cellvalue, options, rowObject){
	        		var result = "";
	        		if(cellvalue != null){
	        			var d = new Date(cellvalue);
	        			result = d.getFullYear() + '-' + formatDate(d.getMonth() + 1) + "-" + formatDate(d.getDate()) + ' ' + formatDate(d.getHours()) + ":" + formatDate(d.getMinutes()) + ":" + formatDate(d.getSeconds());
	        		}
	        		return result;
	        	}
	        	
	        	function formatDate(d){
	        		var result = "";
	        		if(d > 9){
	        			result = d.toString();
	        		}else{
	        			result = '0' + d.toString();
	        		}
	        		return result;
	        	}

	     		function optionFormatter(cellvalue, options, cell) {
	     			var template = "<button data-toggle='modal' onclick='showdetail(\""+cell.orderId+
	     					"\")' class='btn btn-minier btn-yellow'><i class='ace-icon fa fa-hdd-o '></i>去补单</button>&nbsp;|&nbsp;";
	     					
	     			template += "<button data-toggle='modal' onclick='showEditOrder(\""+cell.orderId+
	     					"\")' class='btn btn-minier btn-yellow'><i class='ace-icon fa fa-hdd-o '></i>修改</button>";
	     			return template;
	     		}
	     		
        		$(window).triggerHandler('resize.jqGrid');// trigger window resize to make the grid get the correct size
        		// enable search/filter toolbar
        		// jQuery(grid_selector).jqGrid('filterToolbar',{defaultSearch:true,stringResult:true})
        		// jQuery(grid_selector).filterToolbar({});
        		// switch element when editing inline
        		function aceSwitch(cellvalue, options, cell) {
        			setTimeout(function() {
        				$(cell).find('input[type=checkbox]').addClass('ace ace-switch ace-switch-5').after('<span class="lbl"></span>');
        			}, 0);
        		}
        		// navButtons
        		jQuery(grid_selector).jqGrid('navGrid', pager_selector, { // navbar options
        			edit : false,
        			editicon : 'ace-icon fa fa-pencil blue',
        			add : false,
        			addicon : 'ace-icon fa fa-plus-circle purple',
        			del : false,
        			delicon : 'ace-icon fa fa-trash-o red',
        			search : false,
        			searchicon : 'ace-icon fa fa-search orange',
        			refresh : true,
        			refreshicon : 'ace-icon fa fa-refresh blue',
        			view : false,
        			viewicon : 'ace-icon fa fa-search-plus grey'
        		}, {
        			// edit record form
        			// closeAfterEdit: true,
        			// width: 700,
        			recreateForm : true,
        			beforeShowForm : function(e) {
        				var form = $(e[0]);
        				form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
        				style_edit_form(form);
        			},
    				errorTextFormat: function (response) {
    					var result = eval('('+response.responseText+')');
    				    return result.message;
    				}
        		}, {
        			// new record form
        			// width: 700,
        			closeAfterAdd : true,
        			recreateForm : true,
        			viewPagerButtons : false,
        			beforeShowForm : function(e) {
        				var form = $(e[0]);
        				form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
        				style_edit_form(form);
        			},
    				errorTextFormat: function (response) {
    					var result = eval('('+response.responseText+')');
    				    return result.message;
    				}
        		}, {
        			// delete record form
        			recreateForm : true,
        			beforeShowForm : function(e) {
        				var form = $(e[0]);
        				if (form.data('styled'))
        					return false;
        				form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
        				style_delete_form(form);
        				form.data('styled', true);
        			},
        			onClick : function(e) {
        				// alert(1);
        			}
        		}, {
        			// search form
        			recreateForm : true,
        			afterShowSearch : function(e) {
        				var form = $(e[0]);
        				form.closest('.ui-jqdialog').find('.ui-jqdialog-title').wrap('<div class="widget-header" />')
        				style_search_form(form);
        			},
        			afterRedraw : function() {
        				style_search_filters($(this));
        			},
        			multipleSearch : true 
	        		/**
	        		 * multipleGroup:true, showQuery: true
	        		 */
        		}, {
        			// view record form
        			recreateForm : true,
        			beforeShowForm : function(e) {
        				var form = $(e[0]);
        				form.closest('.ui-jqdialog').find('.ui-jqdialog-title').wrap('<div class="widget-header" />')
        			}
        		})
        		
        		
        		function style_edit_form(form) {
        			// form.find('input[name=statusCn]').addClass('ace ace-switch ace-switch-5').after('<span class="lbl"></span>');
        			// don't wrap inside a label element, the checkbox value won't be submitted (POST'ed)
        			// .addClass('ace ace-switch ace-switch-5').wrap('<label class="inline" />').after('<span class="lbl"></span>');

        			// update buttons classes
        			var buttons = form.next().find('.EditButton .fm-button');
        			buttons.addClass('btn btn-sm').find('[class*="-icon"]').hide();// ui-icon, s-icon
        			buttons.eq(0).addClass('btn-primary').prepend('<i class="ace-icon fa fa-check"></i>');
        			buttons.eq(1).prepend('<i class="ace-icon fa fa-times"></i>')

        			buttons = form.next().find('.navButton a');
        			buttons.find('.ui-icon').hide();
        			buttons.eq(0).append('<i class="ace-icon fa fa-chevron-left"></i>');
        			buttons.eq(1).append('<i class="ace-icon fa fa-chevron-right"></i>');
        		}

        		function style_delete_form(form) {
        			var buttons = form.next().find('.EditButton .fm-button');
        			buttons.addClass('btn btn-sm btn-white btn-round').find('[class*="-icon"]').hide();// ui-icon, s-icon
        			buttons.eq(0).addClass('btn-danger').prepend('<i class="ace-icon fa fa-trash-o"></i>');
        			buttons.eq(1).addClass('btn-default').prepend('<i class="ace-icon fa fa-times"></i>')
        		}

        		function style_search_filters(form) {
        			form.find('.delete-rule').val('X');
        			form.find('.add-rule').addClass('btn btn-xs btn-primary');
        			form.find('.add-group').addClass('btn btn-xs btn-success');
        			form.find('.delete-group').addClass('btn btn-xs btn-danger');
        		}
        		function style_search_form(form) {
        			var dialog = form.closest('.ui-jqdialog');
        			var buttons = dialog.find('.EditTable')
        			buttons.find('.EditButton a[id*="_reset"]').addClass('btn btn-sm btn-info').find('.ui-icon').attr('class', 'ace-icon fa fa-retweet');
        			buttons.find('.EditButton a[id*="_query"]').addClass('btn btn-sm btn-inverse').find('.ui-icon').attr('class', 'ace-icon fa fa-comment-o');
        			buttons.find('.EditButton a[id*="_search"]').addClass('btn btn-sm btn-purple').find('.ui-icon').attr('class', 'ace-icon fa fa-search');
        		}

        		function beforeDeleteCallback(e) {
        			var form = $(e[0]);
        			if (form.data('styled'))
        				return false;
        			form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
        			style_delete_form(form);
        			form.data('styled', true);
        		}

        		function beforeEditCallback(e) {
        			var form = $(e[0]);
        			form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
        			style_edit_form(form);
        		}

        		// it causes some flicker when reloading or navigating grid
        		// it may be possible to have some custom formatter to do this as the grid is being created to prevent this
        		// or go back to default browser checkbox styles for the grid
        		function styleCheckbox(table) {
        			/**
        			 * $(table).find('input:checkbox').addClass('ace') .wrap('<label />') .after('<span class="lbl align-top" />') $('.ui-jqgrid-labels th[id*="_cb"]:first-child')
        			 * .find('input.cbox[type=checkbox]').addClass('ace') .wrap('<label />').after('<span class="lbl align-top" />');
        			 */
        		}

        		// unlike navButtons icons, action icons in rows seem to be hard-coded
        		// you can change them like this in here if you want
        		function updateActionIcons(table) {
        			/**
        			 * var replacement = { 'ui-ace-icon fa fa-pencil' : 'ace-icon fa fa-pencil blue', 'ui-ace-icon fa fa-trash-o' : 'ace-icon fa fa-trash-o red', 'ui-icon-disk' : 'ace-icon fa fa-check green', 'ui-icon-cancel' :
        			 * 'ace-icon fa fa-times red' }; $(table).find('.ui-pg-div span.ui-icon').each(function(){ var icon = $(this); var $class = $.trim(icon.attr('class').replace('ui-icon', '')); if($class in replacement)
        			 * icon.attr('class', 'ui-icon '+replacement[$class]); })
        			 */
        		}

        		// replace icons with FontAwesome icons like above
        		function updatePagerIcons(table) {
        			var replacement = {
        				'ui-icon-seek-first' : 'ace-icon fa fa-angle-double-left bigger-140',
        				'ui-icon-seek-prev' : 'ace-icon fa fa-angle-left bigger-140',
        				'ui-icon-seek-next' : 'ace-icon fa fa-angle-right bigger-140',
        				'ui-icon-seek-end' : 'ace-icon fa fa-angle-double-right bigger-140'
        			};
        			$('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function() {
        				var icon = $(this);
        				var $class = $.trim(icon.attr('class').replace('ui-icon', ''));

        				if ($class in replacement)
        					icon.attr('class', 'ui-icon ' + replacement[$class]);
        			})
        		}

        		function enableTooltips(table) {
        			$('.navtable .ui-pg-button').tooltip({
        				container : 'body'
        			});
        			$(table).find('.ui-pg-div').tooltip({
        				container : 'body'
        			});
        		}

        		// var selr = jQuery(grid_selector).jqGrid('getGridParam','selrow');

        		$(document).one('ajaxloadstart.page', function(e) {
       			$(grid_selector).jqGrid('GridUnload');
       			$('.ui-jqdialog').remove();
        		});
        		
    		    $('#sendStart').datepicker({
    		        language: 'zh-CN',
    		        pickTime: false,
    		        todayBtn: true,
    		        autoclose: true,
    		        minView: '2',
    		        forceParse: false,
    		        format:"yyyy-mm-dd"
    		    });
    			$('#sendEnd').datepicker({
    		        language: 'zh-CN',
    		        pickTime: false,
    		        todayBtn: true,
    		        autoclose: true,
    		        minView: '2',
    		        forceParse: false,
    		        format:"yyyy-mm-dd"
    		    }); 			
        	});
        });
		
		function checkNotDate(dateStr){
			var result = false;
			var re = /^(\d{4})-(\d{2})-(\d{2})$///正则表达式
		    if(!re.test(dateStr)){
		       result = true;
		    }
		    return result;
		}
		
		function formatStr(str){
			var result = '';
			if(str != undefined && str != null){
				result = str;
			}
			return result;
		}

		function initModalTableBody(){
			$('#modal-table-body').html(hiddenModalBody);
		}
		
		function isNotBlank(obj){
			var result = true;
			if(obj == undefined || obj == null || obj == 'null' || obj.length < 1){
				result = false;
			}
			return result;
		}
		
		function isNotDouble(obj){
			var reg = /\d+(\.\d+)?/; 
			return !reg.test(obj);
		}
		
		function isNotNumber(obj){
			var reg = /^[0-9]*[1-9][0-9]*$/; 
			return !reg.test(obj);
		}
		
		function isNotNaturalNumber(obj){
			var reg = /^[0-9]+$/;
			return !reg.test(obj);
		}
				
      function showEditOrder(orderId){
         $('#mod-edit-orderId').val(orderId);
         $("#modal-edit-order").modal("toggle");
      }
      
      $('#modal-edit-order-submit').click(function(event) {
          editOrder();
       });
      
      function showdetail(){
    	  window.location.href="${contextPath}/sys/sysuser/home#page/ssdbOrder";
    	  //alert("请前往诉宝订单信息模块进行补单！");
      }
      function editOrder(){
         $.ajax({
            dataType : "json",
            url : "${contextPath}/sys/ssdbOrderrep/editOrder",
            type : "post",
            data : {
               'orderId' : $('#mod-edit-orderId').val(),
               'state' : $('#mod-edit-state').val()
            },
            complete : function(ret) {
               var ret = eval("(" + ret.responseText + ")");
               if(ret.success){
                  $("#modal-edit-order").modal("toggle");
                  alert('保存成功');
                  myGrid.trigger("reloadGrid");
               }else{
                  alert(ret.message);
               }
            }
         });
      }      
	      
		function exportOrder(){
			var keys = [], ii = 0, rows = "";
			var grid_selector = "#grid-table";
		 	var ids = $(grid_selector).getDataIDs(); // Get All IDs
			var row = $(grid_selector).getRowData(ids[0]); // Get First row to get the labels
			
			for (var k in row) {
				keys[ii++] = k; // capture col names
				rows = rows + k + "\t"; // output each Column as tab delimited
			}
			rows = rows + "\n"; // Output header with end of line
			for (i = 0; i < ids.length; i++) {
				row = $(grid_selector).getRowData(ids[i]); // get each row
				//var rowData = $('#gridTable').jqGrid('getRowData',rowId);
				for (j = 0; j < keys.length-1; j++){
					rows = rows + row[keys[j]] + "\t"; // output each Row as tab delimited
				}					
				rows = rows + "\n"; // output each row with end of line
			}
			rows = rows + "\n"; // end of line at the end
			var form = "<form name='csvexportform' action='${contextPath}/sys/ssdbOrder/operateOrder?oper=excel' method='post'>";
			form = form + "<input type='hidden' name='csvBuffer' value='" + encodeURIComponent(rows) + "'>";
			form = form + "</form><script>document.csvexportform.submit();</sc" + "ript>";
			OpenWindow = window.open('', '');
			OpenWindow.document.write(form);
			OpenWindow.document.close();
		}
		
</script>
