<?xml version="1.0" encoding="utf-8"?>
<s:TitleWindow xmlns:fx="http://ns.adobe.com/mxml/2009"
			   xmlns:s="library://ns.adobe.com/flex/spark"
			   xmlns:mx="library://ns.adobe.com/flex/mx"
			   xmlns:common="port.query.*"
			   xmlns:show="port.show*"
			   xmlns:AdvancedDataGrid="com.AdvancedDataGrid.*"
			   xmlns:SubClasses="com.AdvancedDataGrid.SubClasses.*"
			   width="400" height="280" borderVisible="false" close="{PopUpManager.removePopUp(this);}" color="#314a5e" fontFamily="宋体" fontSize="12" fontWeight="bold"
			   skinClass="com.skins.tdt.TitleWinSkin" title='绘制 {((!ship.name||ship.name=="null")?"":ship.name)+"（"+ship.mmsi+"）"}的航行轨迹' initialize="init(event)" xmlns:model="port.query.model.*" xmlns:show1="port.show.*" xmlns:ais="com.xt.hb.ais.*">
	<fx:Declarations>
		<!-- 将非可视元素（例如服务、值对象）放在此处 -->
	</fx:Declarations>
	<fx:Script>
		<![CDATA[
			import com.AdvancedDataGrid.Util.ItemRendererIFactory;
			import com.esri.ags.Graphic;
			import com.esri.ags.geometry.MapPoint;
			import com.esri.ags.geometry.Polyline;
			import com.esri.ags.layers.GraphicsLayer;
			import com.esri.ags.symbols.SimpleLineSymbol;
			import com.esri.ags.symbols.SimpleMarkerSymbol;
			import com.xt.hb.common.InfoModel;
			import com.xt.hb.utils.CommonUtils;
			import com.xt.hb.utils.MapUtils;
			import com.xt.hb.utils.RemoteUtils;
			
			import mx.collections.ArrayCollection;
			import mx.controls.Alert;
			import mx.core.FlexGlobals;
			import mx.events.FlexEvent;
			import mx.formatters.DateFormatter;
			import mx.managers.PopUpManager;
			import mx.rpc.events.AbstractEvent;
			import mx.rpc.events.FaultEvent;
			import mx.rpc.events.ResultEvent;
			import mx.rpc.remoting.RemoteObject;
			
			import spark.events.IndexChangeEvent;
			
			private var _ship:Object ; //船舶信息
			[Bindable]
			private var resultData:ArrayCollection = new ArrayCollection();
			[Bindable]
			private var hourArr:ArrayCollection = new ArrayCollection();
			private const DEFAULT_DAYS_AGE:int = 2;
			
			protected function queryLocus(event:MouseEvent):void{
				var btn:QueryButton = event.currentTarget as QueryButton ;
				clearData();
				//				var ro:RemoteObject=new RemoteObject();
				//				ro.destination="service_hscb_AIS";
				
				RemoteUtils.callRemote("aisCtl","queryAISCBsByMMSI",function(e:AbstractEvent):void{
					if(e is FaultEvent){
						queryInfoFault(e as FaultEvent);
						btn.unLocked();
					}else {
						var hscbArr:ArrayCollection = ResultEvent(e).result as ArrayCollection;
						queryInfoResult(hscbArr);
						btn.unLocked();
					}
				},ship.mmsi,startTime()+"",endTime()+"");
				//查询显示小时
				//				ro.queryAISCBsByMMSI(ship.mmsi,startTime(),endTime());
				//				ro.addEventListener(ResultEvent.RESULT,
				//					function(e:ResultEvent):void{
				//						var hscbArr:ArrayCollection = e.result as ArrayCollection;
				//						queryInfoResult(hscbArr);
				//						btn.unLocked();
				//					});
				//				ro.addEventListener(FaultEvent.FAULT, function(e:FaultEvent):void{ 
				//					queryInfoFault(e);
				//					btn.unLocked();
				//				});
			}
			//清除上次的数据
			private function clearData():void{
				resultData.removeAll();
				clearLocusFeature();
			}
			private function startTime():Number{
				var strdate:String = beginDate.text+" 00:00:00";
				var date:Date = DateFormatter.parseDateString(strdate);
				return date.time;
			}
			private function endTime():Number{
				var strdate:String = endDate.text+" 23:59:59";
				var date:Date = DateFormatter.parseDateString(strdate);
				return date.time;
			}
			private function housAge():Number{
				var date:Date = new Date();
				var hour:int = Number(hous.selectedItem.value);
				date.hours = date.hours-hour ; 
				return date.time;
			}
			public function hourQuery(param:Object):void{
				currentState = "inOneDay";
				menuBar.selectedIndex=0;
				hous.selectedIndex = param["hour"];
				hourBtn.dispatchEvent(new MouseEvent(MouseEvent.CLICK));
			}
			public function dayQuery(param:Object):void{
				currentState = "outOneDay";
				menuBar.selectedIndex=1;
				beginDate.text =  param["startTime"];
				endDate.text = param["endTime"] ;
				dayBtn.dispatchEvent(new MouseEvent(MouseEvent.CLICK));
			}
			private function queryInfoResult(hscbArr:ArrayCollection):void{
				if(hscbArr.length==0){
					Alert.show("没有记录");
					return ;
				}
				if(shipHasExists()){
					ship.sog = ship.speed;
					ship.angle = ship.course;
					hscbArr.addItemAt(ship,0);
				}
				//显示详情
				resultData.addAll(hscbArr);
				//加上本次船舶
				var begin:Object = hscbArr[0];
				addLocusFeature(madeLineFeature(begin,begin)); //画出线
				addLocusFeature(madePointFeature(begin),true); //画出起点船
				var end:Object = null ;
				for(var i:int=1;i<hscbArr.length;i++){
					begin = hscbArr[i-1];
					end = hscbArr[i] ;
					addLocusFeature(madeLineFeature(begin,end)); //画出线
					addLocusFeature(madePointFeature(end),true); //画出终点
				}
			}
			//船只是否有位置
			private function shipHasExists():Boolean{
				return ship.hasOwnProperty("lon")&&ship.hasOwnProperty("lat") ;
			}
			//添加轨迹图层
			private function addLocusFeature(fea:Graphic,isFront:Boolean=false):void{
				fea.name = "Locus";
				if(isFront){
					MapUtils.getTempGraphicLayer().add(fea);
				}else{
					MapUtils.getTempGraphicLayer().addChildAt(fea,0);
				}
			}
			//删除轨迹图
			public function clearLocusFeature():void{
				var tempFeatureLayer:GraphicsLayer = MapUtils.getTempGraphicLayer();
				for(var i:int=tempFeatureLayer.graphicProvider.length-1;i>=0 ;i--){
					var f:Graphic=tempFeatureLayer.graphicProvider[i] as Graphic;
					if(f.name=="Locus"){
						tempFeatureLayer.remove(f);
						tempFeatureLayer.removeChildAt(0);
					}
				}
			}
			private function queryInfoFault(event:FaultEvent):void
			{
				Alert.show("ERROR:"+event.fault.message);
			}
			[Bindable]
			public function get ship():Object
			{
				return _ship;
			}
			
			public function set ship(value:Object):void
			{
				if(_ship==null){
					_ship = value;
					return ;
				}
				if(_ship["mmsi"]!=value["mmsi"]){
					_ship = value;
					clearData();
					return ;
				}
				if(_ship["time"]!=value["time"]){
					if(resultData.length>0){
						//更新数据第一个节点	
						resultData.addItemAt(value,0);	
						//重绘轨迹
						addLocusFeature(madeLineFeature(resultData.getItemAt(1),resultData.getItemAt(0))); //画出线
						addLocusFeature(madePointFeature(value),true); //画出终点
					}
					_ship = value ;
				}
			}
			
			/**
			 * 格式化日期
			 * 去掉毫秒数
			 * */
			public static function getTimeStr(time:Number):String{
				var strTime:String = time+"";
				//截取秒数
				return strTime.substr(0,strTime.length-3);	
			}
			private function madePointFeature(obj:Object):Graphic{
				var x:Number=Number(obj.lon);
				var y:Number=Number(obj.lat);
				var fc:Number=0xff0000;//计算颜色
				var cbFea:Graphic = new Graphic(new MapPoint(x,y),
					new SimpleMarkerSymbol(SimpleMarkerSymbol.STYLE_CIRCLE,
						10,0xFFFF00,1,0,0,0,new SimpleLineSymbol("solid",0xEA1F00,1,3) ));//new Feature(new GeoPoint(x,y));
				// 添加点移入移出事件
				cbFea.attributes = obj;
				cbFea.addEventListener(MouseEvent.MOUSE_OVER,tracePointMouseOver);
				cbFea.addEventListener(MouseEvent.MOUSE_OUT,tracePointMouseOut);
				return cbFea;
			}
			private function madeLineFeature(begin:Object,end:Object):Graphic{
				var p1:MapPoint = new MapPoint(Number(begin.lon),Number(begin.lat));
				var p2:MapPoint = new MapPoint(Number(end.lon),Number(end.lat));
				var line:Polyline = new Polyline();
				line.addPath([p1,p2]);
				var fea:Graphic = new Graphic(line,getLocusStyle());
				return fea ;
			}
			private function getLocusStyle():SimpleLineSymbol{
				var ret:SimpleLineSymbol  = new SimpleLineSymbol();
				ret.color = 0x0099FF;
				ret.width = 3;
				ret.alpha = 1;
				ret.style=SimpleLineSymbol.STYLE_SOLID;
				return ret ;
			}
			private function formatTime(item:Object,column:AdvancedDataGridColumn):String{
				if(item[column.dataField] is Date){
					return CommonUtils.formatDate(item[column.dataField]);
				}else if(item[column.dataField] is Number){
					var date:Date = new Date(Number(item[column.dataField])*1000);
					return  CommonUtils.formatDate(date);
				}else {
					return null;
				}
			}
			
			protected function locationShip(e:MouseEvent):void{
				var item:Object = this.historyList.selectedItem; 
				var x:Number=Number(item.lon);
				var y:Number=Number(item.lat);
				MapUtils.map.centerAt(new MapPoint(x,y));
				//				var point:MapPoint  = new MapPoint();
				//				point.x = x;
				//				point.y = y;
				//				MapUtils.map.centerAt(point);
				//				MapUtils.map.move(x,y);
				//				FlexGlobals.topLevelApplication.map.panTo((new Point2D(x,y)));
			}
			protected function dateTypeChangeHandler(event:IndexChangeEvent):void{
				currentState =  this.menuBar.selectedItem.stateName ;		
			}
			
			protected function init(event:FlexEvent):void{
				initHourArr();
			}
			protected function initHourArr():void{
				for	(var i:int=1 ;i<=24;i++){
					var obj:Object = {lable:i+"小时以内",value:i+""};
					hourArr.addItem(obj)
				}
			}
			
			protected function queryHourLocus(event:MouseEvent):void{
				var btn:QueryButton = event.currentTarget as QueryButton ;
				clearData();
				RemoteUtils.callRemote("aisCtl","queryAISCBsByMMSI",function(e:AbstractEvent):void{
					if(e is FaultEvent){
						queryInfoFault(e as FaultEvent);
						btn.unLocked();
					}else {
						var hscbArr:ArrayCollection = ResultEvent(e).result as ArrayCollection;
						queryInfoResult(hscbArr);
						btn.unLocked();
					}
				},ship.mmsi,housAge()+"",new Date().time+"");
			}
			private function today():String{
				var fr:DateFormatter=new DateFormatter();
				fr.formatString="YYYY-MM-DD";
				var d:Date = new Date();
				return  fr.format(d);
			}
			private function daysAge():String{
				var fr:DateFormatter=new DateFormatter();
				fr.formatString="YYYY-MM-DD";
				var d:Date = new Date();
				d.date = d.date-DEFAULT_DAYS_AGE ;
				return  fr.format(d);
			}
			
			/**
			 * 海事船舶轨迹移入事件
			 */ 
			private function tracePointMouseOver(e:MouseEvent):void
			{
				var model:InfoModel = new InfoModel();
				var obj = e.currentTarget.attributes;
				var strDate:String = "";
				if(typeof(obj.time) == "number") {
					strDate = CommonUtils.formatPatternDate(
						new Date(Number(obj.time)*1000),
						CommonUtils.DATE_MIN_FMT);
				} else if(typeof(obj.time) == "object") {
					strDate = CommonUtils.formatPatternDate(
						obj.time,
						CommonUtils.DATE_MIN_FMT);
				}
				var infoArr: Array = [
					"时间 ： " + strDate,
					"位置 ： " + obj.lat + "E " + obj.lon+ "N ",
					"状态 ： " + ship.status,
					"航速 ： " + CommonUtils.nullToEmpty(obj.sog),
					"航向 ： " + CommonUtils.nullToEmpty(obj.angle),
					"目的港 ： " + ship.dest,
					"E.T.A ： " + ship.eta
				];
				var g:Graphic=e.currentTarget as Graphic;
				model.showInfoWindow(infoArr, e);
			}
			/**
			 * 海事船舶轨迹移出事件
			 */ 
			private function tracePointMouseOut(e:MouseEvent):void
			{
				MapUtils.map.infoWindow.hide();
				var g:Graphic=e.currentTarget as Graphic;
			}
		]]>
	</fx:Script>
	<s:states>
		<s:State name="inOneDay"/>
		<s:State name="outOneDay"/>
	</s:states>
	<mx:VBox width="100%" height="100%" backgroundColor="#cce8ff" borderVisible="false" horizontalGap="0" verticalGap="0">
		<mx:VBox width="100%" height="56" backgroundColor="#ffffff"  verticalGap="-1">
			<s:HGroup width="100%" height="24"  >
				<s:TabBar id="menuBar" buttonMode="true" change="dateTypeChangeHandler(event);"  labelField="label"
						  requireSelection="true" useHandCursor="true" >
					<s:ArrayCollection>
						<fx:Object label="一天以内" stateName="inOneDay" />
						<fx:Object label="一天以上" stateName="outOneDay"/>
					</s:ArrayCollection>
				</s:TabBar>
			</s:HGroup>
			<mx:VBox  backgroundColor="#B4B4B5" width="100%" height="30">			
				<mx:HBox id="inOneDayBox" width="100%" height="30" includeIn="inOneDay"   verticalAlign="middle" horizontalGap="6" verticalGap="0"  borderVisible="false">
					<s:Spacer width="8" height="100%"/>
					<s:ComboBox  id="hous" dataProvider="{hourArr}"  width="280" labelField="lable"  selectedIndex="2"/>
					<ais:QueryButton id="hourBtn" label="查询" click="queryHourLocus(event)" />
					<s:Spacer width="8" height="100%"/>
				</mx:HBox>
				<mx:HBox id="outOneDayBox" width="100%" height="30" includeIn="outOneDay"   verticalAlign="middle" horizontalGap="5" verticalGap="0"  borderVisible="false">
					<s:Spacer width="8" height="100%"/>
					<s:Label text="航行日期：" />
					<mx:DateField formatString="YYYY-MM-DD" id="beginDate" width="97" monthNames='["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"]' 
								  dayNames="['日','一','二','三','四','五','六']"  text="{daysAge()}" yearNavigationEnabled="true" showToday="true"  />
					<s:Label text="至" />
					<mx:DateField formatString="YYYY-MM-DD" id="endDate" 	width="97" monthNames='["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"]' 
								  dayNames="['日','一','二','三','四','五','六']" text="{today()}" yearNavigationEnabled="true" showToday="true" />
					<ais:QueryButton id="dayBtn" label="查询" click="queryLocus(event)" />
					<s:Spacer width="8" height="100%"/>
				</mx:HBox>
			</mx:VBox>
		</mx:VBox>
		<s:Spacer width="8"/>		
		<mx:VBox width="100%"  height="100%" backgroundColor="#FFFFFF" horizontalGap="0" verticalGap="0"  borderVisible="false">			
			<s:Spacer  height="8"/>				
			<AdvancedDataGrid:AdvancedDataGrid id="historyList" width="300%" height="100%"
											   alternatingItemColors="[#f5faff,#eaefff]"
											   dataProvider="{this.resultData}"
											   borderAlpha="0"  horizontalScrollPolicy="on"
											   draggableColumns="true"  wordWrap="true" variableRowHeight="true"  
											   sortableColumns="false" 
											   sortExpertMode="true" doubleClick="locationShip(event)" doubleClickEnabled="true">
				<AdvancedDataGrid:groupedColumns>				
					<SubClasses:AdvancedDataGridColumn dataField="lon" headerText="经度" itemRenderer="{new ItemRendererIFactory()}"  />		
					<SubClasses:AdvancedDataGridColumn dataField="lat" headerText="纬度" />										
					<SubClasses:AdvancedDataGridColumn  dataField="time" headerText="信号采集时间" labelFunction="formatTime" />	
				</AdvancedDataGrid:groupedColumns>
			</AdvancedDataGrid:AdvancedDataGrid>
		</mx:VBox>
	</mx:VBox>
</s:TitleWindow>
