<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!doctype html>
<html>
<head>
	<meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1"/>
	
	<%@ include file="/WEB-INF/views/common.jsp" %>
	<link rel="stylesheet" type="text/css" href="${contextRoot }/css/common.css" />
	<link rel="stylesheet" type="text/css" href="${contextRoot }/css/main.css" />
	
	<title>SIGINFO_MAP</title>
</head>
<body class="sang">
<div id="staticMap" style="width:600px;height:300px;border:1px solid #000"></div>

<div style="float:left">
<canvas id="aring_0_canvas" width="80" height="80" style="border:1px solid #000"></canvas>
<canvas id="aring_1_canvas" width="80" height="80" style="border:1px solid #000"></canvas>
<canvas id="aring_2_canvas" width="80" height="80" style="border:1px solid #000"></canvas>
<canvas id="aring_3_canvas" width="80" height="80" style="border:1px solid #000"></canvas>
<canvas id="aring_4_canvas" width="80" height="80" style="border:1px solid #000"></canvas>
<canvas id="aring_5_canvas" width="80" height="80" style="border:1px solid #000"></canvas>
<canvas id="aring_6_canvas" width="80" height="80" style="border:1px solid #000"></canvas>
<canvas id="aring_7_canvas" width="80" height="80" style="border:1px solid #000"></canvas>
<canvas id="bring_0_canvas" width="80" height="80" style="border:1px solid #000"></canvas>
<canvas id="bring_1_canvas" width="80" height="80" style="border:1px solid #000"></canvas>
<canvas id="bring_2_canvas" width="80" height="80" style="border:1px solid #000"></canvas>
<canvas id="bring_3_canvas" width="80" height="80" style="border:1px solid #000"></canvas>
<canvas id="bring_4_canvas" width="80" height="80" style="border:1px solid #000"></canvas>
<canvas id="bring_5_canvas" width="80" height="80" style="border:1px solid #000"></canvas>
<canvas id="bring_6_canvas" width="80" height="80" style="border:1px solid #000"></canvas>
<canvas id="bring_7_canvas" width="80" height="80" style="border:1px solid #000"></canvas>
</div>
<h3 id="exportCnt" style="padding:10px">엑셀파일 생성..</h3>
<img src="/images/dataLoading.jpg" class="imgDataLoading" />

<script src="${contextRoot }/js/common/hashmap.js"     type="text/javascript" ></script>
<script src="${contextRoot }/js/common/common-all.js"  type="text/javascript" ></script>
<script src="${contextRoot }/js/common/common.js"      type="text/javascript" ></script>
<script src="${contextRoot }/js/common/html2canvas.js" type="text/javascript" ></script>
<script type="text/javascript">

var regionCd  = '${regionCd}';
var regionNm  = '${regionNm}';
var strtIntNo = '${strtIntNo}';
var endIntNo  = '${endIntNo}';
var intNoArr = [];

var staticMapContainer = document.getElementById('staticMap'),
   staticMapOption = {
       center: new kakao.maps.LatLng(37.482006958003396, 127.04298636046764), // 이미지 지도의 중심좌표
       level: 1
   };
var staticMap = new kakao.maps.Map(staticMapContainer, staticMapOption);

$.ajax({
	type : 'post',
	url  : 'getEventIntNo.do',
	data : 'regionCd='+regionCd+
	       '&strtIntNo='+strtIntNo+
	       '&endIntNo='+endIntNo,
	beforeSend: function() {
	    $('.imgDataLoading').show();
	},
	success : function(data) {
		var totLength = data.length;
		console.log('totLength : ' + totLength);
		var ii = 0;
		var mapImg;
		if (totLength > 0)
		{
			var regionNm = data[0].REGION_NM;
			var staticARingPhaseArr;
			var staticBRingPhaseArr;
			var aRing0,aRing1,aRing2,aRing3,aRing4,aRing5,aRing6,aRing7,
			bRing0,bRing1,bRing2,bRing3,bRing4,bRing5,bRing6,bRing7;
			
			callback();
			function callback()
			{
				mapImg = null;
				staticARingPhaseArr = [];
				staticBRingPhaseArr = [];
				intNoArr.push(data[ii].INT_NO);
				
				var regionCd = data[ii].REGION_CD;
				var intNo    = data[ii].INT_NO;
				var lng  = data[ii].X_COORD;
				var lat  = data[ii].Y_COORD;
				
				staticMap.setCenter(new kakao.maps.LatLng(lat, lng));
				
				staticAringPhaseArr = [data[ii].A_RING_1_PHASE_CONF_CD,data[ii].A_RING_2_PHASE_CONF_CD,data[ii].A_RING_3_PHASE_CONF_CD,data[ii].A_RING_4_PHASE_CONF_CD
				                       ,data[ii].A_RING_5_PHASE_CONF_CD,data[ii].A_RING_6_PHASE_CONF_CD,data[ii].A_RING_7_PHASE_CONF_CD,data[ii].A_RING_8_PHASE_CONF_CD];
				staticBringPhaseArr = [data[ii].B_RING_1_PHASE_CONF_CD,data[ii].B_RING_2_PHASE_CONF_CD,data[ii].B_RING_3_PHASE_CONF_CD,data[ii].B_RING_4_PHASE_CONF_CD
				                       ,data[ii].B_RING_5_PHASE_CONF_CD,data[ii].B_RING_6_PHASE_CONF_CD,data[ii].B_RING_7_PHASE_CONF_CD,data[ii].B_RING_8_PHASE_CONF_CD];
				
				var marker = new kakao.maps.Marker({
					position: new kakao.maps.LatLng(lat, lng),
				   	image: new kakao.maps.MarkerImage (
				   		    '/images/sigCtlr.png',
				   		    new kakao.maps.Size(30, 30),
				   		    {
				   		        offset: new kakao.maps.Point(0, 15)
				   		    }),
				    map: staticMap
				});
				
				var aringInCoords = null;
				var aringOutCoords = null;
				var bringInCoords = null;
				var bringOutCoords = null;
				var aRingTemp = null;
				var bRingTemp = null;
				var ringAIn = null;
				var ringAOut = null;
				var ringBIn = null;
				var ringBOut = null;
				
				var aPhaseArr = [];
				var bPhaseArr = [];
				var centerPoint = {x:40, y:40};
				
				for(var jj = 0; jj < staticAringPhaseArr.length; jj++)
				{
					aRingTemp = staticAringPhaseArr[jj];
					var pedeFlag = false;
					if(typeof aRingTemp != 'undefined')
					{
						ringAIn  = Number(aRingTemp.substring(1,4));
						if(aRingTemp.substring(4,7) == '') 
						{
							ringAOut = Number(aRingTemp.substring(1,4)) + 180;
							if(ringAOut > 360) ringAOut = ringAOut - 360;
							pedeFlag = true;
						}
						else ringAOut = aRingTemp.substring(4,7);
						
						var strtAPoint = calRealToScreen(ringAIn);
						var endAPoint  = calRealToScreen(ringAOut);
						
						aPhaseArr.push(drawLinesOnCanvas('aring_'+jj+'_canvas', strtAPoint, centerPoint, endAPoint, pedeFlag));
					}
					else
					{
						aPhaseArr.push(drawLinesOnCanvas('aring_'+jj+'_canvas', null, null, null, pedeFlag));
					}
				}
				for(var kk = 0; kk < staticBringPhaseArr.length; kk++)
				{
					bRingTemp = staticBringPhaseArr[kk];
					var pedeFlag = false;
					if(typeof bRingTemp != 'undefined')
					{
						ringBIn  = Number(bRingTemp.substring(1,4));
						if(bRingTemp.substring(4,7) == '') 
						{
							ringBOut = Number(bRingTemp.substring(1,4)) + 180;
							if(ringBOut > 360) ringBOut = ringBOut - 360;
							pedeFlag = true;
						}
						else ringBOut = bRingTemp.substring(4,7);
						
						var strtBPoint = calRealToScreen(ringBIn);
						var endBPoint  = calRealToScreen(ringBOut);
						
						bPhaseArr.push(drawLinesOnCanvas('bring_'+kk+'_canvas', strtBPoint, centerPoint, endBPoint, pedeFlag));
					}
					else
					{
						bPhaseArr.push(drawLinesOnCanvas('bring_'+kk+'_canvas', null, null, null, pedeFlag));
					}
				}

				setTimeout(function() {
					//지도 이미지 캡처..
					html2canvas($('#staticMap')[0], {
						useCORS: true, // 다른사이트의리소스가있을때활성화(그러나...Access-Control-Allow-Origin 필요)
						logging: false,
						//removeContainer: true,
						ignoreElements: true
						//imageTimeout:5000
					}).then(function(canvas) {
						mapImg = canvas.toDataURL('image/png');
						$.ajax({
					        type : 'post',
					        url  : 'saveIntMap.do',
					        data : 'mapImg='+mapImg+
					        	   '&aPhaseArr='+aPhaseArr+
					        	   '&bPhaseArr='+bPhaseArr+
					        	   '&regionCd='+regionCd+
					        	   '&intNo='+intNo,
					        success : function() {
					        	
					        	if (ii < totLength)
								{
						        	//console.log('--------------------'+ii+'번 캡처파일 생성--------------------');
						        	makeExcelFile(intNo);
				    				ii++;
				    				if (ii != totLength)
				    				{
				    					callback();
				    				}
				    				else
				    				{
				    					console.log('--------------------캡처파일 생성 종료--------------------');
				    					//makeExcelFile();
				    					$('.imgDataLoading').hide();
				    	            	alert('다운로드를 완료하였습니다.');
				    				}
								}
					        },
					        complete: function() {

					        },
					        error : function(error) {
								console.log(error);
					        }
					    });
					});
					
				}, 1000 * 1);
			}
		}
	},
	error : function(error) {
		
	}
});

function makeExcelFile(intNo) {
	/* $('#intNoArr').val(intNoArr);
	$('#writeSiginfoExcel').submit(); */
	
	$.ajax({
        type : 'post',
        url  : 'writeSiginfoExcel.do',
        data : 'regionCd='+regionCd+
               '&regionNm='+regionNm+
               '&intNo='+intNo,
        success : function(data) {
        	console.log(intNo+'성공');
        	$('#exportCnt').empty().html(regionNm+'_'+intNo+' 엑셀파일 생성..');
        	//if(data.length > 0)
        	/* {
        		$('.imgDataLoading').hide();
            	alert('다운로드를 완료하였습니다.');
        	} */
        },
        complete: function() {
        	/* $('.imgDataLoading').hide();
        	alert('다운로드를 완료하였습니다.'); */
        },
        error : function(error) {
            //alert('다운로드에 실패하였습니다.');
        	//window.close();
            /* $.ajax({
                type : 'post',
                url  : 'deletePosImgs.do',
                data : 'regionCd='+regionCd+
                       '&intNoArr='+intNoArr,
                success : function(data) {
                	$('.imgDataLoading').hide();
                }
        	}); */
        }
	});
	
	
}

/* function pointFromCoords(map,lat,lng) {
	
	
	var mapProjection = map.getProjection(),
   	latlng = new kakao.maps.LatLng(lat, lng);
	
	return mapProjection.pointFromCoords(latlng);
} */

/* function coordToAngle(ring, lat, lng) {
	
	var distance = 0.007;
	
	var rad = ring * 0.017453293;
	var deltaLat = distance * Math.cos(rad);
	var deltaLng = distance * Math.sin(rad);
	
	deltaLat = (deltaLat * 360) / 40000;
	deltaLng = (deltaLng * 360) / 40000;
	
	deltaLat += lat;
	deltaLng += lng;
	
	return {lat : deltaLat, lng : deltaLng};
} */

function calRealToScreen(ring) {
	var rad = ring - 90;
	if(rad < 360) rad + 360;
	
	rad = rad * 3.14159/180;
	var x = 40 + 20 * Math.cos(rad);
	var y = 40 + 20 * Math.sin(rad);
	
	return {x : x, y : y};
}

function drawLinesOnCanvas(cvs, strtPoint, centerPoint, endPoint, pedeFlag) {
	
	//canvas에 현시 그리기..
	var sigCanvas = document.getElementById(cvs);
	var ctx = sigCanvas.getContext('2d');
	
	ctx.clearRect(0, 0, sigCanvas.width, sigCanvas.height);
	ctx.imageSmoothingEnabled = true;
	
	if(strtPoint != null)
	{
		ctx.lineCap = 'butt';
		ctx.lineWidth = 2;
		ctx.beginPath();
		ctx.moveTo(strtPoint.x,strtPoint.y);
		ctx.lineTo(centerPoint.x,centerPoint.y);
		ctx.stroke();
		ctx.lineTo(endPoint.x,endPoint.y);
		ctx.stroke();
		
		//화살표 그리기..
		canvas_arrow(ctx, centerPoint.x, centerPoint.y, endPoint.x, endPoint.y);
		
		if(pedeFlag) canvas_arrow(ctx, centerPoint.x, centerPoint.y, strtPoint.x, strtPoint.y);
	}
	
	var cvsStr = sigCanvas.toDataURL('image/png').replace('data:image/png;base64,','').replace('/ /gi','+');
	
	return cvsStr;
}

function canvas_arrow(context, fromx, fromy, tox, toy) {
    var headlen = 10;   // length of head in pixels
    var angle = Math.atan2(toy-fromy,tox-fromx);
    context.imageSmoothingEnabled = true;
    context.moveTo(fromx, fromy);
    context.lineTo(tox, toy);
    context.stroke();
    context.lineTo(tox-headlen*Math.cos(angle-Math.PI/6),toy-headlen*Math.sin(angle-Math.PI/6));
    context.stroke();
    context.moveTo(tox, toy);
    context.lineTo(tox-headlen*Math.cos(angle+Math.PI/6),toy-headlen*Math.sin(angle+Math.PI/6));
    context.stroke();
}

</script>

</body>
</html>

