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="conciergeConditionMap";
		reservationId = $("#reservationId").val();
		initDate();
		hotKeyDistrict();
		if(reservationId!=""){
			search();
		}
		bindEvent();
	});
	
	function initDate(){
		$("#lockDateStart").datepicker();
		var d;
		if(reservationId==""){
			d = new Date();
		}else{
			var da = $("#lockDateStart").val().split("-");
			d = new Date(da[0],da[1]-1,da[2]);
		}
		//$("#lockDateStart").datepicker("option","minDate",d);
		$("#lockDateStart").val(d.getFullYear()+'-'+(d.getMonth()+1)+'-'+d.getDate());
	}
	
	function bindEvent(){
		$("#search").bind('click',search);
		$("#resetCondition").bind('click',resetCondition);
		$("a[id^='detail']").live('click',function(){
			var reservationId = $("#reservationId").val();
			var detail = ""+$(this).attr("id");
			var urlStr = $("#queryPeopleUsabilityMapDetailUrl").val();
			var urlTemp = new $.Template(urlStr);
			var urlParams = {'districtId':$(this).attr("districtId"),'lockDateStart':$("#lockDateStart").val(),'peopleId':detail.substring(6,detail.length),'reservationId':reservationId==""?$("#restEmpty").val():reservationId};
			var url = urlTemp.expand(urlParams);
			$("#openDetailForm").attr("action",url).attr("target",window.name).submit();
		});
		$(document).bind("keyup",function(e){
			var e = e ? e : window.event;
			if(e.keyCode==13){
				search();
			}
		});
		
	}
	
	
	
	//地区热键
	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);
					});
		}
		});
	}
	/**
	 * reset query condtion
	 */
	function resetCondition(){
		$("#districtHokKey").val($("#districtHokKeyReset").val());
		$("#districtId").val($("#districtIdReset").val());
		$("#lockDateStart").val($("#lockDateStartReset").val());
		if(reservationId==""){
			var d = new Date();
			$("#lockDateStart").val(d.getFullYear()+'-'+(d.getMonth()+1)+'-'+d.getDate());
		}
	}
	
	function validateCondition(){
		var districtKey= $("#districtHokKey").val();
		var districtId = $("#districtId").val();
		if(districtId==""||districtKey==""){
			$.msg.alert(i18n['ConditionMap.PlselectCity']);
			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 = $("#queryPeopleUsabilityMapUrl").val();
	   $("#result").grid({
	  		url:queryUrl,
	  		root:"peopleUsabilityMapData",  
	  		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();
	   		}
	  	});
   }
   
   function convertJsonToArray(data){
	   var arr =[];
	   var datas = {};
	   var peopleInfo;
	   for(var name in data['value']){
		   var res = data['value'][name][0];
		   peopleInfo = res.cnName+"<br/>"+res.enName+ (res.isAvailable==0?"<br/>(<span style='color:red'>"+i18n['ConditionMap.UnAvailable']+"</span>)":"");
		   datas["isAvailable"] =res.isAvailable; 
		   datas["peopleId"] = res.peopleId;
		   datas["districtId"] = res.districtId;
		   break;
	   }
	   for(var i=1;i<=7;i++){
		   arr.push(data['value']['day_'+i]);
	   }
	   datas["onePeopleData"]= arr;
	   datas["peopleInfo"] = peopleInfo;
	   return datas;
   }
   
   function renderResultHead(data){
	   $("#result").find("table>thead>tr>th").remove();
	   var str = "<th style='width:150px'>"+i18n['ConciergeMap.ConciergeInfo']+"</th>";
	   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);
   }
   
   function addScrollBar(){
	   $($("#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[class='xTable martop']").parent().attr("colspan",9);
   }
   
   
   /**
    * 组装最后结果
    */
   function renderResultBody(data){
	var datas =  convertJsonToArray(data);
	var result = $("<table cellspacing='0' style='border:0px solid silver;width:100%' class='xTable martop' ></table>");
	var tr = $("<tr style='float:left' ></tr>");
	var onePeopleData = datas.onePeopleData;
	var len = onePeopleData.length;
	var available = datas.isAvailable;
	var peopleId = datas.peopleId;
	var districtId = datas.districtId;
	if(available=='1'){
		tr.append("<td style='border:0;width:120px;text-align:center'><a href='#' id='detail"+peopleId+"' districtId="+districtId+"  >"+datas.peopleInfo+"</a></td>");
	}else{
		tr.append("<td style='border:0;width:120px;text-align:center'>"+datas.peopleInfo+"</td>");
	}
	for(var i=0;i<len;i++){
		var oneDay = onePeopleData[i];
		var div = $("<div class='pane'></div>");
		var ul;
		if(available=='1'){
		 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 plateNumber = "";//驾驶员名称
				for(var name in divitionDetail){//找到分割信息中最早的记录
					if(j==divitionDetail[name].begin){
						billable = divitionDetail[name].billable;
						isBegin = true;
						plateNumber = divitionDetail[name].plateNumber;
						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;"+plateNumber+"</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]={"plateNumber":oneRes.vehicleId==null?i18n['ConditionMap.UnDispatch']:oneRes.plateNumber,"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)};
   }
   
});