<%@ 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="/statistics/connStat.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="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, false)">
							<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, 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>
						<div class="to-box" style="display: none">
							~
							<select title="검색 종료 년도" id="to-year" onchange="selectDateChanger(true, 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="to-month" onchange="selectDateChanger(false, true)">
								<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="to-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>
						</div>
						<a class="bt" href="#">검색</a>
					</div>
					<div class="statsList">
						<ul class="tabUI f-clear">
							<a href="javascript:dayClick()">
								<li class="tab1 on" >
									시간 통계
								</li>
							</a>
							<a href="javascript:monthClick()">
								<li class="tab2">
									일 통계
								</li>
							</a>
							<a href="javascript:yearClick()">
								<li class="tab4">
									월 통계
								</li>
							</a>
						</ul>
						<table id="ddStatsTb" style="display: none" >
							<caption>접속 통계</caption>
							<colgroup class="colgroup ddColgroup">
								<col width="130"/>
								<col width="60"/>
								<c:forEach begin="1" end="${thisDate}" varStatus="status">
									<col width="calc(calc(100% - 190px) / ${thisDate})"/>
								</c:forEach>
							</colgroup>
							<thead>
							<tr class="ddTh1">
								<th scope="col" rowspan="2">웹페이지/일</th>
								<th scope="col" rowspan="2">계</th>
								<th scope="col" colspan="${thisDate}">${thisYear}년 ${thisMonth}월</th>
							</tr>
							<tr class="ddTh2">
								<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" style="display: none" >
							<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="periodStatsTb">
							<caption>접속 통계</caption>
							<colgroup class="periodColgroup">
								<col width="95"/>
								<col width="40"/>
								<col width="25"/>
							</colgroup>
							<thead>
								<tr class="periodTh1">
									<th rowspan="2" scope="col">웹페이지/월</th>
									<th rowspan="2" scope="col">계</th>
									<th scope="col">${thisYear}</th>
								</tr>
								<tr class="periodTh2">
									<th scope="col">${thisMonth}</th>
								</tr>
							</thead>
							<tbody id="periodStats"></tbody>
						</table>
					</div>

				</div>
				<!--  그래프  -->
				<div>
					<article id="highcharts" style="min-width:310px;height:370px; 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');
	const prTb  = $('#periodStatsTb');
	const toYear = $('#to-year');
	const toMonth = $('#to-month');
	const toDay  = $('#to-day');
	const colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b',
		'#e377c2', '#7f7f7f', '#bcbd22', '#17becf', '#aec7e8', '#ffbb78',
		'#98df8a', '#ff9896', '#c5b0d5', '#c49c94' ];

	/**
	 * 년도 날짜에 따른 월, 일 범위값 설정
	 * @param(boolean) isSetMonth 일만 변경할건지
	 */
	function selectDateChanger(isSetMonth, isTo) {
		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 yearVal         = year.val();
		let monthEl         = month;
		let dayEl           = day;
		if (isTo) {
			dayVal  = toDay.val();
			monthVal = toMonth.val();
			yearVal = toYear.val();
			monthEl = toMonth;
			dayEl  = toDay;
		}

		let lastDate        = new Date(yearVal, monthVal, 0);
		let minDay 	    	= lastDate.getDate();
		let minMonth        = 12;

		if (nowYear.toString() === yearVal) {
			minMonth = nowMonth;
			if (nowMonth === Number(monthVal)) minDay = nowDay;
		}
		if (isSetMonth) {
			setSelectOption(minMonth, monthVal, monthEl, '월');
		}
		setSelectOption(minDay, dayVal, dayEl, '일');
	}

	/**
	 * 날짜 Select Box option Setting
	 * @param min 마지막 값
	 * @param value 현재 값
	 * @param target 요소
	 * @param word 날짜 글자
	 */
	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);
		}
	}

	/**
	 * 날짜 Select option for문
	 * @param rate 종료 값
	 * @param word 날짜 글짜
	 * @returns {string}
	 */
	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');
	const tab4 = $('.tab4');
	const toBox = $('.to-box');
	const btn   = $('.bt');
	showStatsList();

	function showStatsList() {

		let date = year.val() + month.val() + day.val();
		showHide([year, month, day, hhTb], [mnTb, prTb, toDay, ddTb, toBox], [tab1], [tab4, tab2, tab3], 'showStatsList');

		$.ajax({
			type:"POST",
			url:'/statistics/getStatsList.do',
			data: {"date": date},
			success: function(jsonData) {
				let str = '';
				if (jsonData.length > 0) {
					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 lastHours = 23;
					if (Number(monthVal) === nowMonth && Number(yearVal) === nowYear && Number(dateVal) === nowDate) {
						lastHours = nowHour;
					}
					let range 		= lastHours;
					let word  		= '시';
					let classFront  = 'hh';
					let info        = '시간';
					let strt        = 0;
					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 : colors[idx]});
						str += '</tr>';
					});

					$('#hhStats').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>';
					$('#hhStats').empty().html(str);
				}
			}, beforeSend: function () {
				$('#loading').show();
			},
			complete: function () {
				$('#loading').hide();
			},
			error: function(e) {
				alert('시간 통계 데이터 호출 중 오류가 발생하였습니다.');
			}
		});
	}


	function dayClick() {
		const now = new Date();
		let monthVal = now.getMonth() + 1;
		let dayVal = now.getDate();
		if (dayVal < 10) {
			dayVal = "0" + dayVal;
		}
		if (monthVal < 10) {
			monthVal = "0"+ monthVal;
		}
		year.val(now.getFullYear());
		month.val(monthVal);
		day.val(dayVal);
		showStatsList();
	}
	function monthClick() {
		const now = new Date();
		let monthVal = now.getMonth() + 1;
		let dayVal = now.getDate();
		if (dayVal < 10) {
			dayVal = "0" + dayVal;
		}
		if (monthVal < 10) {
			monthVal = "0"+ monthVal;
		}
		year.val(now.getFullYear());
		month.val(monthVal);
		day.val('01');
		toYear.val(now.getFullYear());
		toMonth.val(monthVal)
		toDay.val(dayVal);
		monthStat();
	}

	function yearClick() {
		const now = new Date();
		let monthVal = now.getMonth() + 1;
		if (monthVal < 10) {
			monthVal = "0"+ monthVal;
		}
		year.val(now.getFullYear());
		month.val('01');
		toYear.val(now.getFullYear());
		toMonth.val(monthVal);
		yearStat();
	}

	function showHide(showArr, hideArr, onArr, offArr, clickEvent) {
		if (showArr.length) {
			showArr.forEach((show)=>{
				show.show();
			})
		}

		if (hideArr.length) {
			hideArr.forEach((hide)=>{
				hide.hide();
			})
		}
		if (onArr.length) {
			onArr.forEach((on)=>{
				on.addClass('on');
			})
		}

		if (offArr.length) {
			offArr.forEach((off)=>{
				off.removeClass('on');
			})
		}
		btn.attr('href', 'javascript:'+clickEvent+'()');
	}

	function monthStat() {
		showHide([ddTb, year, month, day, toBox, toDay], [mnTb, hhTb, prTb], [tab2], [tab1, tab3, tab4], 'monthStat');

		let from = year.val() + '-' + month.val() + '-' + day.val();
		let to   = toYear.val() + '-' + toMonth.val() + '-' + toDay.val();
		if (from > to) {
			return alert('검색 시작일이 종료일 보다 큽니다.');
		}

		const betweenPeriod = Number(toYear.val() + toMonth.val() + toDay.val()) - Number(year.val() + month.val() + day.val());
		if (betweenPeriod > 100) {
			return alert('검색 기간을 1개월 이하로 설정해주세요.');
		}
		$('#highcharts').empty();
		const colspan = getThead('일', 'dd');

		$.ajax({
			type:"POST",
			url:'/statistics/getMonthStatsList.do',
			data: {"from":from, "to": to},
			success: function(jsonData) {
				drawTable(jsonData, '일', '일', colspan, 'dd');
			}, beforeSend: function () {
				$('#loading').show();
			},
			complete: function () {
				$('#loading').hide();
			},
			error: function(e) {
				alert('일 통계 데이터 호출 중 오류가 발생하였습니다.');
			}
		});
	}

    function getColInfo(toVal, fromVal, from, to, lastVal , type, pageName) {
        let colspan = Number(toVal) - Number(fromVal) + 1;
        let limit = colspan;
		let colGroupText =`<col width="130"><col width="60">`;
		let th1Text 	 =`<th rowspan="2" scope="col">웹페이지/\${pageName}</th>
						   <th rowspan="2" scope="col">계</th>`;
		let th2Text      = '';
        let text = `<th scope="col" colspan="\${colspan}">\${from}</th>`;
        if (from !== to) {
            colspan = lastVal - Number(fromVal) + 1;
            text = `<th scope="col" colspan="\${colspan}">\${from}</th>`;
            text += `<th scope="col" colspan="\${Number(toVal)}">\${to}</th>`;
            limit = colspan + Number(toVal);
        }
		th1Text += text;

		for (let ii = 0; ii < limit; ii++) {
			colGroupText += '<col width="calc(calc(100% - 190px) / \${limit})">';
			let dt = Number(fromVal) + ii;
			if (dt > lastVal) {
				dt -= lastVal;
			}

			if (dt < 10) {
				dt = "0" + dt;
			}
			th2Text += `<th scope="col">\${dt}</th>`;
		}


		const colGroup = $('.' + type + 'Colgroup');
		const th1 = $('.' + type + 'Th1');
		const th2 = $('.' + type + 'Th2');
		colGroup.html(colGroupText);
		th1.html(th1Text);
		th2.html(th2Text);

		return limit;
    }

	function getThead(pageName, type) {

		let yearVal = year.val();
		let monthVal = month.val();
		let dayVal = day.val();
		let toYearVal = toYear.val();
		let toMonthVal = toMonth.val();
		let toDayVal = toDay.val();
		let lastDate = new Date(yearVal, Number(monthVal), 0);
		let lastDateVal = lastDate.getDate();
		let totalCol = 2;
		if (type === 'dd') {
			const from = `\${yearVal}년 \${monthVal}월`;
			const to   = `\${toYearVal}년 \${toMonthVal}월`;
			totalCol += getColInfo(toDayVal, dayVal, from, to, lastDateVal, type, pageName);
		}
		else{
			const from = `\${yearVal}년`;
			const to   = `\${toYearVal}년`;
			totalCol += getColInfo(toMonthVal, monthVal, from, to, 12, type, pageName);
		}

		return totalCol;
	}

	function yearStat() {
		showHide([year, month, toBox, prTb], [mnTb, day, toDay, hhTb, ddTb], [tab4], [tab1, tab2, tab3], 'yearStat');

		let from = year.val() + '-' + month.val();
		let to   = toYear.val() + '-' + toMonth.val();
		if (from > to) {
			return alert('검색 시작일이 종료일 보다 큽니다.');
		}

		const betweenPeriod = Number(toYear.val() + toMonth.val()) - Number(year.val() + month.val());
		if (betweenPeriod > 100) {
			return alert('검색 기간을 1년 이하로 설정해주세요.');
		}
		$('#highcharts').empty();
		const colspan = getThead('월', 'period');

		$.ajax({
			type:"POST",
			url:'/statistics/getYearStatsList.do',
			data: {"from":from, "to": to},
			success: function(jsonData) {
				drawTable(jsonData, '월', '월', colspan, 'period');
			}, beforeSend: function () {
				$('#loading').show();
			},
			complete: function () {
				$('#loading').hide();
			},
			error: function(e) {
				alert('월 통계 데이터 호출 중 오류가 발생하였습니다.');
			}
		});
	}

	function drawTable(jsonData, xTitle, word, colspan, type) {
		let str = '';
		const tbody = $('#'+type+'Stats');
		tbody.empty();
		$('#highcharts').empty();

		if (jsonData.length > 0) {
			let yAxis = [];
			let set = new Set();
			let pageMap = new Map();
			jsonData.forEach(function (el) {
				const {
					conn_cnt,
					page_name,
					stat_mn,
					stat_year,
					stat_dd
				} = el;
				let xLegend = '';
				if (xTitle === '일') {
					const year = stat_mn.substr(0, 4);
					const month = stat_mn.substr(4, 2);
					xLegend = year + '-' + month +'-' + stat_dd;
				}
				else {
					xLegend = stat_year + '년 ' + stat_mn + '월';
				}

				set.add(xLegend);
				if (!pageMap.get(page_name)) {
					pageMap.set(page_name, new Map());
					pageMap.get(page_name).set('total', 0);
					pageMap.get(page_name).set('array', []);
				}
				pageMap.get(page_name).get('array').push(Number(conn_cnt));
				pageMap.get(page_name).set('total', pageMap.get(page_name).get('total') + Number(conn_cnt));
			});

			const xAxis = Array.from(set);
			pageMap.forEach((obj, key) => {
				str += `<tr>
						   <td style="text-align:center">\${key}</td>
						   <td style="text-align:center">\${obj.get("total")}</td>`;
				obj.get('array').forEach((connCnt) => {
					str += `<td style="text-align: center;">\${connCnt}</td>`
				});
				str += '</tr>';
				yAxis.push({
					name: key,
					data: obj.get('array'),
				})
			});

			drawPeriodChart(xAxis, yAxis, xTitle, word);
		}
		else {
			str += `<tr><td colspan="\${colspan}" style="text-align:center">데이터가 없습니다.</td></tr>`;
		}

		tbody.html(str);
	}

	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 drawPeriodChart(xAxis, series, xTitle, word) {
		Highcharts.chart('highcharts', {
			chart: {
				type: 'line',
				shadow: true
			},
			title: {
				text: '홈페이지 접속통계 그래프',
				y : 20,
				style: {
					fontWeight: 'bold',
					fontFamily: '맑은 고딕',
				}
			},
			xAxis: {
				categories: xAxis,
				title: {
					text: xTitle
				}
			},
			yAxis: {
				min: 0,
				title: {
					text: '접속통계(건)'
				},
				labels: {
					format : '{value:,.0f}'
				},
				tickInterval: 10
			},
			plotOptions: {
				series: {
					dataLabels: {
						enabled: true
					},
				}
			},
			tooltip: {
				formatter : function () {
					return '<b>'+word+' 통계</b><br><b>'+ this.x +'</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
		});
	}


	function drawCharts(title, xAxis, xTitle, yTitle, series, legendTitle, date) {

		Highcharts.chart('highcharts', {
			chart: {
				type: 'line',
				shadow: true
			},
			title: {
				text: title,
				y : 20,
				style: {
					fontWeight: 'bold',
					fontFamily: '맑은 고딕',
				}
			},
			xAxis: {
				categorie: xAxis,
				title: {
					text: xTitle
				}
			},
			yAxis: {
				min: 0,
				title: {
					text: '접속통계(건)'
				},
				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>
