<%@ page language="java" contentType="text/html; charset=utf-8"%>
<%@ page import="java.io.*"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ include file="/jsp/common/include/localemessage.jsp" %>
<%
	response.setHeader("Pragma", "No-cache");
	response.setHeader("Cache-Control", "no-cache");
	response.setHeader("Expires", "0");
	request.setCharacterEncoding("UTF-8");
%>
<html>
<head>
	<title>시간별 통계 조회</title>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<jsp:include page="/jsp/common/include/css.jsp"/>
	<style>
		.chart-container {
			display: flex;
			justify-content: space-between;
			margin-bottom: 15px;
			gap: 10px;
		}
		.chart-container.full-width {
			display: block;
		}
		.chart {
			width: 49%;
			height: 300px;
			border: 1px solid #ddd;
			background: #fff;
		}
		.chart.full-width {
			width: 100%;
			height: 250px;
		}
	</style>
	<jsp:include page="/jsp/common/include/script.jsp"/>
	<script src="<c:url value="/addon/echarts/echarts.min.js"/>"></script>
	<script language="javascript">
		var url = '<c:url value="/onl/kjb/statistics/apiStatsHourMan.json"/>';
		var url_view = '<c:url value="/onl/kjb/statistics/apiStatsHourMan.view"/>';
		var url_minute_view = '<c:url value="/onl/kjb/statistics/apiStatsMinuteMan.view"/>';

		var totalDonutChart, callChart;

		function numberFormatter(cellvalue, options, rowObject) {
			if (cellvalue == null || cellvalue == '') return '0';
			return Number(cellvalue).toLocaleString();
		}

		function decimalFormatter(cellvalue, options, rowObject) {
			if (cellvalue == null || cellvalue == '') return '0';
			return Math.round(Number(cellvalue)).toLocaleString();
		}

		function initCharts() {
			totalDonutChart = echarts.init(document.getElementById('totalDonutChart'));
			callChart = echarts.init(document.getElementById('callChart'));

			// 총건수 도넛 차트
			var totalDonutOption = {
				title: {
					text: '총 건수 분포',
					left: 'center',
					top: 10,
					textStyle: { fontSize: 14 }
				},
				tooltip: {
					trigger: 'item',
					formatter: function (params) {
						return params.name + ': ' + params.value.toLocaleString() + ' (' + params.percent + '%)';
					}
				},
				legend: {
					orient: 'vertical',
					right: 30,		
					top: 'middle',
					data: ['성공', 'Timeout', '시스템오류']
				},
				series: [{
					name: '총건수',
					type: 'pie',
					radius: ['38%', '65%'],
					center: ['44%', '55%'],
					avoidLabelOverlap: true,
					label: {
						show: true,
						formatter: function (params) {
							return params.name + ': ' + params.value.toLocaleString();
						}
					},
					emphasis: {
						label: {
							show: true,
							fontSize: 16,
							fontWeight: 'bold'
						}
					},
					labelLine: {
						show: true
					},
					data: [
						{ value: 0, name: '성공', itemStyle: { color: '#91CC75' } },
						{ value: 0, name: 'Timeout', itemStyle: { color: '#FAC858' } },
						{ value: 0, name: '시스템오류', itemStyle: { color: '#EE6666' } }
					]
				}]
			};

			totalDonutChart.setOption(totalDonutOption);

			

			// 호출량 차트
			var callOption = {
				title: { text: '호출량 추이', left: 'center', top: 10, textStyle: { fontSize: 14 } },
				tooltip: {
					trigger: 'axis',
					axisPointer: { type: 'cross', label: { backgroundColor: '#6a7985' } }
				},
				legend: { data: ['성공', 'Timeout', '시스템오류'], bottom: 0 },
				grid: { left: '3%', right: '4%', bottom: '15%', top: '15%', containLabel: true },
				xAxis: { type: 'category', boundaryGap: false, data: [] },
				yAxis: { type: 'value', minInterval: 1 },
				series: [
					{ name: '성공', type: 'line', stack: 'Total', smooth: true, areaStyle: { opacity: 0.5 }, itemStyle: { color: '#5470C6' }, data: [] },
					{ name: 'Timeout', type: 'line', stack: 'Total', smooth: true, areaStyle: { opacity: 0.5 }, itemStyle: { color: '#FAC858' }, data: [] },
					{ name: '시스템오류', type: 'line', stack: 'Total', smooth: true, areaStyle: { opacity: 0.5 }, itemStyle: { color: '#EE6666' }, data: [] }
				]
			};

			callChart.setOption(callOption);


			// 드릴다운 이벤트 (시간 클릭 시 분단위 화면으로 이동)
			callChart.on('click', function(params) {
				drillDownToMinute(callChart, params.dataIndex);
			});
		}

		function drillDownToMinute(chart, dataIndex) {
			if (!chart.rawData || dataIndex < 0 || dataIndex >= chart.rawData.length) return;

			// rawData에서 실제 statTime 가져오기 (yyyyMMddHH00 형식)
			var statTime = chart.rawData[dataIndex].statTime;
			var year = statTime.substring(0, 4);
			var month = statTime.substring(4, 6);
			var day = statTime.substring(6, 8);
			var hour = parseInt(statTime.substring(8, 10));

			var startDate = year + '-' + month + '-' + day;
			var startTime = (hour < 10 ? '0' + hour : hour) + ':00';

			// 1시간 후 계산 (23시인 경우 다음날 00시로 자동 계산)
			var d = new Date(parseInt(year), parseInt(month) - 1, parseInt(day), hour, 0, 0);
			d.setHours(d.getHours() + 1);

			var endDate = d.getFullYear() + '-' +
						  (d.getMonth() + 1 < 10 ? '0' : '') + (d.getMonth() + 1) + '-' +
						  (d.getDate() < 10 ? '0' : '') + d.getDate();
			var endTime = (d.getHours() < 10 ? '0' : '') + d.getHours() + ':00';

			var params = '?searchStartDate=' + startDate + '&searchStartTime=' + startTime
					+ '&searchEndDate=' + endDate + '&searchEndTime=' + endTime;
			params += '&menuId='+'${param.menuId}';
			params += '&cmd='+'LIST';
			params += '&serviceType='+'APIGW';

			location.href = url_minute_view + params;
		}

		function updateCharts(data) {
			// 시계열 차트용 변수
			var times = [];
			var successData = [];
			var timeoutData = [];
			var systemErrData = [];
			var bizErrData = [];
			var avgRespData = [];
			var p50RespData = [];
			var p95RespData = [];

			// 도넛 차트용 총계 변수
			var totalSuccess = 0;
			var totalTimeout = 0;
			var totalSystemErr = 0;
			var totalBizErr = 0;
			var seq900Timeout = 0;
			var seq900SystemErr = 0;
			var seq900BizErr = 0;

			data.forEach(function(item) {
				times.push(item.statTime);

				// 시계열 차트 데이터
				successData.push(item.successCnt);
				timeoutData.push(item.timeoutCnt);
				systemErrData.push(item.systemErrCnt);
				bizErrData.push(item.bizErrCnt);
				avgRespData.push(item.avgRespTime);
				p50RespData.push(item.p50RespTime);
				p95RespData.push(item.p95RespTime);

				// 도넛 차트용 합산
				totalSuccess += (item.successCnt || 0);
				totalTimeout += (item.timeoutCnt || 0);
				totalSystemErr += (item.systemErrCnt || 0);
				totalBizErr += (item.bizErrCnt || 0);
				seq900Timeout += (item.seq900TimeoutCnt || 0);
				seq900SystemErr += (item.seq900SystemErrCnt || 0);
				seq900BizErr += (item.seq900BizErrCnt || 0);
			});

			// 총건수 도넛 차트 업데이트
			var grandTotal = totalSuccess + totalTimeout + totalSystemErr + totalBizErr;
			totalDonutChart.setOption({
				series: [{
					data: [
						{ value: totalSuccess, name: '성공' },
						{ value: totalTimeout, name: 'Timeout' },
						{ value: totalSystemErr, name: '시스템오류' }
					]
				}]
			});
			$("#totalDonutCenterText").text(grandTotal.toLocaleString());


			// 호출량 차트 업데이트
			callChart.setOption({
				xAxis: { data: times.map(function(t) { return t.substring(8, 10) + '시'; }) },
				series: [
					{ data: successData },
					{ data: timeoutData },
					{ data: systemErrData }
				]
			});


			// 드릴다운을 위해 원본 데이터 저장
			callChart.rawData = data;
		}

		function fetchChartData() {
			var searchDate = $("input[name=searchDate]").val().replace(/-/g, "");

			var postData = {
				cmd: 'CHART',
				searchApiName: $("input[name=searchApiName]").val(),
				searchGwInstanceId: $("input[name=searchGwInstanceId]").val(),
				searchBizDivCode: $("input[name=searchBizDivCode]").val(),
				searchClientId: $("input[name=searchClientId]").val(),
				searchInboundAdapter: $("input[name=searchInboundAdapter]").val(),
				searchOutboundAdapter: $("input[name=searchOutboundAdapter]").val()
			};

			if (searchDate) {
				postData.searchStartDateTime = searchDate + "00";
				postData.searchEndDateTime = searchDate + "23";
			}

			$.ajax({
				url: url,
				type: 'POST',
				data: postData,
				success: function(response) {
					updateCharts(response);
				},
				error: function(xhr, status, error) {
					console.error('Chart data fetch error:', error);
				}
			});
		}

		function search() {
			var postData = getSearchForJqgrid("cmd", "LIST");

			var searchDate = $("input[name=searchDate]").val().replace(/-/g, "");

			if (searchDate) {
				postData.searchStartDateTime = searchDate + "00";
				postData.searchEndDateTime = searchDate + "23";
			}

			var summaryPostData = getSearchForJqgrid("cmd", "LIST_SUMMARY");
			if (searchDate) {
				summaryPostData.searchStartDateTime = searchDate + "00";
				summaryPostData.searchEndDateTime = searchDate + "23";
			}

			$("#gridSummary").setGridParam({ url: url, postData: summaryPostData, page: 1 }).trigger("reloadGrid");
			$("#grid").setGridParam({ url: url, postData: postData, page: 1 }).trigger("reloadGrid");
			fetchChartData();
		}

		function exportToExcel(isSummary) {
			var cmdType = isSummary ? 'EXCEL_EXPORT_SUMMARY' : 'EXCEL_EXPORT';
			console.log('[Excel Export] Starting... (type: ' + cmdType + ')');

			var postData = {
				cmd: cmdType,
				searchApiName: $("input[name=searchApiName]").val(),
				searchGwInstanceId: $("input[name=searchGwInstanceId]").val(),
				searchBizDivCode: $("input[name=searchBizDivCode]").val(),
				searchClientId: $("input[name=searchClientId]").val(),
				searchInboundAdapter: $("input[name=searchInboundAdapter]").val(),
				searchOutboundAdapter: $("input[name=searchOutboundAdapter]").val(),
				serviceType: '${param.serviceType}'
			};

			var searchDate = $("input[name=searchDate]").val().replace(/-/g, "");
			if (searchDate) {
				postData.searchStartDateTime = searchDate + "00";
				postData.searchEndDateTime = searchDate + "23";
			}

			console.log('[Excel Export] Request data:', postData);

			var xhr = new XMLHttpRequest();
			xhr.open('POST', url, true);
			xhr.responseType = 'blob';
			xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');

			xhr.onload = function() {
				console.log('[Excel Export] Response received - Status:', xhr.status);

				if (xhr.status === 200) {
					var blob = xhr.response;
					var contentType = xhr.getResponseHeader('Content-Type');
					console.log('[Excel Export] Blob size:', blob.size, 'Content-Type:', contentType);

					// JSON 에러 응답인지 확인
					if (contentType && contentType.indexOf('application/json') !== -1) {
						var reader = new FileReader();
						reader.onload = function() {
							try {
								var errorObj = JSON.parse(reader.result);
								alert(errorObj.message || 'Excel 파일 생성에 실패했습니다.');
							} catch (e) {
								alert('Excel 파일 생성에 실패했습니다.');
							}
						};
						reader.readAsText(blob);
						return;
					}

					// Blob 크기가 0이면 에러
					if (blob.size === 0) {
						alert('Excel 파일 생성에 실패했습니다. (빈 응답)');
						return;
					}

					// 파일명 추출
					var filename = 'api_stats.xlsx';
					var disposition = xhr.getResponseHeader('Content-Disposition');
					console.log('[Excel Export] Content-Disposition:', disposition);

					if (disposition && disposition.indexOf('filename=') !== -1) {
						var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
						var matches = filenameRegex.exec(disposition);
						if (matches != null && matches[1]) {
							filename = matches[1].replace(/['"]/g, '');
							filename = decodeURIComponent(filename);
						}
					}

					console.log('[Excel Export] Downloading as:', filename);

					// 파일 다운로드
					var link = document.createElement('a');
					link.href = window.URL.createObjectURL(blob);
					link.download = filename;
					document.body.appendChild(link);
					link.click();
					document.body.removeChild(link);
					window.URL.revokeObjectURL(link.href);

					console.log('[Excel Export] Download triggered');

				} else if (xhr.status === 204) {
					alert('조회된 데이터가 없습니다.');
				} else {
					// 에러 응답 처리
					var reader = new FileReader();
					reader.onload = function() {
						var message = 'Excel 다운로드 중 오류가 발생했습니다.';
						try {
							var errorObj = JSON.parse(reader.result);
							if (errorObj.message) message = errorObj.message;
						} catch (e) {
							console.error('[Excel Export] Error parsing error response:', e);
						}
						alert(message);
					};
					reader.readAsText(xhr.response);
				}
			};

			xhr.onerror = function() {
				console.error('[Excel Export] Network error');
				alert('네트워크 오류가 발생했습니다.');
			};

			// Form data 생성
			var formData = [];
			for (var key in postData) {
				if (postData.hasOwnProperty(key) && postData[key] != null && postData[key] !== '') {
					formData.push(encodeURIComponent(key) + '=' + encodeURIComponent(postData[key]));
				}
			}

			xhr.send(formData.join('&'));
		}

		function listSummary() {
			var gridPostData = getSearchForJqgrid("cmd", "LIST_SUMMARY");
			$('#gridSummary').jqGrid({
				datatype: "json",
				mtype: 'POST',
				postData: gridPostData,
				colNames: [
					'API명',
					'총건수', '성공', 'Timeout', '시스템오류',
					'평균응답(ms)', '최소응답(ms)', '최대응답(ms)'
				],
				colModel: [
					{ name: 'apiName', align: 'left', width: '250', sortable: false },
					{ name: 'totalCnt', align: 'right', width: '80', formatter: numberFormatter, sortable: false },
					{ name: 'successCnt', align: 'right', width: '80', formatter: numberFormatter, sortable: false },
					{ name: 'timeoutCnt', align: 'right', width: '80', formatter: numberFormatter, sortable: false },
					{ name: 'systemErrCnt', align: 'right', width: '80', formatter: numberFormatter, sortable: false },
					{ name: 'avgRespTime', align: 'right', width: '90', formatter: decimalFormatter, sortable: false },
					{ name: 'minRespTime', align: 'right', width: '90', formatter: decimalFormatter, sortable: false },
					{ name: 'maxRespTime', align: 'right', width: '90', formatter: decimalFormatter, sortable: false }
				],
				jsonReader: { repeatitems: false },
				pager: $('#pagerSummary'),
				page: '${param.page}',
				rowNum: '${rmsDefaultRowNum}',
				autoheight: true,
				height: 'auto',
				autowidth: true,
				viewrecords: true,
				rowList: eval('[${rmsDefaultRowList}]'),
				loadComplete: function(d) {
					var colModel = $(this).getGridParam("colModel");
					for (var i = 0; i < colModel.length; i++) {
						$(this).setColProp(colModel[i].name, { sortable: false });
					}
					// 조회(reloadGrid) 시 컬럼 폭이 고정폭(shrinkToFit:false)으로 남아
					// 실제 컨테이너 폭과 어긋나 가로 스크롤이 생기는 것을 방지
					$(this).jqGrid('setGridWidth', $('#content_middle').width(), true);
				}
			});
		}

		function list() {
			var gridPostData = getSearchForJqgrid("cmd", "LIST");
			$('#grid').jqGrid({
				datatype: "json",
				mtype: 'POST',
				postData: gridPostData,
				colNames: [
					'통계시간', 'API명', '인스턴스', '업무구분', '클라이언트ID',
					'Inbound Adapter', 'Outbound Adapter',
					'총건수', '성공', 'Timeout', '시스템오류',
					'평균응답(ms)', '최소응답(ms)', '최대응답(ms)'
				],
				colModel: [
					{ name: 'statTime', align: 'center', width: '120', sortable: false },
					{ name: 'apiName', align: 'left', width: '150', sortable: false },
					{ name: 'gwInstanceId', align: 'center', width: '80', sortable: false },
					{ name: 'bizDivCode', align: 'center', width: '80', sortable: false },
					{ name: 'clientId', align: 'left', width: '100', sortable: false },
					{ name: 'inboundAdapter', align: 'left', width: '120', sortable: false },
					{ name: 'outboundAdapter', align: 'left', width: '120', sortable: false },
					{ name: 'totalCnt', align: 'right', width: '70', formatter: numberFormatter, sortable: false },
					{ name: 'successCnt', align: 'right', width: '70', formatter: numberFormatter, sortable: false },
					{ name: 'timeoutCnt', align: 'right', width: '70', formatter: numberFormatter, sortable: false },
					{ name: 'systemErrCnt', align: 'right', width: '70', formatter: numberFormatter, sortable: false },
					{ name: 'avgRespTime', align: 'right', width: '80', formatter: decimalFormatter, sortable: false },
					{ name: 'minRespTime', align: 'right', width: '80', formatter: decimalFormatter, sortable: false },
					{ name: 'maxRespTime', align: 'right', width: '80', formatter: decimalFormatter, sortable: false }
				],
				jsonReader: { repeatitems: false },
				pager: $('#pager'),
				page: '${param.page}',
				rowNum: '${rmsDefaultRowNum}',
				autoheight: true,
				height: $("#container").height(),
				autowidth: true,
				viewrecords: true,
				rowList: eval('[${rmsDefaultRowList}]'),
				loadComplete: function(d) {
					var colModel = $(this).getGridParam("colModel");
					for (var i = 0; i < colModel.length; i++) {
						$(this).setColProp(colModel[i].name, { sortable: false });
					}
					// 조회(reloadGrid) 시 컬럼 폭이 고정폭(shrinkToFit:false)으로 남아
					// 실제 컨테이너 폭과 어긋나 가로 스크롤이 생기는 것을 방지
					$(this).jqGrid('setGridWidth', $('#content_middle').width(), true);
				}
			});
		}

		$(document).ready(function() {
			// 날짜 입력 마스크
			$("input[name=searchDate]").inputmask("9999-99-99", { 'autoUnmask': true });

			// 기본값 설정 (오늘)
			var today = getToday();
			if (!$("input[name=searchDate]").val()) {
				$("input[name=searchDate]").val(today);
			}

			initCharts();
			listSummary();
			list();
			search();
			fetchChartData();
			resizeJqGridWidth('gridSummary', 'content_middle', '1200');
			resizeJqGridWidth('grid', 'content_middle', '1200');

			$("#btn_search").click(function() {
				search();
			});

			$("#btn_excel_export_summary").click(function() {
				exportToExcel(true);
			});

			$("#btn_excel_export").click(function() {
				exportToExcel(false);
			});

			$("input[name^=search]").keydown(function(key) {
				if (key.keyCode == 13) {
					$("#btn_search").click();
				}
			});

			// 윈도우 리사이즈 시 차트 리사이즈
			$(window).resize(function() {
				if (totalDonutChart) totalDonutChart.resize();
				if (callChart) callChart.resize();
			});

			buttonControl();
		});
	</script>
</head>
<body>
<div class="right_box">
	<div class="content_top">
		<ul class="path">
			<li><a href="#">${rmsMenuPath}</a></li>
		</ul>
	</div>
	<div class="content_middle" id="content_middle">
		<div class="search_wrap">
			<button type="button" class="cssbtn" id="btn_search" level="R">
				<i class="material-icons">search</i> <%= localeMessage.getString("button.search") %>
			</button>
		</div>
		<div class="title" id="title">API 시간별 통계</div>
		<table class="search_condition" cellspacing="0" style="table-layout:fixed;">
			<colgroup>
				<col style="width:150px;">
				<col>
				<col style="width:150px;">
				<col>
				<col style="width:150px;">
				<col>
			</colgroup>
			<tbody>
				<tr>
					<th>조회일자</th>
					<td colspan="5">
						<input type="text" name="searchDate" value="${param.searchDate}" style="width:100px;">
						<span style="color:#888; font-size:12px; margin-left:10px;">(선택일 00시 ~ 23시 조회)</span>
					</td>
				</tr>
				<tr>
					<th>API명</th>
					<td>
						<input type="text" name="searchApiName" value="${param.searchApiName}">
					</td>
					<th>업무구분</th>
					<td>
						<input type="text" name="searchBizDivCode" value="${param.searchBizDivCode}">
					</td>
					<th>인스턴스</th>
					<td>
						<input type="text" name="searchGwInstanceId" value="${param.searchGwInstanceId}">
					</td>
				</tr>
				<tr>
					<th>클라이언트ID</th>
					<td>
						<input type="text" name="searchClientId" value="${param.searchClientId}">
					</td>
					<th>Inbound Adapter</th>
					<td>
						<input type="text" name="searchInboundAdapter" value="${param.searchInboundAdapter}">
					</td>
					<th>Outbound Adapter</th>
					<td>
						<input type="text" name="searchOutboundAdapter" value="${param.searchOutboundAdapter}">
					</td>
				</tr>
			</tbody>
		</table>
		<!-- 도넛 차트 (상단 50%씩) -->
		<div class="chart-container">
			<div class="chart" style="position:relative; padding:0;">
				<div id="totalDonutChart" style="width:100%; height:100%;"></div>
				<div id="totalDonutCenterText" style="position:absolute; left:44.5%; top:55%; transform:translate(-50%,-50%); font-size:24px; font-weight:bold; color:#333; pointer-events:none; z-index:10;">0</div>
			</div>
			<div id="callChart" class="chart"></div>
		</div>

		<!-- 요약 그리드 -->
		<div style="margin-top: 20px;">
			<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
				<div class="title" style="margin: 0;">API명별 요약 통계</div>
				<button type="button" class="cssbtn" id="btn_excel_export_summary" level="R">
					<i class="material-icons">file_download</i> Excel 다운로드 (요약)
				</button>
			</div>
			<table id="gridSummary"></table>		
			<div id="pagerSummary"></div>
		</div>

		<!-- 상세 그리드 -->
		<div style="margin-top: 20px;">
			<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
				<div class="title" style="margin: 0;">상세 통계</div>
				<button type="button" class="cssbtn" id="btn_excel_export" level="R">
					<i class="material-icons">file_download</i> Excel 다운로드 (상세)
				</button>
			</div>
			<table id="grid"></table>
			<div id="pager"></div>
		</div>
	</div>
</div>
</body>
</html>
