/************************************
 * 地图公共参数定义
 *************************************/
var minLeave = 5;//地图最小展示级别
var maxLeave = 15;//地图最大展示级别
var defaultlevel = 12;//地图默认展示级别
var point = new BMap.Point(120.029012,30.024203); //地图加载中心点(成都电科院地址)

/************************************
获取监测点经纬度信息加载到地图
************************************/
//创建图标
var redIcon = new BMap.Icon("../images/img/pred.png", new BMap.Size(25, 25));
var greenIcon = new BMap.Icon("../images/img/pgreen.png", new BMap.Size(25, 25));
var yellowIcon = new BMap.Icon("../images/img/pyellow.png", new BMap.Size(25, 25));
var grayIcon = new BMap.Icon("../images/img/pgray.png", new BMap.Size(25, 25));
var stationIcon = new BMap.Icon("../images/img/station.png", new BMap.Size(25, 25));
var wingrayIcon = new BMap.Icon("../images/img/wingray.gif", new BMap.Size(40, 40));
var winyellowIcon = new BMap.Icon("../images/img/winyellow.gif", new BMap.Size(40,40));
var wingreenIcon = new BMap.Icon("../images/img/wingreen.gif", new BMap.Size(40,40));
var winredIcon = new BMap.Icon("../images/img/winred.gif", new BMap.Size(40, 40));
//终端状态
var redMarkerOptions = {icon:redIcon,enableDragging:false}
var greenMarkerOptions = {icon:greenIcon,enableDragging:false}
var yellowMarkerOptions = {icon:yellowIcon,enableDragging:false}
var grayMarkerOptions = {icon:grayIcon,enableDragging:false}
var stationOptions = {icon:stationIcon,enableDragging:false}
var wingrayMarkerOptions = {icon:wingrayIcon,enableDragging:false}
var winyellowMarkerOptions = {icon:winyellowIcon,enableDragging:false}
var wingreenMarkerOptions = {icon:wingreenIcon,enableDragging:false}
var winredMarkerOptions = {icon:winredIcon,enableDragging:false}

/************************************
 * 加载地里信息地图
 *************************************/
function getGISMap(element,drgging,scrollwheel,leave) {
	defaultlevel = leave;//地图的放大等级

    var map = new BMap.Map(element, {minZoom:minLeave,maxZoom: maxLeave, enableMapClick: false});//实例化地图
    map.centerAndZoom(point, defaultlevel);//设初始化地图
    /********************
     * 拖拽地图
     ********************/
    if(drgging)
    	map.enableDragging();//启用地图拖拽，默认启用
    else
    	map.disableDragging();//禁用地图拖拽
    /********************
     * 地图滚轮
     *******************/
    if(scrollwheel)
    	map.enableScrollWheelZoom();//启用滚轮放大缩小，默认禁用
    else
    	map.disableScrollWheelZoom();//禁用滚轮放大缩小

    map.disableContinuousZoom();//禁用连续缩放效果
    map.disableDoubleClickZoom();//禁用双击放大
    return map;
}

/********************************************
查询所有监测点信息
*******************************************/
function searchLineMaps(){
	var resultData = null;
	$.ajax({
		type : "POST",
		async: false,
		url : "/pqs9200/overview/getLineMaps",
		dataType : "text",
		success : function(data) {
			resultData = $.parseJSON(data);
		 }
	});

	return resultData;
}

/********************************************
获取网络拓扑图信息
*******************************************/
function getGridTop(){
	$.ajax({
			type : "POST",
		url : "/pqs9200/overview/getGridTop",
		dataType : "text",
		success : function(data) {
			var info = $.parseJSON(data);
			//取数据失败，则进行不进行操作
			if (info.code == 500) {
			} else {
				if (info.body != null) {
					drawline(info.body);
				}
			}
		 }
	});
}

/********************************************
采用算法计算出变电站和监测点位信息
***基础数据***变电站点***变电站跟监测点连线***监测点点位信息
*******************************************/
var subMarkers= [];subpointLines= [];pointMarkers= [];
function drawElement(dataarr,map,iFlag){
	var gisInfo = new Object();//存放所有的地理信息地图
	subMarkers= [];subpointLines= [];pointMarkers= [];

	//解析Map
	for(key in dataarr){
		var strkey = key.split(",");
		if(strkey.length == 3){
			//新增变电站的点
			var submarker = new BMap.Marker(new BMap.Point(strkey[1], strkey[2]), stationOptions); //创建变电站点
			submarker.name = strkey[0];//设置变电站名称
			var strTitle = '变电站名称：' + submarker.name;
			submarker.setTitle(strTitle);//设置标注的标题，当鼠标移至标注上时显示此标题

			subMarkers.push(submarker);//把变电站信息放到集合中去
			//解析监测点信息
			var lineMaps = dataarr[key];
			for(var i = 0; i < lineMaps.length; i++){
				var pointmarker = getPoint(lineMaps[i],map,iFlag);
				pointMarkers.push(pointmarker);//把监测点信息放到集合中去
				var polyline = new BMap.Polyline([submarker.getPosition(),pointmarker.getPosition()], {strokeColor:"#006A6A", strokeWeight:2, strokeOpacity:0.5});//创建变电站-监测点折线
				polyline.setStrokeStyle("dashed");
				subpointLines.push(polyline);
			}
		}
	}
	//赋值
	gisInfo.subMarkers = subMarkers;
	gisInfo.subpointLines = subpointLines;
	gisInfo.pointMarkers = pointMarkers;

	/************************************
	把所有元素打到地图上并且影藏
	************************************/
	 for(var i = 0;i <subMarkers.length; i++){
	     map.addOverlay(subMarkers[i]);
	     subMarkers[i].hide();
	 }

	 for(var i = 0;i < subpointLines.length; i++){
	     map.addOverlay(subpointLines[i]);
	     subpointLines[i].hide();
	 }
	return gisInfo;
}

/************************************
获取监测点经纬度信息加载到地图上
***监测点信息（lineMap）***生成类型(iFlag:0 概览界面；1 监测点界面)
************************************/
var dataPoint = 'monitor';
function getPoint(lineMap,map,iFlag) {
   var point = new BMap.Point(lineMap.longitude, lineMap.latitude);
   //监测点点位信息;终端状态;终端状态颜色
   var marker,strState =  '退运',fontState ='#808080';
   //通讯状态,通讯状态颜色
   var strStatus = '中断',fontStatus='#FF0000';
	/********************************
	  终端状态：  2退运    灰色 128,128,128  #808080
	             1检修   金色 255,215,0   #FFD700
	             0投运（正常的则判断通讯状态）
	  通讯状态：  0正常    绿色  0,128,0   #08CF5A
	              1中断    红色  255,0,0   #FF0000
	**********************************/
   switch(lineMap.devflag){
	   case 0:
		   strState = '投运';
	       fontState='#08CF5A';
	       //终端通讯状态（0：中断；1：正常）
		   switch(lineMap.status){
			   case 0:
			       strStatus = '中断';
			       fontStatus='#FF0000';
			       if(lineMap.totalcount > 0)
					   marker = new BMap.Marker(point, winredMarkerOptions);//假如终端出现了暂降事件
			       else
			    	   marker = new BMap.Marker(point, redMarkerOptions);
			       break;
			   case 1:
			       strStatus = '正常';
			       fontStatus='#08CF5A';
			       if(lineMap.totalcount > 0)
					   marker = new BMap.Marker(point, wingreenMarkerOptions);//假如终端出现了暂降事件
			       else
			    	   marker = new BMap.Marker(point, greenMarkerOptions);
			       break;
		    }
	       break;
	   case 1:
		   strState = '检修';
	       fontState='#FFD700';
		   if(lineMap.totalcount > 0)
			   marker = new BMap.Marker(point, winyellowMarkerOptions);//假如终端出现了暂降事件
		   else
	           marker = new BMap.Marker(point, yellowMarkerOptions);
	       break;
	   case 2:
		   strState = '退运';
	       fontState='#808080';
		   if(lineMap.totalcount > 0)
			   marker = new BMap.Marker(point, wingrayMarkerOptions);
		   else
	           marker = new BMap.Marker(point, grayMarkerOptions);
		   break;
   }
   //设置marker其他属性
   marker.index = lineMap.lineindex;//存储监测点的id
   marker.name = lineMap.linename;//存储监测点的名称
   marker.devflag = lineMap.devflag;//存储监测点的状态
   marker.totalcount = lineMap.totalcount;//存储未处理事件

   marker.lineMap = lineMap;//所存储的监测点信息

   var strTitle = '监测点名称：' + lineMap.linename;
   if(lineMap.totalcount > 0){
	   strTitle += '\n' + '未处理暂降事件：' + lineMap.totalcount + '(次)';
   }

  //概览界面才有右击操作
   if(iFlag == 0){
	   marker.addEventListener("rightclick", function (){
		   if(lineMap.totalcount > 0){
			   querySagEvents(lineMap.lineindex);//双击事件的执行代码
		   }else{
			   parent.layer.msg("该监测点未找到未处理暂降事件", {icon: 6,time:1000});
		   }
	   });
   }

   marker.setTitle(strTitle);//设置标注的标题，当鼠标移至标注上时显示此标题
   /************************************
   设置弹出框相关内容
   ************************************/
   //概览界面
   if(iFlag == 0){
	  //组装TIP
	   var showInfo = '<div class="mystyle" style="margin:0;line-height:19px;padding:2px;font-size:12px;font-family:"微软雅黑";font-weight:bold;">' +
	   '<label>&nbsp;供电公司&nbsp;</label>&nbsp;' + lineMap.gdname + '<br/>' +
	   '<label>&nbsp;&nbsp;&nbsp;变电站&nbsp;&nbsp;&nbsp;</label>&nbsp;' + lineMap.subname + '<br/>' +
	   '<label>&nbsp;&nbsp;&nbsp;&nbsp;母线&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</label>&nbsp;' + lineMap.subvname + '<br/>' +
	   '<label>&nbsp;&nbsp;&nbsp;网络参数&nbsp;&nbsp;&nbsp;</label>&nbsp;' + lineMap.ip + '<br/>' +
	   '<label>&nbsp;&nbsp;PT变比&nbsp;&nbsp;</label>&nbsp;' + lineMap.pt1/1000 +'/'+ lineMap.pt2/1000 +'<br/>' +
	   '<label>&nbsp;&nbsp;CT变比&nbsp;&nbsp;</label>&nbsp;' + lineMap.ct1 +'/' + lineMap.ct2 + '<br/>' +
	   '<label>&nbsp;生产厂家&nbsp;</label>&nbsp;' + lineMap.manufacturer + '<br/>' +
	   '<label>&nbsp;终端状态&nbsp;</label>&nbsp;<font color="'+ fontState +'">' + strState + '</font><br/>' +
	   '<label>&nbsp;通讯状态&nbsp;</label>&nbsp;<font color="'+ fontStatus +'">' + strStatus + '</font><br/>' +
	   '<div class="form-inline fr" style="margin:5px 0px 1px 2px;">'+
	   '<button type="button" class="btn btn-primary btn-xs" onclick="openmonitor(\''+ lineMap.lineindex +'\')"> <i class="glyphicon glyphicon-screenshot"></i>查看监测点</button>'+
	   '<button type="button" style="margin:0px 0px 0px 2px;" class="btn btn-primary btn-xs" onclick="openSagEvents(\''+ lineMap.lineindex +'\',\''+ lineMap.totalcount +'\')"> <i class="glyphicon glyphicon-warning-sign"></i>未处理事件('+ marker.totalcount +')</button>'+
	   '</div>';

	   var searchInfoWindow = new BMapLib.SearchInfoWindow(map, showInfo, {
	       title: '监测点名称：' + lineMap.linename, //标题
	       width: 25, //宽度
	       height: 265, //高度
	       searchTypes: [],
	       enableSendToPhone: false
	   });
	   marker.searchInfoWindow = searchInfoWindow;

	   //定义setTimeout执行方法
	   var TimeFn = null;
	   marker.addEventListener("click", function () {
		   // 取消上次延时未执行的方法
		   clearTimeout(TimeFn);
		   //执行延时
		   TimeFn = setTimeout(function(){
			  searchInfoWindow.open(point);
			  activesearchInfoWindow = searchInfoWindow;
		   },250);
	   });

	   marker.addEventListener("dblclick", function () {
		  // 取消上次延时未执行的方法
		   clearTimeout(TimeFn);
		   //双击则弹到监测点界面
			if(window.top.document.getElementById(dataPoint) != null){
				window.top.addTab(dataPoint,'监测点');
				window.top.document.getElementById(dataPoint).contentWindow.zTreeOnAsyncSuccess(marker.index);
			} else if(window.top.document.getElementById('monitor') != null){
				window.top.addTab('monitor','监测点');
				window.top.document.getElementById('monitor').contentWindow.zTreeOnAsyncSuccess(marker.index);
			}else{
				window.top.addTab('monitor?line_index='+ marker.index,'监测点');
				dataPoint = 'monitor?line_index='+ marker.index;

				window.parent.parent.document.getElementById('dataPoint').value=dataPoint;
			}
	   });
   }
   //监测点界面
   else if(iFlag == 1){
       //组装TIP
       var showInfo = '<div class="mystyle" style="margin:0;line-height:19px;padding:2px;font-size:12px;font-family:"微软雅黑";font-weight:bold;">' +
           '<label>&nbsp;供电公司&nbsp;</label>&nbsp;' + lineMap.gdname + '<br/>' +
           '<label>&nbsp;&nbsp;&nbsp;变电站&nbsp;&nbsp;&nbsp;</label>&nbsp;' + lineMap.subname + '<br/>' +
           '<label>&nbsp;&nbsp;&nbsp;&nbsp;母线&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</label>&nbsp;' + lineMap.subvname + '<br/>' +
           '<label>&nbsp;&nbsp;&nbsp;网络参数&nbsp;&nbsp;&nbsp;</label>&nbsp;' + lineMap.ip + '<br/>' +
           '<label>&nbsp;&nbsp;PT变比&nbsp;&nbsp;</label>&nbsp;' + lineMap.pt1/1000 +'/'+ lineMap.pt2/1000 +'<br/>' +
           '<label>&nbsp;&nbsp;CT变比&nbsp;&nbsp;</label>&nbsp;' + lineMap.ct1 +'/'+ lineMap.ct2 + '<br/>' +
           '<label>&nbsp;生产厂家&nbsp;</label>&nbsp;' + lineMap.manufacturer + '<br/>' +
           '<label>&nbsp;终端状态&nbsp;</label>&nbsp;<font color="'+ fontState +'">' + strState + '</font><br/>' +
           '<label>&nbsp;通讯状态&nbsp;</label>&nbsp;<font color="'+ fontStatus +'">' + strStatus + '</font><br/>' +
           '<div class="form-inline fr" style="margin:5px 0px 1px 2px;">'+
           '<button type="button" class="btn btn-primary btn-xs" onclick="openEventStatis()"> <i class="glyphicon glyphicon-screenshot"></i>事件统计</button>'+
           '<button type="button" class="btn btn-primary btn-xs" style="margin:0px 0px 0px 5px;" onclick="openEventSys()"> <i class="glyphicon glyphicon-warning-sign"></i>事件分析</button>'+
           '<button type="button" class="btn btn-primary btn-xs" style="margin:0px 0px 0px 5px;" onclick="openDevRunning()"> <i class="glyphicon glyphicon-briefcase"></i>终端运行管理</button>'+
           '</div>';

       var searchInfoWindow = new BMapLib.SearchInfoWindow(map, showInfo, {
           title: '监测点名称：' + lineMap.linename, //标题
           width: 280, //宽度
           height: 265, //高度
           searchTypes: [],
           enableSendToPhone: false
       });

       marker.searchInfoWindow = searchInfoWindow;

       marker.addEventListener("click", function () {
           searchInfoWindow.open(point);
           $.fn.zTree.getZTreeObj("tree").expandAll(false);
           zTreeOnAsyncSuccess(lineMap.lineindex);
           var nowIndex=$("#lineIndex").val();
//		   pantoPoint(nowIndex);
           changeFlag(true);

           activesearchInfoWindow = searchInfoWindow;
           activepoint = point;
       });
   }
   //范围分析界面
   else if(iFlag == 2){
       //组装TIP
       var showInfo = '<div class="mystyle" style="margin:0;line-height:19px;padding:2px;font-size:12px;font-family:"微软雅黑";font-weight:bold;">' +
           '<label>&nbsp;供电公司&nbsp;</label>&nbsp;' + lineMap.gdname + '<br/>' +
           '<label>&nbsp;&nbsp;&nbsp;变电站&nbsp;&nbsp;&nbsp;</label>&nbsp;' + lineMap.subname + '<br/>' +
           '<label>&nbsp;&nbsp;&nbsp;&nbsp;母线&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</label>&nbsp;' + lineMap.subvname + '<br/>' +
           '<label>&nbsp;&nbsp;&nbsp;网络参数&nbsp;&nbsp;&nbsp;</label>&nbsp;' + lineMap.ip + '<br/>' +
           '<label>&nbsp;&nbsp;PT变比&nbsp;&nbsp;</label>&nbsp;' + lineMap.pt1/1000 +'/'+ lineMap.pt2/1000 +'<br/>' +
           '<label>&nbsp;&nbsp;CT变比&nbsp;&nbsp;</label>&nbsp;' + lineMap.ct1 +'/'+ lineMap.ct2 + '<br/>' +
           '<label>&nbsp;生产厂家&nbsp;</label>&nbsp;' + lineMap.manufacturer + '<br/>' +
           '<label>&nbsp;终端状态&nbsp;</label>&nbsp;<font color="'+ fontState +'">' + strState + '</font><br/>' +
           '<label>&nbsp;通讯状态&nbsp;</label>&nbsp;<font color="'+ fontStatus +'">' + strStatus + '</font><br/>';

       var searchInfoWindow = new BMapLib.SearchInfoWindow(map, showInfo, {
           title: '监测点名称：' + lineMap.linename, //标题
           width: 200, //宽度
           height: 245, //高度
           searchTypes: [],
           enableSendToPhone: false
       });

       marker.searchInfoWindow = searchInfoWindow;

       //定义setTimeout执行方法
       var TimeFn = null;
       marker.addEventListener("click", function () {
           // 取消上次延时未执行的方法
           clearTimeout(TimeFn);
           //执行延时
           TimeFn = setTimeout(function(){
               searchInfoWindow.open(point);
               activesearchInfoWindow = searchInfoWindow;
           },250);
       });
   }
    return marker;
}

/************************************
地图增加相应的元素
 ***********************************/
function controlMapElements(map){
	 var zoom = map.getZoom();

	 var bs = map.getBounds();//获取可视区域
	 for(var i=0;i<subMarkers.length;i++){
		 if(zoom >=15){
			 var subpoint = subMarkers[i].getPosition();
			 var result = BMapLib.GeoUtils.isPointInRect(subpoint, bs);
		     if(result == true){
		    	 subMarkers[i].show();
		     }
		 }else{
			 subMarkers[i].hide();
		 }
	 }

	 for(var i=0;i<subpointLines.length;i++){
		 if(zoom >=15){
			 var subpointarr = subpointLines[i].getPath();
			 var result = true;
			 for(var j=0;j<subpointarr.length;j++){
				 result = BMapLib.GeoUtils.isPointInRect(subpointarr[j], bs);
				 if(result == false)
					 break;
			 }
		     if(result == true){
		    	 subpointLines[i].show();
		     }
		 }else{
			 subpointLines[i].hide();
		 }
	 }
}

/************************************
对所有监测点进行偏移算法
 ***********************************/
function getDataOffset(data){
	var maparr={};
	var tmpmap = {};
	for (var i = 0; i < data.length; i++) {
		//获取变电站名称（key，由变电站名称，经度，纬度组成：事例：变电站1,123.00,135.00）
		var key = data[i].subname + "," + data[i].longitude + "," + data[i].latitude;
		//假如key已经存在了
		if(tmpmap[key]){
			var tmpdata = tmpmap[key];
			tmpdata.push(data[i]);
	    }else{
	    	var tmpdata= [];
	    	tmpdata.push(data[i]);
	    	tmpmap[key] = tmpdata;
	    }
    }

	//根据分组后的监测点进行偏移算法
	var r = 0.0035;
	for(tmpkey in tmpmap){
		var arr = tmpmap[tmpkey];
		var tmplength = arr.length;
		var dataarr = [];
		for(var i = 0;i < tmplength;i++){
			var info = arr[i];
			info.longitude =info.longitude + r*Math.cos(2*Math.PI*(i)/tmplength);
			info.latitude =info.latitude + r*Math.sin(2*Math.PI*(i)/tmplength);
			dataarr.push(info);
		}
		maparr[tmpkey] = dataarr;
	}
	return maparr;
}

/************************************
调用此方法则画范围分析
 ***********************************/
function getRangeAnalysis(map,markers){
  //假如只有一个监测点
  var marlength = markers.length;
  if(marlength > 0){
	  //假如只有一个监测点
	  if(marlength == 1){
		   var marker = markers[0]; //获取marker
		   var c = marker.getPosition();//获取圆心
		   var circle = new BMap.Circle(c, 500);//测试圆
		   //清除地图信息
		   map.clearOverlays();
		   //将圆添加到地图
		   map.addOverlay(circle);
		   //将点打到地图上
		   map.addOverlay(marker);

		   map.centerAndZoom(c, 12);//设置地图等级
		   setTimeout(function(){
			   map.panTo(c);//地图移动到当前位置
			}, 2000);

	  }else{
		  //获取最长距离
		  var marker_start;//最长距离起始监测点
		  var marker_end;//最长距离终点监测点
		  var maxlenght = 0;//最长距离
		  for(var i = 0; i < marlength;i++){
			  marker1 = markers[i];
			  for(var j = i + 1; j < marlength; j++){
				  marker2 = markers[j];
				  //根据几何算法算出两点的距离
				  var length = BMapLib.GeoUtils.getDistance(marker1.getPosition(), marker2.getPosition());
				  //假如距离大于之前长度则重新
				  if(length > maxlenght){
					  maxlenght = length;
					  marker_start = marker1;
					  marker_end = marker2;
				  }
			  }
		  }
		  //计算中心点经纬度
		  var lng = ((marker_start.getPosition().lng + marker_end.getPosition().lng)/2).toFixed(5);
		  var lat = ((marker_start.getPosition().lat + marker_end.getPosition().lat)/2).toFixed(5);
		  var c = new BMap.Point(lng, lat); //圆心
		  var circle = new BMap.Circle(c, maxlenght/2 + 500);//测试圆

	      //将点与圆形添加到地图上
	      map.clearOverlays();
	      map.addOverlay(circle);

	      for(var i = 0; i < marlength;i++){
	    	  map.addOverlay(markers[i]);
		  }

	      map.centerAndZoom(c, 13);//设置地图等级
		  setTimeout(function(){
			   map.panTo(c);//地图移动到当前位置
			}, 2000);
	  }
  }
}
