<%@ page pageEncoding="UTF-8" %>

<script type="text/javascript">
var employeeCertFiles = [];

$(document).ready(function() {
	$(document).on("click", "[data-tooltip='worker_count_popup']", function() {
		prepareEmployeeCertPopup($(this).attr("data-cert-mode"));
	});
	$("#employeeCertFileInput").on("change", function() {
		addEmployeeCertFiles(this.files);
		this.value = "";
	});
	$("#employeeCertDropZone").on("dragenter dragover", function(event) {
		event.preventDefault();
		event.stopPropagation();
	}).on("drop", function(event) {
		event.preventDefault();
		event.stopPropagation();
		addEmployeeCertFiles(event.originalEvent.dataTransfer.files);
	});
});

function prepareEmployeeCertPopup(mode) {
	var isReapply = mode === "REAPPLY";
	var title = mode === "UPDATE" ? "종사자 수 변경" : (isReapply ? "종사자 수 재신청" : "종사자 수 등록");
	var workerCnt = mode === "UPDATE"
		? currentSendNumberStatus.certCnt
		: (isReapply ? currentSendNumberStatus.applyCnt : "");

	$("#employeeCertPopupTitle").text(title);
	$("#employeeCertMode").val(mode);
	$("#employeeCnt").val(workerCnt === null || workerCnt === undefined ? "" : workerCnt);
	$("#employeeCertRejectReason").toggle(isReapply);
	$("#employeeCertRejectReasonText").text(isReapply
		? (currentSendNumberStatus.rejectReason || "반려 사유를 확인할 수 없습니다.")
		: "");
	$("#agreeEmployeeEvidence").prop("checked", false);
	resetEmployeeCertFiles();
}

function addEmployeeCertFiles(fileList) {
	var files = Array.prototype.slice.call(fileList || []);
	var maxFileCount = 5;
	var maxFileSize = 50 * 1024 * 1024;
	var allowedExtension = /\.(pdf|png|jpe?g)$/i;

	if (employeeCertFiles.length + files.length > maxFileCount) {
		alert("증빙서류는 최대 " + maxFileCount + "개까지 첨부할 수 있습니다.");
		return;
	}

	for (var i = 0; i < files.length; i++) {
		if (!allowedExtension.test(files[i].name)) {
			alert("PDF 또는 이미지(PNG, JPG, JPEG) 파일만 첨부할 수 있습니다.");
			return;
		}
		if (files[i].size > maxFileSize) {
			alert("파일당 최대 크기는 50MB입니다.");
			return;
		}
	}

	employeeCertFiles = employeeCertFiles.concat(files);
	drawEmployeeCertFiles();
}

function drawEmployeeCertFiles() {
	var $tbody = $("#employeeCertFileList").empty();
	$.each(employeeCertFiles, function(index, file) {
		var $row = $("<tr>");
		$("<td>").text(file.name).appendTo($row);
		$("<td>").text(formatEmployeeCertFileSize(file.size)).appendTo($row);
		$("<td>").text(new Date().toLocaleString("ko-KR")).appendTo($row);
		$("<td>").addClass("file_del").append(
			$("<button>", {type: "button", "class": "delBtn", text: "삭제"})
				.on("click", function() { deleteEmployeeCertFile(index); })
		).appendTo($row);
		$tbody.append($row);
	});

	$("#employeeCertDropZone").toggle(employeeCertFiles.length === 0);
	$("#employeeCertFileTable").toggle(employeeCertFiles.length > 0);
}

function deleteEmployeeCertFile(index) {
	employeeCertFiles.splice(index, 1);
	drawEmployeeCertFiles();
}

function resetEmployeeCertFiles() {
	employeeCertFiles = [];
	$("#employeeCertFileInput").val("");
	drawEmployeeCertFiles();
}

function formatEmployeeCertFileSize(size) {
	return size >= 1024 * 1024
		? (size / (1024 * 1024)).toFixed(2) + " MB"
		: (size / 1024).toFixed(2) + " KB";
}

function submitEmployeeCertApplication() {
	var employeeCnt = $.trim($("#employeeCnt").val());
	if (!/^\d+$/.test(employeeCnt) || Number(employeeCnt) < 1) {
		alert("종사자 수를 1명 이상 입력해 주세요.");
		$("#employeeCnt").focus();
		return;
	}
	if (employeeCertFiles.length === 0) {
		alert("종사자 수를 확인할 수 있는 증빙서류를 첨부해 주세요.");
		return;
	}
	if (!$("#agreeEmployeeEvidence").is(":checked")) {
		alert("증빙서류 수집·이용에 동의해 주세요.");
		return;
	}

	var formData = new FormData();
	formData.append("applyCnt", employeeCnt);
	formData.append("agreeYn", "Y");
	$.each(employeeCertFiles, function(index, file) {
		formData.append("file" + index, file);
	});

	$("#employeeCertApplyButton").prop("disabled", true);
	$.ajax({
		url: "/web/user/send-number/employee-cert/apply.do",
		type: "POST",
		data: formData,
		dataType: "json",
		processData: false,
		contentType: false,
		cache: false,
		success: function(response) {
			if (!response || !response.success) {
				alert(response && response.message ? response.message : "종사자 수 인증 신청에 실패했습니다.");
				return;
			}
			alert(response.message || "종사자 수 인증을 신청했습니다.");
			$("#employeeCertPopupClose").trigger("click");
			resetEmployeeCertFiles();
			checkNumberLineCount();
		},
		error: function() {
			alert("종사자 수 인증 신청 중 오류가 발생했습니다.");
		},
		complete: function() {
			$("#employeeCertApplyButton").prop("disabled", false);
		}
	});
}
</script>

<!-- 종사자 수 등록/변경/재신청 -->
<div class="tooltip-wrap">
	<div class="popup-com worker_count_popup" tabindex="0"
		data-tooltip-con="worker_count_popup" data-focus="worker_count_popup"
		data-focus-prev="worker_count_popup-close">
		<div class="popup_heading">
			<p id="employeeCertPopupTitle">종사자 수 등록</p>
			<button type="button" class="tooltip-close" id="employeeCertPopupClose" data-focus="worker_count_popup-close">
				<img src="/publish/images/content/layerPopup_close.png" alt="팝업 닫기">
			</button>
		</div>

		<div class="layer_in">
			<div class="badge_wrap red" id="employeeCertRejectReason" style="display:none;">
				<div class="badge red">
					<i class="icon error"></i>이전 신청이 반려되었습니다. 아래 사유를 확인하고 서류를 다시 첨부해 주세요.
				</div>
				<div class="white_box" id="employeeCertRejectReasonText"></div>
			</div>

			<div class="titBox">
				<p>- 유선 발신번호는 <span class="fwMd c_222">종사자 수 인증</span> 후 인증된 종사자 수만큼 등록할 수 있습니다.</p>
				<p>- 이미 등록된 발신번호는 종사자 수와 관계없이 계속 사용할 수 있습니다.</p>
				<p>- 사업장 전체 인원을 확인할 수 있는 자료(4대보험 사업장 가입자 명부, 임직원 명부, 조직도 등)를 첨부해 주세요.</p>
				<p>- <span class="fwBold c_e40000">주민등록번호 · 주소 · 급여 등 불필요한 개인정보는 마스킹 처리 후 제출해 주세요.</span></p>
			</div>

			<form id="employeeCertForm" enctype="multipart/form-data" onsubmit="return false;">
				<input type="hidden" id="employeeCertMode" name="certMode">
				<table class="layer_tType1">
					<colgroup>
						<col style="width:155px;">
						<col style="width:auto;">
					</colgroup>
					<tbody>
						<tr>
							<th>사업자등록번호</th>
							<td>
								<input type="text" class="readonly" readonly
									value="<c:out value='${fn:substring(userInfo.bizNo, 0, 3)}'/>-<c:out value='${fn:substring(userInfo.bizNo, 3, 5)}'/>-<c:out value='${fn:substring(userInfo.bizNo, 5, 10)}'/>">
							</td>
						</tr>
						<tr>
							<th><label for="employeeCnt">종사자 수</label></th>
							<td>
								<div class="form_wrap">
									<input type="number" class="worker_number" id="employeeCnt" name="employeeCnt"
										min="1" step="1" placeholder="종사자 수 입력">명
								</div>
							</td>
						</tr>
						<tr>
							<th>증빙서류</th>
							<td>
								<div class="btn_area right">
									<button type="button" class="btnType btnType9" onclick="$('#employeeCertFileInput').click();">파일첨부</button>
									<input type="file" id="employeeCertFileInput" multiple
										accept=".pdf,.png,.jpg,.jpeg" style="display:none;">
								</div>

								<div class="tb_wrap file_upload_box no_img_box fileWrap employee-cert-drop-zone" id="employeeCertDropZone">
									<table class="tType4">
										<tbody>
											<tr>
												<td>
													<div class="file_add">
														<p><img src="/publish/images/content/file_add.png" alt="">파일을 여기에 끌어다 놓으세요</p>
													</div>
												</td>
											</tr>
										</tbody>
									</table>
								</div>

								<div class="tb_wrap fileWrap" id="employeeCertFileTable" style="display:none;">
									<table class="tType4">
										<colgroup>
											<col style="width:auto;">
											<col style="width:15%;">
											<col style="width:26%;">
											<col style="width:8%;">
										</colgroup>
										<thead>
											<tr><th>파일명</th><th>파일크기</th><th>등록일시</th><th>삭제</th></tr>
										</thead>
										<tbody id="employeeCertFileList"></tbody>
									</table>
								</div>

								<label for="agreeEmployeeEvidence" class="form_row">
									<input type="checkbox" id="agreeEmployeeEvidence">
									증빙서류 수집·이용에 동의합니다.
								</label>
							</td>
						</tr>
					</tbody>
				</table>
			</form>

			<div class="popup_btn">
				<button type="button" class="btnType btnType2" id="employeeCertApplyButton" onclick="submitEmployeeCertApplication();">신청하기</button>
				<button type="button" class="btnType fill_gray tooltip-close">닫기</button>
			</div>
		</div>
	</div>
</div>
<!-- // 종사자 수 등록/변경/재신청 -->
