
//实时温湿度曲线
$(".single .list").delegate("li","click",function(event){
	//var target = $(event.target);
	var i = $(this).attr("build-index");
	var title = $(this).find('.room_num').text();
	var deviceId = $(this).attr("device-id");
	$(".window-ssqx .window-title").text(title)
	$(".window-ssqx").show();
	myChart_ssqx.resize();
	var date = new Date();
	var fromDate = date.setHours(0,0,0,0)/1000;
	var toDate = date.setHours(24,0,0,0)/1000;
	if(deviceId != ''){
		var date = new Date();
		var getTempLineUrl="/analyse/hm/device/history/by-device-id";
		var getTempLineParam={
			deviceId:deviceId,
			type:1,
			fromDate:fromDate,
			toDate:toDate		
		}
		var getHumiLineParam={
			deviceId:deviceId,
			type:2,
			fromDate:fromDate,
			toDate:toDate
			
		}
		
		//
		var xAxis = [];
		var nowHour = moment.getHours();
		for(var i=0;i<=nowHour;++i){
			xAxis[i] = (i<10?"0"+i:i)+":00";
		}
		
		var humiArr = [];
					
		var series = [];
		
		
		option_ssqx.series = series;
			
		myChart_ssqx.setOption(option_ssqx, true);
		getData(getTempLineUrl,getTempLineParam,"GET").then(res => {
			var xAxis = [];
			
			var contentlen = res.content!=undefined?res.content.length:0;
			var tempChannel = [];//构建多路温度曲线
			for(var i=0;i<contentlen;++i){
				var d = new Date(res.content[i].created)
				var h = d.getHours();
				var m = d.getMinutes();
				var oneXaxis = (h<10?"0"+h:h)+":"+(m<10?"0"+m:m)
				
				if(xAxis.indexOf(oneXaxis)<0){
					xAxis.push(oneXaxis);
				}
				
				var channelNo = 'channel-'+res.content[i].channelNo;
				if(tempChannel[channelNo]==undefined){
					tempChannel[channelNo] = [];
					//多路温度传感器
				}
					tempChannel[channelNo].push({
						value:res.content[i].value,
						name:'℃('+channelNo+')'
					})			
			}
			
			for(var k in tempChannel){
				
				var seriesData = {
					name:'温度',
					type:'line',					
					smooth: true,
					data:tempChannel[k],				
					lineStyle:{ 
						normal:{
							color:'#ef1a0f'  
						}
					} 
										
				}
				series.push(seriesData);
			}
			option_ssqx.xAxis.data = xAxis.reverse();
			option_ssqx.series = series;
			console.log(xAxis)
			myChart_ssqx.setOption(option_ssqx, true);
			
		})
		getData(getTempLineUrl,getHumiLineParam,"GET").then(res => {
			var xAxis = [];
			var contentlen = res.content!=undefined?res.content.length:0;
			var humiChannel = [];//构建多路湿度曲线
			for(var i=0;i<contentlen;++i){
				var d = new Date(res.content[i].created)
				var h = d.getHours();
				var m = d.getMinutes();
				var oneXaxis = (h<10?"0"+h:h)+":"+(m<10?"0"+m:m)
				
				if(xAxis.indexOf(oneXaxis)<0){
					xAxis.push(oneXaxis);
				}
				var channelNo = 'channel-'+res.content[i].channelNo;
				if(humiChannel[channelNo]==undefined){
					humiChannel[channelNo] = [];
					//多湿度传感器
				}
					humiChannel[channelNo].push({
						value:res.content[i].value,
						name:'RH('+channelNo+')'
					})			
			}
			for(var k in humiChannel){	
				var seriesData = {
					name:'湿度',
					type:'line',					
					smooth: true,
					data:humiChannel[k],				
					lineStyle:{ 
						normal:{
							color:'#0fc6ef'  
						}
					} 
										
				}
				series.push(seriesData);
			}
			//console.log(series)
			option_ssqx.series = series;
			option_ssqx.xAxis.data = xAxis.reverse();
			console.log(xAxis)
			myChart_ssqx.setOption(option_ssqx, true);
		})
	}			
})
$("#dataSet").click(function(){
	//$(".windows-dataset").show();
	
})

//播放器
var player=null;
$(".open-box-container").on('click',function(){
	$(this).hide();
	if(player!=null){
		player.stop();
		player.destroy()
		player=null;
	}
	
})


//ESC 关闭layer弹窗
	$(window).keyup(function (e) {
		if (e.keyCode == 27) {			
			$(".open-box-container").hide();
			
			if(player!=null){
				///console.log(player)
				player.stop();
				player.destroy();
				player=null;
			}	
		}
	});
$(".open-lauer-box").on('click',function(){
	event.stopPropagation();
})
//地图热点
var img_width = $(".img_window").width();
var img_height = $(".img_window").height();
$("#diagonal").attr('width',img_width+'px');
$("#diagonal").attr('height',img_height+'px');

var videoDevice = [1,2,4,5,10,11,13,14,21,24,26,33,34,42,45,46,47,48];
var tempDevice = [0,2,5,6,8,13,21,24,26];

$("#img_map").delegate("area","click",function(event){
				
				var canvers = document.getElementById("diagonal");//为了区域现形做一个画布
				 var context = canvers.getContext("2d");
				 context.globalAlpha = 0.5;
				 context.clearRect(0, 0, 1010, 468);
                 var target = $(event.target);               
				var i = target.index();
				console.log(i)
				var n = videoDevice.indexOf(i);//是否有视频设备
				var m = tempDevice.indexOf(i);//是否有监测设备
				
				if(n>=0){
					//有视频
					var title = target.attr('title');
					var channel = target.attr('channel-data');
					$(".windows-spjk .window-title").text(title);
					$(".windows-spjk").show();
					//获取设备信息					
					//监控设备
					var d = JSON.parse(channel);
					if(currIp==loginIp){
					//登录IP和设备IP一致
							
						videoIp = lanIp
						player = play(0,d[0].rtsp,d[0].size);
							
					}else{
						//用普清
						videoIp = currIp;
								
						player = play(0,d[1].rtsp,d[1].size)
					}

				}
				if(m>=0){
					//有监测
					$(".single .list li").removeClass('select')
					$(".single .list li.buildEnv-"+m).addClass('select')
					//15S后移除
					setTimeout(function(){
						$(".single .list li").removeClass('select');
						context.clearRect(0, 0, 1130, 476);
					},15000)
				}
				
				context.beginPath();
                    var strs = new Array(); //定义一数组
					var coords = target.attr('coords');
					coords=coords.replace("\"","");
					coords=coords.replace("\"","");
                    strs = coords.split(",");
					//console.log(strs);
                    var i1, i2;
                    for (var i = 0; i < strs.length; i++) {
						//console.log(strs[i])
                        if (i % 2 == 0) {
                            i1 = strs[i];
                        }
                        if (i % 2 == 1) {
                            i2 = strs[i];
                            if (i == 1) {
                                context.moveTo(i1, i2);
                            }
                            else {
                                context.lineTo(i1, i2);
                            }
                        }
                    }
                    context.fillStyle = "#f00";
                    context.fill();
					//console.log(context);
                    context.closePath(); //闭合
})

/**
  * 小数保留n位，四舍五入
  * @param  {[type]} decimal [十进制小数]
  * @param  {[type]} n       [保留小数点后有效位]
  * @return {[type]}         [十进制保留小数点后n位]
  */
function decimal_common(decimal,n){
	var pv = Math.pow(10,n);
	return Math.round(decimal*pv)/pv;
}
/**
 * [根据比例系数数组重新计算位置坐标coords]
 * @param  {[type]} class_      [area的class]
 * @param  {[type]} ratio_Array [area的比例系数数组]
 * @param  {[type]} shape       [area的shape属性]
 * @param  {[type]} radius      [area为circle时的半径]
 * @return {[type]}             [description]
 */
function reCoords_(class_,ratio_Array,shape,radius){
	var picw = $("#pic").width(); //当前图片的宽度
	var pich = $("#pic").height(); //当前图片的高度
	if(shape=="rect"){
		//根据每个area标签的位置比例系数计算出新的坐标位置
		var xy_arr = ratio_Array.map(function(item,index){
			if(index % 2 === 0){ //X坐标值
			//console.log(picw)
				return parseInt(picw*item);
			}else{ //Y坐标值
				return parseInt(pich*item);
			}	
	 	});
		var xy_str = xy_arr.join(","); //拼接出新的坐标位置coords
	 	$("."+class_).attr("coords",'"'+xy_str+'"');
	}else if(shape=="poly"){
		//根据每个area标签的位置比例系数计算出新的坐标位置
		//console.log(picw)
		var xy_arr = ratio_Array.map(function(item,index){
			if(index % 2 === 0){ //X坐标值
				return parseInt(picw*item);
			}else{ //Y坐标值
				return parseInt(pich*item);
			}	
	 	});
		var xy_str = xy_arr.join(","); //拼接出新的坐标位置coords
	 	$("."+class_).attr("coords",'"'+xy_str+'"');
	}else if(shape=="circle"){
		//根据每个area标签的位置比例系数计算出新的坐标位置
		var xy_arr = ratio_Array.map(function(item,index){
			if(index == 0){ //X坐标值
				return parseInt(picw*item);
			}else if(index == 1){ //Y坐标值
				return parseInt(pich*item);
			}else{
				return parseInt(radius*item);
			}
	 	});
		var xy_str = xy_arr.join(","); //拼接出新的坐标位置coords
	 	$("."+class_).attr("coords",'"'+xy_str+'"');
	}				
}
//热点图片自适应坐标
var oldPicW = 1130; //原始图片宽
var oldPicH = 476; //原始图片高
/********************************计算area标签的位置比例系数************************************/
	//获取map标签里的所有area标签
	var $area = $("#buildmap").find("area");
	$.each($area,function(index,data){
		var shape = $(data).attr("shape"); //获取area标签的shape属性（矩形rect，圆形circle，多边形poly）
		var coordsArray  = $(data).attr("coords").replace(/\"/g,"").split(","); //将area标签的coords转换成数组
		var class_ = $(data).attr("class"); //获取area标签的class属性
		if(shape=="rect"){ //矩形rect
			//根据每个area标签的位置坐标计算出在整张图片的位置比例系数
			var coords_Array = [],ratio_Array = []; //coords_Array用于存放根据coords计算出来的比例系数数组
			for(var j=0,len=coordsArray.length;j<len;j++){
				if(j % 2 === 0){ //X坐标值
					coords_Array.push(decimal_common(coordsArray[j]/oldPicW,4));
				}else{ //Y坐标值
					coords_Array.push(decimal_common(coordsArray[j]/oldPicH,4));
				}
			}
			//ratio_Array作为比例系数数组形参重新计算位置坐标
			ratio_Array = coords_Array.concat(ratio_Array);
			reCoords_(class_,ratio_Array,shape,0);
			$(window).resize(function() {
			 	reCoords_(class_,ratio_Array,shape,0);
			});
		}else if(shape=="poly"){ //多边形poly
			//根据每个area标签的位置坐标计算出在整张图片的位置比例系数
			
			var coords_Array = [],ratio_Array = [];
			for(var j=0,len=coordsArray.length;j<len;j++){
				if(j % 2 === 0){ //X坐标值
					coords_Array.push(decimal_common(coordsArray[j]/oldPicW,4));
				}else{ //Y坐标值
					coords_Array.push(decimal_common(coordsArray[j]/oldPicH,4));
				}
			}
			ratio_Array = coords_Array.concat(ratio_Array);
			reCoords_(class_,ratio_Array,shape,0);
			$(window).resize(function() {
			 	reCoords_(class_,ratio_Array,shape,0);
			});
		}else if(shape=="circle"){ //圆形circle
			//根据每个area标签的位置坐标计算出在整张图片的位置比例系数
			var coords_Array = [],ratio_Array = [];
			for(var j=0;j<2;j++){ //圆只有两个坐标值和一个半径，半径以最大的比率去缩放
				if(j % 2 === 0){ //X坐标值
					coords_Array.push(decimal_common(coordsArray[j]/oldPicW,4));
				}else{ //Y坐标值
					coords_Array.push(decimal_common(coordsArray[j]/oldPicH,4));
				}
			}
			coords_Array.push(coords_Array[0]>=coords_Array[1]?coords_Array[0]:coords_Array[1]);//设置半径的比率
 
 
			ratio_Array = coords_Array.concat(ratio_Array);
			reCoords_(class_,ratio_Array,shape,coordsArray[2]);
			$(window).resize(function() {
			 	reCoords_(class_,ratio_Array,shape,coordsArray[2]);
			});
		}
	});

	
	
	
	////////////////////////////////////////////////
	let step = 0.1;
    let INNER = false;
	let SCALE = 1;
    /*function $(select) {
      return document.querySelector(select);
    }*/
    // 鼠标相对页面的位置
    function getMousePos(event) {
      let e = event || window.event;
      let scrollX =
        document.documentElement.scrollLeft || document.body.scrollLeft;
      let scrollY =
        document.documentElement.scrollTop || document.body.scrollTop;
      let x = e.pageX || e.clientX + scrollX;
      let y = e.pageY || e.clientY + scrollY;
      //alert('x: ' + x + '\ny: ' + y);
      return { x: x, y: y };
    }
    function getElementPosition(select) {
      let dom = document.querySelector(select);
      let scrollX =
        document.documentElement.scrollLeft || document.body.scrollLeft;
      let scrollY =
        document.documentElement.scrollTop || document.body.scrollTop;
      let rect = dom.getBoundingClientRect();
      let x = scrollX + dom.getBoundingClientRect().left;
      let y = scrollY + dom.getBoundingClientRect().top;
      let height = dom.getBoundingClientRect().height;
      let width = dom.getBoundingClientRect().width;
      return { x: x, y: y, height: height, width: width };
    }
    function mouseIndom(event) {
      let mouseMsg = getMousePos(event);
      let domMsg = getElementPosition('#img_map');
      let flagX = mouseMsg.x > domMsg.x && mouseMsg.x < domMsg.x + domMsg.width;
      let flagY =
        mouseMsg.y > domMsg.y && mouseMsg.y < domMsg.y + domMsg.height;
      if (flagX && flagY) {
        //console.log('鼠标位于元素里面啦！');
        return true;
      } else {
        //console.log('鼠标位于元素外面拉！');
        return false;
      }
    }
    // 文档鼠标移动
    document.onmousemove = function(event) {
      INNER = mouseIndom(event);
      //console.log(INNER)
    };
    if (window.addEventListener)
      //FF,火狐浏览器会识别该方法
      window.addEventListener('DOMMouseScroll', wheel, { passive: false });
    window.onmousewheel = document.onmousewheel = wheel; //W3C
    //统一处理滚轮滚动事件
    function wheel(event) {
		//console.log(mouseIndom(event));
      var delta = 0;
      if (!event) event = window.event;
      if (event.wheelDelta) {
        //IE、chrome浏览器使用的是wheelDelta，并且值为“正负120”
        delta = event.wheelDelta / 120;
        if (window.opera) delta = -delta; //因为IE、chrome等向下滚动是负值，FF是正值，为了处理一致性，在此取反处理
      } else if (event.detail) {
        //FF浏览器使用的是detail,其值为“正负3”
        delta = -event.detail / 3;
      }
	  
      if (delta) handle(delta, event);
    }
    //上下滚动时的具体处理函数
    function handle(delta, event) {
	
      if (INNER) {
        if (delta < 0) {
          //向下滚动
          console.log('向下滚动');
          let scale =
            Number.parseFloat(document.querySelector('#box').style.transform.replace('scale(', '')) +
            step;
			if(scale>5){
				return;
			}
		  SCALE = scale;
          document.querySelector('#box').style.webkitTransform = 'scale(' + scale + ')';
		  
          //$('#box').innerText = '缩小了' + scale;
        } else {
          //向上滚动
          console.log('向上滚动');
		  
          let scale =
            Number.parseFloat(document.querySelector('#box').style.transform.replace('scale(', '')) -
            step;
			if(scale<1){
				return;
			}
			SCALE = scale;
          document.querySelector('#box').style.webkitTransform = 'scale(' + scale + ')';
          //$('#box').innerText = '放大了' + scale;
        }
        //event.preventDefault();
        event.stopPropagation();
        return;
      }
    }
	 window.onload=function() {
    var disX = disY = 0;                         // 鼠标距离div的左距离和上距离
    var div1 = document.getElementById("box");  // 得到div1对象
     
    // 鼠标按下div1时
    div1.onmousedown = function(e) {
		
        var evnt = e || event;                   // 得到鼠标事件
        disX = evnt.clientX - div1.offsetLeft;   // 鼠标横坐标 - div1的left
		console.log("evnt.clientX:"+evnt.clientX)
		console.log("box.offsetLeft:"+div1.offsetLeft)
        disY = evnt.clientY - div1.offsetTop;    // 鼠标纵坐标 - div1的top
        if($("#box").css("transform") == "matrix(1, 0, 0, 1, 0, 0)" && $("#box").css("left")=="0px" && $("#box").css("top")=="0px"){
			return;
		}
        // 鼠标移动时
        document.onmousemove = function(e) {
			
			
            var evnt = e || event;
            var x = evnt.clientX - disX;
            var y = evnt.clientY - disY;
            //var window_width  = document.documentElement.clientWidth  - div1.offsetWidth;
            //var window_height = document.documentElement.clientHeight - div1.offsetHeight;
             
            //x = ( x < 0 ) ? 0 : x;                          // 当div1到窗口最左边时
            //x = ( x > window_width ) ? window_width : x;    // 当div1到窗口最右边时
            //y = ( y < 0 ) ? 0 : y;                          // 当div1到窗口最上边时
            //y = ( y > window_height ) ? window_height : y;  // 当div1到窗口最下边时
             
            div1.style.left = x + "px";
            div1.style.top  = y + "px";
        };
         
        // 鼠标抬起时
        document.onmouseup = function() {
            document.onmousemove =null;
            document.onmouup = null;
        };
         
        return false;
    };
	$("#box").on('dblclick',function(e){
		//双击还原
		div1.style.webkitTransform = 'scale(1)';
		div1.style.left = "0px";
        div1.style.top  = "0px";
		//INNER = false;
		document.onmousemove = function(event) {
		  INNER = mouseIndom(event);
		  console.log(INNER)
		};
	});
};
	
	