<%@ 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"/>
	<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/apiUseStatsMan.json"/>';
		var url_view = '<c:url value="/onl/kjb/statistics/apiUseStatsMan.view"/>';


		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 (cellvalue).toFixed(2);
		}
		
		function getPostData() {
			var postData = {}
			if (arguments.length == 2) {
		        postData[arguments[0]] = arguments[1];
		    }
			
			var searchStartDate = $("input[name=searchStartDate]").val().replace(/-/g, "");
			var searchEndDate = $("input[name=searchEndDate]").val().replace(/-/g, "");

			if (searchStartDate && searchEndDate) {
				var start = new Date(searchStartDate.substring(0, 4), parseInt(searchStartDate.substring(4, 6)) - 1, searchStartDate.substring(6, 8));
				var end = new Date(searchEndDate.substring(0, 4), parseInt(searchEndDate.substring(4, 6)) - 1, searchEndDate.substring(6, 8));
				var diffDays = Math.ceil((end - start) / (1000 * 60 * 60 * 24));

				if (diffDays > 31) {
					alert('조회 기간은 최대 31일까지 가능합니다.');
					return null;
				}
			}
			
			postData.searchType = $('input[name="searchType"]:checked').val();
			postData.searchOrgName = $('#searchOrgName').val();
			postData.searchApiName = $('#searchApiName').val();
			postData.searchStartDateTime = searchStartDate;
			postData.searchEndDateTime = searchEndDate;
			
			return postData;
		}


		function search() {
			var postData = getPostData("cmd", "LIST");
			if (postData) {
				$("#grid").setGridParam({ url: url, postData: postData, page: 1 }).trigger("reloadGrid");
			}
		}

		function exportToExcel() {
			
			var postData = getPostData("cmd", "EXCEL_EXPORT");
			if (!postData) {
				return;
			}
			postData.serviceType = '${param.serviceType}';

			
			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 다운로드 중 오류가 발생했습니다.';
						console.log('reader.result', reader.result)
						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 list() {
			var gridPostData = getPostData("cmd", "LIST");
			
			$('#grid').jqGrid({
				datatype: "json",
				mtype: 'POST',
				postData: gridPostData,
				colNames: [
					'구분',
					'총건수', '성공', '성공율(%)', '실패율(%)', 'Timeout', '시스템오류', 
					'평균응답(ms)', '최소응답(ms)', '최대응답(ms)'
				],
				colModel: [
					{ name: 'orgName', 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: 'successRate', align: 'right', width: '80', formatter: decimalFormatter, sortable: false },
					{ name: 'failRate', align: 'right', width: '80', formatter: decimalFormatter, 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: numberFormatter, sortable: false },
					{ name: 'minRespTime', align: 'right', width: '90', formatter: numberFormatter, sortable: false },
					{ name: 'maxRespTime', align: 'right', width: '90', formatter: numberFormatter, sortable: false }
				],
				jsonReader: { repeatitems: false },
				pager: $('#pager'),
				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 });
					}
				}
			});
		}


		$(document).ready(function() {
			// 날짜/시간 입력 마스크
			$("input[name=searchStartDate], input[name=searchEndDate]").inputmask("9999-99-99", { 'autoUnmask': true });
			$("input[name=searchStartDate], input[name=searchEndDate]").datepicker();
			
			var today = getToday();
			var startDate = today.substring(0,6)+"01";
			var endDate = today;
			

			if (!$("input[name=searchStartDate]").val()) {
				$("input[name=searchStartDate]").val(startDate);
			}
			if (!$("input[name=searchEndDate]").val()) {
				$("input[name=searchEndDate]").val(endDate);
			}

			list();
			search();

			resizeJqGridWidth('grid', 'content_middle', '1200');

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

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

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


			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_excel" level="R" style="display: inline-block;"><i class="material-icons">table_view</i> 엑셀</button>
			<button type="button" class="cssbtn" id="btn_search" level="R" style="display: inline-block;">
				<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">
			<tbody>
				<tr>
					<th style="width:120px;">조회기간</th>
					<td colspan="5">	
						<input type="text" name="searchStartDate" id="searchStartDate" value="${param.searchStartDate}" style="width:100px;">
						~
						<input type="text" name="searchEndDate" id="searchEndDate" value="${param.searchEndDate}" style="width:100px;">
						<span style="color:#888; font-size:12px; margin-left:10px;">(최대 31일)</span>
					</td>
				</tr>
				<tr>
					<th style="width:120px;">조회구분</th>
					<td>
						<input type="radio" name="searchType" id="searchTypeORG" value="ORG" checked="checked"><label for="searchTypeORG">제휴사</label></input>
						<input type="radio" name="searchType" id="searchTypeAPI" value="API"><label for="searchTypeAPI">API</label></input>
						<input type="radio" name="searchType" id="searchTypeDATE" value="DATE"><label for="searchTypeDATE">사용일</label></input>
					</td>
					<th style="width:120px;">제휴사명</th>
					<td>
						<input type="text" name="searchOrgName" id="searchOrgName" value="${param.searchOrgName}">
					</td>
					<th style="width:120px;">API명</th>
					<td>
						<input type="text" name="searchApiName" id="searchApiName" value="${param.searchApiName}">
					</td>
				</tr>
			</tbody>		
		</table>

		<div>
			<table id="grid"></table>
			<div id="pager"></div>
		</div>

		
	</div>
</div>
</body>
</html>
