define(function(require){
	var $ = require('jquery');
	require('uriTemplate')($);
	require('dialog')($);
	require('datepicker')($);
	require('validation')($);
	require('grid')($);
	var IFA = require('util');
	require('../../../styles/cim/jquery-ui-1.8.14.custom.css');
	require('../../../styles/cim/cim-grid.css');
	require('../../../styles/cim/autoComplete.css');
	require('../../../js/seaJsExtends/autoComplete.js')($);
	$(function(){
		searchResult();
		hotKeyCompany();
		
		$("#reset").bind("click",reset);
		$("#searchBtn").bind("click",searchResult);
		$("#new").bind("click",newProductPrice);
		$("#import").bind("click",importData);
		$("#export").bind("click",exportData);
		$("#exportAll").bind("click",exportAllData);
		
		$("#deleteBatch").bind("click",batchDelete);
		
	});
	//条件导出数据
	function exportData(){
		var ratetype=$("#productType").find("option:selected").text();
		var url="";
		if(ratetype=="APT transfer"){
			url=$("#aptExportUrl").val().trim();
			$("#searchFrom").attr("action",url);
			$("#searchFrom").submit();
		}
		if(ratetype=="Chauffeur drive"||ratetype=="self-drive"){
			url=$("#cdsdExport").val().trim();
			$("#searchFrom").attr("action",url);
			$("#searchFrom").submit();
		}
		if(ratetype=="Inter City"||ratetype=="Cross Border"){
			url=$("#cityExportUrl").val().trim();
			$("#searchFrom").attr("action",url);
			$("#searchFrom").submit();
		}
	}
	//导出所有数据
	function exportAllData(){
		location.href=$("#exportAllUrl").val().trim();
	}
		//跳转到导出页面
	function importData(){
		location.href=$("#importUrl").val().trim();
	}
	
	//新建
	function newProductPrice(){
		var newRate =$("#newUrl").val();
		window.location.href=newRate;
	}
	
	
	//根据条件查询
	function searchResult(){
		var url=$("#queryUrl").val().trim();
		$("#selectProductType").val($("#productType").val());
		$("#searchResult").grid({
			url:url,
			root:"rateResults",
			pageTheme:'Theme1',
			isREST :false,
			method:"post",
			defaultParams:$("#searchFrom").serialize(),
			fields:[
			        {id:"id",name:"id",style:'width:2%',type:"checkbox"},
			        {name:i18n["RateSheet.ProductPrce.CDP"],id:"cdp",style:{width:"4%"},render:function(data){
			        	if(data.cdp == -1){
			        		return "";
			        		}
			        	else{
			        		return data.cdp;
			        	}
			        }},
			        {name:i18n["RateSheet.ProductPrce.VehicleCategory"],id:"carCategory",style:{width:"11%"}},
			        {name:i18n["Entity.Enquire.ServiceType"],id:"category",style:{width:"11%"}},
			        {name:i18n["RateSheet.ProductPrce.productCode"],id:"pccode",style:{width:"8%"},render:function(data){
			        	if(data.pccode == -1){
			        		return "";
			        		}
			        	else{
			        		return data.pccode;
			        	}
			        }},
			        {name:i18n["Entity.Enquire.PickupLocation"],id:"pickupLocation",style:{width:"8%"}},
			        {name:i18n["Entity.Enquire.ReturnLocation"],id:"dropoffLocation",style:{width:"8%"}},
			        {name:i18n["RateSheet.ProductPrce.hireTime"],id:"timeDescription",style:{width:"9%"}},
			        {name:i18n["RateSheet.ProductPrce.privce"],id:"price",style:{width:"6%"},render:function(data){
			        	if(data.price == -1){
			        		return "";
			        		}
			        	else{
			        		return "￥" + data.price;
			        	}
			        }},
			        {name:i18n["RateSheet.ProductPrce.outNumberkilometerFee"],id:"extraKmCharge",style:{width:"6%"},render:function(data){
			        	if(data.extraKmCharge == -1){
			        		return "";
			        		}
			        	else{
			        		return "￥" + data.extraKmCharge;
			        	}
			        }},
			        {name:i18n["RateSheet.ProductPrce.overTimeFee"],id:"extraHourCharge",style:{width:"5%"},render:function(data){
			        	if(data.extraHourCharge == -1){
			        		return "";
			        		}
			        	else{
			        		return "￥" + data.extraHourCharge;
			        		
			        	}
			        }},
			        {name:i18n["RateSheet.productPrice.maxKmPerDay"],id:"kilometerLimit",style:{width:"7%"}},
			        {name:i18n["RateSheet.productPrice.maxHoursPerDay"],id:"serviceHoursLimit",style:{width:"7%"}},
			        {name:i18n['Entity.Operation'],style:{width:"12%"},operation:[
			        			                                              
											  {text:i18n['Entity.page.edit'],display:function(){
												  		
													  return true;
												
											  },action:function(data){editRate(data.id,data.productType);}},
											  {text:i18n['Entity.page.Delete'],display:function(){
												
													  return true;
												
											  },action:function(data){deleteRate(data.id,data.productType);}}]}
				    
			        ] 
			});
		
	}

		$("#productType").change(function(){
		  var status = $("#productType").val();
		  //CS-DS
		  if(status == 1 || status == 2){
			  $("#hours").attr("disabled",false);
			  $("#dropoffLocation").attr("disabled",true);
			  $("#dropoffLocation").val("");
		  }
		  //intercity
		  else if (status == 3 || status == 4){
			  $("#hours").attr("disabled",true);
			  $("#dropoffLocation").removeAttr("disabled");		
		  }
		  else{
			  $("#hours").attr("disabled",true);
			  $("#dropoffLocation").attr("disabled",true);
			  $("#dropoffLocation").val("");
		  }		
		}
	);
	function hotKeyCompany(){
		
		//产品代码		
		$.ajax({
			type:"post",
			url:$("#HotkeyPCcode").val().trim(),
			data:{hotKey:""},
			success:function(response){
			var pc= response.pc;
			$("#productCode").autocomplete(pc,
				      {
						caption: "&nbsp;&nbsp;"+i18n["JS.pcHotKey.caption"],
						findCaption: "&nbsp;,"+i18n["JS.districtHotKey.findCaption"],
						noFindCaption: "&nbsp;&nbsp;"+i18n["JS.pcHotKey.noFindcaption"]+":&nbsp; ",
						max: 5,
						selectedFirst:true,
						width: 200,
						formatItem: function(row, i, max) {
				             var title=row.pcRemarks;
				             var content=row.pcRemarks;
				             if(row.pcRemarks.length>10){
				            	 content= row.pcRemarks.substring(0,15)+"...";
				             }
							return '<span title="{2}"><span class="ac_code" >{0}</span><span class="ac_Name">{1}</span></span>'.patchContent(row.pcId,content,title);
						},
						formatMatch: function(row, i, max) {
							return "{0} {1}".patchContent(row.pcId, row.pcRemarks);
						},
						formatResult: function(row) {
							return "{0}".patchContent(row.pcId);
						}
					}).result(function(event, data, formatted) {
						
					});
			}
		});
		
		
		var url=$("#companyCdpUrl").val();
		
		$.ajax({
			type:"get",
			url:url,
			success:function(response){
			$("#cdp").autocomplete(response.company,
				      {
						caption: i18n["JS.districtHotKey.caption"],
						findCaption: i18n["JS.districtHotKey.findCaption"],
						noFindCaption: i18n["JS.companyHotKey.noFindCaption"],
						max: 5,
						width: 200,
						formatItem: function(row, i, max) {
				             var cpdNo="cdpNo:"+row.cdpNo+"&#13;";
				             var companyName=i18n["JS.companyHotKey.coName"]+row.companyName+"&#13;";
				             var companyHotkey=i18n["JS.companyHotKey"]+row.companyHotkey+"&#13;";
				             var companyAddress=i18n["JS.companyHotKey.coAddr"]+row.companyAddress+"&#13;";
				             var companyContact1st=i18n["JS.companyHotKey.coContact"]+row.companyContact1st+"&#13;";
				             var title=cpdNo+companyName+companyHotkey+companyAddress+companyContact1st;
				             var companyName=row.companyName+"("+row.companyHotkey+")";
							return '<span title="{2}"><span class="ac_code" >{0}</span><span class="ac_Name">{1}</span></span>'.patchContent(row.cdpNo,companyName,title);
						},
						formatMatch: function(row, i, max) {
							return "{0} {1} {2}".patchContent(row.cdpNo,row.companyHotkey,row.companyName);
						},
						formatResult: function(row) {
							return "{0}".patchContent(row.cdpNo);
						}
					}).result(function(event, data, formatted) {
						$("#cdp").html(data.cdpNo);
					});
		}
		});
	}
	
	/**
	 * 编辑
	 */
	function editRate(id,productType){
		var url = $("#editUrl").val();
		var temple = new $.Template(url);
		var params = {"id":id,"productType":productType};
		url = temple.expand(params);
		location.href=url;	
	}


function deleteRate(id,productType){
	$.msg.confirm(i18n['Page.title.deleteSure'],function(result){
		if(result){
			$.ajax({
				type:"post",
				url:$("#deleteUrl").val().trim(),
				async:false,
				data:{"id":id,"productType":productType,'_method':'DELETE'},
				dataType:"json",
				timeout:3000,
				success:function(response,ioArgs){
					$.msg.alert(i18n['Entity.page.Delete.Success']);
					searchResult();
				},
				error:function(){
					$.msg.alert(i18n['Entity.page.Delete.Failed']);
				}
			});
		}
	});
}
	function reset(){
	$("#searchFrom :input").val("");
	$("#carCategory").attr("checked",false);
	$("#productType").attr("checked",false);	
	$("#hours").attr("disabled",true);
	$("#dropoffLocation").attr("disabled",true);
	}
	
	  // 批量删除
	  function batchDelete(){
	  	var ids = getCheckedIds(this);
	  	// 用户未选择删除项
	  	if(ids.length==0){
	  		$.msg.alert(i18n["Page.title.dialogshow.title"], i18n["Page.warnning.tips"],{
		  			 buttons: IFA.generateJson(i18n["Entity.Operation.ok"], function() {
			               $(this).dialog("close");
			           }),
	  		        width:350,height:150
	  			});
	  	}else{
	  		var selectProductType = $("#selectProductType").val();
	  		$.msg.confirm(i18n['Page.title.deleteSure'],function(result){
	  			if(result){
	  				$.ajax({
	  					type:"post",
	  					url:$("#deleteBatchUrl").val().trim(),
	  					async:false,
	  					data:{"id":ids,"productType":selectProductType,'_method':'DELETE'},
	  					dataType:"json",
	  					timeout:3000,
	  					success:function(response,ioArgs){
	  						$.msg.alert(i18n['Entity.page.Delete.Success']);
	  						searchResult();
	  					},
	  					error:function(){
	  						$.msg.alert(i18n['Entity.page.Delete.Failed']);
	  					}
	  				});
	  			}
	  		});
	  	}
	  }
	  // 获取用户选择的Id(字符串形式),(通过选择checkbox)
	  function getCheckedIds(context){
	  	var ids = "";
	  	$("#searchResult").find(":checkbox[name='id'][checked]").each(function(i,data){
	  		ids = ids + data.value.toString()+",";
	  	});
	  	return ids;
	  }
});