<%@ 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");
%>
<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 language="javascript" >
	var url = '<c:url value="/onl/apim/portalnotice/portalNoticeMan.json" />';
	var url_view = '<c:url value="/onl/apim/portalnotice/portalNoticeMan.view" />';
	var file_download = '<c:url value="/file/download.do" />';
	var isDetail = false;
	var fileInfo = null;

	function init() {
		// 초기화 로직
	}

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

	function formatFileSize(bytes) {
		if(bytes == 0) return '0 Bytes';
		var k = 1024,
				sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'],
				i = Math.floor(Math.log(bytes) / Math.log(k));
		return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
	}

	function displayAttachFile(file) {
		var $attachFiles = $('#attachFiles');
		$attachFiles.empty();

		if (file) {
			var iconPath = '${pageContext.request.contextPath}/images/icon_file.png';
			var fileItem = $('<div>').addClass('file-item');

			$('<img>').attr('src', iconPath).css({'marginLeft': '15px','marginRight': '5px' ,'height': '1.2em'}).appendTo(fileItem);

			var fileNameSpan = $('<span>')
					.addClass('fileName')
					.text(file.originalFileName + '.' + file.fileExtension + ' (' + formatFileSize(file.size) + ')')
					.css('cursor', 'pointer')
					.on('click', function() {
						if (file.fileId) {
							downloadFile(file.fileId);
						}
					});

			fileNameSpan.appendTo(fileItem);
			$('<button>').text('X').addClass('delete-file').css('marginLeft', '15px')
					.on('click', function() {
						fileInfo = null;
						displayAttachFile(null);
						// 폼에 삭제 플래그 추가
						$('<input>').attr({
							type: 'hidden',
							name: 'fileDeleted',
							value: 'true'
						}).appendTo('#ajaxForm');
					})
					.appendTo(fileItem);

			fileItem.appendTo($attachFiles);
		}
	}

	function downloadFile(fileId) {
		if (fileId) {
			var fileSn = 1;  // 단일 파일이므로 시리얼 넘버를 1로 고정
			window.location.href = file_download + '?fileId=' + fileId + '&fileSn=' + fileSn;
		} else {
			console.log("File not yet uploaded or doesn't have an ID");
		}
	}


	function detail(key) {
		if (!isDetail) return;
		$.ajax({
			type: "POST",
			url: url,
			dataType: "json",
			data: {cmd: 'DETAIL', id: key},
			success: function (data) {
				$("#id").val(key);
				$("#noticeSubject").val(data.noticeSubject);
				$("#useYn").prop("checked", data.useYn === "Y");

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

				// 파일 정보 표시
				if (data.fileInfo) {
					fileInfo = {
						originalFileName: data.fileInfo.fileDetails[0].originalFileName,
						fileExtension: data.fileInfo.fileDetails[0].fileExtension,
						fileId: data.fileInfo.fileDetails[0].fileId,
						size: data.fileInfo.fileDetails[0].fileSize
					};
					displayAttachFile(fileInfo);
				}
			},
			error: function (e) {
				alert(e.responseText);
			}
		});
	}

	$(document).ready(function () {
		var returnUrl = getReturnUrlForReturn();
		var key = "${param.id}";
		isDetail = key != "" && key != "null";

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

		init();

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

		if (key) {
			detail(key);
		}

		$('#fileInput').change(function(e) {
			var file = e.target.files[0];
			if (file) {
				fileInfo = {
					originalFileName: file.name.split('.').slice(0, -1).join('.'),
					fileExtension: file.name.split('.').pop(),
					file: file,
					size: file.size
				};
				displayAttachFile(fileInfo);
			}
			this.value = '';  // 입력 필드 초기화
		});

		$('#addFile').click(function() {
			$('#fileInput').click();
		});


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

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

			var formData = new FormData($("#ajaxForm")[0]);

			formData.set("useYn", $("#useYn").is(":checked") ? "Y" : "N");
			formData.set("noticeDetail", $('#contents').summernote('code'));

			formData.append("cmd", isDetail ? "UPDATE" : "INSERT");

			// 파일 처리
			if (fileInfo && fileInfo.file) {
				formData.set("files", fileInfo.file);
				formData.set("fileName", fileInfo.originalFileName + '.' + fileInfo.fileExtension);
			}

			$.ajax({
				type: "POST",
				url: url,
				data: formData,
				processData: false,
				contentType: false,
				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 postData = $('#ajaxForm').serializeArray();
				postData.push({name: "cmd", value: "DELETE"});

				$.ajax({
					type: "POST",
					url: url,
					data: postData,
					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" enctype="multipart/form-data" accept-charset="UTF-8">
			<input type="hidden" name="id" id="id">
			<table class="table_row" cellspacing="0">
				<tr>
					<th style="width:20%;">사용여부</th>
					<td>
						<input type="checkbox" name="useYn" id="useYn" value="Y" ${portalNoticeUI.useYn eq 'Y' ? 'checked' : ''}> 사용</td>
				</tr>
				<tr>
					<th style="width:20%;">제목 <font color="red">*</font></th>
					<td><input type="text" id="noticeSubject" name="noticeSubject" style="width:100%" data-required data-warning="제목을 입력하여 주십시오."/></td>
				</tr>
				<tr>
					<th style="width:20%;">본문 <font color="red">*</font></th>
					<td>
						<textarea id="contents" name="noticeDetail" style="width:100%;height:300px" data-required data-warning="본문을 입력하여 주십시오."></textarea>
					</td>
				</tr>
				<tr>
					<th style="width:20%;">첨부파일</th>
					<td>
						<div style="margin: 5px 0px;  display: inline-block;">
							<input type="file" id="fileInput" name="files" style="display:none;" />
							<button type="button" id="addFile" class="cssbtn smallBtn">파일 선택</button>
						</div>
						<div id="attachFiles" style="margin: 5px 0px; display: inline-block;"></div>
					</td>
				</tr>
			</table>
		</form>
	</div>
</div>
</body>
</html>