define(function(require){
	var $ = require('jquery');
	var IFA = require('util');
	require('uriTemplate')($);
	require('validation')($);
	require('dialog')($);
	require('jqueryCSS');
	require('dateTimePicker')($);
	//记录最初的升级车组的id,查询后恢复用
	var upgradeId=$("#upgradeCategoryId").val()||-1;
	$(function(){
		window.name = "vehicleConditionDetailEdit";
		
		bindEvent();
		initData();
		$("#dispatchForm").validate({
			rules:{
			vehicle:{
			required:true	
			},
			driver:{
			required:true	
			}
			},
			messages:{
			vehicle:{
			required:i18ns("VehicleConditionMap.Validate.vehicle")	
			},
			driver:{
			required:i18ns("VehicleConditionMap.Validate.driver")	
			}	
			}
			});
		searchVehicle.lastHasBeenClick = false;
	});
	
	function initData(){
		bindVehicle();
	}
	function bindEvent(){
		
//		$("#isApplyAll").bind('change', function(){
//			if(searchVehicle.lastHasBeenClick == true){
//				searchVehicle();
//			}else{
//				bindVehicle();
//			}			
//			});
		$("#perLock").bind('change',function(){
			if(searchVehicle.lastHasBeenClick == true){
				searchVehicle();
			}else{
				initData();
			}			
			});
		$("#afterLock").bind('change',function(){
			if(searchVehicle.lastHasBeenClick == true){
				searchVehicle();
			}else{
				initData();
			}			
			});
		$("#vehicle").bind('change',bindDriver);
		$("#driver").bind('change',bindVehicle);
		$("input[name='selectType']").bind('change',initData);
		$("#upgradeVehicle").bind('click',upgradeVCategory);
		$("#searchVehicle").bind('click',showSearchVehicle);
		$("#searchChauffeur").bind('click',showSearchChauffeur);
		$("#btnSave").bind('click',todispatch);
		$("#searchPlateNumber").bind('click',function(){
			if ($("#plateNumber").val() == "") {
				var selectedCategoryId=upgradeId;
				if (selectedCategoryId==null||selectedCategoryId ==-1||selectedCategoryId==categoryId) {
					$("#tdCategory").find("option[value=-1]").attr(
							"selected", true);			
					$("#thCategory").hide();
					$("#tdCategory").hide();
				}else{
					$("#tdCategory").find("option[value=" + selectedCategoryId + "]").attr(
							"selected", true);
					$("#thCategory").show();
					$("#tdCategory").show();
				}
				bindVehicle();				
			}else{
				searchVehicle();
			}
		});
		$("#upgradeCategoryId").bind('change',function() {
			bindVehicle();
		});
		
		$("#back").bind("click",function(){
			window.open(document.referrer,"vehicleConditionDetail");
		});
		
		$("#lockDate").datetimepicker({
			stepMinute:15,
			showSecond:false,
			onSelect:function(){
			var date=$(this).datetimepicker("getDate");
			var returnDate = $("#unlockDate").datetimepicker("getDate");
			var returnDateShow;
			if(returnDate){
			  returnDateShow = $("#unlockDate").val();
			}
			$("#unlockDate").datetimepicker("option","minDate",new Date(date.getTime()));
			$("#unlockDate").datetimepicker("option","minDateTime",new Date(date.getTime()));
			if(returnDate){
			if(date.getTime()>returnDate.getTime()){
				$("#unlockDate").val($(this).val());
			}else{
				$("#unlockDate").val(returnDateShow);
			}
			}
			$("#dispatchForm").validate().element("#lockDate");
		}
		});
		$("#unlockDate").datetimepicker({
			stepMinute:15,
			showSecond:false,
			onSelect:function(date){
			var date=$(this).datetimepicker("getDate");
			var pickupDate = $("#lockDate").datetimepicker("getDate");
			var pickupDateShow;
			if(pickupDate){
				pickupDateShow = $("#lockDate").val();
			}
			$("#lockDate").datetimepicker("option","maxDate",new Date(date.getTime()));
			$("#lockDate").datetimepicker("option","maxDateTime",new Date(date.getTime()));
			if(pickupDate){
			if(date.getTime()<pickupDate.getTime()){
				$("#lockDate").val($(this).val());
			}else{
				$("#lockDate").val(pickupDateShow);
			}
			}
			$("#dispatchForm").validate().element("#unlockDate");
			}
		});
		$("#return").bind("click",function(){
			window.returnValue=0;
			window.close();}
		);
	}
	function initData(){
		$("#vehicle").val("");
		$("#driver").val("");
		bindVehicle();
		bindDriver();
	}
	function showSearchChauffeur(){
			$("#cnName").show();
			$("#searchChauffeurNameBTN").show();
	    }
	$("#searchChauffeurNameBTN").bind('click',function(){
			var disType=$("input:checked[name='selectType']").val();
			if(disType==1){
				 $("#vehicleId").val(''); 
	        	 $("#vehicle").val('');
			}
			bindDriver();
		});
	
	function upgradeVCategory(){
		$("#thCategory").show();
		$("#tdCategory").show();
		$("#thUpgradeReason").show();
		$("#tdUpgradeReason").show();
	}

	function searchVehicle(){
		$("#searchVehicleId").show();
	}
	
	 function todispatch(){
     	if($("#dispatchForm").valid()){
     		 //当isApplyAll选中时，先检查下各子订单的冲突情况，有冲突时提示用户，确认后提交
     	    var isApplyAll=document.getElementById("isApplyAll").checked;
     	    if(isApplyAll==true){
         		$.ajax({
     				type:"POST",
     				url:$("#queryConflictVehicle").val(),
     				data: $("#dispatchForm").serialize(),
     				success:function(response,ioArgs){
     					if(response.total>0){
     						//存在有冲突的订单
     						var temp=i18ns('page.workOrder.confirmSubmit');
     						for(var i=0;i<response.total;i++){
     							temp+=response.reservation[i].rentalNo+";";
     						}
     						$.msg.alert(i18ns('Page.title.warning'),temp,function(){},{buttons:
     							IFA.generateJson(i18ns('ConditionMap.ok'),function(){
     								submitForm();
     						},
     						i18ns('ConditionMap.cancel'),function(){
     							$(this).dialog('close');
     						}
     						)});
     					}else{
     						submitForm();
     					}
     				},
     				error:function(){
     					$.msg.alert('error');
     				}
     			});
     	    }else{
         		submitForm();
         	}
     	}
 }
 function  submitForm(){

		var url = $("#dispatchForm").attr('action');
		
 	if($("#dispatchForm").valid()){
 		$.ajax({
				type:"POST",
				url:url + ".json",
				data: $("#dispatchForm").serialize(),
				success:function(response,ioArgs){
					if(response.result == -1){
						   $.msg.alert(i18ns('Page.Dialog.title'),i18ns("VehicleConditionMap.nonbusinessExist"));
					} else if(response.result == 0){
						$.msg.alert(i18ns('ConditionMap.reDispatch.success'),function(){window.returnValue=1;self.close();},{buttons:
							IFA.generateJson(i18ns('ConditionMap.ok'),function(){
								window.returnValue=1;
								self.close();
								})
							}
						);	
					}
				},
				error:function(response,ioArgs){
					$.msg.alert('error');
				}
			});
 	}
 	
 }
	
	function unlocked(reservationId,obj){
		$.msg.alert(i18ns('ConditionMap.reDispatch.confirm'),function(){},{buttons:
			IFA.generateJson(i18ns('ConditionMap.ok'),function(){
			var urlTemplate=$("#unlockedUrl").val();
			var urlString=new $.Template(urlTemplate);
			var urlParam = {"reservationId":reservationId};
			var url=urlString.expand(urlParam);
			$.ajax({
				type:"GET",
				url:url,
				timeout:3000,
				success:function(response,ioArgs){
					$(obj).parent().parent().hide();
					$.msg.alert(i18ns('ConditionMap.reDispatch.success'));
				},
				error:function(){
					$.msg.alert('error');
				}
			});
			$(this).dialog('close');
		},
		i18ns('ConditionMap.cancel'),function(){
			$(this).dialog('close');
		}
		)});

	}
	
	function bindVehicle(){
		searchVehicle.lastHasBeenClick = false;
		//$("#driver").empty();
		var lastVehicleId = $("#lastVehicleId").val();
		var disType=$("input:checked[name='selectType']").val();
		var driverId =$("#driver").val();
		if(driverId != null&&disType==0){
			return ;
		}
		lockSelects();
		var url = $("#queryVehicleUrl").val();
		$.ajax({
			  type: 'POST',
			  url: url,
			  data: $("#dispatchForm").serialize() ,
			  success:function(response,ioArgs){
				  var select = $("#vehicle");
					select.empty();
					var vehicles = response.vehicle;
					var length = response.vehicle.length;
					for(var i=0;i<length;i++){
						var vehicleDes = vehicles[i].plateNumber+"("+vehicles[i].carTypeName+","+vehicles[i].color
						+","+vehicles[i].lastChauffeurCnName+")";
						if(vehicles[i].isSuggest){
							vehicleDes += i18ns('ConditionMap.recommend');
						}
						if(vehicles[i].vehicleId == lastVehicleId){
							vehicleDes += i18ns('ConditionMap.selected');
						}
						var option = $("<option value='"+vehicles[i].vehicleId+"' >"+vehicleDes+"</option>");
						
						option.appendTo(select);
					}
					select.val(lastVehicleId);
					unlockSelects();
			  },
			  error:function(){
				  $.msg.alert('error');
			  }
	});
	}

	function bindDriver(){
		if (searchVehicle.lastHasBeenClick == true) {
			var categoryId=$("#categoryId").val();
			var selectedCategoryId = $("#vehicle").find(
					"option[value=" + $("#vehicle").val() + "]").attr("data");			
			if (selectedCategoryId ==null||categoryId==selectedCategoryId) {
				$("#tdCategory").find("option[value=-1]").attr(
						"selected", true);			
				$("#thCategory").hide();
				$("#tdCategory").hide();
			}else{
				$("#tdCategory").find("option[value=" + selectedCategoryId + "]").attr(
						"selected", true);
				$("#thCategory").show();
				$("#tdCategory").show();
			}
		}
		var lastDriverId = $("#lastDriverId").val();
		var disType=$("input:checked[name='selectType']").val();
		var vehicleId =$("#vehicle").val();
		if(vehicleId != null&&disType==1){
			return ;
		}
		var url = $("#queryDriverUrl").val();
		lockSelects();
		$.ajax({
			  type: 'POST',
			  url: url,
			  data: $("#dispatchForm").serialize() ,
			  success:function(response,ioArgs){
					var select = $("#driver");
					select.empty();
					var drivers = response.driver;
					var length = response.driver.length;
					
					var option = $("<option value='-1' >"+i18ns('Page.dispatch.noChauffeur')+"</option>");
					option.appendTo(select);
					for(var i=0;i<length;i++){
						var driverDes = drivers[i].cnName+"("+drivers[i].language+","+drivers[i].level
						  +","+drivers[i].lastPlateNumber+")";
						
						if(drivers[i].isSuggest){
							driverDes += i18ns('ConditionMap.recommend');
						}
						if(drivers[i].peopleId == lastDriverId){
							driverDes += i18ns('ConditionMap.selected');
						}
						var option = $("<option value='"+drivers[i].peopleId+"' >"+driverDes+"</option>");
						
						option.appendTo(select);
					}
					select.val(lastDriverId);
					unlockSelects();
			  },
			  error:function(){
				  $.msg.alert('error');
			  }
	});
	}

	function lockSelects(){
		$("#upgradeCategoryId").attr("readonly","true");
		$("#perLock").attr("readonly","true");
		$("#afterLock").attr("readonly","true");
		$("#vehicle").attr("readonly","true");
		$("#driver").attr("readonly","true");
	}
	
	function unlockSelects(){
		$("#upgradeCategoryId").removeAttr("readonly");
		$("#perLock").removeAttr("readonly");
		$("#afterLock").removeAttr("readonly");
		$("#vehicle").removeAttr("readonly");
		$("#driver").removeAttr("readonly");
	}
	
	function searchVehicle() {
		searchVehicle.lastHasBeenClick = true;
		lockSelects();
		var url = $("#queryVehicleByPlateNumberUrl").val();
		$.ajax({
			type : 'POST',
			url : url,
			data : $("#dispatchForm").serialize(),
			success : function(response) {
				var select = $("#vehicle");
				select.empty();
				var vehicles = response.vehicle;
				var length = response.vehicle.length;

				for ( var i = 0; i < length; i++) {
					var vehicleDes = vehicles[i].plateNumber + "("
							+ vehicles[i].carTypeName + "," + vehicles[i].color
							+","+vehicles[i].lastChauffeurCnName+")";
					if (vehicles[i].isSuggest) {
						vehicleDes += i18ns('ConditionMap.recommend');
					}
					if(vehicles[i].isSelect){
					var option = $("<option value='" + vehicles[i].vehicleId
							+ "' data='" + vehicles[i].categoryId + "' selected>"
							+ vehicleDes + "</option>");}
					else{
						var option = $("<option value='" + vehicles[i].vehicleId
								+ "' data='" + vehicles[i].categoryId + "'>"
								+ vehicleDes + "</option>");	
					}
					option.appendTo(select);
				}
				unlockSelects();
			}
		});
	}
	
	
	function showSearchVehicle(){
		$("#plateNumber").show();
		$("#searchPlateNumber").show();
	}
	//为选中的订单分配车辆和司机
	$("#isApplyAll").bind("change",
	function(){
		//取消选择时不弹出对话框
		if(document.getElementById("isApplyAll").checked==false){
			$("#allSelectedSegment").val("");
			bindVehicle();
			return false;
		}
		//查出所有的子订单
		$.ajax({
			type:"post",
			url:$("#workOrderSearchAllSegment").val(),
			data:{"segmentNo":$("input[name='rentalNO']").val()},
			success:function(response){
				var temp="<table cellpadding='15' class='segmentTable' cellspacing='20'><tr><th><input type='checkbox' onchange='selectSegment()' name='allSegment' id='allSegment'/></th>" +
						"<th>"+i18n["Entity.report.seq"]+"</th><th>"+i18n["Page.workOrder.bookingNumber"]+"</th><th>"+i18n["Entity.reservation.pickupDate"]+"</th><th>"+i18n["Entity.reservation.returnDate"]+"</th></tr>";
				for(var i=0;i<response.total;i++){
					//不显示已分配和不属于同一车组的订单
					var categoryId=response.order[i].categoryId;
				  if(response.order[i].resStatus==2&&$("#categoryId").val()==categoryId&&$("#segmentId").val()!=response.order[i].id){
				 temp+="<tr><td><input type='hidden' id='flag_"+response.order[i].id+"' value='"+i+"'/>" +
				 "<input type='checkbox' name='subSegment' value='"+response.order[i].id+"' /></td><td><b>"+parseInt(i+1)+"</b>&nbsp;</td>"+
				 "<td class='segment_td'>"+response.order[i].rentalNo+"</td><td>"+response.order[i].pickupDate
				   +"</td><td>"+response.order[i].returnDate+"</td></tr>";
				  }else if($("#segmentId").val()==response.order[i].id){
					  temp+="<tr><td><input type='hidden' id='flag_"+response.order[i].id+"' value='"+i+"'/>" +
						 "<input type='checkbox' disabled='disabled' checked='checked' value='"+response.order[i].id+"' /> </td><td><b>"+parseInt(i+1)+"</b>&nbsp;</td>"+
						 "<td class='segment_td'>"+response.order[i].rentalNo+"</td><td>"+response.order[i].pickupDate
						   +"</td><td>"+response.order[i].returnDate+"</td></tr>";  
				  }else{
					  temp+="<tr><td><input type='hidden' id='flag_"+response.order[i].id+"' value='"+i+"'/>" +
						 "<input type='checkbox' disabled='disabled' /> </td><td><b>"+parseInt(i+1)+"</b>&nbsp;</td>"+
						 "<td class='segment_td'>"+response.order[i].rentalNo+"</td><td>"+response.order[i].pickupDate
						   +"</td><td>"+response.order[i].returnDate+"</td></tr>";   
				  }
				}
				temp+="</table><script>function selectSegment(){" +
						"var a=document.getElementsByName('subSegment');for(var i=0;i<a.length;i++){" +
						"a[i].checked=document.getElementById('allSegment').checked;}" +
						"} </script>";
				//弹出提示框   
				var flag=0;
				$.msg.alert(i18n["page.workOrder.selectSegment"],temp,function(){$(".segmentTable").remove();if(flag==0){document.getElementById("isApplyAll").checked=false;}},{width:'600px',buttons:
					IFA.generateJson(i18n["Entity.Enquire.Opereation.ok"],function(){
						 var allSelectedSegment="";
						$("input:checked[name='subSegment']").each(
								function(){
									allSelectedSegment+=$(this).val()+";";	
							})
							if(allSelectedSegment==""){
								if(confirm(i18n["page.workOrder.notSelectSegment"])){
									$(this).dialog("close");
								}
							}else{
								//先判断所选订单是否都属于默认车组
//								var temp=allSelectedSegment.split(";");
//								var invalidSegment="";
//								for(var i=0;i<temp.length-1;i++){
//									var temp1=$("#flag_"+temp[i]).val();
//									var categoryId=response.order[temp1].categoryId;
//									if(categoryId!=$("#categoryId").val()){
//										invalidSegment+=response.order[temp1].rentalNo+";";
//									}
//								}
//								if(invalidSegment!=""){
//									alert("以下订单不属于车组："+$("#categoryName").val()+"，无法分配订单,请确认！"+invalidSegment);
//								}
//								else{
								$("#allSelectedSegment").val(allSelectedSegment+$("#segmentId").val());
								bindVehicle();
								flag=1;
								$(this).dialog("close");
								}
//							}
							
					},
					i18n["Entity.Enquire.Opereation.cancel"],function(){
						$("#allSelectedSegment").val("");
						$(this).dialog("close");
						//取消弹出框时清空提示框内容，防止再次点击时内容冲突
						$(".segmentTable").remove();
						document.getElementById("isApplyAll").checked=false;
					})
				});
				//订单详情提示框
				$(".segment_td").each(
					function(i){
						$(this).mouseover(
						function(){
							var mouseLeft = $(this).offset().left + 130;
							var mouseTop = $(this).offset().top - 50;
							$(this).css("background-color","#EDC332");
							$(this).css("cursor","pointer");
							$("#order_hint").html("<b>Order No.: "+response.order[i].rentalNo+"</b><br>" +
									"<b>Product Type:</b> "+response.order[i].productTypeName+"<br>" +
									"<b>Pick-up Location:</b>"+response.order[i].pickupLocation+"<br>" +
									"<b>Drop-off Location:</b>"+response.order[i].returnLocation+"<br>" +
									"<b>Rental Remark:</b>"+response.order[i].resRemarks).css({top:mouseTop, left:mouseLeft}).show();
						}		
						)
						$(this).mouseout(
						function(){
							$("#order_hint").hide();
							$(this).css("background-color","#ffffff");
						}		
						)
					}
				)
			}
		});
	})
});