
/* ##############################################################
	설  명 : [Modal]근태관리 - 연차 상세/수정 팝업
	작성일 : 2023. 01. 19.
	작성자 : NTsoft
	수정일 	        수정자 	 수정내용
	-------         -------- ---------------------------
	2023. 01. 19.	NTsoft 	 최초 생성
*/
let attendanceVacationManagerUpdateModal = {
	callback : null,
	reqParam : null,
	dataList : null,
	/* 모달 초기화 작업 */
	init : function () {
		$('#attendanceVacationManagerUpdateModal').remove();
		$('body').append( this.HtmlTemplate);
		//그리드 이벤트
		this.setEvent();
	},
	/* 그리드 이벤트 설정 */
	setEvent:function() {
		$('#attendanceVacationManagerUpdateModal .btnCancle').on("click", function(){
			attendanceVacationManagerUpdateModal.close();
		});
		
		$('#attendanceVacationManagerUpdateModal .btnSave').on("click", function(){
			attendanceVacationManagerUpdateModal.save("I");
		});
		

		// 날짜 datepicker
		fn_updateModal_searchAttendanceVacationManagerDatePicker("#attendanceVacationManagerUpdateModal #modalStartDate", "#attendanceVacationManagerUpdateModal #modalEndDate");
	},
	/* 데이터 선택 */
	setSelect:function(selectNumber) {
		let checkedData = dataList[selectNumber];
		if(dataList==null||checkedData==undefined){
			return ;
		}
		
		if( attendanceVacationManagerUpdateModal.callback )  {
			attendanceVacationManagerUpdateModal.callback(checkedData);
		}
		attendanceVacationManagerUpdateModal.close();
	},
	// 상세 조회
	search:function(state) {
		let muAttendanceId  = attendanceVacationManagerUpdateModal.reqParam.muAttendanceId;
		let muMemberId      = attendanceVacationManagerUpdateModal.reqParam.muMemberId;
		
		if(true != fn_emptyCheck(muAttendanceId) && true != fn_emptyCheck(muAttendanceId2)){
			modalEvent.warning("수정", "근태 정보가 없습니다.");	
			return;
		}
		
		if(true != fn_emptyCheck(muMemberId)){
			modalEvent.warning("수정", "직원 정보가 없습니다.");	
			return;
		}
		
		let formData = new FormData();
		formData.append("menuClass", menuClass);
		formData.append("muAttendanceId", muAttendanceId);
		formData.append("muMemberId", muMemberId);

		$.ajax({
			url: encodeURI('/webattendance/selectAttendanceVacation.do'),
			data: formData,
			dataType: "json",
			processData: false,
			contentType: false,
			type: 'POST',
			async: true,
			success: function(data){
				if('0'==data.msgCode) {
					if (0 < data.rows.length) {
						$("#attendanceVacationManagerUpdateModal #modalMemberId").val(data.rows[0].muMemberId);
						$("#attendanceVacationManagerUpdateModal #modalMemberNameId").text(data.rows[0].memberName + '(' + data.rows[0].loginId + ')');


						$('#attendanceVacationManagerUpdateModal #li_' + data.rows[0].muVacationId).click();

						$("#attendanceVacationManagerUpdateModal #modalStartDate").val(data.rows[0].startDate).trigger("change");
						$("#attendanceVacationManagerUpdateModal #modalEndDate").val(data.rows[0].endDate).trigger("change");

						if ("D" != data.rows[0].attendanceType) {
							$("#attendanceVacationManagerUpdateModal #modalStartTime").siblings("button").text(data.rows[0].startTime);
							$("#attendanceVacationManagerUpdateModal #modalStartTime").val(data.rows[0].startTime);
							$("#attendanceVacationManagerUpdateModal #modalEndTime").siblings("button").text(data.rows[0].endTime);
							$("#attendanceVacationManagerUpdateModal #modalEndTime").val(data.rows[0].endTime);
						}

						$("#attendanceVacationManagerUpdateModal #modalDays").text(data.rows[0].days);
						$("#attendanceVacationManagerUpdateModal #modalEtc").val(data.rows[0].etc);
					}
				}
				else{
					modalEvent.danger("조회 오류", data.msgDesc);
				}
			},
			error : function(xhr, status, error) {
				modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
			},
			beforeSend:function(){
				
			},
			complete:function(){
				
			}
		});
	},
	//저장
	save:function(state) {
		let muAttendanceId  = attendanceVacationManagerUpdateModal.reqParam.muAttendanceId;
		let muMemberId      = $("#attendanceVacationManagerUpdateModal #modalMemberId").val();
		let muVacationId    = $("#attendanceVacationManagerUpdateModal #modalVacationId").val();
		let startDate       = $("#attendanceVacationManagerUpdateModal #modalStartDate").val();
		let endDate         = $("#attendanceVacationManagerUpdateModal #modalEndDate").val();
		let startTime       = $("#attendanceVacationManagerUpdateModal #modalStartTime").val();
		let endTime         = $("#attendanceVacationManagerUpdateModal #modalEndTime").val();
		let etc             = $("#attendanceVacationManagerUpdateModal #modalEtc").val();
		let timeYn          = $("#attendanceVacationManagerUpdateModal .toggle_box").is(':visible');
		
		if(true != fn_emptyCheck(muAttendanceId)){
			modalEvent.warning("수정", "근태 정보가 없습니다.");	
			return;
		}
		
		if(true != fn_emptyCheck(muMemberId)){
			modalEvent.warning("수정", "직원 정보가 없습니다.");	
			return;
		}
		
		if(true != fn_emptyCheck(muVacationId)){
			modalEvent.warning("수정", "연차사용단위 정보가 없습니다.");
			return;
		}
		
		if(true != fn_emptyCheck(startDate)){
			modalEvent.warning("수정", "시작날짜 정보가 없습니다.");
			return;
		}

		if(true != fn_emptyCheck(endDate)){
			modalEvent.warning("수정", "종료날짜 정보가 없습니다.");
			return;
		}
		
		if(timeYn){
			if(true != fn_emptyCheck(startTime)){
				modalEvent.warning("수정", "시작시간 정보가 없습니다.");
				return;
			}
	
			if(true != fn_emptyCheck(endTime)){
				modalEvent.warning("수정", "종료시간 정보가 없습니다.");
				return;
			}
		}
		else{
			startTime = '';
			endTime = '';
		}
		
		modalEvent.info("수정", "근태관리의 연차 정보를 수정하시겠습니까?", function(){
			let formData = new FormData();
			formData.append("menuClass", menuClass);
			formData.append("muAttendanceId", muAttendanceId);
			formData.append("muMemberId", muMemberId);
			formData.append("muVacationId", muVacationId);
			formData.append("startDate", startDate);
			formData.append("endDate", endDate);
			formData.append("startTime", startTime);
			formData.append("endTime", endTime);
			formData.append("etc", etc);
	
			$.ajax({
				url: encodeURI('/webattendance/updateAttendanceVacation.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( attendanceVacationManagerUpdateModal.callback )  {
								attendanceVacationManagerUpdateModal.callback();
							}
							attendanceVacationManagerUpdateModal.close();
						});
					}
					else{
						modalEvent.danger("수정 오류", data.msgDesc);
					}
				},
				error : function(xhr, status, error) {
					modalEvent.danger("수정 오류", "수정 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
				},
				beforeSend:function(){
					
				},
				complete:function(){
					
				}
			});
		});
	},
	/*
	 * 팝업
	 * callback : 콜백함수, reqParam: 팝업파라미터
	 */
	popup:function(callback, reqParam) {
		// 초기화 후 열기
		attendanceVacationManagerUpdateModal.init();
		
		//콜백함수 지정.
		attendanceVacationManagerUpdateModal.callback = callback;
		attendanceVacationManagerUpdateModal.reqParam = reqParam;
		attendanceVacationManagerUpdateModal.dataList = null;
		
		
		// 연차유형 콤보데이타 설정 조회
		fn_updateModal_setVacationCombo();
		
		// 기본 셋팅
		fn_setTimeValue("updateVacationStartTime", "00:00");
		fn_setTimeValue("updateVacationEndTime", "00:00");
		
		setTimeout(function(){
			$('#attendanceVacationManagerUpdateModal').modal('show')
		}, 200);
		
		attendanceVacationManagerUpdateModal.search();
	},
	/*
	 * 팝업 닫기
	 */
	close:function() {
		$('#attendanceVacationManagerUpdateModal').modal('hide');

		setTimeout(function(){
			$('#attendanceVacationManagerUpdateModal').remove();
		},500);
	},
	HtmlTemplate : `
	<div id="attendanceVacationManagerUpdateModal" class="modal hyuga_info_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">
						<ul class="info_list">
							<li>
								<label>직원</label>
								<p id="modalMemberNameId"></p>
								<input type="hidden" id="modalMemberId">
							</li>
							<li>
								<div class="input_box three_wrap">
									<label>연차 사용단위</label>
		
									<div class="select_box dropdown">
										<button class="label" class="label dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">연차 사용단위</button>
										<input type="hidden" id="modalVacationId"></input>
										
										<ul class="select_option_list dropdown-menu"></ul>
									</div>
		
									<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>
								</div>
							</li>
							<li class="toggle_box">
								<div class="select_time_list_box">
									<div class="select_list first">
										<div class="select_box dropdown">
											<button class="label" class="label dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">00:00</button>
											<input type="hidden" id="modalStartTime">
											
											<ul class="select_option_list dropdown-menu" id="updateVacationStartTime"></ul>
										</div><!--select_box-->
									</div>
	
									<span class="slash">~</span>
										
									<div class="select_list">
										<div class="select_box">
											<button class="label" class="label dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">00:00</button>
											<input type="hidden" id="modalEndTime">
											
											<ul class="select_option_list dropdown-menu" id="updateVacationEndTime"></ul>
										</div><!--select_box-->
									</div>
								</div>
							</li>
							<li class="hide_box">
								<label>사용 일 수</label>
								<p id="modalDays">0</p>
							</li>
							<li>
								<div class="input_box">
									<label>메모</label>
	
									<div class="textarea_box">
										<textarea id="modalEtc" placeholder=""></textarea>
									</div>
								</div>
							</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>
    `
};

/****************************************************************************
* 연차유형 콤보데이타 설정
****************************************************************************/
function fn_updateModal_setVacationCombo(){
	// 대상
	const target = $("#attendanceVacationManagerUpdateModal #modalVacationId").siblings("ul.select_option_list");

	// 데이터 조회
	let comboData = fn_selectListVacationOption();
	
	// 조회 데이터 셋팅
	let comboHTML = '';
	for(let i = 0; i < comboData.length; i++){
		let muVacationId     = comboData[i].muVacationId;
		let vacationName     = comboData[i].vacationName;
		let hourType         = comboData[i].hourType;
		
		comboHTML += '<li id="li_'+muVacationId+'" class="option_list_item">';
		comboHTML += '	<input type="hidden" name="MODAL_HOUR_TYPE" value="'+hourType+'">';
		comboHTML += '	<span>'+vacationName+'</span>';
		comboHTML += '</li>';
	}
	target.empty().html(comboHTML).trigger("create");

	// 콤보 이벤트
	target.find("li.option_list_item").click(function () {
		// 1. 선택값 셋팅
		let selectIdArr = $(this).prop("id").split('_');
		let selectId    = selectIdArr[1];
		let selectName  = $(this).text();
		
		$(this).parent().siblings("button").text(selectName);
		$(this).parent().siblings("input").val(selectId);
		
		let hourType = $(this).find("input[name='MODAL_HOUR_TYPE']").val();
		if('A'==hourType){
			// 연차일경우
			$("#attendanceVacationManagerUpdateModal .toggle_box").hide();
		}
		else{
			// 반차일경우
			$("#attendanceVacationManagerUpdateModal .toggle_box").show();
		}
	});
}

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

/****************************************************************************
* datePicker 일수구하기
****************************************************************************/
function fn_updateModal_getAttendanceVacationManagerDateDiff(target){
	const startVal = $(target).closest(".calendar_box").find(".startDate").val();
	const endVal   = $(target).closest(".calendar_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)); // 밀리세컨 * 초 * 분 * 시 = 일
	
	$("#attendanceVacationManagerUpdateModal #modalDays").text(days+1);
}

