
/* ##############################################################
	설  명 : [Modal]연차관리 등록 팝업
	작성일 : 2023. 01. 19.
	작성자 : NTsoft
	수정일 	        수정자 	 수정내용
	-------         -------- ---------------------------
	2023. 01. 19.	NTsoft 	 최초 생성
*/
let vacationManagementInsertModal = {
	callback : null,
	reqParam : null,
	dataList : null,
	/* 모달 초기화 작업 */
	init : function () {
		$('#vacationManagementInsertModal').remove();
		$('body').append( this.HtmlTemplate);
		//그리드 이벤트
		this.setEvent();
	},
	/* 그리드 이벤트 설정 */
	setEvent:function() {
		let modalMemberId = $('#vacationManagementInsertModal #modalMemberId')
		modalMemberId.on("click", function(){
				let reqParam = {};
			memberSearchModal.popup(function (obj) {
				modalMemberId.data('modalMemberId',obj.selectMemberId);
				modalMemberId.val(obj.selectMemberName);
				}, reqParam);
		});
		$('#vacationManagementInsertModal .btnCancle').on("click", function(){
			vacationManagementInsertModal.close();
		});

        $('#vacationManagementInsertModal #modalDays').on('input', function() {
            // 입력된 키가 숫자가 아닌 경우 입력을 막음
            this.value = this.value.replace(/\D/g, '');
        });

		$('#vacationManagementInsertModal .btnFileSave').on("click", function(){
			let currentTabMenu = $('#vacationManagementInsertModal .nav-tabs .active a p').text();

			if('연차 발행'===currentTabMenu) {
				vacationManagementInsertModal.save("I");
			}
			else if('연차 일괄등록'===currentTabMenu) {
				vacationManagementInsertModal.saveUpload("I");
			}
		});

		$('#vacationManagementInsertModal #btn_downloadExcel').on("click", function(){
			let url = encodeURI("/webvacationmanagement/downloadVacationManagementInsertExcel.do?fileName=Vacation_Upload_Sample.xlsx");

			let newForm = $("<form><form/>");
			newForm.attr("name", "excelForm");
			newForm.attr("method", "POST");
			newForm.attr("target", "_blank");
			newForm.attr("action", url);
			newForm.appendTo('body');
			newForm.submit();
		});
		$('#vacationManagementInsertModal #file').on("change", handleFileSelect);

		// 날짜 datepicker
		$("#vacationManagementInsertModal #modalYear").datetimepicker({
			format: 'YYYY',
			viewMode: "years", 
			defaultDate: moment().format('YYYY')
		});
		
		fn_searchDatePicker("#vacationManagementInsertModal #modalStartDate", "#vacationManagementInsertModal #modalEndDate");
	},
	/* 데이터 선택 */
	setSelect:function(selectNumber) {
		let checkedData = dataList[selectNumber];
		if(dataList==null||checkedData==undefined){
			return ;
		}
		
		if( vacationManagementInsertModal.callback )  {
			vacationManagementInsertModal.callback(checkedData);
		}
		vacationManagementInsertModal.close();
	},
	//저장
	save:function(state) {
		let formData = new FormData();
		let muMemberId = $("#vacationManagementInsertModal #modalMemberId").data('modalMemberId');
		let year = $("#vacationManagementInsertModal #modalYear").val();
		let days = $("#vacationManagementInsertModal #modalDays").val();
		let startDate = $("#vacationManagementInsertModal #modalStartDate").val();
		let endDate = $("#vacationManagementInsertModal #modalEndDate").val();
		let etc = $("#vacationManagementInsertModal #modalEtc").val();

		if (true != fn_emptyCheck(muMemberId)) {
			modalEvent.warning("등록", "직원 정보가 없습니다.");
			return;
		}

		if (true != fn_emptyCheck(year)) {
			modalEvent.warning("등록", "발행연도 정보가 없습니다.");
			return;
		}

		if (true != fn_emptyCheck(days)) {
			modalEvent.warning("등록", "발행일수 정보가 없습니다.");
			return;
		}

		if (true != fn_emptyCheck(startDate)) {
			modalEvent.warning("등록", "사용기한 시작시간 정보가 없습니다.");
			return;
		}

		if (true != fn_emptyCheck(endDate)) {
			modalEvent.warning("등록", "사용기한 종료시간 정보가 없습니다.");
			return;
		} else {
			if (startDate > endDate) {
				modalEvent.warning("등록", "사용기한을 다시 확인하십시오.");
				return;
			}
		}
		formData.append("menuClass", menuClass);
		formData.append("muMemberId", muMemberId);
		formData.append("year", year);
		formData.append("days", days);
		formData.append("startDate", startDate);
		formData.append("endDate", endDate);
		formData.append("etc", etc);

		modalEvent.info("등록", "연차관리 정보를 등록하시겠습니까?", function(){
			$.ajax({
				url: encodeURI('/webvacationmanagement/insertVacationManagement.do'),
				data: formData,
				dataType: "json",
				processData: false,
				contentType: false,
				type: 'POST',
				async: true,
				success: function(data){
					if('0'==data.msgCode){
						modalEvent.success("등록 성공", data.msgDesc, function(){
							if( vacationManagementInsertModal.callback )  {
								vacationManagementInsertModal.callback();
							}
							vacationManagementInsertModal.close();
						});
					}
					else{
						modalEvent.danger("등록 오류", data.msgDesc);
					}
				},
				error : function(xhr, status, error) {
					modalEvent.danger("등록 오류", "등록 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
				},
				beforeSend:function(){

				},
				complete:function(){

				}
			});
		});
	},
	saveUpload:function(state) {
		let dataFile = $("#vacationManagementInsertModal #file")[0].files[0];

		if(!dataFile){
			modalEvent.warning("입력 오류", "엑셀파일 정보가 없습니다. 파일을 선택하세요.");
			return;
		}

		modalEvent.info("등록", "연차 일괄 등록하시겠습니까?", function(){
			let formData = new FormData();
			formData.append("file", dataFile);
			formData.append("menuClass", menuClass);

			$.ajax({
				url: encodeURI('/webvacationmanagement/insertVacationManagementExcel.do'),
				data: formData,
				enctype: 'multipart/form-data',
				dataType: "json",
				processData: false,
				contentType: false,
				cache:false,
				type: 'POST',
				async: true,
				success: function(data){
					if('0'==data.msgCode){
						modalEvent.success("일괄 등록 성공", data.msgDesc, function(){
							if( vacationManagementInsertModal.callback )  {
								vacationManagementInsertModal.callback();
							}
							vacationManagementInsertModal.close();
						});
					}
					else{
						modalEvent.danger("등록 오류", data.msgDesc);
					}
				},
				error : function(xhr, status, error) {
					modalEvent.danger("등록 오류", "등록 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
				},
				beforeSend:function(){

				},
				complete:function(){

				}
			});
		});
	},
	/*
	 * 팝업
	 * callback : 콜백함수, reqParam: 팝업파라미터
	 */
	popup:function(callback, reqParam) {
		// 초기화 후 열기
		vacationManagementInsertModal.init();
		
		//콜백함수 지정.
		vacationManagementInsertModal.callback = callback;
		vacationManagementInsertModal.reqParam = reqParam;
		vacationManagementInsertModal.dataList = null;

		setTimeout(function(){
			$('#vacationManagementInsertModal').modal('show')
		}, 200);

	},
	/*
	 * 팝업 닫기
	 */
	close:function() {
		$('#vacationManagementInsertModal').modal('hide');

		setTimeout(function(){
			$('#vacationManagementInsertModal').remove();
		},500);
	},
	HtmlTemplate : `
	<div id="vacationManagementInsertModal" class="modal hyuga_modal fade" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="">
		<div class="modal-dialog">
			<div class="modal-content">
				<div class="modal-header">
					<!-- Nav tabs -->
					<div class="nav_box">
						<ul class="nav nav-tabs" role="tablist">
							<li role="presentation" class="active">
								<a href="#publish" aria-controls="publish" role="tab" data-toggle="tab">
									<p>연차 발행</p>
								</a>
							</li>

							<li role="presentation">
								<a href="#registration" aria-controls="registration" role="tab" data-toggle="tab">
									<p>연차 일괄등록</p>
								</a>
							</li>
						</ul>
					</div>
				</div>

				<div class="modal-body">
					<div class="tab-content">
						<div role="tabpanel" class="tab-pane active" id="publish">
							<div class="form_box">
								<div class="input_box">
									<label>직원</label>

									<div class="search_box">
										<img src="/image/web/search_G.svg" alt="search"/>
										<input type="text" id="modalMemberId" placeholder="직원 검색" readonly>
									</div>
								</div>

								<div class="input_box">
									<label>발행연도</label>
									<div class="calendar_box">
										<div class="date_box">
											<img src="/image/web/calendar.svg">
											<input type="text" class="date_picker" id="modalYear">
										</div>
									</div>
								</div>

								<div class="input_box">
									<label>발행 일수</label>
									<div class="text_box">
										<input type="text" id="modalDays" placeholder="00일" maxlength="2">
										<!--<p>00h</p>-->
									</div>
								</div>

								<div class="input_box">
									<label>사용 기한</label>

									<div class="calendar_box">
										<div class="date_box">
											<img src="/image/web/calendar.svg" alt="calendar"/>
											<input type="text" class="date_picker" id="modalStartDate">
										</div>

										<span class="slash">-</span>

										<div class="date_box last">
											<img src="/image/web/calendar.svg">
											<input type="text" class="date_picker" id="modalEndDate">
										</div>
									</div>
								</div>

								<div class="input_box">
									<label>연차 발행 메모</label>
								
									<div class="textarea_box">
										<textarea id="modalEtc" placeholder="메모를 입력해주세요."></textarea>
									</div>
								</div>
							</div>
						</div>

						<div role="tabpanel" class="tab-pane" id="registration">
							<div class="form_box">
								<div class="input_box">
									<label>파일</label>

									<div class="file_box">
										<input class="upload-name" id="fileName" placeholder="파일을 업로드해주세요.">
										<label for="file" class="file_btn"><img src="/image/web/add.svg" alt="파일찾기"></label> 
										<input type="file" id="file">
										<button id="btn_downloadExcel">양식다운로드</button>
									</div>
								</div>

								<div class="input_box last">
									<label>등록된 직원 수</label>

									<p class="reservation_total">00명</p>
								</div>

								<div class="table_box">
									<label>등록내역</label>
									<div class="table_scroll">
										<table>
											<thead>
												<tr>
													<th>직원명</th>
													<th>아이디</th>
													<th>발행연도</th>
													<th>연차 발행 수</th>
													<th>사용기한</th>
												</tr>
											</thead>
											<tbody id="registration-details">
												<tr>
													<td></td>
													<td></td>
													<td></td>
													<td></td>
													<td></td>
												</tr>
											</tbody>
										</table>
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>

				<div class="modal-footer">
					<div class="btn_box">
						<button type="button" class="cancel_btn btnCancle">취소</button>
						<button type="button" class="registration_bth btnFileSave">등록</button>
					</div>
				</div>
			</div>
		</div>
		<form id="vacationManagementForm"></form>
	</div>
    `
};


function handleFileSelect(event) {
	const file = event.target.files[0];
	if (!file) {
		return;
	}

	document.getElementById('fileName').value = file.name;

	const reader = new FileReader();
	reader.onload = function(event) {
		const data = new Uint8Array(event.target.result);
		const workbook = XLSX.read(data, { type: 'array' });
		const firstSheetName = workbook.SheetNames[0];
		const worksheet = workbook.Sheets[firstSheetName];
		const jsonSheet = XLSX.utils.sheet_to_json(worksheet, { header: 1 }); // Read with header as 1
		displayData(jsonSheet);
	};
	reader.readAsArrayBuffer(file);
}

function displayData(data) {
	const tbody = document.getElementById('registration-details');
	tbody.innerHTML = '';
	const jsonData = [];
	let errorCount = 0;

	// Check if header row exists and read from the second row
	if (data.length < 2) {
		modalEvent.warning("오류", "엑셀 파일에 데이터가 없습니다.");
		return;
	}

	// Get headers from the first row
	const headers = data[1];

	// Loop through the data starting from the second row
	for (let i = 2; i < data.length; i++) {
		const row = data[i];
		const rowData = {};

		if(0===row.length){
			continue;
		}
		// Map row data to header keys
		for (let j = 0; j < row.length; j++) {
			rowData[headers[j]] = row[j];
		}

		// Validation checks
		if (!rowData['발행연도'] ||!rowData['연차발행 수'] || !rowData['사용기한 시작일자'] || !rowData['사용기한 종료일자']) {
			errorCount++;
			continue;
		}

		// let check = checkId(rowData['로그인 아이디']);
		// console.log(check);
		// if (check) {
		// 	// Check for duplicate login IDs
		// 	if (jsonData.some(data => data.loginId === rowData['로그인 아이디'])) {
		// 		errorCount++;
		// 		continue;
		// 	}

		const tr = document.createElement('tr');

		const tdName = document.createElement('td');
		tdName.textContent = rowData['직원명'];
		const tdLoginId = document.createElement('td');
		tdLoginId.textContent = rowData['로그인 아이디'];
		const tdVacationYear = document.createElement('td');
		tdVacationYear.textContent = rowData['발행연도'];
		const tdVacationCount = document.createElement('td');
		tdVacationCount.textContent = rowData['연차발행 수'];
		const startDate = convertExcelDate(rowData['사용기한 시작일자']);
		const endDate = convertExcelDate(rowData['사용기한 종료일자']);
		const tdUsagePeriod = document.createElement('td');
		tdUsagePeriod.textContent = `${startDate} ~ ${endDate}`;

		tr.appendChild(tdName);
		tr.appendChild(tdLoginId);
		tr.appendChild(tdVacationYear);
		tr.appendChild(tdVacationCount);
		tr.appendChild(tdUsagePeriod);

		tbody.appendChild(tr);

		const indexData = {
			memberName: rowData['직원명'],
			loginId: rowData['로그인 아이디'],
			year: rowData['발행연도'],
			days: rowData['연차발행 수'],
			startDate: startDate,
			endDate: endDate,
			etc: rowData['연차발행 메모']
		};
		jsonData.push(indexData);
		// } else {
		// 	errorCount++;
		// }
	}

	console.log(jsonData);
	// $('#vacationManagementInsertModal #file').val('');
	if (errorCount > 0) {
		tbody.innerHTML = '';
		modalEvent.warning("오류", `잘못된 직원데이터 ${errorCount}건이 있습니다.`);
		return;
	}
	document.querySelector('.reservation_total').textContent = `${jsonData.length} 명`;
	vacationManagementInsertModal.dataList = jsonData;
}

function convertExcelDate(excelDate) {
	if (!excelDate || isNaN(excelDate)) {
		return excelDate;
	}
	const date = new Date((excelDate - 25569) * 86400 * 1000);
	const year = date.getFullYear();
	const month = ('0' + (date.getMonth() + 1)).slice(-2);
	const day = ('0' + date.getDate()).slice(-2);
	return `${year}-${month}-${day}`;
}
//
// function checkId(id){
// 	let formData = new FormData();
// 	formData.append("menuClass", menuClass);
// 	formData.append("loginId", id);
// 	let result = false;
// 	$.ajax({
// 		url: encodeURI('/webmember/selectMemberId.do'),
// 		data: formData,
// 		dataType: "json",
// 		processData: false,
// 		contentType: false,
// 		type: 'POST',
// 		async: false,
// 		success: function(data){
// 			if('0' === data.msgCode){
// 				if(1 === data.totalCount){
// 					result = true;
// 				} else {
// 					result = false;
// 				}
// 			} else {
// 				result = false;
// 				return false;
// 			}
// 		},
// 		error : function(xhr, status, error) {
// 			modalEvent.danger("등록 오류", "등록 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
// 		},
// 		beforeSend: function(){
// 		},
// 		complete: function(){
// 		}
// 	});
// 	return result;
// }
function getActiveTab() {
	const activeTab = document.querySelector('#vacationManagementInsertModal .nav-tabs .active a');
	if (activeTab) {
		return activeTab.getAttribute('aria-controls');
	}
	return null;
}