define(function(require) {
	var $ = require('jquery');
	var IFA = require('util');
	require('dialog')($);
	require('dateTimePicker')($);
	require('uriTemplate')($);
	require('validation')($);
	require('jqueryCSS');
	require('grid')($);
	require('block')($);
	require('../../../../styles/cim/cim-grid.css');
	require('../../../../styles/cim/validation.css');
	require('../../../../styles/cim/autoComplete.css');
	require('../../../../js/seaJsExtends/autoComplete.js')($);
	require('../../../../js/jquery/jquery.fn.gantt.js')($);
	require('../../../../styles/gantt/style.css');
	var reservationId;
	var innerLocck = true;
	$(function() {
		window.name = "vehicleConditionMap";
		hotKeyCity();
		initDate();
		bindEvent();
		//首次可能从其他处进来,默认是空不应该调用
		if($("#startTime").val()!=""&&$("#cityId").val()!=""){
			initGantt();
		}
	});

	// 加载gantt图
	function initGantt() {

		if (!validateCondition()) {
			return;
		}
		$(".gantt").show();
		var urlStr = new $.Template($("#ganttUrl").val());
		var segmentId = $("#reservationId").val();
		var urlparams = {
			'reservationId' : segmentId
		};
		var getUrl = urlStr.expand(urlparams);

		var categoryName = $("#categoryId").find("option:selected").text();
		var para = $("#queryUsabilityMapForm").serialize();
		if (innerLocck) {
			$.blockUI({
				message : i18ns("Entity.Operation.Wait"),
				timeout : 10000,
				css : {
					color : '#fff',
					border : '3px solid #aaa'
				},
				overlayCSS : {
					opacity : '0.0',
					top : '108px',
					left : '208px'
				}
			});
			innerLocck = false;
			$
					.ajax({
						url : getUrl,
						type : "POST",
						dataType : "json",
						data : para,
						timeout : 5000,
						success : function(response, ioArgs) {
							var list = response.data;
							$(".gantt")
									.gantt(
											{
												source : list,
												navigate : 'scroll',
												scale : 'hours',
												maxScale : 'weeks',
												minScale : 'hours',
												startPos : response.lockDateStart,
												onItemClick : function(id) {
													var urlString = new $.Template(
															$(
																	"#queryVehicleUsabilityMapDetailUrl")
																	.val());
													var urlParams = {
														"reservationId" : id
													};
													var url = urlString
															.expand(urlParams);
													window
															.showModalDialog(
																	url,
																	window,
																	'dialogWidth=1050px;dialogHeight=700px');
													initGantt();
													// location.href = url;
												},
												onDispatchItemClick : function(
														id) {
													var urlString = new $.Template(
															$(
																	"#viewVehicleUsabilityMapDetailUrl")
																	.val());
													var urlParams = {
														"reservationId" : id
													};
													var url = urlString
															.expand(urlParams);
													window
															.showModalDialog(
																	url,
																	window,
																	'dialogWidth=1050px;dialogHeight=700px');
													initGantt();
													// location.href = url;
												},
												onConflictItemClick : function(
														currentId,
														currentRentalNo,
														conflictIds,
														conflictRentalNos) {
													// 重新提交取得conflictIds
													createConflictSegmentsList(
															currentId,
															currentRentalNo,
															conflictIds,
															conflictRentalNos);
													var div = $('#conflictIds');
													$.msg
															.alert(
																	i18n["Validation.send.plzchoose"],
																	div,
																	{
																		buttons : IFA
																				.generateJson(
																						i18n["Entity.Operation.ok"],
																						function() {
																							$(
																									this)
																									.dialog(
																											"close");
																							var resId = $(
																									":radio[name='cid']:checked")
																									.val();
																							var urlString = new $.Template(
																									$(
																											"#viewVehicleUsabilityMapDetailUrl")
																											.val());
																							var urlParams = {
																								"reservationId" : resId
																							};
																							var url = urlString
																									.expand(urlParams);
																							window
																									.showModalDialog(
																											url,
																											window,
																											'dialogWidth=1100px;dialogHeight=700px');
																							initGantt();
																						}),
																		width : 350,
																		height : 210
																	});
												},
												onMenuNameClick : function(
														chaufferId) {
													addNoneBillable(chaufferId);
												},
												onNoneBillItemClick : function(
														noneBillId) {
													showNoneBillInfo(noneBillId);
												},
												// invoke call back function to
												// reload
												reload : function(day,
														categoryId) {

													var da = $("#startTime")
															.val().split("-");
													var d = new Date(da[0],
															da[1] - 1, da[2]);
													d
															.setDate(d
																	.getDate()
																	+ day);
													$("#startTime")
															.val(
																	d
																			.getFullYear()
																			+ '-'
																			+ (d
																					.getMonth() + 1)
																			+ '-'
																			+ (d
																					.getDate()));

													if (categoryId != null) {
														$("#reservationId")
																.val(categoryId);
													}

													initGantt();
												},
												// call back function to unlock
												// gantt chart
												// prevent clicking too fast and
												// make gantt chart die.
												onSuccess : function() {
													innerLocck = true;
													$.unblockUI();
												}
											});

						}
					});
		}
	}

	function selectCategory(categoryId) {
		$("categoryId").val(categoryId);
		initGantt();
	}

	function initDate() {
		$("#startTime").datepicker({
			changeYear : true,
			changeMonth : true,
			dateFormat : "yy-mm-dd"
		});
		$("#lockDate").datetimepicker({
			stepHour : 1,
			showMinute : false,
			showSecond : false,
			beforeShow : function(date) {
			},
			onSelect : function(date) {
				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);
					}
				}
			}
		});
		$("#unlockDate")
				.datetimepicker(
						{
							stepHour : 1,
							showMinute : false,
							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);
									}
								}
							}
						});
		var d = new Date();
		d.setDate(d.getDate());
		$("#startTime").val(
				d.getFullYear() + '-' + (d.getMonth() + 1) + '-'
						+ (d.getDate()));
	}

	function createConflictSegmentsList(currentSegmentId, currentRentalNo,
			conflictIds, conflictRentalNos) {
		$("#conflictIds").empty();
		$("#conflictIds").append(
				"<input type='radio' name='cid' value='" + currentSegmentId
						+ "' checked='true' />" + currentRentalNo + "<br>");

		for ( var i = 0; i < conflictIds.length; i++) {
			$("#conflictIds").append(
					"<input type='radio' name='cid' value='" + conflictIds[i]
							+ "' checked='false' />" + conflictRentalNos[i]
							+ "<br>");
		}
	}

	function bindEvent() {
//		 var today=new Date();
//		 var count=0;
//		 setInterval(function(){
//		 today.setDate(today.getDate()-1);
//		 $("#startTime").val(today.getFullYear()+'-'+(today.getMonth()+1)+'-'+(today.getDate()));
//		 if(count<357){
//		 count++;
//		 initGantt();
//		 }
//		 },2000);
		$("#btnGantt").bind('click', initGantt);
		$("#resetCondition").bind('click', resetCondition);
		$("#btnNomenu").bind('click',noMenu);
	}
	// 地区热键
	function hotKeyCity() {
		$
				.ajax({
					type : "get",
					url : $("#hotkeyCity").val(),
					success : function(response) {
						var acdata = response.district;
						$("#cityHokKey")
								.autocomplete(
										acdata,
										{
											caption : "&nbsp;&nbsp;"
													+ i18ns("JS.districtHotKey.caption"),
											findCaption : "&nbsp;,"
													+ i18ns("JS.districtHotKey.findCaption"),
											noFindCaption : "&nbsp;&nbsp;"
													+ i18ns("JS.hotkey.district.city.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) {
											$("#cityId").val(data.districtId);
										});
					}
				});
	}
	/**
	 * reset query condtion
	 */
	function resetCondition() {
		$("#queryUsabilityMapForm :input").val("");
		var d = new Date();
		d.setDate(d.getDate());
		$("#startTime").val(
				d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate());
	}

	$("#queryUsabilityMapForm").validate({
		rules : {
			startTime : {
				required : true
			},
			cityHokKey : {
				required : true
			},
			mobilePhone : {
				digits : true
			}
		}
	});
	function validateCondition() {

		if ($("#queryUsabilityMapForm").valid()) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 获取所有时间点,以及分割区间的开始和结束以及驾驶员信息
	 */
	function fillupMap(oneDayData) {
		var len = oneDayData.length;
		var times = [];
		var datas = {};
		datas['divition'] = {};
		for ( var i = 0; i < len; i++) {
			var oneRes = oneDayData[i];
			var hourDivition = getHourDivition(oneRes.lockDate,
					oneRes.unLockDate);
			var begin = hourDivition.begin;
			var end = hourDivition.end;
			var billable = oneRes.billable;
			datas['divition']["res" + i] = {
				"driver" : oneRes.chaufferId == null ? i18n['ConditionMap.UnDispatch']
						: oneRes.cnName,
				"begin" : begin,
				"end" : end,
				"billable" : billable
			};
			for ( var j = 0; j < 24; j++) {
				if (j >= begin && j <= end) {
					times[j] = 1;
				} else {
					if (!times[j]) {
						times[j] = 0;
					}
				}
			}
		}
		datas['times'] = times;
		return datas;
	}

	/**
	 * 获取时间间隔
	 */
	function getHourDivition(lockDate, unlockDate) {
		var beginTime = new Date(lockDate).getHours();
		var endTime = new Date(unlockDate).getHours();
		return {
			begin : Number(beginTime),
			end : Number(endTime)
		};
	}
	function addNoneBillable(chaufferId) {

		$("#noneBillableId").val("");
		$("#lockDate").val("");
		$("#unlockDate").val("");
		$("#remark").val("");
		$("#chaufferId").val(chaufferId);

		$.msg
				.alert(
						i18ns("VehicleConditionMap.addNonbusiness"),
						$("#addTemplate"),
						function() {
						},
						{
							width : 550,
							height : 300,
							buttons : IFA
									.generateJson(
											i18ns("ConditionMap.ok"),
											function() {
												var url = $(
														"#checkNoneBillableUrl")
														.val();
												if ($("#addForm").valid()) {
													$
															.ajax({
																url : url,
																type : "POST",
																dataType : "json",
																data : $(
																		"#addForm")
																		.serialize(),
																timeout : 5000,
																success : function(
																		response,
																		ioArgs) {

																	if (response.result == -1) {
																		$.msg
																				.alert(
																						i18n['Page.Dialog.title'],
																						i18ns("VehicleConditionMap.nonbusinessExist"));
																	} else if (response.result == 0) {
																		var conflictRes = response.listRes;
																		var strResNos = "";
																		for ( var i = 0; i < conflictRes.length; i++) {
																			strResNos += "<font color='red'>"
																					+ conflictRes[i].rentalNo
																					+ "</font><br/>";
																		}
																		var warnMessage = i18n['ConditionMap.addNoneBill.WarningMessage']
																				+ "<br/>"
																				+ strResNos;

																		$.msg
																				.alert(
																						i18n['Page.title.dialogshow.warnning'],
																						warnMessage,
																						{
																							buttons : IFA
																									.generateJson(
																											i18n["Entity.Operation.ok"],
																											function() {
																												createNoneBillable();
																												$(
																														this)
																														.dialog(
																																"close");
																											},
																											i18ns("ConditionMap.cancel"),
																											function() {
																												$(
																														this)
																														.dialog(
																																"close");

																											})
																						});
																	} else {
																		createNoneBillable();
																	}
																}
															});
													$(this).dialog("close");
												}
											}, i18ns("ConditionMap.cancel"),
											function() {
												$(this).dialog("close");
											})
						});
	}
	function createNoneBillable() {
		var url = $("#addNoneBillableUrl").val();
		$.post(url, $("#addForm").serialize(), function(data) {
			if (data.result == "-1") {
				$.msg.alert(i18n['Page.Dialog.title'],
						i18ns("VehicleConditionMap.exist"));
				return;
			} else {
				$.msg.alert(i18n['DriverGanttMap.Dispatch.Success'],
						function() {
						}, {
							buttons : IFA.generateJson(i18n['ConditionMap.ok'],
									function() {
										initGantt();
										$(this).dialog("close");
									})
						});
			}

		});
	}
	function showNoneBillInfo(noneBillId) {

		var url = $("#getNoneBillableUrl").val();

		$
				.ajax({
					url : url,
					type : "POST",
					dataType : "json",
					data : "noneBillableId=" + noneBillId,
					timeout : 5000,
					success : function(response, ioArgs) {
						var noneBill = response.noneBillRes;

						$("#show_noneBillableId").val(noneBillId);
						$("#show_codeId").val(noneBill.codeId);
						$("#show_lockDate").val(
								new Date(noneBill.lockDate)
										.format("yyyy-MM-dd hh:mm"));
						$("#show_unlockDate").val(
								new Date(noneBill.unlockDate)
										.format("yyyy-MM-dd hh:mm"));
						$("#show_remark").val(noneBill.remark);

						$.msg
								.alert(
										i18ns("VehicleConditionMap.deleteNonbusiness"),
										$("#showTemplate"),
										function() {
										},
										{
											width : 550,
											height : 300,
											buttons : IFA
													.generateJson(
															i18ns("Entity.Operation.delete"),
															function() {

																$.msg
																		.alert(
																				i18ns("Entity.Sure.tip"),
																				function() {
																				},
																				{
																					buttons : IFA
																							.generateJson(
																									i18ns('ConditionMap.ok'),
																									function() {
																										$(
																												this)
																												.dialog(
																														"close");
																										delNoneBillable(noneBillId);
																									},
																									i18ns("ConditionMap.cancel"),
																									function() {
																										$(
																												this)
																												.dialog(
																														"close");
																									})
																				});

																$(this)
																		.dialog(
																				"close");

															},
															i18ns("ConditionMap.cancel"),
															function() {
																$(this)
																		.dialog(
																				"close");
															})
										});
					}
				});
	}
	function delNoneBillable(noneBillId) {

		var url = $("#delNoneBillableUrl").val();

		$.ajax({
			url : url,
			type : "POST",
			dataType : "json",
			data : "noneBillableId=" + noneBillId,
			timeout : 5000,
			success : function(response, ioArgs) {
				var result = response.result;

				if (result == 1) {
					$.msg.alert(i18n['Page.Dialog.title'],
							i18ns("Entity.page.Delete.Success"), function() {
							}, {
								buttons : IFA.generateJson(
										i18n['ConditionMap.ok'], function() {
											initGantt();
											$(this).dialog("close");
										})
							});
				} else {
					$.msg.alert(i18n['Page.Dialog.title'],
							i18ns("Entity.page.Delete.Failed"));
				}
			}
		});
	}
	 function noMenu(){
		   	var weeklyUrl=new $.Template($("#noMenuGanttChartUrl").val());
			var cityId=setDefaultParam($("#cityId").val());
			var cityName=setDefaultParam($("#cityHokKey").val());
			var cnName=setDefaultParam($("#cnName").val());
			var enName=setDefaultParam($("#enName").val());
			var mobilePhone=setDefaultParam($("#mobilePhone").val());
			var params = {
			'cityId':cityId,
			'cityName':cityName,
			'startTime':$("#startTime").val(),
			'rentalType':$("#rentalType").val(),
			'cnName':cnName,
			'enName':enName,
			'mobilePhone':mobilePhone
			};
			var noMenuUrl=weeklyUrl.expand(params);
			window.open(noMenuUrl,window);
	   }
	   function setDefaultParam(param){
		   if(!param){
			   return $("#restEmpty").val();
		   }else{
			   return param; 
		   }
	   }
});