<%@ page language="java" contentType="text/html; charset=utf-8"%>
<%@ page import="java.io.*"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ include file="/jsp/common/include/localemessage.jsp" %>
<%
	response.setHeader("Pragma", "No-cache");
	response.setHeader("Cache-Control", "no-cache");
	response.setHeader("Expires", "0");
%>
<!DOCTYPE html>
<html>
<head>
	<title>API 통계</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;
		}
		.chart {
			width: 48%;
			height: 500px;
		}
		.filter-container {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 20px;
		}
		.select-group {
			display: flex;
			gap: 10px;
		}
		.date-group {
			display: flex;
			gap: 10px;
		}
		.date-picker {
			width: 120px;
		}
	</style>
</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="title">API 통계</div>

		<%--<div class="filter-container">
			<div class="select-group">
				<div class="select-style">
					<select name="searchOrgId">
						<option value="">기관 선택</option>
						<!-- 동적으로 옵션이 추가 -->
					</select>
				</div>
				<div class="select-style">
					<select name="searchAppId">
						<option value="">APP 선택</option>
						<option value="app1">앱1</option>
						<option value="app2">앱2</option>
						<option value="app3">앱3</option>
					</select>
				</div>
				<div class="select-style">
					<select name="searchApiId">
						<option value="">API 선택</option>
						<option value="api1">API1</option>
						<option value="api2">API2</option>
						<option value="api3">API3</option>
					</select>
				</div>
				<div class="select-style">
					<select name="searchTimeUnit">
						<option value="">시간 단위</option>
						<option value="hour">시간별</option>
						<option value="day">일별</option>
						<option value="month">월별</option>
					</select>
				</div>
			</div>
			<div class="date-group">
				<input type="text" name="searchStartYYYYMMDD" id="startDatepicker" readonly="readonly" class="date-picker" placeholder="시작일">
				<input type="text" name="searchEndYYYYMMDD" id="endDatepicker" readonly="readonly" class="date-picker" placeholder="종료일">
				<button type="button" class="cssbtn" id="btn_search" level="R">
					<i class="material-icons">search</i> <%= localeMessage.getString("button.search") %>
				</button>
			</div>
		</div>--%>

		<div class="chart-container">
			<div id="normalChart" class="chart"></div>
			<div id="errorChart" class="chart"></div>
		</div>
	</div>
</div>

<jsp:include page="/jsp/common/include/script.jsp"/>
<script src="<c:url value="/addon/echarts/echarts.min.js"/>"></script>
<script type="text/javascript">
	var url = '<c:url value="/onl/apim/portalstatistics/portalStatisticsDailyMan.json" />';
	var normalChart, errorChart;
	var hours = ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11',
		'12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23'];
	var todayNormal = new Array(24).fill(0);
	var todayError = new Array(24).fill(0);
	var yesterdayNormal = new Array(24).fill(0);
	var yesterdayError = new Array(24).fill(0);

	function initializeCharts() {
		normalChart = echarts.init(document.getElementById('normalChart'));
		errorChart = echarts.init(document.getElementById('errorChart'));

		var normalOption = {
			title: { text: '정상 호출 통계' },
			tooltip: {
				trigger: 'axis',
				axisPointer: { type: 'cross', label: { backgroundColor: '#6a7985' } }
			},
			legend: { data: ['금일 정상', '전일 정상'] },
			toolbox: { feature: { saveAsImage: {} } },
			grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
			xAxis: [{ type: 'category', boundaryGap: false, data: hours }],
			yAxis: [{ ype: 'value', minInterval: 1  }],// 최소 간격을 1로 설정
			series: [
				{
					name: '전일 정상',
					type: 'line',
					showSymbol: false,
					itemStyle: { color: '#b9bcc4' },
					lineStyle: { width: 2 },
					areaStyle: { color: '#b9bcc4', opacity: 0.08 },
					data: yesterdayNormal
				},
				{
					name: '금일 정상',
					type: 'line',
					showSymbol: false,
					itemStyle: { color: '#5470C6' },
					lineStyle: { width: 3 },
					areaStyle: { color: '#5470C6', opacity: 0.5 },
					data: todayNormal
				}
			]
		};

		var errorOption = {
			title: { text: '오류 호출 통계' },
			tooltip: {
				trigger: 'axis',
				axisPointer: { type: 'cross', label: { backgroundColor: '#6a7985' } }
			},
			legend: { data: ['금일 오류', '전일 오류'] },
			toolbox: { feature: { saveAsImage: {} } },
			grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
			xAxis: [{ type: 'category', boundaryGap: false, data: hours }],
			yAxis: [{  type: 'value', minInterval: 1 }],
			series: [
				{
					name: '전일 오류',
					type: 'line',
					showSymbol: false,
					itemStyle: { color: '#b9bcc4' },
					lineStyle: { width: 2 },
					areaStyle: { color: '#b9bcc4', opacity: 0.08 },
					data: yesterdayError
				},
				{
					name: '금일 오류',
					type: 'line',
					showSymbol: false,
					itemStyle: { color: '#EE6666' },
					lineStyle: { width: 3 },
					areaStyle: { color: '#EE6666', opacity: 0.5 },
					data: todayError
				}
			]
		};

		normalChart.setOption(normalOption);
		errorChart.setOption(errorOption);
	}

	function updateCharts() {
		normalChart.setOption({
			series: [
				{ data: yesterdayNormal },
				{ data: todayNormal }
			]
		});
		errorChart.setOption({
			series: [
				{ data: yesterdayError },
				{ data: todayError }
			]
		});
	}

	function fetchData(startDate, endDate) {
		$.ajax({
			url: url,
			type: 'POST',
			data: {
				cmd: 'LIST',
				startDate: startDate,
				endDate: endDate,
				serviceType: 'APIGW'
			},
			success: function(response) {
				console.log(response);

				// 데이터 초기화
				todayNormal = new Array(24).fill(0);
				todayError = new Array(24).fill(0);
				yesterdayNormal = new Array(24).fill(0);
				yesterdayError = new Array(24).fill(0);

				// 응답 데이터 처리
				if (response.today) {
					response.today.forEach(function(item) {
						var hour = parseInt(item.statisticsTime.substring(8, 10));
						todayNormal[hour] = item.requestCount;
						todayError[hour] = item.failureCount;
					});
				}

				if (response.yesterday) {
					response.yesterday.forEach(function(item) {
						var hour = parseInt(item.statisticsTime.substring(8, 10));
						yesterdayNormal[hour] = item.requestCount;
						yesterdayError[hour] = item.failureCount;
					});
				}

				updateCharts();
			},
			error: function(xhr, status, error) {
				console.error('Error fetching data:', error);
			}
		});
	}

	function getPreviousDay(date) {
		var d = new Date(date.substring(0, 4) + "-" + date.substring(4, 6) + "-" + date.substring(6, 8));
		d.setDate(d.getDate() - 1);
		return d.toISOString().split('T')[0].replace(/-/g, "");
	}

	function initCombo() {
		$.ajax({
			url: url,
			type: 'POST',
			data: {
				cmd: 'LIST_INIT_COMBO'
			},
			success: function(response) {
				var orgList = response.orgList;
				var selectOrg = $("select[name=searchOrgId]");
				selectOrg.empty().append($('<option>').val('').text('기관 선택'));
				$.each(orgList, function(i, item) {
					selectOrg.append($('<option>').val(item.CODE).text(item.NAME));
				});
			},
			error: function(xhr, status, error) {
				console.error('Error initializing combo boxes:', error);
			}
		});
	}

	$(document).ready(function() {
		$("input[name=searchStartYYYYMMDD],input[name=searchEndYYYYMMDD]").inputmask("yyyy-mm-dd",{'autoUnmask':true});

		initializeCharts();
		initCombo();

		$("#startDatepicker").datepicker({
			dateFormat: 'yy-mm-dd'
		});
		$("#endDatepicker").datepicker({
			dateFormat: 'yy-mm-dd'
		});

		$("#btn_search").click(function(){
			var start = $("input[name=searchStartYYYYMMDD]").val().replace(/-/g, "");
			var end = $("input[name=searchEndYYYYMMDD]").val().replace(/-/g, "");

			if(start > end){
				alert("조회기간을 확인해주세요.");
				return false;
			}

			fetchData(start, end);
		});

		var today = new Date().toISOString().split('T')[0].replace(/-/g, "");
		$('#startDatepicker').val(today);
		$('#endDatepicker').val(today);
		fetchData(today, today);
	});
</script>
</body>
</html>