<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="_csrf" content="${_csrf.token}"/>
<meta name="_csrf_header" content="${_csrf.headerName}"/>
<title>statistics</title>
<script
	src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/highcharts-more.js"></script>
<script src="https://code.highcharts.com/modules/solid-gauge.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/export-data.js"></script>
<script src="https://code.highcharts.com/modules/accessibility.js"></script>
<link rel="stylesheet" href="/css/header.css">
<link rel="stylesheet" href="/css/statistics_new.css">
<script type="text/javascript" src="/js/header.js"></script>
<%--<script type="text/javascript" src="/js/statistics.js"></script>--%>
</head>
<body>
<jsp:include page="header.jsp"></jsp:include>
<div class="container">
	<div class="top-tab api-search on">
		<div class="date on" onclick="topTabClick(this, 'month')">월별 통계 조회</div>
		<div class="api" onclick="topTabClick(this, 'day')">일별 통계 조회</div>
	</div>
	<div class="content-box">
		<div class="left-tab">
			<div class="api-search on" onclick="leftTabClick(this)">
				<div>API 호출 /</div>
				<div>API Token 인증</div>
			</div>
			<div class="system-search" id="systemResource" onclick="leftTabClick(this)">
				<div>시스템 리소스</div>
				<div>정보</div>
			</div>
			<div class="signalStatusGather" id="signalStatusGather" onclick="leftTabClick(this)">
				<div>신호상태 정보</div>
				<div>수집</div>
			</div>
			<div class="signalStatusSend" id="signalStatusSend" onclick="leftTabClick(this)">
				<div>신호상태 정보</div>
				<div>발송</div>
			</div>
		</div>
		<div class="content">
			<div class="search-box">
				<div class="on">
					<div class="month-box on">
						<div>조회 기간 : </div>
						<input type="month" name="searchStartMonth" class="searchStartMonth">
						~
						<input type="month" name="searchEndMonth" class="searchEndMonth">
					</div>
					<div class="day-box">
						<div>조회 기간 : </div>
						<input type="date" name="searchStartDay" class="searchStartDay">
						~
						<input type="date" name="searchEndDay" class="searchEndDay">
					</div>
					<div class="search-button" onclick="drawTable()">조회</div>
				</div>
			</div>
			<div class="table-box">
				<div class="search-content">
					<div class="date-box on">검색기간 : <span class="start"></span> ~ <span class="end"></span></div>
				</div>
				<div class="search-table-box">
					<table class="search-table">
						<thead>
						<tr class="month-head on">
							<th>날짜</th>
							<th>계</th>
							<c:forEach var="day" begin="1" end="31">
								<th>${day}일</th>
							</c:forEach>
						</tr>
						<tr class="day-head">
							<th class="day-th">날짜</th>
							<th class="day-th">계</th>
							<c:forEach var="time" begin="0" end="23">
								<c:if test="${time < 10}">
									<th class="day-th">0${time}시</th>
								</c:if>
								<c:if test="${time >= 10}">
									<th class="day-th">${time}시</th>
								</c:if>
							</c:forEach>
						</tr>
						</thead>
						<tbody class="table-content">
							<tr class="empty-box">
								<td colspan="33" class='nullRow'>조회 내용이 없습니다.</td>
							</tr>
						</tbody>
					</table>
				</div>
				<div class="chart-box">
					<div class="on" id="chart"></div>
				</div>
			</div>
		</div>
	</div>
</div>
</body>
</html>

<script>
	const $startMonth = $('.searchStartMonth');
	const $endMonth   = $('.searchEndMonth');
	const $startDay   = $('.searchStartDay');
	const $endDay     = $('.searchEndDay');
	const $content 	  = $(".table-content");
	const emptyStr    = `<tr class="empty-box">
							<td colspan="33" class='nullRow'>조회 내용이 없습니다.</td>
						</tr>`;
	const now 		  = new Date();
	const nowMonth 	  = now.getFullYear() + '-' + (getDate(now.getMonth() + 1));
	const nowDay      = nowMonth + '-' +  getDate(now.getDate());
	const yesterday   = nowMonth + '-' +  getDate(now.getDate() - 1);
	$startMonth.val(nowMonth);
	$endMonth.val(nowMonth);
	$startDay.val(yesterday);
	$endDay.val(nowDay);

	function getDate(date) {
		if (date < 10) {
			date = "0" + date;
		}
		return date;
	}
	const token = $("meta[name='_csrf']").attr("content");
	const header = $("meta[name='_csrf_header']").attr("content");
	$(document).ajaxStart(()=>{
		$('.content').append('<div class="loading-box"><img src="/image/loading.gif" style="width: 100px; height: 100px; filter:brightness(0.4);"></div>');
	})
	$(document).ajaxStop(()=>{
		$('.content > .loading-box').remove();
	})
	$.ajaxSetup({
		beforeSend: function (xhr) { // 보내기전 로딩바구현
			xhr.setRequestHeader(header, token);
		},
	});

	drawTable();

	function drawTable() {
		const className = $('.left-tab > div.on').attr('class');
		const betweenUrl = $('.search-box > div > div.on').attr('class') === 'month-box on' ? 'Monthly' : 'Daily';
		const inputArr = $('.search-box > div > div.on > input');
		let start = inputArr.eq(0).val();
		let end = inputArr.eq(1).val();

		$('.start').text(start);
		$('.end').text(end);
		const param = {
			start : start,
			end : end,
		}
		let url = '';
		switch (className) {
			case 'api-search on':
				url = '/get' + betweenUrl + 'InvokeTableData.do';
				break;
			case 'system-search on':
				url = '/systemResource' + betweenUrl + 'Data.do';
				break;
			case 'signalStatusGather on':
				url = '/signalStatusGather'+ betweenUrl +'Data.do';
				break;
			case 'signalStatusSend on':
				url = '/signalStatusSend'+ betweenUrl +'Data.do';
				break;
			default:
				return;
		}
		getData("/api"+url, 'post', param, (jsonData)=>{
			if (betweenUrl === 'Daily') {
				recvDailyTableData(jsonData);
			}
			else {
				recvMonthlyTableData(jsonData)
			}
		})
	}

	function recvMonthlyTableData(data) {
		//테이블 초기화
		$content.empty();
		let str = emptyStr;
		const series = [];
		const yAxis = [];
		const leftText = $('.left-tab > div.on').children().eq(0).text();
		let chartWord = '';
		if (leftText === '시스템 리소스') {
			chartWord = '%'
		}
		else {
			chartWord = '건';
		}

		if (data && data.length > 0) {
			str = '';
			const monthMap = new Map() ;
			for (let obj of data) {
				if (!monthMap.get(obj.monthly)) {
					monthMap.set(obj.monthly, []);
				}
				monthMap.get(obj.monthly).push(obj);
			}

			monthMap.forEach((array, key)=>{

				if (leftText === '시스템 리소스') {
					let str1 = '<tr><td rowspan="3">' + key + '</td><td>CPU</td>';
					let str2 = '<tr><td>MEMORY</td>';
					let str3 = '<tr><td>DISK</td>';
					let subStr1 = '';
					let subStr2 = '';
					let subStr3 = '';
					let cpuTot = 0;
					let diskTot = 0;
					let memTot = 0;
					let cpuData = [];
					let memData = [];
					let diskData = [];
					let avgLength = 0;
					for (let ii = 0; ii < 31; ii++) {
						let cpu  = 0;
						let mem  = 0;
						let disk = 0;
						if (array[ii]) {
							cpu  = setTwoDecimalPoint(array[ii].cpuAverage);
							mem  = setTwoDecimalPoint(array[ii].memoryAverage);
							disk = setTwoDecimalPoint(array[ii].diskAverage);
							avgLength++;
						}

						cpuTot += cpu
						memTot += mem;
						diskTot += disk;

						subStr1 += '<td>' + cpu + '</td>';
						subStr2 += '<td>' + mem + '</td>';
						subStr3 += '<td>' + disk + '</td>';

						cpuData.push(cpu);
						memData.push(mem);
						diskData.push(disk);
						if (series.length < 31) {
							series.push((1 + ii) + '일');
						}
					}

					let cpuAvg = setTwoDecimalPoint((cpuTot/avgLength));
					let memAvg = setTwoDecimalPoint((memTot/avgLength));
					let diskAvg = setTwoDecimalPoint((diskTot/avgLength));

					str1 += '<td>'+cpuAvg+'</td>' + subStr1 + '</tr>';
					str2 += '<td>'+memAvg+'</td>' + subStr2 + '</tr>';
					str3 += '<td>'+diskAvg+'</td>' + subStr3 + '</tr>';
					str += str1 + str2 + str3;

					yAxis.push(
							{
								name : key + ' CPU 점유율',
								data : cpuData,
							},
							{
								name : key +' MEMORY 점유율',
								data : memData,
							},
							{
								name : key + ' DISK 점유율',
								data : diskData,
							}
					)

				}
				else {
					str += '<tr><td>' + key + '</td>';
					let total = 0;
					let dailyStr = '';
					const yData = [];
					let avgLength = 0;
					for (let ii = 0; ii < 31; ii++) {

						let dailyCount = 0;
						if (array[ii]) {
							total += array[ii].daily_count;
							dailyCount = array[ii].daily_count;
							avgLength++;
						}

						if (series.length < 31) {
							series.push((1 + ii) + '일');
						}
						yData.push(dailyCount);

						dailyStr += '<td>'+ setThousandComma(dailyCount) + '</td>';
					}
					yAxis.push({
						name: key,
						fillOpacity: 0.1, //투명도 0 - 1
						data: yData
					})
					if (leftText === '신호상태 정보') {
						total = setTwoDecimalPoint(total / avgLength);
					}

					str += '<td>' + setThousandComma(total) + '</td>';
					str += dailyStr;
					str += '</tr>';
				}
			});
		}
		$content.html(str);

		//테이블 내용의 차트 그리는 함수
		drawChart(series, yAxis, chartWord);
	}

	function drawChart(categories, yAxis, chartWord) {
		const $selectedChildren = $('.left-tab > div.on').children();
		const $selectedOnTab = $('.top-tab > div.on');
		const title = $selectedChildren.eq(0).text() +' ' + $selectedChildren.eq(1).text() + '<br>' + $selectedOnTab.text();
		Highcharts.setOptions({
			lang: {
				thousandsSep: ','
			}
		});

		Highcharts.chart('chart', { //id값이 부여된 태그를 불러온다 CSS 선택자를 위해서 id 값을 입력하는 것과 같다.

			//chart 설정
			chart: {
				backgroundColor: '#22252b',
				// width: '100%',
				// height: 343,
			},
			//highchart 로고 등등 제거
			exporting: { //우측상단 목록아이콘
				enabled: false
			},
			//highchart 로고 등등 제거
			credits: { // 우측하단 로고
				enabled: false
			},
			//범례(지도나 도표의 내용을 알기 위해 본보기로 표시해 둔 기호나 부호의 설명) 설정 0이 중앙인듯
			legend: {
				itemStyle:{
					color: "#eeeeee",
				}
			},
			//마우스 오버시 나오는 이벤트 문구 설정
			tooltip: {
				formatter: function(e) {//category x축 값, point.y y축값, series.name 설정 name 값, chartWord chart별 단위 기재
					return '<b>' + title+ '</b><br><p>' + this.series.name + ' ( ' + this.point.category +' )</p><br>' + '<p>' + setThousandComma(this.point.y) + ' '+chartWord+'</p>';
				}
			},
			//표 제목 설정
			title: {
				text: title,
				style: {
					color: '#7b7c7d',
					fontSize: 20,
					fontWeight: 'bold'
				}
			},
			//x축 설정
			xAxis: {
				//시작 값
				startOntick: false,

				//끝 값
				endOntick: false,

				//x축 값
				categories: categories, // 월의 데이터값 (1~31일)


				//x축 보여주는 설정
				labels: {
					style: {
						color: '#eeeeee',
						fontSize: '10px'
					},
					formatter: function() {
						return this.value

					}
				}
			},

			//y축 설정
			yAxis: {
				startOntick: false,
				endOntick: false,
				title: '',
				labels: {
					style: {
						color: '#eeeeee'
					},
					format: '{value:,.0f}' + chartWord
				},
			},
			//y축 값 세팅
			series: yAxis
		});
	}

	function recvDailyTableData(data) {
		//테이블 초기화
		$content.empty();
		let str = emptyStr;
		const leftText = $('.left-tab > div.on').children().eq(0).text();

		let yAxis = [];
		let xAxis = [];
		let chartWord = '';
		if (leftText === '시스템 리소스') {
			chartWord = '%'
		}
		else {
			chartWord = '건';
		}

		if (data && data.length > 0) {
			str = '';
			const countMap = new Map();
			const dailyMap = new Map();
			for (let obj of data) {
				const time = obj.time.substr(0,2);
                if (!dailyMap.get(obj.daily)) {
                    dailyMap.set(obj.daily, new Map());
					countMap.set(obj.daily, 0);
					for (let ii = 0; ii <= 23; ii++ ) {
                        let key = ii;
                        if (key < 10) {
                            key = "0" + ii.toString();
                        }
						if (leftText === '시스템 리소스') {
							dailyMap.get(obj.daily).set('cpuAverage_'+key.toString(), 0);
							dailyMap.get(obj.daily).set('diskAverage_'+key.toString(), 0);
							dailyMap.get(obj.daily).set('memoryAverage_'+key.toString(), 0);
						}
						else {
							dailyMap.get(obj.daily).set(key.toString(), 0);
						}
						if (xAxis.length < 24) {
							xAxis.push(key + '시');
						}
                    }

				}
				countMap.set(obj.daily, countMap.get(obj.daily) + 1);
                const timeMap = dailyMap.get(obj.daily);

				if (leftText === '시스템 리소스') {
					timeMap.set('cpuAverage_'+time, obj.cpuAverage);
					timeMap.set('diskAverage_'+time, obj.diskAverage);
					timeMap.set('memoryAverage_'+time, obj.memoryAverage);
				}
				else {
					timeMap.set(time, timeMap.get(time) + obj.time_count);
				}
            }

			str = '';
			dailyMap.forEach((array, key)=>{
				const yData = [];
				const avgLength = countMap.get(key);
				if (leftText === '시스템 리소스') {
					let str1 = '<tr><td rowspan="3">' + key + '</td><td>CPU</td>';
					let str2 = '<tr><td>MEMORY</td>';
					let str3 = '<tr><td>DISK</td>';
					let subStr1 = '';
					let subStr2 = '';
					let subStr3 = '';
					let cpuTot = 0;
					let diskTot = 0;
					let memTot = 0;
					let cpuData = [];
					let memData = [];
					let diskData = [];
					for (let ii = 0; ii < 24; ii++) {
						let value = ii;
						if (value < 10) {
							value = '0' + ii;
						}

						let cpu = setTwoDecimalPoint(array.get('cpuAverage_'+value));
						let mem = setTwoDecimalPoint(array.get('memoryAverage_'+value));
						let disk = setTwoDecimalPoint(array.get('diskAverage_'+value));

						cpuTot += cpu
						memTot += mem;
						diskTot += disk;

						subStr1 += '<td>' + cpu + '</td>';
						subStr2 += '<td>' + mem + '</td>';
						subStr3 += '<td>' + disk + '</td>';

						cpuData.push(cpu);
						memData.push(mem);
						diskData.push(disk);
					}

					let cpuAvg = setTwoDecimalPoint((cpuTot/avgLength));
					let memAvg = setTwoDecimalPoint((memTot/avgLength));
					let diskAvg = setTwoDecimalPoint((diskTot/avgLength));

					str1 += '<td>'+cpuAvg+'</td>' + subStr1 + '</tr>';
					str2 += '<td>'+memAvg+'</td>' + subStr2 + '</tr>';
					str3 += '<td>'+diskAvg+'</td>' + subStr3 + '</tr>';
					str += str1 + str2 + str3;

					yAxis.push(
							{
								name : key + ' CPU 점유율',
								data : cpuData,
							},
							{
								name : key +' MEMORY 점유율',
								data : memData,
							},
							{
								name : key + ' DISK 점유율',
								data : diskData,
							}
					)

				}
				else {
					let total = 0;
					let subStr = '';
					str += '<tr><td>' + key + '</td>';
					array.forEach((count, hour) => {
						total += count;
						subStr += '<td>' + setThousandComma(count) + '</td>';
						yData.push(count);
					});

					yAxis.push({
						name: key,
						fillOpacity: 0.1, //투명도 0 - 1
						data: yData
					});
					if (leftText === '신호상태 정보') {
						total = setTwoDecimalPoint(total / avgLength);
					}
               	 	str += '<td>'+ setThousandComma(total) + '</td>' + subStr + '</tr>';
				}

            })

		}
        $content.html(str);
		drawChart(xAxis, yAxis, chartWord);
	}

	function setThousandComma(value) {
		return value.toLocaleString('ko-KR');
	}

	function setTwoDecimalPoint(decimal) {
		const decimalStr = decimal.toString();
		const pointIndex = decimalStr.indexOf('.');
		if (pointIndex >= 0 && decimalStr.substr(pointIndex + 1, decimalStr.length) > 2) {
			return Number(decimal.toFixed(2));
		}
		return decimal;
	}

	function getData(url, method, param, callBack) {
		$.ajax({
			url: url,
			type: method,
			dataType: "json",
			data: param,
			success: function(req) {
				//drawDailyTable(result)
				callBack(req);
			}, error: function(error) {
				console.log(error)
			}
		})
	}
	function topTabClick(el, box) {
		$('.top-tab > div.on').removeClass('on');
		$(el).addClass('on');
		$('.search-box > div > div.on').removeClass('on');
		$('thead > tr.on').removeClass('on');
		$('.'+ box + '-box').addClass('on');
		$('.'+ box + '-head').addClass('on');
		const colspan = $('thead > tr.on').children().length;
		$content.html(`<tr class="empty-box">
							<td colspan="\${colspan}" class='nullRow'>조회 내용이 없습니다.</td>
						</tr>`);
		$('#chart').empty();
	}

	function leftTabClick(el) {
		$('.left-tab > div.on').removeClass('on');
		$(el).addClass('on');
		const searchType = $('.search-box > div > div.on').attr('class');
		const leftText = $('.left-tab > div.on').children().eq(0).text();
		let dayThead = '<td>날짜</td><td>'
		let monthThead = '<td>날짜</td><td>';
		let str = '';
		if (leftText === 'API 호출 /') {
			str += '계</td>';
		}
		else if (leftText === '시스템 리소스') {
			str += '구분</td><td>평균</td>';
		}
		else {
			str += '평균</td>';
		}

		dayThead += str;
		monthThead += str;

		for (let ii = 0; ii < 31; ii++) {
			let month = ii;
			monthThead += '<td>'+ (month + 1) + '일</td>';
			if (ii < 24) {
				let day = ii;
				if (day < 10) {
					day = '0' + ii;
				}
				dayThead += '<td>'+ day + '시</td>'
			}
		}
		$('.month-head').html(monthThead);
		$('.day-head').html(dayThead);

		const colspan = $('thead > tr.on').children().length;

		$content.html(`<tr class="empty-box">
							<td colspan="\${colspan}" class='nullRow'>조회 내용이 없습니다.</td>
						</tr>`);
		$('#chart').empty();
	}
</script>