<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<jsp:include page="${data._INCLUDE}/header.jsp"></jsp:include>
<link rel="stylesheet" href="/resources/bower_components/mdi/css/materialdesignicons.min.css">
<script src="/resources/bower_components/jquery-bootpag-master/lib/jquery.bootpag.min.js"></script>
<script>

var totalList = ${total}; // 저장된 데이터 항목 수
var viewEntry = 30;		// 한 화면에 표시되는 갯수 
var totalPage = Math.ceil(totalList / viewEntry);
var reloadIntervalTime = 30;	// 
var reloadTimer = null;

function changeReloadInterval() {
	reloadIntervalTime = $("#reloadIntervalSelect option:selected").val();
}

function activeReloadTimer() {	
	if (reloadIntervalTime) {
		if (reloadTimer) {
			deactiveReloadTimer();
		}
		
		reloadTimer = setInterval(function() {
			nextPage();
		}, reloadIntervalTime * 1000);

		return true;
	}
	else {
		
		return false;
	}
}

function deactiveReloadTimer() {	
	if (reloadTimer) {
		clearInterval(reloadTimer);
		reloadTimer = null;
	}
}

function searchPatients() {
	var keyword = $("#searchKeyword").val();

	location.href = "./state?searchText="+keyword;
}

function retrieveStateData(page) {

	var searchText = '<c:out value="${searchText}" />';
	var params = {page: page, searchText: searchText};

	$.ajax({
        url      : "./api/state",
        data     : params,
        method   : "GET",
        dataType : "json",
        success  : function( datas ){
            
           	var html = '<div class="blankItem">표시할 데이터가 없습니다.</div>';
						if (datas.length > 0) {
							html = "";
							datas.forEach(d => {
								var danger = (d.isTemperatureWarning || d.isBloodPressureWarning || d.isOxygenSaturationeWarning) ? "danger" : "";
								var temperatureStep = d.isTemperatureWarning ? "step_two" : "step_one";
								var bloodPressureStep = d.isBloodPressureWarning ? "step_two" : "step_one";
								var oxygenSaturationStep = d.isOxygenSaturationeWarning ? "step_two" : "step_one";
								var temperatureCheck = d.needTemperatureCheck ? "timeover" : "";
								var bloodPressureCheck = d.needBloodPressCheck ? "timeover" : "";
								var oxygenSaturationCheck = d.needOxygenSaturationCheck ? "timeover" : "";
								
								var temperature = (d.temperature || "--") + ' ℃ ';
								var bloodPressure = (d.bloodPressureDisplay) + " ";
								var oxygenSaturation = (d.oxygenSaturation || "--") + " % ";
								html += '<div class="col-lg-2 col-md-6 mb-4">';
								html += '	<div class="patients-stats" data-url="./info?patientIdx='+d.patientIdx+'">';
								html += '		<div class="name">';
								html += '			'+d.roomNumber+'('+d.patientName+')';
								html += '			<div class="check">';
								html += '				<ul>';
								if (d.memoCount > 0) {
								html += '					<li><a href="javscript:;" class="memo"><i class="align-middle ml-2 fas fa-fw fa-edit"></i></a></li>';
								}
								if (d.hasTodaySymptom) {
								html += '					<li><a href="javscript:;" class="symptom"><i class="align-middle ml-2 fas fa-fw fa-user-plus"></i></a></li>';
								}
								html += '				</ul>';
								html += '			</div>';
								html += '		</div>';
								html += '      <div class="stats '+danger+'">';
								html += '			<ul>';
								html += '				<li class="fever '+temperatureStep+' '+temperatureCheck+'">'+temperature+'</li>';
								html += '				<li class="bloodPressure '+bloodPressureStep+' '+bloodPressureCheck+'">'+bloodPressure+'</li>';
								html += '				<li class="oxygen '+oxygenSaturationStep+' '+oxygenSaturationCheck+'">'+oxygenSaturation+'</li>';
								html += '			</ul>';
								html += '		</div>';
								html += '	</div>';
								html += '</div>';
							});
						};

						$(".patients-list").fadeOut('fast',function(){
							$(".patients-list").html(html).fadeIn('fast');
						});
        },
        error : function(error){
            alert(error.message);
        }
    }).done( function(){

    });
}

function nextPage() {

	if (totalPage === 1) {
		retrieveStateData(1);
		return;
	}
	
	var next = $("#pagination .active").next();

	if (!next.is(':visible')) {
		$("#pagination .first").click();
	}
	else {
		next.click();
	}
}

//윈도우 폭에 따른 반응형 목록 수 분기 함수
function responsiblePagination() {
	var window_width = $(window).width();

	if(window_width >= 1200) {
		$('#pagination').bootpag({
			maxVisible: 10, // 한번에 보여지는 페이지수
			firstLastUse: true
		});
	}
	if(window_width < 1200 && window_width >= 600) {
		$('#pagination').bootpag({
			maxVisible: 5, // 한번에 보여지는 페이지수
			firstLastUse: true
		});
	}
	if(window_width < 600){
		$('#pagination').bootpag({
			maxVisible: 3, // 한번에 보여지는 페이지수
			firstLastUse: false
		});
	}
}

$(document).ready(function() {

	$(document).on("click", ".patients-stats", function() {
		location.href = $(this).attr("data-url");
	});

	// 반복 start/stop 클릭
	$('#playButton').click(function () {
		if (activeReloadTimer()) {	
			$('#playButton').addClass('disabled');
			$('#pauseButton').removeClass('disabled');
			$("#reloadIntervalSelect").prop("disabled", true);
		}
	});
	$('#pauseButton').click(function () {
		deactiveReloadTimer();
		$('#playButton').removeClass('disabled');
		$('#pauseButton').addClass('disabled');
		$("#reloadIntervalSelect").prop("disabled", false);
	});

	////////////////////////////////////////////////////////////////////////////////
	//// Pagination
	////////////////////////////////////////////////////////////////////////////////

	// 페이지 네이션 실행
	// Pagination  API -> http://botmonster.com/jquery-bootpag/#.XD2VElwzaUk
	$('#pagination').bootpag({
		// maxVisible: 10, // 한번에 보여지는 페이지수
		// firstLastUse: true,
		// href: 'URL',// template for pagination links (default javascript:void(0);)
		// hrefVariable: false,// variable name in href template for page number (default {{number}})
		total: totalPage, // 페이지 수
		page: 1, // 초기 페이지
		leaps: true,
		first: '<i class="mdi mdi-chevron-double-left"></i>',
		prev: '<i class="mdi mdi-chevron-left"></i>',
		next: '<i class="mdi mdi-chevron-right"></i>',
		last: '<i class="mdi mdi-chevron-double-right"></i>',
		wrapClass: 'pagination',
		activeClass: 'active',
		disabledClass: 'disabled',
		nextClass: 'next',
		prevClass: 'prev',
		lastClass: 'last',
		firstClass: 'first'
	}).on("page", function(event, num){
		retrieveStateData(num);
	});
	responsiblePagination();

	// 윈도우 폭 변경에 따른 반응형 목록 수 적용
	$(window).resize(function(){
		responsiblePagination();
	});
});
</script>
</head>

<body>
	<div class="wrapper">
		<jsp:include page="${data._INCLUDE}/sidebar.jsp"></jsp:include>

		<div class="main">
			<jsp:include page="${data._INCLUDE}/top.jsp"></jsp:include>

			<main class="content">
				<div class="container-fluid p-0">
					<!-- 환자관리 : 신규환자 등록 START -->
					<div class="row">
						<div class="col-12 col-lg-6">
							<h1 class="h3 mb-3">진료관리</h1>
						</div>
						<div class="col-12 col-lg-6  text-right">
							<nav aria-label="breadcrumb">
								<ol class="breadcrumb">
									<li class="breadcrumb-item"><a href="javscript:;">Home</a></li>
									<li class="breadcrumb-item active">진료관리</li>
								</ol>
							</nav>
						</div>
					</div>
					<div class="row">
						<div class="col-12">
							<div class="card">
								<div class="card-header">
									<div class="row">
										<div class="col-lg-6">
											<h1 class="h4">- 상태현황</h1>
										</div>
										<div class="col-lg-6 search text-right">
											<label> <select id="reloadIntervalSelect" class="custom-select" onchange="changeReloadInterval()">
													<option value="10">10초</option>
													<option value="30" selected>30초</option>
													<option value="60">60초</option>
											</select>
											</label> <label>
												<button type="button" id="playButton" class="btn btn-primary">
													<i class="fas fa-play"></i>
												</button>
												<button type="button" id="pauseButton" class="btn btn-primary disabled">
													<i class="fas fa-pause"></i>
												</button>
											</label> <input type="text" class="form-control w150" id="searchKeyword" placeholder="호실 or 환자명" value="${searchText}" onkeyup="if(event.keyCode===13){searchPatients()}">
											<button class="btn btn-primary" onclick="searchPatients()">검색</button>
										</div>
									</div>
								</div>
								<div class="card-body">
									<div class="row patients-list">
										<c:choose>
										<c:when test="${total == 0}">
										<div class="blankItem">표시할 데이터가 없습니다.</div>
										</c:when>
										<c:otherwise>
										<c:forEach var="patient" items="${items}" varStatus="status">
											<c:set var="title" value="${patient.roomNumber}(${patient.patientName})" />
											<c:set var="viewLink" value="./info?patientIdx=${patient.patientIdx}" />
											<c:set var="temperatureStep" value="${patient.isTemperatureWarning ? 'step_two' : 'step_one'}" />
											<c:set var="bloodPressureStep" value="${patient.isBloodPressureWarning ? 'step_two' : 'step_one'}" />
											<c:set var="oxygenSaturationStep" value="${patient.isOxygenSaturationeWarning ? 'step_two' : 'step_one'}" />
											<c:set var="temperatureCheck" value="${patient.needTemperatureCheck ? 'timeover' : ''}" />
											<c:set var="bloodPressureCheck" value="${patient.needBloodPressCheck ? 'timeover' : ''}" />
											<c:set var="oxygenSaturationCheck" value="${patient.needOxygenSaturationCheck ? 'timeover' : ''}" />
											<div class="col-lg-2 col-md-6 mb-4">
												<div class="patients-stats" data-url="${viewLink}">
													<div class="name">
														<c:out value="${title}" />
														<div class="check">
															<ul>
																<c:if test="${patient.memoCount > 0}">
																<li><a href="javscript:;" class="memo"><i class="align-middle ml-2 fas fa-fw fa-edit"></i></a></li>
																</c:if>
																<c:if test="${patient.hasTodaySymptom}">
																<li><a href="javscript:;" class="symptom"> <i class="align-middle ml-2 fas fa-fw fa-user-plus"></i></a></li>
																</c:if>
															</ul>
														</div>
													</div>
													<div class="stats ${patient.isTemperatureWarning || patient.isBloodPressureWarning || patient.isOxygenSaturationeWarning ? 'danger' : '' }">
														<ul>
															<li class="fever ${temperatureStep} ${temperatureCheck}"><c:out value="${patient.temperature != null ? patient.temperature : '--'} ℃ " /></li>
															<li class="bloodPressure ${bloodPressureStep} ${bloodPressureCheck}"><c:out value='${patient.bloodPressureDisplay} ' /></li>
															<li class="oxygen ${oxygenSaturationStep} ${oxygenSaturationCheck}"><c:out value="${patient.oxygenSaturation != null ? patient.oxygenSaturation : '--'} %" />
														</ul>
													</div>
												</div>
											</div>
										</c:forEach>
										</c:otherwise>
										</c:choose>
									</div>
								</div>
								<div class="card-footer">
									<div id="pagination" class="paginationContainer"></div>
								</div>
							</div>
						</div>
					</div>
					<!-- 환자관리 : 신규환자 등록 END -->
				</div>
			</main>

			<jsp:include page="${data._INCLUDE}/footer.jsp"></jsp:include>
		</div>
	</div>
</body>
</html>