
/* ##############################################################
	설  명 : [Modal]휴무관리 상세/수정 팝업
	작성일 : 2023. 01. 19.
	작성자 : NTsoft
	수정일 	        수정자 	 수정내용
	-------         -------- ---------------------------
	2023. 01. 19.	NTsoft 	 최초 생성
*/
let holidayManagementUpdateModal = {
	callback : null,
	reqParam : null,
	dataList : null,
	/* 모달 초기화 작업 */
	init : function () {
		$('#holidayManagementUpdateModal').remove();
		$('body').append( this.HtmlTemplate);
		//그리드 이벤트
		this.setEvent();
	},
	/* 그리드 이벤트 설정 */
	setEvent:function() {
		$('#holidayManagementUpdateModal .btnCancle').on("click", function(){
			holidayManagementUpdateModal.close();
		});
		
		$('#holidayManagementUpdateModal .btnSave').on("click", function(){
			holidayManagementUpdateModal.save("I");
		});
		
		// 휴무 취소
		$('#holidayManagementUpdateModal #btnModalUpdateHolidayManagementCancelEtc').on("click", function(){
			fn_updateModal_updateHolidayManagementCancelEtcPopup();
		});
		
		// 날짜 datepicker
		fn_updateModal_searchDatePicker("#holidayManagementUpdateModal #modalStartDate", "#holidayManagementUpdateModal #modalEndDate");
	},
	/* 데이터 선택 */
	setSelect:function(selectNumber) {
		let checkedData = dataList[selectNumber];
		if(dataList==null||checkedData==undefined){
			return ;
		}
		
		if( holidayManagementUpdateModal.callback )  {
			holidayManagementUpdateModal.callback(checkedData);
		}
		holidayManagementUpdateModal.close();
	},
	// 상세 조회
	search:function(state) {
		let muAttendanceId = holidayManagementUpdateModal.reqParam.muAttendanceId;
		
		if(true != fn_emptyCheck(muAttendanceId)){
			modalEvent.warning("등록", "휴무관리 정보가 없습니다.");	
			return;
		}
		
		let formData = new FormData();
		formData.append("menuClass", menuClass);
		formData.append("muAttendanceId", muAttendanceId);

		$.ajax({
			url: encodeURI('/webholidaymanagement/selectHolidayManagement.do'),
			data: formData,
			dataType: "json",
			processData: false,
			contentType: false,
			type: 'POST',
			async: true,
			success: function(data){
				if('0'==data.msgCode){
					$("#holidayManagementUpdateModal #modalMemberNameId").text(data.rows[0].memberName+'('+data.rows[0].loginId+')');
					$("#holidayManagementUpdateModal #modalGroupName").text(data.rows[0].groupName);
					$("#holidayManagementUpdateModal #modalDutyName").text(data.rows[0].dutyName);
					$("#holidayManagementUpdateModal #modalStartDate").val(data.rows[0].startDate).trigger("change");
					$("#holidayManagementUpdateModal #modalEndDate").val(data.rows[0].endDate).trigger("change");
					$("#holidayManagementUpdateModal #modalEtc").val(data.rows[0].etc);
					$("#holidayManagementUpdateModal #modalWriteDate").text(data.rows[0].writeDate+','+data.rows[0].writeTime);
					$("#holidayManagementUpdateModal #modalWriteName").text(data.rows[0].writeMemberName);
				}
				else{
					modalEvent.danger("조회 오류", data.msgDesc);
				}
			},
			error : function(xhr, status, error) {
				modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
			},
			beforeSend:function(){
				
			},
			complete:function(){
				
			}
		});
	},
	//저장
	save:function(state) {
		let muAttendanceId = holidayManagementUpdateModal.reqParam.muAttendanceId;
		let startDate      = $("#holidayManagementUpdateModal #modalStartDate").val();
		let endDate        = $("#holidayManagementUpdateModal #modalEndDate").val();
		let etc            = $("#holidayManagementUpdateModal #modalEtc").val();
		
		
		if(true != fn_emptyCheck(muAttendanceId)){
			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("muAttendanceId", muAttendanceId);
			formData.append("startDate", startDate);
			formData.append("endDate", endDate);
			formData.append("etc", etc);
	
			$.ajax({
				url: encodeURI('/webholidaymanagement/updateHolidayManagement.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( holidayManagementUpdateModal.callback )  {
								holidayManagementUpdateModal.callback();
							}
							holidayManagementUpdateModal.close();
						});
					}
					else{
						modalEvent.danger("수정 오류", data.msgDesc);
					}
				},
				error : function(xhr, status, error) {
					modalEvent.danger("수정 오류", "등록 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
				},
				beforeSend:function(){
					
				},
				complete:function(){
					
				}
			});
		});
	},
	/*
	 * 팝업
	 * callback : 콜백함수, reqParam: 팝업파라미터
	 */
	popup:function(callback, reqParam) {
		// 초기화 후 열기
		holidayManagementUpdateModal.init();
		
		//콜백함수 지정.
		holidayManagementUpdateModal.callback = callback;
		holidayManagementUpdateModal.reqParam = reqParam;
		holidayManagementUpdateModal.dataList = null;
		
		setTimeout(function(){
			$('#holidayManagementUpdateModal').modal('show')
		}, 200);
		
		holidayManagementUpdateModal.search();
	},
	/*
	 * 팝업 닫기
	 */
	close:function() {
		$('#holidayManagementUpdateModal').modal('hide');

		setTimeout(function(){
			$('#holidayManagementUpdateModal').remove();
		},500);
	},
	HtmlTemplate : `
	<div id="holidayManagementUpdateModal" class="modal cencell_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>
					<button id="btnModalUpdateHolidayManagementCancelEtc" class="cencell_btn">휴무 취소</button>
				</div>
	
				<div class="modal-body">
					<div class="form_box">
						<ul class="info_list">
							<li>
								<label>이름(ID)</label>
								<p id="modalMemberNameId"></p>
							</li>
							<li>
								<label>조직</label>
								<p id="modalGroupName"></p>
							</li>
							<li class="different">
								<label>직무</label>
								<p id="modalDutyName"></p>
							</li>
							<li>
								<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="total"><span class="holiday_sum_number">0</span> 일</p>
								</div>
							</li>
							<li>
								<div class="input_box">
									<label>메모</label>
	
									<div class="textarea_box">
										<textarea id="modalEtc" placeholder="메모를 입력해주세요."></textarea>
									</div>
								</div>
							</li>
							<li>
								<label>등록일/담당자</label>
								<p>
									<span id="modalWriteDate"></span>
									<span id="modalWriteName"></span>
								</p>
							</li>
						</ul>
					</div>
				</div>

				<div class="modal-footer">
					<div class="btn_box">
						<button type="button" class="cancel_btn btnCancle">취소</button>
						<button type="button" class="seve_bth btnSave">수정</button>
					</div>
				</div>
			</div>
		</div>
	</div>
    `
};

/****************************************************************************
* datePicker 
****************************************************************************/
function fn_updateModal_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_updateModal_getDateDiff(startId);
	});
	
	
	$(endId).on("dp.change", function (e) {
		fn_updateModal_getDateDiff(startId);
	});
}

/****************************************************************************
* datePicker 일수구하기
****************************************************************************/
function fn_updateModal_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);
}

function fn_updateModal_updateHolidayManagementCancelEtcPopup(){
	let reqParam =  {
		"muAttendanceId" : holidayManagementUpdateModal.reqParam.muAttendanceId
	};
	
	if("Y"==updateUseYn){
		// 수정가능
		holidayManagementCancelEtcModal.popup(function(obj, reqParam) {
			if(holidayManagementUpdateModal.callback){
				holidayManagementUpdateModal.callback();
			}else{
				fn_holidayManagementOk();
			}
			holidayManagementUpdateModal.close();
		}, reqParam);
	}
	else{
		modalEvent.warning("수정", "수정 권한이 없습니다.");	
		return;
	}
}