<%@ 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");
%>
<%!
	public String getRequiredLabel(String label) {
		return label + " <span class=\"required-mark\">*</span>";
	}
%>
<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"/>
	<jsp:include page="/jsp/common/include/portal.jsp"/>
	<script language="javascript">
		var url = '<c:url value="/onl/apim/portalterms/portalTermsMan.json" />';
		var url_view = '<c:url value="/onl/apim/portalterms/portalTermsMan.view" />';
		var isDetail = false;

		function decodeHTMLEntities(text) {
			var textArea = document.createElement('textarea');
			textArea.innerHTML = text;
			return textArea.value;
		}

		function init() {
			$.ajax({
				type: "POST",
				url: url,
				dataType: "json",
				data: {cmd: 'LIST_INIT_COMBO'},
				success: function(json) {
					new makeOptions("CODE", "NAME")
							.setObj($("select[name=agreementsType]"))
							.setData(json.termsTypeRows)
							.setFormat(nameOptionFormat)
							.rendering();

					if (isDetail && "${param.agreementsType}" && "${param.revision}") {
						detail("${param.agreementsType}", "${param.revision}");
					}
				},
				error: function(e) {
					alert(e.responseText);
				}
			});
		}

		function detail(agreementsType, revision) {
			if (!isDetail) {
				$('#revisionHidden').val("0");
				return;
			}
			$.ajax({
				type: "POST",
				url: url,
				dataType: "json",
				data: {cmd: 'DETAIL', agreementsType: agreementsType, revision: revision},
				success: function (data) {
					$("#agreementsType").val(data.agreementsType);
					$("#revision").text(data.revision);
					$("#revisionHidden").val(data.revision);
					$("#name").val(data.name);
					$("#status").val(data.status);

					var decodedContent = decodeHTMLEntities(data.contents);
					$('#contents').summernote('code', decodedContent);

					if (data.publishedOn) {
						$("#publishedOnDisplay").val(gridDateFormat(data.publishedOn));
						$("#publishedOn").val(data.publishedOn);
					}
					if (data.status !== 'DRAFT') {
						$("#publishedOnDisplay").prop('disabled', true);
					}
					$("#createdByName").text(data.createdByName);
					$("#createdDate").text(timeStampFormat(data.createdDate));
					$("#lastModifiedDate").text(timeStampFormat(data.lastModifiedDate));
					$("#lastModifiedByName").text(data.lastModifiedByName);
				},
				error: function (e) {
					alert(e.responseText);
				}
			});
		}

		$(document).ready(function() {
			var returnUrl = getReturnUrlForReturn();
			var agreementsType = "${param.agreementsType}";
			var revision = "${param.revision}";

			isDetail = agreementsType != "" && agreementsType != "null" && revision != "" && revision != "null";

			if (isDetail) {
				$("#title").append(" 수정");
				$("#agreementsType").prop('disabled', true);
				buttonControl(true);
			} else {
				$("#title").append(" 등록");
				$("#revisionHidden").val("0");
				$("#btn_modify").html('<i class="material-icons">save</i> <%= localeMessage.getString("button.register") %>');
				buttonControl(false);
			}

			init();

			$("#publishedOnDisplay").datepicker({
				format: 'yyyy-mm-dd',
				language: 'ko',
				autoclose: true,
				minDate: 0,
			}).on('changeDate', function(e) {
				var formattedDate = e.format('yyyymmdd') + '000000';
				$("#publishedOn").val(formattedDate); // 변경된 날짜만 설정
			}).on('hide', function(e) {
				if (!$("#publishedOnDisplay").val()) {
					$("#publishedOnDisplay").val(gridDateFormat($("#publishedOn").val()));
				}
			});

			$('#contents').summernote({
				placeholder: '여기에 답변을 입력하세요.',
				height: 300,
				toolbar: [
					['style', ['style']],
					['font', ['bold', 'underline', 'clear']],
					['color', ['color']],
					['para', ['ul', 'ol', 'paragraph']],
					['table', ['table']],
					['insert', ['link']],
					['view', ['fullscreen', 'codeview', 'help']]
				],
				callbacks: {
					onInit: function() {
						$('.note-editable').on('keydown', function(e) {
							if (e.keyCode === 8) {
								e.stopPropagation();
							}
						});
					}
				}
			});

			if (agreementsType && revision) {
				detail(agreementsType, revision);
			}

			$("#btn_modify").click(function() {
				if (!checkRequired("ajaxForm")) return;

				// Summernote 에디터 내용 검증
				var contents = $('#contents').summernote('code');
				if (contents === "" || contents === "<p><br></p>" || contents === "<p></p>") {
					alert("약관 내용을 입력하여 주십시오.");
					$('#contents').summernote('focus');
					return;
				}

				if (confirm("<%= localeMessage.getString("common.checkSave")%>") != true)
					return;

				$("#agreementsType").prop('disabled', false);
				var postData = $('#ajaxForm').serializeArray();

				if (isDetail) {
					postData.push({ name: "cmd", value: "UPDATE" });
				} else {
					postData.push({ name: "cmd", value: "INSERT" });
				}

				$.ajax({
					type: "POST",
					url: url,
					data: postData,
					success: function (json) {
						alert("<%= localeMessage.getString("common.saveMsg") %>");
						goNav(returnUrl);
					},
					error: function (e) {
						alert(e.responseText);
					}
				});
			});

			$("#btn_delete").click(function () {
				if (confirm("<%= localeMessage.getString("common.confirmMsg")%>")) {
					var deleteData = {
						cmd: "DELETE",
						agreementsType: $("#agreementsType").val(),
						revision: $("#revisionHidden").val()
					};

					$.ajax({
						type: "POST",
						url: url,
						data: deleteData,
						success: function (args) {
							alert("<%= localeMessage.getString("common.deleteMsg") %>");
							goNav(returnUrl);
						},
						error: function (e) {
							alert(e.responseText);
						}
					});
				}
			});

			$("#btn_previous").click(function() {
				goNav(returnUrl);
			});
		});
	</script>
</head>
<body>
<div class="right_box">
	<div class="content_top">
		<ul class="path">
			<li><a href="#">${rmsMenuPath}</a></li>
		</ul>
	</div><!-- end content_top -->
	<div class="content_middle">
		<div class="search_wrap">
			<button type="button" class="cssbtn" id="btn_modify" level="W" status="DETAIL,NEW"><i class="material-icons">save</i> <%= localeMessage.getString("button.modify") %></button>
			<button type="button" class="cssbtn" id="btn_delete" level="W" status="DETAIL"><i class="material-icons">delete</i> <%= localeMessage.getString("button.delete") %></button>
			<button type="button" class="cssbtn" id="btn_previous" level="R" status="DETAIL,NEW"><i class="material-icons">arrow_back</i> <%= localeMessage.getString("button.previous") %></button>
		</div>
		<div class="title" id="title">약관</div>
		<form id="ajaxForm">
			<input type="hidden" name="revision" id="revisionHidden">
			<table class="table_row" cellspacing="0">
				<tr>
					<th style="width:10%;"><%= getRequiredLabel("약관명") %></th>
					<td  style="width:40%;" colspan="1">
						<div class="select-style" >
							<select type="text" id="agreementsType" name="agreementsType" style="width:100%"
									data-required data-warning="약관명을 선택하여 주십시오."></select>
						</div>
					</td>
					<th style="width:10%;">버전</th>
					<td style="width:40%;" colspan="1" id="revision"></td>
				</tr>
				<tr>
					<th>등록자</th>
					<td id="createdByName"></td>
					<th style="width:10%;">수정자</th>
					<td id="lastModifiedByName"></td>
				</tr>
				<tr>
					<th>등록일</th>
					<td id="createdDate"></td>
					<th>수정일</th>
					<td id="lastModifiedDate"></td>
				</tr>
				<tr>
					<th><%= getRequiredLabel("약관 시행일") %></th>
					<td colspan="3" >
						<!-- 표시용 날짜 필드 -->
						<input type="text" id="publishedOnDisplay" style="width:200px;"  data-required data-warning="약관시행일을 입력하여 주십시오."/>
						<input type="hidden" id="publishedOn" name="publishedOn"/>
					</td>
				</tr>
				<tr>
					<th><%= getRequiredLabel("약관 내용") %></th>
					<td colspan="3">
						<textarea id="contents" name="contents" style="width:100%;height:300px" data-required data-warning="약관내용을 입력하여 주십시오."></textarea>
					</td>
				</tr>
			</table>
		</form>
	</div>
</div>
</body>
</html>