
/* ##############################################################
	설  명 : [Modal]휴무관리 등록 팝업
	작성일 : 2023. 01. 19.
	작성자 : NTsoft
	수정일 	        수정자 	 수정내용
	-------         -------- ---------------------------
	2023. 01. 19.	NTsoft 	 최초 생성
*/
let holidayManagementInsertModal = {
	callback : null,
	reqParam : null,
	dataList : null,
	/* 모달 초기화 작업 */
	init : function () {
		$('#holidayManagementInsertModal').remove();
		$('body').append( this.HtmlTemplate);
		//그리드 이벤트
		this.setEvent();
	},
	/* 그리드 이벤트 설정 */
	setEvent:function() {
		let modalMemberId = $('#holidayManagementInsertModal #modalMemberId');
		modalMemberId.on("click", function(){
			let reqParam = {};
			memberSearchModal.popup(function (obj) {
				modalMemberId.data('modalMemberId',obj.selectMemberId);
				modalMemberId.val(obj.selectMemberName);
			}, reqParam);
		});
		$('#holidayManagementInsertModal .btnCancle').on("click", function(){
			holidayManagementInsertModal.close();
		});
		
		$('#holidayManagementInsertModal .btnSave').on("click", function(){
			holidayManagementInsertModal.save("I");
		});
		
		// 날짜 datepicker
		fn_insertModal_searchDatePicker("#holidayManagementInsertModal #modalStartDate", "#holidayManagementInsertModal #modalEndDate");
	},
	/* 데이터 선택 */
	setSelect:function(selectNumber) {
		let checkedData = dataList[selectNumber];
		if(dataList==null||checkedData==undefined){
			return ;
		}
		
		if( holidayManagementInsertModal.callback )  {
			holidayManagementInsertModal.callback(checkedData);
		}
		holidayManagementInsertModal.close();
	},
	//저장
	save:function(state) {
		let muMemberId     = $("#holidayManagementInsertModal #modalMemberId").data('modalMemberId');
		let startDate      = $("#holidayManagementInsertModal #modalStartDate").val();
		let endDate        = $("#holidayManagementInsertModal #modalEndDate").val();
		let etc            = $("#holidayManagementInsertModal #modalEtc").val();
		
		if(true != fn_emptyCheck(muMemberId)){
			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;
			}
		}
		
		modalEvent.info("등록", "휴무관리 정보를 등록하시겠습니까?", function(){
			let formData = new FormData();
			formData.append("menuClass", menuClass);
			formData.append("muMemberId", muMemberId);
			formData.append("startDate", startDate);
			formData.append("endDate", endDate);
			formData.append("etc", etc);
	
			$.ajax({
				url: encodeURI('/webholidaymanagement/insertHolidayManagement.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( holidayManagementInsertModal.callback )  {
								holidayManagementInsertModal.callback();
							}
							holidayManagementInsertModal.close();
						});
					}
					else{
						modalEvent.danger("등록 오류", data.msgDesc);
					}
				},
				error : function(xhr, status, error) {
					modalEvent.danger("등록 오류", "등록 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
				},
				beforeSend:function(){
					
				},
				complete:function(){
					
				}
			});
		});
	},
	/*
	 * 팝업
	 * callback : 콜백함수, reqParam: 팝업파라미터
	 */
	popup:function(callback, reqParam) {
		// 초기화 후 열기
		holidayManagementInsertModal.init();
		
		//콜백함수 지정.
		holidayManagementInsertModal.callback = callback;
		holidayManagementInsertModal.reqParam = reqParam;
		holidayManagementInsertModal.dataList = null;
		
		setTimeout(function(){
			$('#holidayManagementInsertModal').modal('show')
		}, 200);
	},
	/*
	 * 팝업 닫기
	 */
	close:function() {
		$('#holidayManagementInsertModal').modal('hide');

		setTimeout(function(){
			$('#holidayManagementInsertModal').remove();
		},500);
	},
	HtmlTemplate : `
	<div id="holidayManagementInsertModal" class="modal holiday_modal fade" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="">
		<div class="modal-dialog">
			<div class="modal-content">
				<div class="modal-header">
					<p class="title">휴무 등록</p>
				</div>
	
				<div class="modal-body">
					<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" alt="calendar"/>
									<input type="date" class="date_picker startDate" id="modalStartDate">
								</div>

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

								<div class="date_box last">
									<img src="/image/web/calendar.svg" alt="calendar"/>
									<input type="date" class="date_picker endDate" id="modalEndDate">
								</div>
							</div>
							<p class="holiday_sum"><span class="holiday_sum_number">0</span> 일</p>
						</div>

						<div class="textarea_box">
							<label>메모</label>
							<textarea id="modalEtc" placeholder="메모를 입력해주세요."></textarea>
						</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 btnSave">등록</button>
					</div>
				</div>
			</div>
		</div>
	</div>
    `
};

/****************************************************************************
* datePicker 
****************************************************************************/
function fn_insertModal_searchDatePicker(startId, endId){
	$(startId).datetimepicker({
		allowInputToggle: true,
		format: 'YYYY-MM-DD'
	});
	
	$(endId).datetimepicker({
		allowInputToggle: true,
		useCurrent: false, //Important! See issue #1075
		format: 'YYYY-MM-DD'
	});
	
	/*$(endId).data("DateTimePicker").minDate(fn_getToDate());*/
	
	//$(endId).data("DateTimePicker").maxDate(fn_getToDate());
	//$(startId).data("DateTimePicker").maxDate(fn_getToDate());
	
	$(startId).on("dp.change", function (e) {
		$(endId).data("DateTimePicker").minDate(e.date);
		
		if($(endId).data("DateTimePicker").date() < e.date){
			$(endId).data("DateTimePicker").date(e.date);   
		}
		
		fn_insertModal_getDateDiff(startId);
	});
	
	
	$(endId).on("dp.change", function (e) {
		fn_insertModal_getDateDiff(startId);
	});
}

/****************************************************************************
* datePicker 일수구하기
****************************************************************************/
function fn_insertModal_getDateDiff(target){
	const startVal = $(target).closest(".input_box").find(".startDate").val();
	const endVal   = $(target).closest(".input_box").find(".endDate").val();
	const date1 = new Date(startVal);
	const date2 = new Date(endVal);
	
	const diffDate = date1.getTime() - date2.getTime();
	
	const days = Math.abs(diffDate / (1000 * 60 * 60 * 24)); // 밀리세컨 * 초 * 분 * 시 = 일
	$(target).closest(".input_box").find(".holiday_sum_number").text(days+1);
}