/* 페이징 관련 변수 */
 // 근무설정
let attendanceTotalCount = 0;
let attendanceTotalPages = 0;
/*aggird*/
let attendanceAgGridData = [];
let attendanceSelectId   = "";


// 휴무관리
let holidayManagementTotalCount = 0;
let holidayManagementTotalPages = 0;
/*aggird*/
let holidayManagementAgGridData = [];
let holidayManagementSelectId   = "";

// 연차관리
let vacationManagementTotalCount = 0;
let vacationManagementTotalPages = 0;
/*aggird*/
let vacationManagementAgGridData = [];
let vacationManagementSelectId   = "";

/****************************************************************************
* 근태관리 - 조직 옵션 조회
****************************************************************************/
function fn_setAttendanceGroupCombo(){
	// 대상
	const target = $("#attendanceSearchGroupId").siblings("ul.select_option_list");

	// 데이터 조회
	let comboData = fn_selectListGroupOption();
	
	// 조회 데이터 셋팅
	let comboHTML = '<li id="li_attendanceGroupAll" class="option_list_item">조직 전체</li>';
	
	for(let i = 0; i < comboData.length; i++){
		let muGroupId     = comboData[i].muGroupId;
		let groupName     = comboData[i].groupName;
		
		comboHTML += '<li id="li_'+muGroupId+'" class="option_list_item">'+groupName+'</li>';
	}
	target.empty().html(comboHTML).trigger("create");

	// 콤보 이벤트
	target.find("li.option_list_item").click(function () {
		let selectIdArr = $(this).prop("id").split('_');
		let selectId    = selectIdArr[1];
		let selectName  = $(this).text();
		
		if(selectId.match("All")){
			selectId = '';
		}
		
		$(this).parent().siblings("button").text(selectName);
		$(this).parent().siblings("input").val(selectId);
	});
}

/****************************************************************************
* 검색 날짜 설정
//(A:오늘, B:3일, C:7일, D:최근30일, E:최근90일, F:이번달, G:올해, H:지난주, I:지난달)
****************************************************************************/
function fn_attendanceSetDate(param){
	if("A"==param){
		// 오늘
		let toDate = new Date();
		let year  = toDate.getFullYear();
		let month = toDate.getMonth() + 1;
		let day   = toDate.getDate();
		
		if(month < 10) month = "0" + month;
		if(day < 10) day = "0" + day;
		
		attendanceSearchStartDate = year+'-'+month+'-'+day;
		attendanceSearchEndDate   = year+'-'+month+'-'+day;
	}
	else if("B"==param){
		// 3일
		// 검색 종료일자
		let toDate = new Date();
		let year  = toDate.getFullYear();
		let month = toDate.getMonth() + 1;
		let day   = toDate.getDate();
		
		if(month < 10) month = "0" + month;
		if(day < 10) day = "0" + day;
		
		attendanceSearchEndDate   = year+'-'+month+'-'+day;
		
		// 검색 시작일자
		toDate.setDate(toDate.getDate() - 3);
		year  = toDate.getFullYear();
		month = toDate.getMonth() + 1;
		day   = toDate.getDate();
		
		if(month < 10) month = "0" + month;
		if(day < 10) day = "0" + day;
		
		attendanceSearchStartDate = year+'-'+month+'-'+day;
	}
	else if("C"==param){
		// 이번주
		// 검색 종료일자
		let toDate = new Date();
		let year  = toDate.getFullYear();
		let month = toDate.getMonth() + 1;
		let day   = toDate.getDate();
		
		if(month < 10) month = "0" + month;
		if(day < 10) day = "0" + day;
		
		attendanceSearchEndDate   = year+'-'+month+'-'+day;
		
		// 검색 시작일자
		toDate.setDate(toDate.getDate() - 7);
		year  = toDate.getFullYear();
		month = toDate.getMonth() + 1;
		day   = toDate.getDate();
		
		if(month < 10) month = "0" + month;
		if(day < 10) day = "0" + day;
		
		attendanceSearchStartDate = year+'-'+month+'-'+day;
	}
	else if("D"==param){
		// 최근30일
		let toDate = new Date();
		let year  = toDate.getFullYear();
		let month = toDate.getMonth() + 1;
		let day   = toDate.getDate();
		
		if(month < 10) month = "0" + month;
		if(day < 10) day = "0" + day;
		
		//최근30일
		toDate.setDate(toDate.getDate() - 30);
		let startYear  = toDate.getFullYear();
		let startMonth = toDate.getMonth() + 1;
		let startDay   = toDate.getDate();
		
		if(startMonth < 10) startMonth = "0" + startMonth;
		if(startDay < 10) startDay = "0" + startDay;
		
		attendanceSearchStartDate = startYear+'-'+startMonth+'-'+startDay;
		attendanceSearchEndDate   = year+'-'+month+'-'+day;
		
	}
	else if("E"==param){
		// 최근90일
		// 검색 종료일자
		let toDate = new Date();
		let year  = toDate.getFullYear();
		let month = toDate.getMonth() + 1;
		let day   = toDate.getDate();
		
		if(month < 10) month = "0" + month;
		if(day < 10) day = "0" + day;
		
		attendanceSearchEndDate   = year+'-'+month+'-'+day;
		
		// 검색 시작일자
		toDate.setDate(toDate.getDate() - 90);
		year  = toDate.getFullYear();
		month = toDate.getMonth() + 1;
		day   = toDate.getDate();
		
		if(month < 10) month = "0" + month;
		if(day < 10) day = "0" + day;
		
		attendanceSearchStartDate = year+'-'+month+'-'+day;
	}
	else if("F"==param){
		//F:이번달
		// 검색 종료일자
		lettoDate = new Date();
		letyear  = toDate.getFullYear();
		letmonth = toDate.getMonth() + 1;
		letday   = toDate.getDate();
		
		if(month < 10) month = "0" + month;
		if(day < 10) day = "0" + day;
		
		attendanceSearchEndDate   = year+'-'+month+'-'+day;
		
		// 검색 시작일자
		attendanceSearchStartDate = year+'-'+month+'-01';
	}
	else if("G"==param){
		// G:올해
		// 검색 종료일자
		let toDate = new Date();
		let year  = toDate.getFullYear();
		let month = toDate.getMonth() + 1;
		let day   = toDate.getDate();
		
		if(month < 10) month = "0" + month;
		if(day < 10) day = "0" + day;
		
		attendanceSearchEndDate   = year+'-'+month+'-'+day;
		
		// 검색 시작일자
		attendanceSearchStartDate = year+'-01-01';
	}
	else if("H"==param){
		// H:지난주, I:지난달
		// 검색 종료일자
		let toDate = new Date();
		let year  = toDate.getFullYear();
		let month = toDate.getMonth() + 1;
		let day   = toDate.getDate();
		
		if(month < 10) month = "0" + month;
		if(day < 10) day = "0" + day;
		
		attendanceSearchEndDate   = year+'-'+month+'-'+day;
		
		// 검색 시작일자
		attendanceSearchStartDate = year+'-01-01';
	}
	else if("I"==param){
		// I:지난달
		// 검색 종료일자
		let toDate = new Date();
		let year  = toDate.getFullYear();
		let month = toDate.getMonth() + 1;
		let day   = toDate.getDate();
		
		if(month < 10) month = "0" + month;
		if(day < 10) day = "0" + day;
		
		attendanceSearchEndDate   = year+'-'+month+'-'+day;
		
		// 검색 시작일자
		attendanceSearchStartDate = year+'-01-01';
	}
	
	$("#attendanceSearchStartDate").val(attendanceSearchStartDate).trigger("change");
	$("#attendanceSearchEndDate").val(attendanceSearchEndDate).trigger("change");
}

/****************************************************************************
* 정렬 이벤트
****************************************************************************/
function fn_alignEvent(param, param2){
	let align = "";
	
	if("A"==param){
		align = "오늘";
		
		fn_attendanceSetDate('A');
	}
	else if("B"==param){
		align = "최근30일";
		
		fn_attendanceSetDate('D');
	}
	else if("C"==param){
		align = "최근90일";
		
		fn_attendanceSetDate('E');
	}
	else if("D"==param){
		align = "이번주";
		
		fn_attendanceSetDate('C');
	}
	else if("E"==param){
		align = "이번달";
		
		fn_attendanceSetDate('F');
	}
	else if("F"==param){
		align = "올해";
		
		fn_attendanceSetDate('G');
	}
	else if("G"==param){
		align = "지난주";
		
		fn_attendanceSetDate('H');
	}
	else if("H"==param){
		align = "지난달";
		
		fn_attendanceSetDate('I');
	}
	else{
		align = "";
	}
	$("#attendanceSearchDateTypeBtn").text(align);
	$("#attendanceSearchDateType").val(param);
}

/****************************************************************************
* 근태관리 정보 리스트 조회
****************************************************************************/
function fn_selectListAttendanceJson(){
	let formData = new FormData();
	formData.append("menuClass", menuClass);
	formData.append("attendanceSearchKeywordParam", attendanceSearchKeywordParam);
	formData.append("attendanceSort", attendanceSort);
	formData.append("attendanceDir", attendanceDir);
	formData.append("attendanceStart", attendanceStart);
	formData.append("attendanceLimit", attendanceLimit);
	formData.append("attendanceSearchDate", attendanceSearchDate);
	formData.append("attendanceSearchGroupId", attendanceSearchGroupId);
	
	$.ajax({
		url: encodeURI('/webattendance/selectListAttendance.do'),
		data: formData,
		dataType: "json",
		processData: false,
		contentType: false,
		type: 'POST',
		async: true,
		success: function(data){
			if('0'==data.msgCode){
				// 날짜 출력
				let listHTML = '';
				listHTML += '		<li class="name">직원</li>';
				for(let i = 0; i < data.dateRows.length; i++){
					let month      = data.dateRows[i].month;
					let day        = data.dateRows[i].day;
					let dayOfWeek  = data.dateRows[i].dayOfWeek;
					let resultDate = data.dateRows[i].resultDate;
					
					if('토'==dayOfWeek){
						listHTML += '<li><p class="day on">'+day+'/'+dayOfWeek+'</p></li>';
					}
					else if('일'==dayOfWeek){
						listHTML += '<li><p class="day red">'+day+'/'+dayOfWeek+'</p></li>';
					}
					else{
						listHTML += '<li><p class="day">'+day+'/'+dayOfWeek+'</p></li>';
					}
				}
				$(".calendar_list").empty().html(listHTML).trigger("create");
				
				// 근태 출력
				listHTML = '';
				for(let j = 0; j < data.memberRows.length; j++){
					let muMemberId  = data.memberRows[j].muMemberId;
					let memberName  = data.memberRows[j].memberName;
					let loginId     = data.memberRows[j].loginId;
					let muGroupId   = data.memberRows[j].muGroupId;
					let groupName   = data.memberRows[j].groupName;
					let muDutyId    = data.memberRows[j].muDutyId;
					let dutyName    = data.memberRows[j].dutyName;
					
					listHTML += '<tr>';
					listHTML += '	<td class="first">';
					listHTML += '		<p class="team">'+groupName+' '+dutyName+'</p>';
					listHTML += '		<p class="user">'+memberName+' <span>('+loginId+')</span></p>';
					listHTML += '	</td>';
					
					// 병합갯수.
					let cellCount = 1;
					let addTdYn  = false;
					
					for(let i = 0; i < data.rows.length; i++){
						let searchDate         = data.rows[i].searchDate;
						let groupId            = data.rows[i].muGroupId;
						let dutyId             = data.rows[i].muDutyId;
						let memberId           = data.rows[i].muMemberId;
						let memberName         = data.rows[i].memberName;
						let attendanceListMap  = data.rows[i].attendanceListMap;
						
						if(muGroupId==groupId && muDutyId==dutyId && muMemberId==memberId){
							if(null==attendanceListMap){
								// 근태 정보 없을 경우
								listHTML += '<td class="nodata">';
								listHTML += '	<div class="dropdown">';
								listHTML += '		<button type="button" class="btn dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"></button>';
								listHTML += '		<ul class="drop_list dropdown-menu">';
								listHTML += '			<li onclick="javascript:fn_insertAttendancePopup(\''+memberId+'\', \''+memberName+'\', \''+searchDate+'\');">출퇴/휴무 등록</li>';
								listHTML += '			<li onclick="javascript:fn_insertAttendanceVacationManagementPopup(\''+memberId+'\',\''+memberName+'\', \''+searchDate+'\');">연차 등록</li>';
								listHTML += '		</ul>';
								listHTML += '	</div>';
								listHTML += '</td>';
							}
							else{
								// 근태 정보 있을 경우
								let muAttendanceId  = attendanceListMap[0].muAttendanceId;
								let muMemberId      = attendanceListMap[0].muMemberId;
								let attendanceType  = attendanceListMap[0].attendanceType;
								let attendanceType2 = attendanceListMap[1]?.attendanceType;
								let searchDate      = attendanceListMap[0].searchDate;
								let startTime       = attendanceListMap[0].startTime;
								let muAttendanceId2 = attendanceListMap[0].muAttendanceId2;
								let endTime         = attendanceListMap[0].endTime;
								let totalWorkHour   = attendanceListMap[0].totalWorkHour;
								let vacationName    = attendanceListMap[0].vacationName;
								let muVacationId;

								if(i!=(data.rows.length-1)){
									// 마지막이 아니면
									// 다음 cell 병합인지 확인.
									if(null==data.rows[i+1].attendanceListMap){
										addTdYn  = true;
									}
									else {
										let nextAttendanceListMap  = data.rows[i+1].attendanceListMap;
										let nextAttendanceId       = nextAttendanceListMap[0].muAttendanceId;
										
										if(muAttendanceId == nextAttendanceId){
											cellCount++;
											addTdYn  = false;
										}
										else{
											addTdYn  = true;
										}
									}
								}
								else{
									addTdYn  = true;
								}

								if(true == addTdYn){
									if('A'==attendanceType&&!attendanceType2){
										// 출/퇴근
										listHTML += '<td class="on">';
										listHTML += '	<div class="dropdown">';
										listHTML += '		<button type="button" class="btn dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">';
										listHTML += '			<p>출근&ensp;<span>'+startTime+'</span></p>';
										listHTML += '			<p>퇴근&ensp;<span>'+endTime+'</span></p>';
										if(true == fn_emptyCheck(totalWorkHour)&&'-'!=totalWorkHour){
											listHTML += '		<p class="work">근무&ensp;<span>'+totalWorkHour+'</span></p>';
										}
										else{
											listHTML += '		<p class="work">근무&ensp;<span>-</span></p>';
										}
										listHTML += '		</button>';
										listHTML += '		<ul class="drop_list dropdown-menu">';
										listHTML += '			<li onclick="javascript:fn_updateAttendancePopup(\''+muAttendanceId+'\',\''+muAttendanceId2+'\',\''+muMemberId+'\',\''+searchDate+'\');">출퇴수정</li>';
										listHTML += '		</ul>';
										listHTML += '	</div>';
										listHTML += '</td>';
									}
									else if('C'==attendanceType){
										// 휴무
										listHTML += '<td class="off" colspan="'+cellCount+'">';
										listHTML += '	<div class="dropdown">';
										listHTML += '		<button type="button" class="btn dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">';
										listHTML += '			<p class="off_txt">휴무</p>';
										listHTML += '		</button>';
										listHTML += '		<ul class="drop_list dropdown-menu">';
										listHTML += '			<li onclick="javascript:fn_updateHolidayManagementPopup(\'A\', \''+muAttendanceId+'\');">휴무수정</li>';
										listHTML += '		</ul>';
										listHTML += '	</div>';
										listHTML += '</td>';
									}
									else if('D'==attendanceType){
										// 연차
										listHTML += '<td class="off" colspan="'+cellCount+'">';
										listHTML += '	<div class="dropdown">';
										listHTML += '		<button type="button" class="btn dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">';
										listHTML += '			<p class="off_txt">'+vacationName+'</p>';
										listHTML += '		</button>';
										listHTML += '		<ul class="drop_list dropdown-menu">';
										listHTML += '			<li onclick="javascript:fn_updateAttendanceVacationManagementPopup(\''+muAttendanceId+'\',\''+muMemberId+'\',);">연차수정</li>';
										listHTML += '		</ul>';
										listHTML += '	</div>';
										listHTML += '</td>';
									}
									else if('E'==attendanceType||attendanceType2){
										if('A'==attendanceType){
											vacationName=attendanceListMap[1].vacationName;
											muVacationId=attendanceListMap[1].muAttendanceId;
										}
										if('E'==attendanceType){
											if(attendanceType2){
												startTime=attendanceListMap[1].startTime;
												endTime=attendanceListMap[1].endTime;
												totalWorkHour=attendanceListMap[1].totalWorkHour;
												muVacationId=attendanceListMap[0].muAttendanceId;
												muAttendanceId=attendanceListMap[1].muAttendanceId;
											}else{
												startTime='-';
												endTime='-';
												totalWorkHour='-';
												muVacationId=attendanceListMap[0].muAttendanceId;
											}
										}
										// 반차
										listHTML += '<td class="on">';
										listHTML += '	<div class="dropdown onOff" onmouseover="javascript:fn_mouseOn(\''+vacationName+'\')" onmouseout="javascript:fn_mouseOut(\''+startTime+'\',\''+endTime+'\',\''+totalWorkHour+'\')">';
										listHTML += '		<button type="button" class="btn dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">';
										listHTML += '			<p>출근&ensp;<span>'+startTime+'</span></p>';
										listHTML += '			<p>퇴근&ensp;<span>'+endTime+'</span></p>';
										if(true == fn_emptyCheck(totalWorkHour)&&'-'!=totalWorkHour){
											listHTML += '		<p class="work">근무&ensp;<span>'+totalWorkHour+'</span></p>';
										}
										else{
											listHTML += '		<p class="work">근무&ensp;<span>-</span></p>';
										}
										// listHTML += '			<p class="off_txt">'+vacationName+'</p>';
										listHTML += '		</button>';
										listHTML += '		<ul class="drop_list dropdown-menu">';
										if(attendanceType2)
											listHTML += '			<li onclick="javascript:fn_updateAttendancePopup(\'' + muAttendanceId + '\',\'' + muAttendanceId2 + '\',\'' + muMemberId + '\',\'' + searchDate + '\');">출퇴수정</li>';
										if(!attendanceType2)
											listHTML += '			<li onclick="javascript:fn_insertAttendancePopup(\''+memberId+'\', \''+memberName+'\', \''+searchDate+'\');">출퇴 등록</li>';
										listHTML += '			<li onclick="javascript:fn_updateAttendanceVacationManagementPopup(\''+muVacationId+'\',\''+muMemberId+'\',);">연차수정</li>';
										listHTML += '		</ul>';
										listHTML += '	</div>';
										listHTML += '</td>';
									}
									cellCount=1;
								}
							}
						}
					}
					listHTML += '</tr>';
				}
				$("#attendTable").empty().html(listHTML).trigger("create");
			}
			else{
				modalEvent.danger("조회 오류", data.msgDesc);
			}
		},
		error : function(xhr, status, error) {
			modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
		},
		beforeSend:function(){
			
		},
		complete:function(){
			
		}
	});
}
let mouseOnTimeout;
let mouseOutTimeout;

function fn_mouseOn(vacationName) {
	clearTimeout(mouseOutTimeout);
	const buttonElement = event.target.closest('button');
	if(buttonElement)
	event.target.closest('button').innerHTML = `<p class="off_txt">${vacationName}</p>`;
}

function fn_mouseOut(startTime, endTime, totalWorkHour) {
	clearTimeout(mouseOnTimeout);
	const buttonElement = event.target.closest('button');
	if(buttonElement)
		event.target.closest('button').innerHTML = `
            <p>출근 <span>${startTime}</span></p>
            <p>퇴근 <span>${endTime}</span></p>
            ${true == fn_emptyCheck(totalWorkHour) && '-' != totalWorkHour ?
			`<p class="work">근무 <span>${totalWorkHour}</span></p>` :
			`<p class="work">근무 <span>-</span></p>`}`;
}
/****************************************************************************
* 검색하기
****************************************************************************/
function fn_attendanceSearch(param){
	if("A"!=param && "Y"!=selectUseYn){
		modalEvent.warning("", "조회 권한이 없습니다.");
		return false;
	}
	
	attendanceSearchKeywordParam = $("#attendanceSearchKeyword").val();

	attendanceSearchDate  = $("#attendanceSearchDate").val();
	attendanceSearchGroupId   = $("#attendanceSearchGroupId").val();

	fn_selectListAttendanceJson();
}


/****************************************************************************
* 초기화하기
****************************************************************************/
function fn_attendanceReset(){
	$('#attendanceSearchDate').datetimepicker({
		allowInputToggle: true,
		viewMode: 'months',
		format: 'YYYY-MM',
		defaultDate: moment().format('YYYY-MM')
	});

	// 조직
	$('#li_attendanceGroupAll').click();
	
	$("#attendanceSearchKeyword").val("");

	fn_attendanceSearch();
}

/****************************************************************************
* 검색 엔터 이벤트
****************************************************************************/
function fn_attendanceEnter(e){
	if(e.which){
		// 파이어폭스
		if(13 == e.which) {
			//로그인 액션 스크립트
			fn_attendanceSearch();
		}
	}
	else{
		// 윈도우, 사파리, 크롬
		if(13 == event.keyCode) {
			//로그인 액션 스크립트
			fn_attendanceSearch();
		}
	}
}

/****************************************************************************
* 완료
****************************************************************************/
function fn_attendanceOk(){
	fn_attendanceReset();
}

function fn_insertAttendancePopup(param, param2, param3){
	if("Y"!=insertUseYn){
		modalEvent.warning("", "등록 권한이 없습니다.");
		return false;
	}
	
	let reqParam =  {'muMemberId':param, 'memberName':param2, 'attendanceDate':param3};
	attendanceInsertModal.popup(function(obj, reqParam) {
		fn_attendanceOk();
	}, reqParam);
}

function fn_insertAttendanceVacationManagementPopup(param, param2,param3){
	if("Y"!=insertUseYn){
		modalEvent.warning("", "등록 권한이 없습니다.");
		return false;
	}
	
	let reqParam =  {'muMemberId':param, 'memberName':param2, 'attendanceDate':param3};
	attendanceVacationManagerInsertModal.popup(function(obj, reqParam) {
		fn_attendanceOk();
	}, reqParam);
}

function fn_updateAttendanceVacationManagementPopup(param,param2){
	if("Y"==updateUseYn){
		let reqParam =  {
			"muAttendanceId"  : param,
			"muMemberId"      : param2
		};
		
		attendanceVacationManagerUpdateModal.popup(function(obj, reqParam) {
			fn_attendanceOk();
		}, reqParam);
	}
	else{
		modalEvent.warning("", "수정 권한이 없습니다.");
		return false;
	}
	
}

function fn_updateAttendancePopup(param, param2, param3, param4){
	if("Y"==updateUseYn){
		let reqParam =  {
			"muAttendanceId"  : param,
			"muAttendanceId2" : param2,
			"muMemberId"      : param3,
			"attendanceDate"  : param4
		};
		
		attendanceUpdateModal.popup(function(obj, reqParam) {
			fn_attendanceOk();
		}, reqParam);
	}
	else{
		modalEvent.warning("", "수정 권한이 없습니다.");
		return false;
	}
}
function fn_updateVacationManagementPopup(param){
	if("Y"!=updateUseYn){
		modalEvent.warning("", "수정 권한이 없습니다.");
		return false;
	}

	let reqParam =  {
		'muMemberId'			:param.muMemberId,
	    'endDate'				:param.endDate,
	    'startDate'				:param.startDate,
	    'memberName'			:param.memberName,
	    'etc'					:param.etc,
	    'muVacationManagementId':param.muVacationManagementId
	};

	vacationManagementUpdateModal.popup(function(obj, reqParam) {
		fn_vacationManagementOk();
	}, reqParam);
}
/****************************************************************************
* 엑셀 다운 다운로드
****************************************************************************/
function fn_downloadAttendanceExcel(){
	if("Y"==downloadUseYn){
		// 수정가능
		let pagingParam = "?menuClass="+menuClass;
		pagingParam    += "&attendanceSearchKeywordParam="+attendanceSearchKeywordParam;
		pagingParam    += "&attendanceSort="+attendanceSort;
		pagingParam    += "&attendanceDir="+attendanceDir;
		pagingParam    += "&attendanceStart="+attendanceStart;
		pagingParam    += "&attendanceLimit="+attendanceLimit;
		pagingParam    += "&attendanceSearchDate="+attendanceSearchDate;
		pagingParam    += "&attendanceSearchGroupId="+attendanceSearchGroupId;
		
		let url = encodeURI("/webattendance/downloadAttendanceExcel.do"+pagingParam);
		$("#attendanceSelectListForm").prop("action",url);
		$("#attendanceSelectListForm").submit();
	}
	else{
		modalEvent.warning("", "내려받기 권한이 없습니다.");
		return false;
	}
}

// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

/****************************************************************************
* 휴무관리 - 조직 옵션 조회
****************************************************************************/
function fn_setHolidayManagementGroupCombo(){
	// 대상
	const target = $("#holidayManagementSearchGroupId").siblings("ul.select_option_list");

	// 데이터 조회
	let comboData = fn_selectListGroupOption();
	
	// 조회 데이터 셋팅
	let comboHTML = '<li id="li_holidayManagementGroupAll" class="option_list_item">조직 전체</li>';
	
	for(let i = 0; i < comboData.length; i++){
		let muGroupId     = comboData[i].muGroupId;
		let groupName     = comboData[i].groupName;
		
		comboHTML += '<li id="li_'+muGroupId+'" class="option_list_item">'+groupName+'</li>';
	}
	target.empty().html(comboHTML).trigger("create");

	// 콤보 이벤트
	target.find("li.option_list_item").click(function () {
		let selectIdArr = $(this).prop("id").split('_');
		let selectId    = selectIdArr[1];
		let selectName  = $(this).text();

		if(selectId.match("All")){
			selectId = '';
		}
		
		$(this).parent().siblings("button").text(selectName);
		$(this).parent().siblings("input").val(selectId);
	});
}

/****************************************************************************
* 휴무관리 - 직무 옵션 조회
****************************************************************************/
function fn_setHolidayManagementDutyCombo(){
	// 대상
	const target = $("#holidayManagementSearchDutyId").siblings("ul.select_option_list");

	// 데이터 조회
	let comboData = fn_selectListDutyOption();
	
	// 조회 데이터 셋팅
	let comboHTML = '<li id="li_holidayManagementDutyAll" class="option_list_item">직무 전체</li>';
	
	for(let i = 0; i < comboData.length; i++){
		let muDutyId     = comboData[i].muDutyId;
		let dutyName     = comboData[i].dutyName;
		
		comboHTML += '<li id="li_'+muDutyId+'" class="option_list_item">'+dutyName+'</li>';
	}
	target.empty().html(comboHTML).trigger("create");

	// 콤보 이벤트
	target.find("li.option_list_item").click(function () {
		let selectIdArr = $(this).prop("id").split('_');
		let selectId    = selectIdArr[1];
		let selectName  = $(this).text();

		if(selectId.match("All")){
			selectId = '';
		}
		
		$(this).parent().siblings("button").text(selectName);
		$(this).parent().siblings("input").val(selectId);
	});
}

/****************************************************************************
* 휴무관리 정보 리스트 조회
****************************************************************************/
function fn_selectListHolidayManagementJson(){
	let formData = new FormData();
	formData.append("menuClass", menuClass);
	formData.append("holidayManagementSearchKeywordParam", holidayManagementSearchKeywordParam);
	formData.append("holidayManagementSort", holidayManagementSort);
	formData.append("holidayManagementDir", holidayManagementDir);
	formData.append("holidayManagementStart", holidayManagementStart);
	formData.append("holidayManagementLimit", holidayManagementLimit);
	formData.append("holidayManagementSearchDate", holidayManagementSearchDate);
	formData.append("holidayManagementSearchGroupId", holidayManagementSearchGroupId);
	formData.append("holidayManagementSearchDutyId", holidayManagementSearchDutyId);

	$.ajax({
		url: encodeURI('/webholidaymanagement/selectListHolidayManagement.do'),
		data: formData,
		dataType: "json",
		processData: false,
		contentType: false,
		type: 'POST',
		async: true,
		success: function(data){
			if('0'==data.msgCode){
				// 페이징 처리
				holidayManagementTotalCount  = data.totalCount;
				//$("#holidayManagementTotalCount").text(holidayManagementTotalCount);

				holidayManagementTotalPages = Math.ceil(holidayManagementTotalCount/holidayManagementLimit);
				
				// 리스트 조회
				holidayManagementAgGridData = data.rows;
				holidayManagementGridOptions.api.setRowData(holidayManagementAgGridData);

				if(0<data.rows.length){
					//페이징 처리
					window.pagObj = $('#holidayManagementPagination').twbsPagination({
						startPage    : ((holidayManagementStart/holidayManagementLimit)+1),
						totalPages   : (holidayManagementTotalPages==0)?1:holidayManagementTotalPages,
						visiblePages : 10,
						initiateStartPageClick: false,
						prev         : '<img src="/image/web/page_navigation_arrow.svg" alt="prev">',
						next         : '<img src="/image/web/page_navigation_arrow.svg" alt="next">',
						first        : '',
						last         : '',
						onPageClick: function (event, page) {
							fn_holidayManagementPagination(page);
						}
					}).on('page', function (event, page) {
						//console.info(page + ' (from event listening)');
					});
				}
				else{
					
				}
			}
			else{
				modalEvent.danger("조회 오류", data.msgDesc);
			}
		},
		error : function(xhr, status, error) {
			modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
		},
		beforeSend:function(){
			// 로딩열기
			holidayManagementGridOptions.api.showLoadingOverlay();
		},
		complete:function(){
			
		}
	});
}

/****************************************************************************
* 검색하기
****************************************************************************/
function fn_holidayManagementSearch(param){
	if("A"!=param && "Y"!=selectUseYn){
		modalEvent.warning("", "조회 권한이 없습니다.");
		return false;
	}
	
	fn_holidayManagementPaginReset();
	
	holidayManagementSearchKeywordParam = $("#holidayManagementSearchKeyword").val();

	holidayManagementSearchDate       = $("#holidayManagementSearchDate").val() || attendanceSearchDate;
	holidayManagementSearchGroupId    = $("#holidayManagementSearchGroupId").val();
	holidayManagementSearchDutyId     = $("#holidayManagementSearchDutyId").val();

	fn_selectListHolidayManagementJson();
}


/****************************************************************************
* 초기화하기
****************************************************************************/
function fn_holidayManagementReset(){
	// 조직
	$('#li_holidayManagementGroupAll').click();
	
	// 직무
	$('#li_holidayManagementDutyAll').click();
	
	$("#holidayManagementSearchKeyword").val("");

	fn_holidayManagementSearch();
}

/****************************************************************************
* 페이징 처리
****************************************************************************/
function fn_holidayManagementPagination(param){
	holidayManagementStart = (parseInt(param)-1)*holidayManagementLimit;
	
	fn_selectListHolidayManagementJson();
}

/****************************************************************************
* 페이징 리셋
****************************************************************************/
function fn_holidayManagementPaginReset(){
	holidayManagementSearchKeywordParam = '';

	holidayManagementStart        = 0;
	holidayManagementLimit        = 100;
	holidayManagementTotalCount   = 0;
	holidayManagementTotalPages   = 0;
	
	//페이징 초기화
	if($("#holidayManagementPagination").data("twbs-pagination")){
		$("#holidayManagementPagination").twbsPagination("destroy");
	}
}

/****************************************************************************
* 휴무관리 삭제
****************************************************************************/
function fn_deleteHolidayManagement(){
	if("Y"!=deleteUseYn){
		modalEvent.warning("", "삭제 권한이 없습니다.");
		return false;
	}
	
	if(!holidayManagementSelectId){
		modalEvent.warning("", "삭제할 대상을 선택하세요.");
		return false;
	}

	modalEvent.info("삭제", "선택한 근무설정 정보를 삭제하시겠습니까?", function(){
		let formData = new FormData();
		formData.append("menuClass", menuClass);
		formData.append("selectId", holidayManagementSelectId);

		$.ajax({
			url: encodeURI('/webholidaymanagement/deleteHolidayManagement.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(){
						fn_holidayManagementOk();
					});
				}
				else{
					modalEvent.danger("삭제 오류", data.msgDesc);
				}
			},
			error : function(xhr, status, error) {
				modalEvent.danger("삭제 오류", "삭제 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
			},
			beforeSend:function(){
				
			},
			complete:function(){
				
			}
		});
	});
}

/****************************************************************************
* 검색 엔터 이벤트
****************************************************************************/
function fn_holidayManagementEnter(e){
	if(e.which){
		// 파이어폭스
		if(13 == e.which) {
			//로그인 액션 스크립트
			fn_holidayManagementSearch();
		}
	}
	else{
		// 윈도우, 사파리, 크롬
		if(13 == event.keyCode) {
			//로그인 액션 스크립트
			fn_holidayManagementSearch();
		}
	}
}

/****************************************************************************
* 완료
****************************************************************************/
function fn_holidayManagementOk(){
	fn_holidayManagementReset();
}

function fn_insertHolidayManagementPopup(){
	if("Y"!=insertUseYn){
		modalEvent.warning("", "등록 권한이 없습니다.");
		return false;
	}
	
	let reqParam =  {};
	holidayManagementInsertModal.popup(function(obj, reqParam) {
		fn_holidayManagementOk();
	}, reqParam);
}

function fn_updateHolidayManagementPopup(param, param2){
	let reqParam = {
		"muAttendanceId": param2
	};

	let callbackFunction = (param === 'A') ? fn_attendanceOk : fn_holidayManagementOk;
	if(updateUseYn === "Y") {
		// 수정 가능
		holidayManagementUpdateModal.popup(function(obj, reqParam) {
			callbackFunction();
		}, reqParam);
	} else {
		// 조회만
		holidayManagementUpdateModal.popup(function(obj, reqParam) {
			if(param === 'A') {
				// 근태
				fn_attendanceOk();
			} else {
				// 휴무
				fn_holidayManagementOk();
			}
		}, reqParam);
	}
}


function fn_cancelHolidayManagementPopup(param){
	let reqParam =  {
		"muAttendanceId" : param
	};
	
	if("Y"==updateUseYn){
		// 수정가능
		holidayManagementCancelModal.popup(function(obj, reqParam) {
			fn_holidayManagementOk();
		}, reqParam);
	}
	else{
		// 조회만
		holidayManagementCancelModal.popup(function(obj, reqParam) {
			fn_holidayManagementOk();
		}, reqParam);
	}
	
}

/****************************************************************************
* 엑셀 다운 다운로드
****************************************************************************/
function fn_downloadHolidayManagementExcel(){
	if("Y"==downloadUseYn){
		// 수정가능
		let pagingParam = "?menuClass="+menuClass;
		pagingParam    += "&holidayManagementSearchKeywordParam="+holidayManagementSearchKeywordParam;
		pagingParam    += "&holidayManagementSort="+holidayManagementSort;
		pagingParam    += "&holidayManagementDir="+holidayManagementDir;
		pagingParam    += "&holidayManagementStart="+holidayManagementStart;
		pagingParam    += "&holidayManagementLimit="+holidayManagementLimit;
		pagingParam    += "&holidayManagementSearchGroupId="+holidayManagementSearchGroupId;
		pagingParam    += "&holidayManagementSearchDutyId="+holidayManagementSearchDutyId;
		pagingParam    += "&holidayManagementSearchDate="+holidayManagementSearchDate;
		
		let url = encodeURI("/webholidaymanagement/downloadHolidayManagementExcel.do"+pagingParam);
		$("#attendanceSelectListForm").prop("action",url);
		$("#attendanceSelectListForm").submit();
	}
	else{
		modalEvent.warning("", "내려받기 권한이 없습니다.");
		return false;
	}
}


// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

/****************************************************************************
* 연차관리 - 조직 옵션 조회
****************************************************************************/
function fn_setVacationManagementGroupCombo(){
	// 대상
	const target = $("#vacationManagementSearchGroupId").siblings("ul.select_option_list");

	// 데이터 조회
	let comboData = fn_selectListGroupOption();
	
	// 조회 데이터 셋팅
	let comboHTML = '<li id="li_vacationManagementGroupAll" class="option_list_item">조직 전체</li>';
	
	for(let i = 0; i < comboData.length; i++){
		let muGroupId     = comboData[i].muGroupId;
		let groupName     = comboData[i].groupName;
		
		comboHTML += '<li id="li_'+muGroupId+'" class="option_list_item">'+groupName+'</li>';
	}
	target.empty().html(comboHTML).trigger("create");

	// 콤보 이벤트
	target.find("li.option_list_item").click(function () {
		let selectIdArr = $(this).prop("id").split('_');
		let selectId    = selectIdArr[1];
		let selectName  = $(this).text();

		if(selectId.match("All")){
			selectId = '';
		}
		
		$(this).parent().siblings("button").text(selectName);
		$(this).parent().siblings("input").val(selectId);
	});
}

/****************************************************************************
* 연차관리 정보 리스트 조회
****************************************************************************/
function fn_selectListVacationManagementJson(){
	let formData = new FormData();
	formData.append("menuClass", menuClass);
	formData.append("vacationManagementSearchKeywordParam", vacationManagementSearchKeywordParam);
	formData.append("vacationManagementSort", vacationManagementSort);
	formData.append("vacationManagementDir", vacationManagementDir);
	formData.append("vacationManagementStart", vacationManagementStart);
	formData.append("vacationManagementLimit", vacationManagementLimit);
	formData.append("vacationManagementSearchYear", vacationManagementSearchYear);
	formData.append("vacationManagementSearchGroupId", vacationManagementSearchGroupId);

	$.ajax({
		url: encodeURI('/webvacationmanagement/selectListVacationManagement.do'),
		data: formData,
		dataType: "json",
		processData: false,
		contentType: false,
		type: 'POST',
		async: true,
		success: function(data){
			if('0'==data.msgCode){
				// 페이징 처리
				vacationManagementTotalCount  = data.totalCount;
				//$("#vacationManagementTotalCount").text(vacationManagementTotalCount);

				vacationManagementTotalPages = Math.ceil(vacationManagementTotalCount/vacationManagementLimit);
				
				// 리스트 조회
				vacationManagementAgGridData = data.rows;
				vacationManagementGridOptions.api.setRowData(vacationManagementAgGridData);

				if(0<data.rows.length){
					//페이징 처리
					window.pagObj = $('#vacationManagementPagination').twbsPagination({
						startPage    : ((vacationManagementStart/vacationManagementLimit)+1),
						totalPages   : (vacationManagementTotalPages==0)?1:vacationManagementTotalPages,
						visiblePages : 10,
						initiateStartPageClick: false,
						prev         : '<img src="/image/web/page_navigation_arrow.svg" alt="prev">',
						next         : '<img src="/image/web/page_navigation_arrow.svg" alt="next">',
						first        : '',
						last         : '',
						onPageClick: function (event, page) {
							fn_vacationManagementPagination(page);
						}
					}).on('page', function (event, page) {
						//console.info(page + ' (from event listening)');
					});
				}
				else{
					
				}
			}
			else{
				modalEvent.danger("조회 오류", data.msgDesc);
			}
		},
		error : function(xhr, status, error) {
			modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
		},
		beforeSend:function(){
			// 로딩열기
			vacationManagementGridOptions.api.showLoadingOverlay();
		},
		complete:function(){
			
		}
	});
}

/****************************************************************************
* 검색하기
****************************************************************************/
function fn_vacationManagementSearch(param){
	if("A"!=param && "Y"!=selectUseYn){
		modalEvent.warning("", "조회 권한이 없습니다.");
		return false;
	}
	
	fn_vacationManagementPaginReset();
	
	vacationManagementSearchKeywordParam = $("#vacationManagementSearchKeyword").val();

	vacationManagementSearchYear       = $("#vacationManagementSearchYear").val();
	vacationManagementSearchGroupId    = $("#vacationManagementSearchGroupId").val();

	fn_selectListVacationManagementJson();
}


/****************************************************************************
* 초기화하기
****************************************************************************/
function fn_vacationManagementReset(){
	// 조직
	$('#li_vacationManagementGroupAll').click();
	
	$("#vacationManagementSearchKeyword").val("");

	fn_vacationManagementSearch();
}

/****************************************************************************
* 페이징 처리
****************************************************************************/
function fn_vacationManagementPagination(param){
	vacationManagementStart = (parseInt(param)-1)*vacationManagementLimit;
	
	fn_selectListVacationManagementJson();
}

/****************************************************************************
* 페이징 리셋
****************************************************************************/
function fn_vacationManagementPaginReset(){
	vacationManagementSearchKeywordParam = '';

	vacationManagementStart        = 0;
	vacationManagementLimit        = 100;
	vacationManagementTotalCount   = 0;
	vacationManagementTotalPages   = 0;
	
	//페이징 초기화
	if($("#vacationManagementPagination").data("twbs-pagination")){
		$("#vacationManagementPagination").twbsPagination("destroy");
	}
}

/****************************************************************************
* 연차관리 삭제
****************************************************************************/
function fn_deleteVacationManagement(){
	if("Y"!=deleteUseYn){
		modalEvent.warning("", "삭제 권한이 없습니다.");
		return false;
	}
	
	if(!vacationManagementSelectId){
		modalEvent.warning("", "삭제할 대상을 선택하세요.");
		return false;
	}

	modalEvent.info("삭제", "선택한 근무설정 정보를 삭제하시겠습니까?", function(){
		let formData = new FormData();
		formData.append("menuClass", menuClass);
		formData.append("selectId", vacationManagementSelectId);

		$.ajax({
			url: encodeURI('/webvacationmanagement/deleteVacationManagement.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(){
						fn_vacationManagementOk();
					});
				}
				else{
					modalEvent.danger("삭제 오류", data.msgDesc);
				}
			},
			error : function(xhr, status, error) {
				modalEvent.danger("삭제 오류", "삭제 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
			},
			beforeSend:function(){
				
			},
			complete:function(){
				
			}
		});
	});
}

/****************************************************************************
* 검색 엔터 이벤트
****************************************************************************/
function fn_vacationManagementEnter(e){
	if(e.which){
		// 파이어폭스
		if(13 == e.which) {
			//로그인 액션 스크립트
			fn_vacationManagementSearch();
		}
	}
	else{
		// 윈도우, 사파리, 크롬
		if(13 == event.keyCode) {
			//로그인 액션 스크립트
			fn_vacationManagementSearch();
		}
	}
}

/****************************************************************************
* 완료
****************************************************************************/
function fn_vacationManagementOk(){
	fn_vacationManagementReset();
}

function fn_insertVacationManagementPopup(){
	if("Y"!=insertUseYn){
		modalEvent.warning("", "등록 권한이 없습니다.");
		return false;
	}
	
	let reqParam =  {};
	vacationManagementInsertModal.popup(function(obj, reqParam) {
		fn_vacationManagementOk();
	}, reqParam);
}



/****************************************************************************
* 수정 화면으로 이동.
****************************************************************************/
function fn_updateVacationManagementIntro(param, param2){
	if("Y"==updateUseYn){
		// 수정가능
		let pagingParam = "?menuClass="+menuClass;
		pagingParam    += "&vacationManagementSearchKeywordParam="+vacationManagementSearchKeywordParam;
		pagingParam    += "&vacationManagementSort="+vacationManagementSort;
		pagingParam    += "&vacationManagementDir="+vacationManagementDir;
		pagingParam    += "&vacationManagementStart="+vacationManagementStart;
		pagingParam    += "&vacationManagementLimit="+vacationManagementLimit;
		pagingParam    += "&vacationManagementSearchYear="+vacationManagementSearchYear;
		pagingParam    += "&vacationManagementSearchGroupId="+vacationManagementSearchGroupId;
		pagingParam    += "&muVacationManagementId="+param;
		pagingParam    += "&year="+param2;
		
		fn_leftFormAction("/webvacationmanagement/updateVacationManagementIntro.do"+pagingParam);
	}
	else{
		if("Y"==selectUseYn){
			let reqParam =  {
				"muVacationManagementId" : param
			};
			// 조회만
			vacationManagementSelectModal.popup(function(obj, reqParam) {
				fn_vacationManagementOk();
			}, reqParam);
		}
		else{
			modalEvent.warning("", "조회 및 수정 권한이 없습니다.");
			return false;
		}
	}
	
}

/****************************************************************************
* 엑셀 다운 다운로드
****************************************************************************/
function fn_downloadVacationManagementExcel(){
	if("Y"==downloadUseYn){
		// 수정가능
		let pagingParam = "?menuClass="+menuClass;
		pagingParam    += "&vacationManagementSearchKeywordParam="+vacationManagementSearchKeywordParam;
		pagingParam    += "&vacationManagementSort="+vacationManagementSort;
		pagingParam    += "&vacationManagementDir="+vacationManagementDir;
		pagingParam    += "&vacationManagementStart="+vacationManagementStart;
		pagingParam    += "&vacationManagementLimit="+vacationManagementLimit;
		pagingParam    += "&vacationManagementSearchYear="+vacationManagementSearchYear;
		pagingParam    += "&vacationManagementSearchGroupId="+vacationManagementSearchGroupId;
		
		let url = encodeURI("/webvacationmanagement/downloadVacationManagementExcel.do"+pagingParam);
		$("#attendanceSelectListForm").prop("action",url);
		$("#attendanceSelectListForm").submit();
	}
	else{
		modalEvent.warning("", "내려받기 권한이 없습니다.");
		return false;
	}
}

// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 휴무관리
// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
let holidayManagementColumnDefs = [
	{field: "checkbox", headerName:"", minWidth:55, maxWidth:55, headerCheckboxSelection: true, checkboxSelection: true},
	{field: "memberNameId", headerName:"이름(ID)", minWidth:150, maxWidth:150, cellStyle:{cursor: 'pointer', color:'#3985EA'}},
	{field: "groupName", headerName:"조직",minWidth:100, maxWidth:100},
	{field: "dutyName", headerName:"직무",minWidth:100 ,maxWidth:100},
	{field: "startEndDate", headerName:"휴무 기간",minWidth:100,maxWidth:100},
	{field: "days", headerName:"휴무 일수",minWidth:100, maxWidth:100},
	{field: "statusKorName", headerName:"상태",minWidth:100, maxWidth:100},
	{field: "etc", headerName:"메모",minWidth:200},
	{field: "cancelEtc", headerName:"취소사유",minWidth:200}
];

// let the grid know which columns and what data to use
let holidayManagementGridOptions = {
	suppressRowTransform: true,
	columnDefs: holidayManagementColumnDefs,
	defaultColDef: {		// 리스트 기본 설정
		flex: 1,
		sortable: true,		//정렬 여부
		resizable: true,	//리사이즈
		editable: true,	// 그리드에서 데이터 수정
		cellStyle:{textAlign:'left',fontSize:'14px',padding:'0'},
		//suppressSizeToFit:true,		//자동 맞춤
		//enableRowGroup: true,		// 그룹 묶음
		enablePivot: true,
		enableValue : true
	},
	//suppressMultiSort:true,  //단일솔트 true가 단일, false가 다중 shift + sort 시
	headerHeight : 41, // header 높이
	rowHeight : 41, // row 높이
	rowData : holidayManagementAgGridData,
	suppressRowClickSelection : true, // 로우 클릭시 체크박스 선택 true no, false yes
	localeText : {
		noRowsToShow : '조회 결과가 없습니다.'
	}, //데이터 없을 시 나오는 문구
	rowSelection : 'multiple', // row 다중 선택
	debug : false,
	onCellClicked: function(event){ //셀 클릭 이벤트
		/* alert(event.column.colId); */
		if('memberNameId'==event.column.colId){
			let status = event.data.status;
			
			if('D'!=status){
				fn_updateHolidayManagementPopup('H', event.data.muAttendanceId);
			}
			else{
				fn_cancelHolidayManagementPopup(event.data.muAttendanceId);
			}
		}
	},
	onSelectionChanged: function(event){ //체크박스 선택
		let selectRows = [];
		selectRows = event.api.getSelectedRows();
		holidayManagementSelectId = '';
		for(let i=0; i<selectRows.length; i++){
			holidayManagementSelectId += selectRows[i].muAttendanceId + ",";
		}
		holidayManagementSelectId = holidayManagementSelectId.substring(0, holidayManagementSelectId.lastIndexOf(','));
	},
	onSortChanged: function(event){
		 //정렬
		holidayManagementSort = ''; //기존 정렬 초기화
		let columnArr = event.columnApi.getColumnState();
		if(0<columnArr.length){
			//sort index 순으로 재정렬
			columnArr.sort(function(a,b){
				return a.sortIndex - b.sortIndex;
			});
			
			let nullCnt = 0;
			for(let i=0; i<columnArr.length; i++){
				let gridSortModel = columnArr[i].colId;
				let gridSort = columnArr[i].sort;
				
				if(gridSort != null){
					holidayManagementStart = 0;
					holidayManagementSort += gridSortModel+' '+ gridSort + ',';
				}
				else{
					nullCnt++;
					if(nullCnt == columnArr.length){
						holidayManagementSort = '';
						holidayManagementDir = '';
						holidayManagementStart = 0;
					}
				}
			}
		}
		holidayManagementSort = holidayManagementSort.substring(0,holidayManagementSort.lastIndexOf( ",")); //맨끝 콤마 지우기
		fn_holidayManagementSearch();
	}
};
// lookup the container we want the Grid to use
let holidayManagementGridDiv = document.querySelector('#holidayManagementGrid');

// create the grid passing in the div to use together with the columns & data we want to use
new agGrid.Grid(holidayManagementGridDiv, holidayManagementGridOptions);

// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 연차 관리
// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
let vacationManagementColumnDefs = [
	{field: "checkbox", headerName:"", minWidth:55, maxWidth:55, headerCheckboxSelection: true, checkboxSelection: true},
	{field: "memberNameId", headerName:"이름(ID)", minWidth:150, maxWidth:150, cellStyle:{cursor: 'pointer', color:'#3985EA'}},
	{field: "groupName", headerName:"조직",maxWidth:100},
	{field: "dutyName", headerName:"직무",maxWidth:100},
	{field: "days", headerName:"발행 연차 수",minWidth:130, maxWidth:120,cellStyle:{cursor: 'pointer', color:'#3985EA'}},
	{field: "useAttendanceCount", headerName:"사용",minWidth:100, maxWidth:100},
	{field: "unuseAttendanceCount", headerName:"잔여",minWidth:100, maxWidth:100},
	{field: "year", headerName:"발행연도",minWidth:140,maxWidth:140},
	{field: "startEndDate", headerName:"사용기한",minWidth:180,maxWidth:180},
	{field: "etc", headerName:"메모",minWidth:200}
];

// let the grid know which columns and what data to use
let vacationManagementGridOptions = {
	suppressRowTransform: true,
	columnDefs: vacationManagementColumnDefs,
	defaultColDef: {		// 리스트 기본 설정
		flex: 1,
		sortable: true,		//정렬 여부
		resizable: true,	//리사이즈
		editable: true,	// 그리드에서 데이터 수정
		cellStyle:{textAlign:'left',fontSize:'14px',padding:'0'},
		//suppressSizeToFit:true,		//자동 맞춤
		//enableRowGroup: true,		// 그룹 묶음
		enablePivot: true,
		enableValue : true
	},
	//suppressMultiSort:true,  //단일솔트 true가 단일, false가 다중 shift + sort 시
	headerHeight : 41, // header 높이
	rowHeight : 41, // row 높이
	rowData : vacationManagementAgGridData,
	suppressRowClickSelection : true, // 로우 클릭시 체크박스 선택 true no, false yes
	localeText : {
		noRowsToShow : '조회 결과가 없습니다.'
	}, //데이터 없을 시 나오는 문구
	rowSelection : 'multiple', // row 다중 선택
	debug : false,
	onCellClicked: function(event){ //셀 클릭 이벤트
		/* alert(event.column.colId); */
		if('memberNameId'==event.column.colId){
			fn_updateVacationManagementIntro(event.data.muVacationManagementId, event.data.year);
		}
		if('days'==event.column.colId){
			fn_updateVacationManagementPopup(event.data);
		}
	},
	onSelectionChanged: function(event){ //체크박스 선택
		let selectRows = [];
		selectRows = event.api.getSelectedRows();
		
		vacationManagementSelectId = '';
		for(let i=0; i<selectRows.length; i++){
			vacationManagementSelectId += selectRows[i].muVacationManagementId + ",";
		}
		vacationManagementSelectId = vacationManagementSelectId.substring(0, vacationManagementSelectId.lastIndexOf(','));
	},
	onSortChanged: function(event){
		 //정렬
		vacationManagementSort = ''; //기존 정렬 초기화
		let columnArr = event.columnApi.getColumnState();
		if(0<columnArr.length){
			//sort index 순으로 재정렬
			columnArr.sort(function(a,b){
				return a.sortIndex - b.sortIndex;
			});
			
			let nullCnt = 0;
			for(let i=0; i<columnArr.length; i++){
				let gridSortModel = columnArr[i].colId;
				let gridSort = columnArr[i].sort;
				
				if(gridSort != null){
					vacationManagementStart = 0;
					vacationManagementSort += gridSortModel+' '+ gridSort + ',';
				}
				else{
					nullCnt++;
					
					if(nullCnt == columnArr.length){
						vacationManagementSort = '';
						vacationManagementDir = '';
						vacationManagementStart = 0;
					}
				}
			}
		}
		vacationManagementSort = vacationManagementSort.substring(0,vacationManagementSort.lastIndexOf( ",")); //맨끝 콤마 지우기
		fn_vacationManagementSearch();
	}
};
// lookup the container we want the Grid to use
let vacationManagementGridDiv = document.querySelector('#vacationManagementGrid');

// create the grid passing in the div to use together with the columns & data we want to use
new agGrid.Grid(vacationManagementGridDiv, vacationManagementGridOptions);




/****************************************************************************
* 페이지 init
****************************************************************************/
function fn_pageInit(){
	// 첫번째 탭 - 근태관리 조회
	// 조직 옵션 조회
	fn_setAttendanceGroupCombo();

	// 날짜 datepicker
	// fn_searchDatePicker("#div_attendanceSearchStartDate", "#div_attendanceSearchEndDate");

	// if(!attendanceSearchStartDate&&!attendanceSearchEndDate){
	// 	// 검색 오늘날짜 셋팅
	// 	fn_attendanceSetDate('D');
	// }
	// else{
	// 	$("#attendanceSearchStartDate").val(attendanceSearchStartDate).trigger("change");
	// 	$("#attendanceSearchEndDate").val(attendanceSearchEndDate).trigger("change");
	// }
	$('#attendanceSearchDate').datetimepicker({
		allowInputToggle: true,
		viewMode: 'months',
		format: 'YYYY-MM',
		defaultDate: moment().format('YYYY-MM')
	});

	if(!attendanceSearchDate){

	}
	else{
		$("#attendanceSearchDate").val(attendanceSearchDate);
	}
	if(!attendanceSearchGroupId){

	}
	else{
		$('#li_'+attendanceSearchGroupId).click();
	}

	$("#attendanceSearchKeyword").val(attendanceSearchKeywordParam);
	fn_attendanceSearch("A");
}

/****************************************************************************
* 페이지 event
****************************************************************************/
function fn_pageEvent(){
	// 근태 관리 - 검색 input
	$(document).on('keypress', '#attendanceSearchKeyword', function(e) {
		fn_attendanceEnter(e);
	});

	// 근태 관리 - 검색 조회 버튼
	$("#btnSearchAttendance").click(function () {
		fn_attendanceSearch();
	});

	// 근태 관리 - 출퇴/휴무 등록 버튼
	$("#btnInsertAttendance").click(function () {
		fn_insertAttendancePopup();
	});

	// 근태 관리 - 연차 사용 버튼
	$("#btnInsertAttendanceVacationManagement").click(function () {
		fn_insertAttendanceVacationManagementPopup();
	});

	// 근태 관리 - 내려받기 버튼
	$("#btnDownloadAttendanceExcel").click(function () {
		fn_downloadAttendanceExcel();
	});

	// ////////////////////////////////////////////////////////////////////

	// 휴무 관리 - 검색 input
	$(document).on('keypress', '#holidayManagementSearchKeyword', function(e) {
		fn_holidayManagementEnter(e);
	});

	// 휴무 관리 - 검색 조회 버튼
	$("#btnSearchHolidayManagement").click(function () {
		fn_holidayManagementSearch();
	});

	// 휴무 관리 - 휴무 등록 버튼
	$("#btnInsertHolidayManagement").click(function () {
		fn_insertHolidayManagementPopup();
	});

	// 휴무 관리 - 내려받기 버튼
	$("#btnDownloadHolidayManagementExcel").click(function () {
		fn_downloadHolidayManagementExcel();
	});

	// ////////////////////////////////////////////////////////////////////

	// 휴무 관리 - 검색 input
	$(document).on('keypress', '#vacationManagementSearchKeyword', function(e) {
		fn_vacationManagementEnter(e);
	});

	// 휴무 관리 - 검색 조회 버튼
	$("#btnSearchVacationManagement").click(function () {
		fn_vacationManagementSearch();
	});

	// 휴무 관리 - 연차 발행 버튼
	$("#btnInsertVacationManagement").click(function () {
		fn_insertVacationManagementPopup();
	});

	// 휴무 관리 - 내려받기 버튼
	$("#btnDownloadVacationManagementExcel").click(function () {
		fn_downloadVacationManagementExcel();
	});

	// ////////////////////////////////////////////////////////////////////

	// 탭 이벤트
	$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
		let target = $(e.target).attr("href");

		if(('#attendance' == target)) {
			// 근태관리
			// 조직 옵션 조회
			fn_setAttendanceGroupCombo();

			// 날짜 datepicker
			// fn_searchDatePicker("#div_attendanceSearchStartDate", "#div_attendanceSearchEndDate");
			//
			// if(!attendanceSearchStartDate&&!attendanceSearchEndDate){
			// 	// 검색 오늘날짜 셋팅
			// 	fn_attendanceSetDate('D');
			// }
			// else{
			// 	$("#attendanceSearchStartDate").val(attendanceSearchStartDate).trigger("change");
			// 	$("#attendanceSearchEndDate").val(attendanceSearchEndDate).trigger("change");
			// }

			$('#attendanceSearchDate').datetimepicker({
				allowInputToggle: true,
				viewMode: 'months',
				format: 'YYYY-MM',
				defaultDate: moment().format('YYYY-MM')
			});

			if(!attendanceSearchDate){

			}
			else{
				$("#attendanceSearchDate").val(attendanceSearchDate);
			}

			if(!attendanceSearchGroupId){

			}
			else{
				$('#li_'+attendanceSearchGroupId).click();
			}

			$("#attendanceSearchKeyword").val(attendanceSearchKeywordParam);
			fn_attendanceSearch("A");
		}
		else if(('#holiday' == target)) {
			// 휴무관리
			// 조직 옵션 조회
			fn_setHolidayManagementGroupCombo();

			// 직무 조회
			fn_setHolidayManagementDutyCombo();

			// 초기 페이징 처리
			$('#holidayManagementSearchDate').datetimepicker({
				allowInputToggle: true,
				viewMode: 'months',
				format: 'YYYY-MM',
				defaultDate: moment().format('YYYY-MM')
			});

			if(!holidayManagementSearchDate){

			}
			else{
				$("#holidayManagementSearchDate").val(holidayManagementSearchDate);
			}

			if(!holidayManagementSearchGroupId){

			}
			else{
				$('#li_'+holidayManagementSearchGroupId).click();
			}

			if(!holidayManagementSearchDutyId){

			}
			else{
				$('#li_'+holidayManagementSearchDutyId).click();
			}

			$("#holidayManagementSearchKeyword").val(holidayManagementSearchKeywordParam);
			fn_holidayManagementSearch("A");
		}
		else if(('#vacation' == target)) {
			// 연차관리

			// 조직 옵션 조회
			fn_setVacationManagementGroupCombo();

			$("#vacationManagementSearchYear").datetimepicker({
				format: 'YYYY',
				viewMode: "years",
				defaultDate: moment().format('YYYY')
			});

			if(!vacationManagementSearchYear){

			}
			else{
				$("#vacationManagementSearchYear").val(vacationManagementSearchYear).trigger("change");
			}

			if(!vacationManagementSearchGroupId){

			}
			else{
				$('#li_'+vacationManagementSearchGroupId).click();
			}

			$("#vacationManagementSearchKeyword").val(vacationManagementSearchKeywordParam);
			fn_vacationManagementSearch("A");
		}
	});
}

$(function(){
	// 페이지 init
	fn_pageInit();

	// 페이지 event
	fn_pageEvent();
});