/*aggird*/
let vacationManagementSubAgGridData = [];
let vacationManagementSubSelectId = "";
let muMemberId='';
/****************************************************************************
* 연차관리 정보 상세 조회 (List)
****************************************************************************/
function fn_selectListVacationManagementSub(){
	let formData = new FormData();
	formData.append("menuClass", menuClass);
	formData.append("year", year);
	formData.append("muVacationManagementId", muVacationManagementId);
	
	$.ajax({
		url: encodeURI('/webvacationmanagement/selectVacationManagement.do'),
		data: formData,
		dataType: "json",
		processData: false,
		contentType: false,
		type: 'POST',
		async: true,
		success: function(data){
			if('0'==data.msgCode){
				// 연차 사용내역 조회
				muMemberId = data.memberRows[0].muMemberId;
				vacationManagementSubAgGridData = data.rows;
				vacationManagementSubGridOptions.api.setRowData(vacationManagementSubAgGridData);
				
				// 연차 사용자 정보 조회
				$("#memberNameId").text(data.memberRows[0].memberName+'('+data.memberRows[0].loginId+')');
				$("#groupName").text(data.memberRows[0].groupName);
				$("#dutyName").text(data.memberRows[0].dutyName);
			}
		},
		error : function(xhr, status, error) {
			modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
		},
		beforeSend:function(){
			// 로딩열기
			vacationManagementSubGridOptions.api.showLoadingOverlay();
		},
		complete:function(){
			
		}
	});
}

/****************************************************************************
* 수정 화면으로 이동.
****************************************************************************/
function fn_vacationManagementCancel(){
	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;

	fn_leftFormAction("/webattendance/selectListAttendanceIntro.do"+pagingParam);
}

/****************************************************************************
* 페이지 init
****************************************************************************/
function fn_pageInit(){
	// 뒤로가기 버튼 이벤트 및 노출
	$(".back").removeAttr("onclick");
	$(".back").attr("onclick", "fn_vacationManagementCancel();");
	$(".back").show();
	
	$("#vacationManagementSubSearchYear").datetimepicker({
		format: 'YYYY',
		viewMode: "years", 
		defaultDate: moment().format('YYYY')
	});

	if(!year){

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

	fn_selectListVacationManagementSub();
}
/****************************************************************************
 * 연차취소
 ****************************************************************************/
function fn_cancelVacationManagement(){
	let reqParam =  {
		"muAttendanceId" : vacationManagementSubSelectId
	};
	if(true != fn_emptyCheck(reqParam.muAttendanceId)){
		modalEvent.warning("수정", "선택된 취소 대상이 없습니다.");
		return;
	}
	if("Y"==updateUseYn){
		// 수정가능
		attendVacationManagementCancelEtcModal.popup(function(obj, reqParam) {
			fn_pageInit();
		}, reqParam);
	}
	else{
		modalEvent.warning("수정", "수정 권한이 없습니다.");
		return;
	}

}
/****************************************************************************
 * 연차상세
 ****************************************************************************/
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_selectAttendanceVacationManagementPopup(param, param2){
	if("Y"==selectUseYn){
		let reqParam =  {
			"muAttendanceId"  : param,
			"muMemberId"      : param2
		};

		attendanceVacationManagerSelectModal.popup(function(obj, reqParam) {
			fn_attendanceOk();
		}, reqParam);
	}
	else{
		modalEvent.warning("", "조회 권한이 없습니다.");
		return false;
	}

}
/****************************************************************************
 * 엑셀 다운 다운로드
 ****************************************************************************/
function fn_downloadVacationManagement(){
	if("Y"==downloadUseYn){
		// 수정가능
		let pagingParam = "?menuClass="+menuClass;
		pagingParam    += "&vacationManagementSort="+vacationManagementSort;
		pagingParam    += "&vacationManagementDir="+vacationManagementDir;
		pagingParam    += "&vacationManagementStart="+vacationManagementStart;
		pagingParam    += "&vacationManagementLimit="+vacationManagementLimit;
		pagingParam    += "&vacationManagementSearchYear="+year;
		pagingParam    += "&muVacationManagementId="+muVacationManagementId;

		var url = encodeURI("/webvacationmanagement/downloadVacationManagementDetailExcel.do"+pagingParam);
		$("#excelForm").prop("action",url);
		$("#excelForm").submit();
	}
	else{
		modalEvent.warning("", "내려받기 권한이 없습니다.");
		return false;
	}
}
/****************************************************************************
 * 검색하기
 ****************************************************************************/
function fn_vacationManagementSearch(param){
	if("A"!=param && "Y"!=selectUseYn){
		modalEvent.warning("", "조회 권한이 없습니다.");
		return false;
	}

	vacationManagementSubSearchYear = $("#vacationManagementSubSearchYear").val();

	fn_selectListVacationManagementSub();
}
/****************************************************************************
* 페이지 event
****************************************************************************/
function fn_pageEvent(){
	// 연차 취소 버튼
	$("#btnCancelVacationManagement").click(function () {
		fn_cancelVacationManagement();
	});

	// 엑셀다운로드 버튼
	$("#btnDownloadVacationManagement").click(function () {
		fn_downloadVacationManagement();
	});
	//조회 검색 버튼
	$("#btnSearchVacationManagement").click(function () {
		fn_vacationManagementSearch("A");
	});
}

$(function(){
	// 페이지 init
	fn_pageInit();
	
	// 페이지 event
	fn_pageEvent();
});
function symbolsRender(param){
	if(0<param.value){
		return '+'+param.value;
	}else{
		return param.value;
	}
}
let vacationManagementSubColumnDefs = [
	{field: "checkbox", headerName:"", minWidth:55, maxWidth:55, headerCheckboxSelection: true, checkboxSelection: true},
	{field: "attendanceTypeKorName", headerName:"사용구분", minWidth:150, maxWidth:150, cellStyle:{cursor: 'pointer', color:'#3985EA'}},
	{field: "muAttendanceId",hide:true},
	{field: "startEndDate", headerName:"사용일",minWidth:200},
	{field: "useDays", headerName:"사용 수",minWidth:150, maxWidth:150, cellRenderer: symbolsRender},
	{field: "days", headerName:"잔여",minWidth:150, maxWidth:150},
	{field: "etc", headerName:"메모",minWidth:200},
	{field: "cancelEtc", headerName:"취소사유",minWidth:200},
	{field: "status", headerName:"상태",minWidth:100, maxWidth:150}
];

// let the grid know which columns and what data to use
let vacationManagementSubGridOptions = {
	suppressRowTransform: true,
	columnDefs: vacationManagementSubColumnDefs,
	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 : vacationManagementSubAgGridData,
	suppressRowClickSelection : true, // 로우 클릭시 체크박스 선택 true no, false yes
	localeText : {
		noRowsToShow : '조회 결과가 없습니다.'
	}, //데이터 없을 시 나오는 문구
	rowSelection : 'multiple', // row 다중 선택
	debug : false,
	onCellClicked: function(event){ //셀 클릭 이벤트
		if(event.column.colId=='attendanceTypeKorName') {
			if('D'===event.data.statusType)
				fn_selectAttendanceVacationManagementPopup(event.data.muAttendanceId, muMemberId);
			if('D'!==event.data.statusType) {
				fn_updateAttendanceVacationManagementPopup(event.data.muAttendanceId, muMemberId);
			}
		}
	},
	onSelectionChanged: function(event){ //체크박스 선택
		let selectRows = [];
		selectRows = event.api.getSelectedRows();

		vacationManagementSubSelectId = '';
		for(let i=0; i<selectRows.length; i++){
			vacationManagementSubSelectId += selectRows[i].muAttendanceId + ",";
		}
		vacationManagementSubSelectId = vacationManagementSubSelectId.substring(0, vacationManagementSubSelectId.lastIndexOf(','));
	},
	onSortChanged: function(event){
		 //정렬
		vacationManagementSubSort = ''; //기존 정렬 초기화
		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){
					vacationManagementSubStart = 0;
					vacationManagementSubSort += gridSortModel+' '+ gridSort + ',';
				}
				else{
					nullCnt++;
					
					if(nullCnt == columnArr.length){
						vacationManagementSubSort = '';
						vacationManagementSubDir = '';
						vacationManagementSubStart = 0;
					}
				}
			}
		}
		vacationManagementSubSort = vacationManagementSubSort.substring(0,vacationManagementSubSort.lastIndexOf( ",")); //맨끝 콤마 지우기

		fn_vacationManagementSubSearch();
	}
};

// lookup the container we want the Grid to use
let vacationManagementSubGridDiv = document.querySelector('#vacationManagementSubGrid');

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