define(function(require){
	var $ = require('jquery');
	require('grid')($);
	var IFA=require('util');
	require('uriTemplate')($);
	require('dialog')($);
	require('cookie')($);
	require('dateTimePicker')($);
	require("../../../styles/cim/jquery-ui-1.8.14.custom.css");
	require('../../../styles/cim/cim-grid.css');
	require('../../../styles/cim/validation.css');
	require('../../../styles/cim/autoComplete.css');
	require('../../../js/seaJsExtends/autoComplete.js')($);
	var common = require('../workOrder/reservationCommon.js');
	require('../paymethod/paymentsList.js');
	$(function(){
		//初始化默认门店
		initializeDefaultDistrict();
		setTimeout(function(){
			common.getCookieData();
			searchResult();
		},300);
     	//searchResult();
		$("#search").bind("click",searchResult);
		$("#reset").bind("click",reset);
		$("#dispatcherSearchForm :input:not(#serviceHokKey,#districtHokKey)").bind("keydown",function(e){
			var e = e ? e : window.event;
			if(e.keyCode==13){
			   searchResult();
			} 
		});
		hotKeyDistrict();
		hotKeyProduct();
		//初始化日期
		initializehDate();
	
	});
	
	//初始化默认门店
	function initializeDefaultDistrict (){
		var defaultDistrictName = $.cookie("defaultDistrictName");
		var defaultDistrictId = $.cookie("defaultDistrictId");
		$("#districtHokKey").val(defaultDistrictName);
		$("#districtId").val(defaultDistrictId);
	}
	function initializehDate(){
		$("#pickupDateStart").datetimepicker({
			stepMinute:15,
			showSecond:false,
		    onSelect:function(date){
			var date=date.split("-").join("/");
			$("#pickupDateEnd").datetimepicker("option","minDate",new Date(date));
			}});
		$("#pickupDateEnd").datetimepicker({
			stepMinute:15,
			showSecond:false,
		    onSelect:function(date){
			var date=date.split("-").join("/");
			$("#pickupDateStart").datetimepicker("option","maxDate",new Date(date));
			}});
		
		$("#returnDateStart").datetimepicker({
			stepMinute:15,
			showSecond:false,
		    onSelect:function(date){
			var date=date.split("-").join("/");
			$("#returnDateEnd").datetimepicker("option","minDate",new Date(date));
			}});
		
		$("#returnDateEnd").datetimepicker({
			stepMinute:15,
			showSecond:false,
		    onSelect:function(date){
			var date=date.split("-").join("/");
			$("#returnDateStart").datetimepicker("option","maxDate",new Date(date));
			}});
	}
	
	//重置查询条件
	function reset(){
		$("#dispatcherSearchForm :input").val("");
		$("#pickupDateStart").datetimepicker("destroy");
		$("#returnDateStart").datetimepicker("destroy");
		$("#pickupDateEnd").datetimepicker("destroy");
		$("#returnDateEnd").datetimepicker("destroy");
		initializehDate();
	}
	
	//根据条件查询
	function searchResult(){
		var district = $("#districtHokKey").val();
		if(district=="" || district ==null){//修正bug（没有清空之前的districtid）
			$("#districtId").val("");
		}
		var url=$("#queryUrl").val().trim();
		$("#searchResult").grid({
			url:url,
			root:"reservationList",
			isREST :false,
			pageTheme:'Theme1',
			method:"POST",
			defaultParams:$("#dispatcherSearchForm").serialize(),
			fields:[{name:i18n["Page.workOrder.bookingNumber"],id:"orderNum",style:{width:"9%"},render:function(data){
				       return $("<a href='#' id='resId"+data.id+"' />").html(data.orderNum).click(function(){
				    	   showDetail(data.id);
				       });
				       }},
				    {name:i18n["Page.workOrder.openJobStatus"],style:{width:"5%"},render:function(data){
					    	 var status = '';
					    	 if(data.openJobStatus == null){
					    		 status = i18n["Page.mdsOpenJobsStatus.unAccepted"];
					    	 }
					    	 if(data.openJobStatus == 1){
					    		 status = i18n["Page.mdsOpenJobsStatus.accepted"];
					    	 }
					    	 if(data.openJobStatus == 2){
					    		 status = i18n["Page.mdsOpenJobsStatus.start"];
					    	 }
					    	 if(data.openJobStatus == 3){
					    		 status = i18n["Page.mdsOpenJobsStatus.pickUp"];
					    	 }
					    	 return status;
					   }},
					   {name:i18n["Page.workOrder.customName"],id:"customerName",style:{width:"6%"},render:function(data){
					    	return $("<a href='#' id=''/>").html(data.customerName).click(function(){
						    	   showCustomerDetail(data.personId,data.phonenumber);
						       });
						       }},
			        {name:i18n["JS.workOrder.paymentType"],id:"paymentType",style:{width:"5%"},render:function(data){
			        	var paymentNames = "";
			        	$.each(data.payments,function(i,item){
			        		paymentNames +=i18ns(item.name)+'<br/>';
			        	});
			        	return paymentNames;
			        }},
			        {name:i18n["Page.workOrder.serviceName"],style:{width:"8%"},render:function(data){
				        var name=data.productName;
		                if(name.length>10){
		             	    name=name.substring(0,10)+"...";
		                }
		 			    return $('<span title="'+data.productName+'" />').html(name);
				        }},
				    {name:i18n["Page.workOrder.ownedStores"],style:{width:"8%"},render:function(data){
				        var name=data.districtName;
		                if(name.length>10){
		             	    name=name.substring(0,10)+"...";
		                }
		 			    return $('<span title="'+data.districtName+'" />').html(name);
				        }},
				    {name:i18n["Page.workOrder.vehicleCategory"], id:"vehicleName",style:{width:"8%"}},
				    {name:i18n["Entity.reservation.carPlateNumber"],id:"carPlate",style:{width:"5%"}},
				    {name:i18n["Entity.report.chauffeurfullname"],style:{width:"10%"},render:function(data){
				    	var driverName = "";
				    	var driverEnName = "";
				    	var driverCnName = "";
				    	if(data.dirverENName!=null){
				    		driverEnName=data.dirverENName;
				    	}
				    	if(data.dirverCNName!=null){
				    		driverCnName = data.dirverCNName;
				    	}
				    	driverName = driverEnName + driverCnName;
				    	return driverName;
				    }},
				    {name:i18n["Page.workOrder.pickupLocation"], id:"pickupLocation",style:{width:"4%"}},
				    {name:i18n["Page.workOrder.returnLocation"],  id:"returnLocation",style:{width:"4%"}},
				    {name:i18n["JS.workOrder.pickupTime"],style:{width:"7%"},render:function(data){
			        	var pickDate=data.pickupDate;
			        	if(pickDate!=null){
			        		pickDate=new Date(pickDate).format("yyyy-MM-dd hh:mm");
			        	}
			        	return pickDate;
			        }},
			        {name:i18n["JS.workOrder.pickOffTime"],style:{width:"7%"},render:function(data){
			        	var returnDate=data.returnDate;
			        	if(returnDate!=null){
			        		returnDate=new Date(returnDate).format("yyyy-MM-dd hh:mm");
			        	}
			        	return returnDate;
			        }},
			        {name:i18n["Page.workOrder.othersDetail"],style:{width:"3%"},render:function(data){
			        	if(data.otherDesc!=null){	        		
			        		var desc = data.otherDesc;
			        		if(desc.length>10){
			        			desc=desc.substring(0,10)+"...";
			        		}
			        		return $('<span tile="'+data.otherDesc+'" />').html(desc);
			        	}
			        }},
			        {name:i18n["Entity.Operation"],style:{width:"6%"},operation:[
			                              {text:i18n["JS.workOrder.editAndDetail"],display:true,action:function(data){showDetail(data.id);}}]}
			        ],
			        callback:function(data){
				addScrollBar();
				var list = data.reservationList;	
				var l = list.length;
				for(var i=0;i<l;i++){
					if(list[i].otherDesc==null||list[i].otherDesc==""){
						$("#resId"+list[i].id).parent().parent().attr("style","background-color:#DFE8FF");
					}
				}
		   		}
			});
		common.setCookieData();
	}


	function addScrollBar(){
		   $($("#searchResult").find("table")[0]).css("width","1600px").wrap("<div style='overflow-x:scroll;overflow-y:auto;' ></div>");
	   }
	
	//显示详情
	function showDetail(id){
		var urlTemplate=$("#detailUrl").val().trim();
		var urlString=new $.Template(urlTemplate);
		var urlParam = {"id":id};
		var url=urlString.expand(urlParam);
		location.href=url;
	}
	
	//显示客户信息
	function showCustomerDetail(personId,phonenumber) {
		var urlTemplate=$("#detailUrl1").val().trim();
		var urlString=new $.Template(urlTemplate);
		var urlParam = {"id":personId,"phonenumber":phonenumber};
		var url=urlString.expand(urlParam);
		location.href=url;
	}
	
	//产品代码热键
	function hotKeyProduct(){
	  	$.ajax({
			type:"get",
			url:$("#hotkeyProduct").val(),
			success:function(response){
			var acdata=response.servicingProduct;
			$("#serviceHokKey").autocomplete(acdata,
				      {
						caption: "&nbsp;&nbsp;"+i18n["JS.productHotKey.caption"],
						findCaption: "&nbsp;,"+i18n["JS.districtHotKey.findCaption"],
						noFindCaption: "&nbsp;&nbsp;"+i18n["JS.productHotKey.noFindCaption"]+":&nbsp; ",
						width: 200,
						max: 5,
						formatItem: function(row, i, max) {
				             var title="";
				             if(row.isRestrictive == 'Y'){
				            	 var maxService=Math.floor(row.fullUsageHrs/row.avgTransactionActual);
				            	 title=i18n["JS.productHotKey.title0"]+".&#13;"+i18n["JS.productHotKey.title1"]+":"+maxService;
				             }else{
				            	 title=i18n["JS.productHotKey.title2"];
				             }
							return '<span title="{2}"><span class="ac_code" >{0}</span><span class="ac_Name" >{1}</span></span>'.patchContent(row.serviceId, row.serviceDescription,title);
						},
						formatMatch: function(row, i, max) {
							return "{0} {1}".patchContent(row.serviceId, row.serviceDescription);
						},
						formatResult: function(row) {
							return "{0}".patchContent(row.serviceDescription);
						}
					}).result(function(event, data, formatted) {
						$("#serviceId").val(data.serviceId);
					});
		}
		});
	}
	//地区热键
	function hotKeyDistrict(){
	  	$.ajax({
			type:"get",
			url:$("#hotkeyDistrict").val(),
			success:function(response){
			var acdata=response.district;
			$("#districtHokKey").autocomplete(acdata,
				      {
						caption: "&nbsp;&nbsp;"+i18n["JS.districtHotKey.caption"],
						findCaption: "&nbsp;,"+i18n["JS.districtHotKey.findCaption"],
						noFindCaption: "&nbsp;&nbsp;"+i18n["JS.districtHotKey.noFindCaption"]+":&nbsp; ",
						width: 200,
						max: 5,
						formatItem: function(row, i, max) {
							return '<span class="ac_code">{0}</span><span class="ac_Name">{1}</span>'.patchContent(row.districtHotkey, row.districtName);
						},
						formatMatch: function(row, i, max) {
							return "{0} {1}".patchContent(row.districtHotkey, row.districtName);
						},
						formatResult: function(row) {
							return "{0}".patchContent(row.districtName);
						}
					}).result(function(event, data, formatted) {
						$("#districtId").val(data.districtId);
					});
		}
		});
	}
	
});

