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

		$('#attendanceVacationManagerInsertModal .btnCancle').on("click", function(){
			attendanceVacationManagerInsertModal.close();
		});
		
		$('#attendanceVacationManagerInsertModal .btnSave').on("click", function(){
			attendanceVacationManagerInsertModal.save("I");
		});
		
		// 날짜 datepicker
		fn_searchDatePicker("#attendanceVacationManagerInsertModal #modalStartDate", "#attendanceVacationManagerInsertModal #modalEndDate");
	},
	/* 데이터 선택 */
	setSelect:function(selectNumber) {
		let checkedData = dataList[selectNumber];
		if(dataList==null||checkedData==undefined){
			return ;
		}
		
		if( attendanceVacationManagerInsertModal.callback )  {
			attendanceVacationManagerInsertModal.callback(checkedData);
		}
		attendanceVacationManagerInsertModal.close();
	},
	//저장
	save:function(state) {
		let muMemberId      = $("#attendanceVacationManagerInsertModal #modalMemberId").data('modalMemberId');
		let muVacationId    = $("#attendanceVacationManagerInsertModal #modalVacationId").val();
		let startDate       = $("#attendanceVacationManagerInsertModal #modalStartDate").val();
		let endDate         = $("#attendanceVacationManagerInsertModal #modalEndDate").val();
		let startTime       = $("#attendanceVacationManagerInsertModal #modalStartTime").val();
		let endTime         = $("#attendanceVacationManagerInsertModal #modalEndTime").val();
		let etc             = $("#attendanceVacationManagerInsertModal #modalEtc").val();
		let timeYn          = $("#attendanceVacationManagerInsertModal .toggle_box").is(':visible');
		
		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("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/insertAttendanceVacation.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( attendanceVacationManagerInsertModal.callback )  {
								attendanceVacationManagerInsertModal.callback();
							}
							attendanceVacationManagerInsertModal.close();
						});
					}
					else{
						modalEvent.danger("등록 오류", data.msgDesc);
					}
				},
				error : function(xhr, status, error) {
					modalEvent.danger("등록 오류", "등록 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
				},
				beforeSend:function(){
					
				},
				complete:function(){
					
				}
			});
		});
	},
	/*
	 * 팝업
	 * callback : 콜백함수, reqParam: 팝업파라미터
	 */
	popup:function(callback, reqParam) {
		// 초기화 후 열기
		attendanceVacationManagerInsertModal.init();
		
		//콜백함수 지정.
		attendanceVacationManagerInsertModal.callback = callback;
		attendanceVacationManagerInsertModal.reqParam = reqParam;
		attendanceVacationManagerInsertModal.dataList = null;
		
		
		// 연차유형 콤보데이타 설정 조회
		fn_insertModal_setVacationCombo();
		
		// 기본 셋팅
		fn_setTimeValue("setVacationModalStartTime", "00:00");
		fn_setTimeValue("setVacationModalEndTime", "00:00");
		
		let muMemberId     = attendanceVacationManagerInsertModal.reqParam.muMemberId;
		let memberName     = attendanceVacationManagerInsertModal.reqParam.memberName;
		let attendanceDate = attendanceVacationManagerInsertModal.reqParam.attendanceDate;

		$("#attendanceVacationManagerInsertModal #modalMemberId").data('modalMemberId',muMemberId);
		$("#attendanceVacationManagerInsertModal #modalMemberId").val(memberName);

		if(true != fn_emptyCheck(attendanceDate)){

		}
		else{
			$("#attendanceVacationManagerInsertModal #modalStartDate").val(attendanceDate).trigger("change");
			$("#attendanceVacationManagerInsertModal #modalEndDate").val(attendanceDate).trigger("change");
		}
		
		setTimeout(function(){
			$('#attendanceVacationManagerInsertModal').modal('show')
		}, 200);
	},
	/*
	 * 팝업 닫기
	 */
	close:function() {
		$('#attendanceVacationManagerInsertModal').modal('hide');

		setTimeout(function(){
			$('#attendanceVacationManagerInsertModal').remove();
		},500);
	},
	HtmlTemplate : `
	<div id="attendanceVacationManagerInsertModal" class="modal yeoncha_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 first">
							<label>직원</label>

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

							<p class="leftDaysBox" style="display:none;">잔여 연차 0일</p>
							<input type="hidden" id="modalVacationManagementId">
						</div>

						<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>
						<div 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="setVacationModalStartTime"></ul>
									</div><!--select_box-->
								</div>

								<span class="slash">~</span>
									
								<div class="select_list">
									<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="modalEndTime">
										
										<ul class="select_option_list dropdown-menu" id="setVacationModalEndTime"></ul>
									</div><!--select_box-->
								</div>
							</div>
						</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>
    `
};

/****************************************************************************
* 연차유형 콤보데이타 설정
****************************************************************************/
function fn_insertModal_setVacationCombo(){
	// 대상
	const target = $("#attendanceVacationManagerInsertModal #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();
		let endDate = $("#attendanceVacationManagerInsertModal #modalEndDate").val();
		let startDate = $("#attendanceVacationManagerInsertModal #modalStartDate").val();

		$(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){
			// 연차일경우
			$("#attendanceVacationManagerInsertModal .toggle_box").hide();
		}
		else{
			// 반차일경우
			$("#attendanceVacationManagerInsertModal .toggle_box").show();
		}
		
		// 2. 잔여 연차 조회
		let muMemberId   = $("#attendanceVacationManagerInsertModal #modalMemberId").data('modalMemberId');
		let muVacationId = selectId;

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

		if(true != fn_emptyCheck(muVacationId)){
			modalEvent.warning("등록", "연차사용단위 정보가 없습니다.");	
			return;
		}
		
		let formData = new FormData();
		formData.append("menuClass", menuClass);
		formData.append("muMemberId", muMemberId);
		formData.append("muVacationId", muVacationId);
		formData.append("endDate", endDate);
		formData.append("startDate", startDate);

		$.ajax({
			url: encodeURI('/webvacationmanagement/selectVacationManagementLeftDays.do'),
			data: formData,
			dataType: "json",
			processData: false,
			contentType: false,
			type: 'POST',
			async: true,
			success: function(data){
				if('0'==data.msgCode){
					if(data.rows.length==1){
						$("#attendanceVacationManagerInsertModal .leftDaysBox").text("잔여 연차 "+data.rows[0].leftDays+"일");
						//$("#attendanceVacationManagerInsertModal #modalStartDate").data("DateTimePicker").minDate(data.rows[0].startDate);
						//$("#attendanceVacationManagerInsertModal #modalStartDate").data("DateTimePicker").maxDate(data.rows[0].endDate);
						//$("#attendanceVacationManagerInsertModal #modalEndDate").data("DateTimePicker").minDate(data.rows[0].startDate);
						//$("#attendanceVacationManagerInsertModal #modalEndDate").data("DateTimePicker").maxDate(data.rows[0].endDate);
					}
					else{
						//$("#attendanceVacationManagerInsertModal #modalStartDate").val(fn_getToDate()).trigger("change");
						$("#attendanceVacationManagerInsertModal .leftDaysBox").text("잔여 연차 0일");
						
						modalEvent.warning("등록", "잔여 연차가 없습니다.");
					}
					$("#attendanceVacationManagerInsertModal .leftDaysBox").show();
				}
				else{
					modalEvent.danger("조회 오류", data.msgDesc);
				}
			},
			error : function(xhr, status, error) {
				modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
			},
			beforeSend:function(){
				
			},
			complete:function(){
				
			}
		});
	});
}