<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>

<section class="sub-container">
	<article class="menu-history">
		<ul>
			<li><a href="/main/main.do" class="home">홈</a></li>
			<li><a href="/ptatms/status.do">접속통계</a></li>
		</ul>
	</article>
	<article class="contents-wrap">
		<div class="title-box">
			<h2 class="h2-title">접속통계</h2>
			<p class="title-info">평택시 교통정보센터</p>
		</div>
		<!--탭버튼-->
		<div class="tab-btn">
			<p><a href="/ptatms/noticeList.do">공지사항</a></p>
			<p><a href="/ptatms/archiveList.do">자료실</a></p>
			<p><a href="/ptatms/popupList.do">팝업창 관리</a></p>
			<p><a href="/ptatms/modifyInfo.do">계정 정보변경</a></p>
			<p><a href="/ptatms/status.do" class="active">접속통계</a></p>
			<p><a href="/ptatms/logout.do">로그아웃</a></p>
		</div>
		<!--//탭버튼-->
		<div class="area">
			<div class="cont_body">
				<img alt="loading" src="/images/ajax_loading.gif" id="loading" style="display:none;position:absolute;left:50%;z-index:10"/>
				<div class="adminStatsWrap">
					<div class="searchBox" style="background: none; border-bottom: none; position: inherit;">
						<select title="검색 년도" id="year" onchange="selectDateChanger(true)">
							<c:forEach begin="${thisYear-5}" end="${thisYear}" varStatus="status"><option value="<fmt:formatNumber pattern="00" value="${status.current}"/>" <c:if test="${status.current == thisYear}">selected</c:if>>${status.current}년</option>
							</c:forEach>
						</select>
						<select title="검색 월" id="month" onchange="selectDateChanger(false)">
							<c:forEach begin="1" end="${thisMonth}" varStatus="status"><option value="<fmt:formatNumber pattern="00" value="${status.current}"/>" <c:if test="${status.current == thisMonth}">selected</c:if>><fmt:formatNumber pattern="00" value="${status.current}"/>월</option>
							</c:forEach>
						</select>
						<select title="검색 일" id="day">
							<c:forEach begin="1" end="${thisDate}" varStatus="status">
								<option value="<fmt:formatNumber pattern="00" value="${status.current}"/>"
							  	<c:if test="${status.current == thisDate}">selected</c:if>>
									<fmt:formatNumber pattern="00" value="${status.current}"/>일</option>
							</c:forEach>
						</select>
						<a href="javascript:showStatsList()" class="bt">검색</a>
					</div>
					<div class="statsList">
						<ul class="tabUI f-clear">
							<a href="javascript:showStatsList('hhStats')">
								<li class="tab1 on" >
									일 통계
								</li>
							</a>
							<a href="javascript:showStatsList('ddStats')">
								<li class="tab2">
									월 통계
								</li>
							</a>
							<a href="javascript:showStatsList('mnStats')">
								<li class="tab3">
									년 통계
								</li>
							</a>
						</ul>
						<table
								id="ddStatsTb"
								summary="이 표는 접속통계 게시판이며 웹페이지 각 페이지에 대한 일별, 월별, 년별로 접속통계를 보여주는 표입니다.">
							<caption>접속 통계</caption>
							<colgroup class="colgroup ddColgroup">
								<col width="95"/>
								<col width="40"/>
								<c:forEach begin="1" end="${thisDate}" varStatus="status">
									<col width="25"/>
								</c:forEach>
							</colgroup>
							<thead>
							<tr class="ddTh">
								<th scope="col">웹페이지/일</th>
								<th scope="col">계</th>
								<c:forEach begin="1" end="${thisDate}" varStatus="status">
									<th scope="col">${status.current }</th>
								</c:forEach>
							</tr>
							</thead>
							<tbody id="ddStats"></tbody>
						</table>
						
						<table
								id="hhStatsTb"
								summary="이 표는 접속통계 게시판이며 웹페이지 각 페이지에 대한 일별, 월별, 년별로 접속통계를 보여주는 표입니다.">
							<caption>접속 통계</caption>
							<colgroup class="hhColgroup">
								<col width="95"/>
								<col width="40"/>
								<c:forEach begin="0" end="${thisHour}" varStatus="status">
									<col width="25"/>
								</c:forEach>
							</colgroup>
							<thead>
							<tr class="hhTh">
								<th scope="col">웹페이지/시</th>
								<th scope="col">계</th>
								<c:forEach var="item" begin="0" end="${thisHour}" varStatus="status">
									<th scope="col">${item }</th>
								</c:forEach>
							</tr>
							</thead>
							<tbody id="hhStats"></tbody>
						</table>
						<table
								id="mnStatsTb"
								summary="이 표는 접속통계 게시판이며 웹페이지 각 페이지에 대한 일별, 월별, 년별로 접속통계를 보여주는 표입니다.">
							<caption>접속 통계</caption>
							<colgroup class="mnColgroup">
								<col width="95"/>
								<col width="40"/>
								<c:forEach begin="1" end="${thisMonth}" varStatus="status">
									<col width="25"/>
								</c:forEach>
							</colgroup>
							<thead>
							<tr class="mnTh">
								<th scope="col">웹페이지/월</th>
								<th scope="col">계</th>
								<c:forEach begin="1" end="${thisMonth}" varStatus="status">
									<th scope="col">${status.current }</th>
								</c:forEach>
							</tr>
							</thead>
							<tbody id="mnStats"></tbody>
						</table>
					</div>

				</div>
				<!--  그래프  -->
				<div>
					<article id="highcharts" style="min-width:310px;height:350px; margin-top: 10px; overflow-y:auto;"></article>
				</div>
			</div>
		</div>
	</article>
</section>
<!--//contents-->
<script src="/js/highcharts/highcharts.js"  type="text/javascript"></script>
<script src="/js/highcharts/exporting.js"   type="text/javascript"></script>
<script type="text/javascript">
	const year  = $('#year');
	const month = $('#month');
	const day   = $('#day');
	const ddTb  = $('#ddStatsTb');
	const hhTb  = $('#hhStatsTb');
	const mnTb  = $('#mnStatsTb');

	/**
	 * 년도 날짜에 따른 월, 일 범위값 설정
	 * @param(boolean) isSetMonth 일만 변경할건지
	 */
	function selectDateChanger(isSetMonth) {
		let now 	 		= new Date();
		let nowDay   		= now.getDate();
		let nowYear  		= now.getFullYear();
		let nowMonth 		= now.getMonth() + 1;
		let dayVal   		= day.val();
		let monthVal 		= month.val();
		let lastDate        = new Date(year.val(), month.val(), 0);
		let minDay 	    	= lastDate.getDate();
		let minMonth        = 12;

		if (nowYear.toString() === year.val()) {
			minMonth = nowMonth;
			if (nowMonth === Number(monthVal)) minDay = nowDay;
		}
		if (isSetMonth) {
			setSelectOption(minMonth, monthVal, month, '월');
		}
		setSelectOption(minDay, dayVal, day, '일');
	}
	
	function setSelectOption(min, value, target, word) {
		let option = getOption(min, word);
		target.html(option);
		if (min < Number(value)) {
			target.val('01');
		}
		else {
			target.val(value);
		}
	}
	
	function getOption(rate, word) {
		let option = ''
		for ( let ii = 1; ii <= rate; ii++) {
			let value = ii;
			if (ii < 10) {
				value = ('0'+ii);
			}
			option += '<option value="'+value+'">'+value + word + '</option>';
		}
		return option;
	}

const tab1 = $('.tab1');
const tab2 = $('.tab2');
const tab3 = $('.tab3');
showStatsList('hhStats');
var _DateType = 'hhStats';

function showStatsList(type) {
	if (typeof type == 'undefined') {
		if(_DateType == null) type = 'hhStats'; 
		else type = _DateType;
	}
	
	let date = year.val();
	
	if(type == 'mnStats') {
		tab1.removeClass('on');
		tab2.removeClass('on');
		tab3.addClass('on');
		ddTb.hide();
		hhTb.hide();
		mnTb.show();
		year.show();
		month.hide();
		day.hide();
		date = year.val();
	}
	else if(type == 'ddStats') {
		tab1.removeClass('on');
		tab2.addClass('on');
		tab3.removeClass('on');
		mnTb.hide();
		hhTb.hide();
		ddTb.show();
		year.show();
		month.show();
		day.hide();
		date += month.val();
	}
	else if(type == 'hhStats') {
		tab1.addClass('on');
		tab2.removeClass('on');
		tab3.removeClass('on');
		mnTb.hide();
		ddTb.hide();
		hhTb.show();

		year.show();
		month.show();
		day.show();
		date += month.val() + day.val();
	}
	
	_DateType = type;
	const color = [
		"#884a4a",
		"#50647d",
		"#8ab047",
		"#c23d38",
		"#673ab7",
		"#00bcd4",
		"#8bc34a",
		"#ffeb3b",
		"#795548",
		"#ffc107",
		"#607d8b",
		"#009ea5",
	];

	$.ajax({
		type:"POST",
		url:'/ptatms/getStatsList.do',
		data: {"dateType":_DateType, "date": date},
		success: function(jsonData) {
			let str = '';
			if (jsonData.length > 0) {
				//el.title : 메인페이지 , el.total_connCnt : 총접속수 , el.statsInArr : 일 ,월,년  각각 통계수
				let title;
				const now = new Date();
				const nowHour  = now.getHours();
				const nowMonth = now.getMonth()+1;
				const nowDate  = now.getDate();
				const nowYear  = now.getFullYear();

				let yearVal    = '';
				let monthVal   = '';
				let dateVal    = '';
				if (date) {
					yearVal = date.substring(0, 4);
					monthVal = date.substring(4,6);
					dateVal  = date.substring(6,8);
				}

				let lastDate = new Date(year.val(), month.val(), 0);
				let word       = '';
				let range      = '';
				let classFront = '';
				let info       = '';
				let strt       = 1;
				switch (_DateType) {
					case 'ddStats' :
						let lastDay    = lastDate.getDate();
						if (Number(monthVal) === nowMonth && Number(yearVal) === nowYear) {
							lastDay = nowDate;
						}
						range      = lastDay;
						word       = '일';
						classFront = 'dd';
						info       = '월';
						break;
					case 'mnStats' :
						let lastMonth = 12;
						if (Number(yearVal) === nowYear) {
							lastMonth = nowMonth;
						}
						range = lastMonth;
						word  = '월';
						classFront = 'mn';
						info       = '년';
						break;
					case 'hhStats' :
						let lastHours = 23;
						if (Number(monthVal) === nowMonth && Number(yearVal) === nowYear && Number(dateVal) === nowDate) {
							lastHours = nowHour;
						}
						range 		= lastHours;
						word  		= '시';
						classFront  = 'hh';
						info        = '일';
						strt        = 0;
						break;
				}
				const tbObj = getTableObj(range, word, strt);
				$('.' + classFront + 'Th').html(tbObj.th);
				$('.' + classFront + 'Colgroup').html(tbObj.colGroup);
				let series = [];
				let xAxis  = tbObj.xAxis;
				jsonData.forEach(function(el, idx) {
					const {title, total_connCnt, statsInArr} = el;
					str += '<tr>';
					str += '<td style="text-align:center">' + title + '</td>';
					str += '<td style="text-align:center">' + total_connCnt + '</td>';
					statsInArr.forEach(function(cnt, index) {
						if (index < xAxis.length) {
							str += '<td style="text-align:center">'+cnt+'</td>';
						}
					});
					series.push({name: title , data: statsInArr.splice(0, xAxis.length), color : color[idx]});
					str += '</tr>';
				});

				$('#'+type).empty().html(str);

				$('#highcharts').show();
				drawCharts('홈페이지 접속통계 그래프', xAxis, word, '접속통계', series, info, date);
			}
			else {
				$('#highcharts').hide();
				str += '<tr><td colspan="31" style="text-align:center">데이터가 없습니다.</td></tr>';
				$('#'+type).empty().html(str);
			}
		}, beforeSend: function () {
            $('#loading').show();
        },
        complete: function () {
            $('#loading').hide();
        },
		error: function(e) {
			alert('getDayStats ajax error');
		}
	});
}

function getTableObj(range, word, strt) {
	let xAxis = [];
	let colGroup = '<col width="95"/><col width="40"/>';
	let th = '<th scope="col">웹페이지/'+word+'</th><th scope="col">계</th>';
	for (let ii = strt; ii <= range; ii++) {
		xAxis.push(ii.toString());
		colGroup += '<col width="25"/>';
		th += '<th scope="col">' + ii +'</th>';
	}
	return {xAxis : xAxis, colGroup: colGroup, th: th};
}

function drawCharts(title, xAxis, xTitle, yTitle, series, legendTitle, date) {
    Highcharts.chart('highcharts', {
        chart: {
            type: 'line',
			shadow: true
        },
        title: {
            text: title,
			style: {
				fontWeight: 'bold',
				fontFamily: '맑은 고딕',
			}
        },
        xAxis: {
            categories: xAxis,
            title: {
                text: xTitle
            }
        },
        yAxis: {
			min: 0,
            title: {
                text: yTitle
            },
			labels: {
				format : '{value:,.0f}'
			},
			tickInterval: 10
        },
        plotOptions: {
			series: {
                dataLabels: {
                    enabled: true
                },
            }
        },
		tooltip: {
			formatter : function () {
				let dateVal = date.substring(0,4) + ' 년';
				if (date.length >= 6) dateVal += ' ' + date.substring(4,6) + ' 월';
				if (date.length >= 8) dateVal += ' ' + date.substring(6,8) +' 일';
				return '<b>' + legendTitle + ' 통계</b><br><b>'+ dateVal +' ' + this.x +' '+ xTitle+'</b><br><b>'+this.series.name + ' : '+this.y+'</b>'
			}
		},
		legend: {
			layout: 'vertical',
			align: 'right',
			verticalAlign: 'top',
			floating: false,
			y: 40,
			borderWidth: 1,
			backgroundColor: {
				className : 'legend-border',
			},
		},
		credits : {
			enabled : false
		},
        series: series
    });
}

</script>
