define(function(require){
	var $ = require('jquery');
	var IFA = require('util');
	require('datepicker')($);
	require('uriTemplate')($);
	require('jqueryCSS');
	require('grid')($);
	//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 reservationId;
	$(function(){
		window.name = "vehicleConditionMap";
		reservationId = $("#reservationId").val();
		var queueFlag = $("#queueFlag").val();
		hotKeyCity();
		initDate();
		hotKeyDistrict();
		if(reservationId!=""){
			search();
		}
		bindEvent();
	});
	
	function initDate(){
		$("#lockDateStart").datepicker();
		var d;
		if(reservationId==""){
			d = new Date();
			d.setDate(d.getDate()-1);
		}else{
			var da = $("#lockDateStart").val().split("-");
			d =new Date(da[0],da[1]-1,da[2]);
			d.setDate(d.getDate()-1);
		}
		//$("#lockDateStart").datepicker("option","minDate",d);
		$("#lockDateStart").val(d.getFullYear()+'-'+(d.getMonth()+1)+'-'+(d.getDate()));
	}
	
	function bindEvent(){
		$("#search").bind('click',search);
		$("#noMenu").bind('click',fullScreen);
		$("#resetCondition").bind('click',resetCondition);
		$("a[id^='detail']").live('click',function(){
			
			var reservationId = $("#reservationId").val();
			var url2 = $("#queryVehicleUsabilityMapDetailNoMenuUrl").val();
			var urlStr = url2?url2:$("#queryVehicleUsabilityMapDetailUrl").val();
			var urlTemp = new $.Template(urlStr);
			var urlParams = {'districtId':$(this).attr("districtId"),'categoryId':$(this).attr("categoryId"),'lockDateStart':$("#lockDateStart").val(),'vehicleId':$(this).attr("id").substring(6,$(this).attr("id").length),'reservationId':reservationId==""?$("#restEmpty").val():reservationId};
			var url = urlTemp.expand(urlParams);
			$("#openDetailForm").attr("action",url).attr("target","vehicleConditionMap").submit();
		});
		$(document).bind("keyup",function(e){
			var e = e ? e : window.event;
			if(e.keyCode==13){
				search();
			}
		});
		
	}
	
	
	function fullScreen(){
		var urlStr;
		var url;
		if(reservationId!=""){
			urlStr = new $.Template($("#VehicleUsabilityMapChannelOneNoMenuUrl").val());
			var params = {"reservationId":reservationId};
			url = urlStr.expand(params);
			window.showModalDialog(url,window, 'dialogLeft=0;dialogTop=0;dialogWidth='+window.screen.width+'px;dialogHeight='+window.screen.height+'px');
		}else{
			url = $("#VehicleUsabilityMapNoMenuUrl").val();
			window.showModalDialog(url,window, 'dialogLeft=0;dialogTop=0;dialogWidth='+window.screen.width+'px;dialogHeight='+window.screen.height+'px');
		}
	}
	
	
	//地区热键
	function hotKeyDistrict(){
	  	$.ajax({
			type:"get",
			url:$("#hotkeyDistrict").val(),
			success:function(response){
			var acdata=response.district;
			$("#districtHokKey").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) {
						$("#districtId").val(data.districtId);
					});
		}
		});
	}
	
	
	//地区热键
	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(){
		$("#cityHokKey").val('');
		$("#cityId").val('');
		$("#districtHokKey").val($("#districtNameReset").val());
		$("#districtId").val($("#districtIdReset").val());
		$("#lockDateStart").val($("#pickupDateReset").val());
		var categoryId = $("#categoryIdReset").val();
		$("#categoryId").find('option[value='+categoryId+']').attr("selected","selected");
		if(reservationId==""){
			var d = new Date();
			$("#lockDateStart").val(d.getFullYear()+'-'+(d.getMonth()+1)+'-'+d.getDate());
		}
	}
	
	function validateCondition(){
		var districtId = $("#districtId").val();
		var cityId = $("#cityId").val();
		if(districtId==""&&cityId==""){
			$.msg.alert(i18n['ConditionMap.PlselectDistrictOrCity']);
			return false;
		}
//		var categoryId = $("#categoryId").val();
//		if(categoryId==""){
//			$.msg.alert(i18n['ConditionMap.PlselectVehicleGroup']);
//			return false;
//		}
		var lockDateStart = $("#lockDateStart").val();
		if(lockDateStart==""){
			$.msg.alert(i18n['ConditionMap.PlselectTime']);
			return false;
		}
		return true;
	}
	
	/**
	 * search
	 */
   function search(){
	   if(!validateCondition()){
		   return;
	   }
	   var queryUrl = $("#queryVehicleUsabilityMapUrl").val();
	   $("#result").grid({
	  		url:queryUrl,
	  		root:"vehicleUsabilityMap",  
	  		method:'POST',
	  		isREST:false,
	  		paging:true,
	  		pageSize:50,
	  		pageTheme:'Theme1',
	  		defaultParams:$("#queryUsabilityMapForm").serialize(),
	  		fields:[
	  				{render:function(data){
	  					return renderResultBody(data);
	  				}}
	  			],
	  		callback:function(data){
		 //  renderResultHead(data);
		   		addScrollBar();
	   		},
	   		before:function(data){
	   		return renderResultHead(data);
	   		}
	  	});
   }
   
   function convertJsonToArray(data){
	   var arr =[];
	   var datas = {};
	   var carInfo;
	   for(var name in data['value']){
		   var res = data['value'][name][0];
		   carInfo = res.carTypeName+"<br/>"+res.color+"<br/>"+res.plateNumber+((res.leasingType=='L'?"(长租)":"(短租)"))+ (res.available=="N"?"<br/>(<span style='color:red'>"+i18n['ConditionMap.UnAvailable']+"</span>)":"");
		   datas["isAvailable"] =res.available; 
		   datas["vehicleId"] = res.vehicleId;
		   datas["districtId"] = res.districtId;
		   datas["categoryId"] = res.categoryId;
		   datas["billable"] = res.billable;
		   break;
	   }
	   for(var i=1;i<=7;i++){
		   arr.push(data['value']['day_'+i]);
	   }
	   datas["oneCarData"]= arr;
	   datas["carInfo"] = carInfo;
	   return datas;
   }
   
   function renderResultHead(data){
	   $($("#result").find("table")[0]).css("width","2800px").wrap("<div style='overflow-x:scroll;overflow-y:hidden;position:relative;top:0;left:0;' ></div>");
	   $("#result").find("table>thead>tr>th").remove();
	   var str = "";
	   var lockDateStart = data.lockDateStart;
	   for(var i=1;i<=7;i++){
		   if(i==1){
		   str+="<th style='width:450px'>"+i18n['ConditionMap.graphics.firstDay']+"("+ new Date(lockDateStart).format("yyyy-MM-dd")+")</th>";
		   }else if(i==2){
		   str+="<th style='width:450px'>"+i18n['ConditionMap.graphics.secondDay']+"("+ new Date(lockDateStart).format("yyyy-MM-dd")+")</th>";	   
		   }else if(i==3){
		   str+="<th style='width:450px'>"+i18n['ConditionMap.graphics.thirdDay']+"("+ new Date(lockDateStart).format("yyyy-MM-dd")+")</th>";			   
		   }else if(i==4){
		   str+="<th style='width:450px'>"+i18n['ConditionMap.graphics.fouthDay']+"("+ new Date(lockDateStart).format("yyyy-MM-dd")+")</th>";			   
		   }else if(i==5){
		   str+="<th style='width:450px'>"+i18n['ConditionMap.graphics.fifthDay']+"("+ new Date(lockDateStart).format("yyyy-MM-dd")+")</th>";			   
		   }else if(i==6){
		   str+="<th style='width:450px'>"+i18n['ConditionMap.graphics.sixtyDay']+"("+ new Date(lockDateStart).format("yyyy-MM-dd")+")</th>";			   
		   }else if(i==7){
		   str+="<th style='width:450px'>"+i18n['ConditionMap.graphics.seventhDay']+"("+ new Date(lockDateStart).format("yyyy-MM-dd")+")</th>";			   
		   }
		   lockDateStart = new Date(lockDateStart).getTime()+24*3600*1000;
	   }
	   $("#result").find("table>thead>tr").append(str);
	   $($("#result").find("div")[0]).before("<div style='float:left;width:130px' ><table class='gridTable' ><tr><th style='width:100%'>"+i18n['VehicleMap.VehicleInfo']+"</th></tr></table></div>");
   }
   
   function addScrollBar(){
	   $("#result").find("table[class='xTable martop']").parent().attr("colspan",9).css("height","60px");
   }
   
   
   /**
    * 组装最后结果
    */
   function renderResultBody(data){
	var datas =  convertJsonToArray(data);
	var result = $("<table cellspacing='0' style='border:0px solid silver;width:100%' class='xTable martop' ></table>");
	var header = $($("#result").find("div")[0]).find("table>tbody");
	var tr = $("<tr style='float:left' ></tr>");
	var oneCarData = datas.oneCarData;
	var len = oneCarData.length;
	var available = datas.isAvailable;
	var vehicleId = datas.vehicleId;
	var districtId = datas.districtId;
	var categoryId = datas.categoryId;
	
	if(available=='Y'){
		header.append("<tr><td style='text-align:center;height:60px'><a href='#' id='detail"+vehicleId+"' districtId='"+districtId+"' categoryId='"+categoryId+"' >"+datas.carInfo+"</a></td></tr>");
	}else{
		header.append("<tr><td style='height:60px;text-align:center'>"+datas.carInfo+"</td></tr>");
	}
	for(var i=0;i<len;i++){
		var oneDay = oneCarData[i];
		var div = $("<div class='pane'></div>");
		var ul;
		if(available=='Y'){
		 ul = $("<ul></ul>");
		}else{
		 ul = $("<ul class='stop' ></ul>");	
		}
		var td = $("<td style='border:0;width:420px;text-align:center' ></td>");
		if(oneDay){
		var oneDayDetail = fillupMap(oneDay);
		var times = oneDayDetail.times;//取得时间范围
		var divitionDetail = oneDayDetail.divition;//取得时间范围的分割信息
		var billable = -1;
		for(var j=0;j<24;j++){
			if(times[j]==1){
				var isBegin =false;//是否是锁定开始时间
				var cnName = "";//驾驶员名称
				for(var name in divitionDetail){//找到分割信息中最早的记录
					if(j==divitionDetail[name].begin){
						billable = divitionDetail[name].billable;
						isBegin = true;
						cnName = divitionDetail[name].driver;
						break;
					}
				}
				if(!isBegin){
					if(billable==1){
					ul.append("<li class='color'>"+j+"</li>");
					}else{
					ul.append("<li class='color2'>"+j+"</li>");	
					}
				}else{
					if(billable==1){
					ul.append("<li class='color'><div style='text-align:left'><span style='color:#666;'></span>&nbsp;"+cnName+"</div>"+j+"</li>");
					}else{
					ul.append("<li class='color2'><div style='text-align:left'><span style='color:#666;'>内部用车</span></div>"+j+"</li>");	
					}
				}
			}else{
				ul.append("<li>"+j+"</li>");
			}
		}
		
	}else{
		for(var j=0;j<24;j++){
		ul.append("<li>"+j+"</li>");	
		}
	}
		div.append(ul);
		td.append(div);
		tr.append(td);
	}
	result.append(tr);
	return result;
   }
   
   /**
    * 获取所有时间点,以及分割区间的开始和结束以及驾驶员信息
    */
   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.chauffeurId==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)};
   }
   
});