/* 페이징 관련 변수 */
let memberTotalCount = 0;
let memberTotalPages = 0;

/*aggird*/
let memberAgGridData = [];

let memberSelectId   = "";

/****************************************************************************
* 직원 정보 리스트 조회
****************************************************************************/
function fn_selectListMemberJson(){
	let formData = new FormData();
	formData.append("menuClass", menuClass);
	formData.append("memberSearchKeywordParam", memberSearchKeywordParam);
	formData.append("memberSort", memberSort);
	formData.append("memberDir", memberDir);
	formData.append("memberStart", memberStart);
	formData.append("memberLimit", memberLimit);
	formData.append("memberSearchGroupId", memberSearchGroupId);
	formData.append("memberSearchDutyId", memberSearchDutyId);
	formData.append("memberSearchAuthId", memberSearchAuthId);

	$.ajax({
		url: encodeURI('/webmember/selectListMember.do'),
		data: formData,
		dataType: "json",
		processData: false,
		contentType: false,
		type: 'POST',
		async: true,
		success: function(data){
			if('0'==data.msgCode){
				// 페이징 처리
				memberTotalCount  = data.totalCount;
				//$("#memberTotalCount").text(memberTotalCount);
				
				memberTotalPages = Math.ceil(memberTotalCount/memberLimit);
				
				// 리스트 조회
				memberAgGridData = data.rows;
				memberGridOptions.api.setRowData(memberAgGridData);
				
				if(0<data.rows.length){
					//페이징 처리
					window.pagObj = $('#memberPagination').twbsPagination({
						startPage    : ((memberStart/memberLimit)+1),
						totalPages   : (memberTotalPages==0)?1:memberTotalPages,
						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_memberPagination(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(){
			// 로딩열기
			memberGridOptions.api.showLoadingOverlay();
		},
		complete:function(){
			
		}
	});
}

/****************************************************************************
* 검색하기
****************************************************************************/
function fn_memberSearch(param){
	if("A"!=param && "Y"!=selectUseYn){
		modalEvent.warning("", "조회 권한이 없습니다.");
		return false;
	}
	
	fn_memberPaginReset();
	
	memberSearchGroupId  = $("#searchGroupId").val();
	memberSearchDutyId   = $("#searchDutyId").val();
	memberSearchAuthId   = $("#searchAuthId").val();

	memberSearchKeywordParam = $("#memberSearchKeyword").val();

	fn_selectListMemberJson();
}


/****************************************************************************
* 초기화하기
****************************************************************************/
function fn_memberReset(){
	// 조직
	fn_setGroupCombo();
	
	// 직무
	fn_setDutyCombo();
	
	// 권한
	fn_setAuthCombo();
	
	// 조직
	$('#li_groupAll').click();
	
	// 직무
	$('#li_dutyAll').click();
	
	// 권한
	$('#li_authAll').click();
	
	$("#memberSearchKeyword").val('');
	
	fn_memberSearch();
}

/****************************************************************************
* 페이징 처리
****************************************************************************/
function fn_memberPagination(param){
	memberStart = (parseInt(param)-1)*memberLimit;
	
	fn_selectListMemberJson();
}

/****************************************************************************
* 페이징 리셋
****************************************************************************/
function fn_memberPaginReset(){
	memberSearchKeywordParam = '';
	
	memberStart        = 0;
	memberLimit        = 100;
	memberTotalCount   = 0;
	memberTotalPages   = 0;
	
	//페이징 초기화
	if($("#memberPagination").data("twbs-pagination")){
		$("#memberPagination").twbsPagination("destroy");
	}
}

/****************************************************************************
* 직원 비활성화
****************************************************************************/
function fn_updateMemberStatus(){
	if("Y"!=updateUseYn){
		modalEvent.warning("", "수정 권한이 없습니다.");
		return false;
	}
	
	if(!memberSelectId){
		modalEvent.warning("", "비활성화할 대상을 선택하세요.");
		return false;
	}

	modalEvent.info("비활성화", "선택한 직원의 계정을 비활성화하시겠습니까?", function(){
		let formData = new FormData();
		formData.append("menuClass", menuClass);
		formData.append("selectId", memberSelectId);
		
		$.ajax({
			url: encodeURI('/webmember/updateMemberStatus.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_memberSearch();
					});
				}
				else{
					modalEvent.danger("비활성화 오류", data.msgDesc);
				}
			},
			error : function(xhr, status, error) {
				modalEvent.danger("비활성화 오류", "비활성화 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
			},
			beforeSend:function(){
				
			},
			complete:function(){
				
			}
		});
	});
}

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

/****************************************************************************
* 조직 옵션 조회
****************************************************************************/
function fn_setGroupCombo(){
	// 대상
	const target = $("#searchGroupId").siblings("ul.select_option_list");

	// 데이터 조회
	let comboData = fn_selectListGroupOption();
	
	// 조회 데이터 셋팅
	let comboHTML = '<li id="li_groupAll" 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_setDutyCombo(){
	// 대상
	const target = $("#searchDutyId").siblings("ul.select_option_list");
	
	// 데이터 조회
	let comboData = fn_selectListDutyOption();
	
	// 조회 데이터 셋팅
	let comboHTML = '<li id="li_dutyAll" 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_setAuthCombo(){
	// 대상
	const target = $("#searchAuthId").siblings("ul.select_option_list");

	// 데이터 조회
	let comboData = fn_selectListAuthOption();
	
	// 조회 데이터 셋팅
	let comboHTML = '<li id="li_groupAll" class="option_list_item">권한 전체</li>';
	
	for(let i = 0; i < comboData.length; i++){
		let muAuthId     = comboData[i].muAuthId;
		let authName     = comboData[i].authName;
		
		comboHTML += '<li id="li_'+muAuthId+'" class="option_list_item">'+authName+'</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_memberOk(){
	fn_memberReset();
}

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

function fn_updateMemberPopup(param){
	let reqParam =  {
		"muMemberId" : param
	};
	
	if("Y"==updateUseYn){
		// 수정가능
		memberUpdateModal.popup(function(obj, reqParam) {
			fn_memberOk();
		}, reqParam);
	}
	else{
		// 조회만
		memberSelectModal.popup(function(obj, reqParam) {
			fn_memberOk();
		}, reqParam);
	}
	
}

/****************************************************************************
* 수정 화면으로 이동.
****************************************************************************/
function fn_updateMemberIntro(param){
	if("Y"==updateUseYn){
		// 수정가능
		let pagingParam = "?menuClass="+menuClass;
		pagingParam    += "&memberSearchKeywordParam="+memberSearchKeywordParam;
		pagingParam    += "&memberSort="+memberSort;
		pagingParam    += "&memberDir="+memberDir;
		pagingParam    += "&memberStart="+memberStart;
		pagingParam    += "&memberLimit="+memberLimit;
		pagingParam    += "&memberSearchGroupId="+memberSearchGroupId;
		pagingParam    += "&memberSearchDutyId="+memberSearchDutyId;
		pagingParam    += "&memberSearchAuthId="+memberSearchAuthId;
		pagingParam    += "&muMemberId="+param;
		
		fn_leftFormAction("/webmember/updateMemberIntro.do"+pagingParam);
	}
	else{
		if("Y"==selectUseYn){
			let reqParam =  {
				"muMemberId" : param
			};
			// 조회만
			memberSelectModal.popup(function(obj, reqParam) {
				fn_memberOk();
			}, reqParam);
		}
		else{
			modalEvent.warning("", "조회 및 수정 권한이 없습니다.");
			return false;
		}
	}
	
}

/****************************************************************************
* 엑셀 다운 다운로드
****************************************************************************/
function fn_downloadMemberExcel(){
	if("Y"==downloadUseYn){
		// 수정가능
		let pagingParam = "?menuClass="+menuClass;
		pagingParam    += "&memberSearchKeywordParam="+memberSearchKeywordParam;
		pagingParam    += "&memberSort="+memberSort;
		pagingParam    += "&memberDir="+memberDir;
		pagingParam    += "&memberStart="+memberStart;
		pagingParam    += "&memberLimit="+memberLimit;
		pagingParam    += "&memberSearchGroupId="+memberSearchGroupId;
		pagingParam    += "&memberSearchDutyId="+memberSearchDutyId;
		pagingParam    += "&memberSearchAuthId="+memberSearchAuthId;
		
		let url = encodeURI("/webmember/downloadMemberExcel.do"+pagingParam);
		$("#memberSelectListForm").prop("action",url);
		$("#memberSelectListForm").submit();
	}
	else{
		modalEvent.warning("", "내려받기 권한이 없습니다.");
		return false;
	}
}



function fn_phoneFormatter(params){
	return fn_setFormatPhone(params.value);
}

let memberColumnDefs = [
	/*{field: "checkbox", headerName:"", minWidth:55, maxWidth:55, headerCheckboxSelection: true, checkboxSelection: true},*/
	/* {field: "rowNum", headerName:"번호", minWidth:80,maxWidth:80, sortable: false}, */
	{field: "orderNumber", headerName:"번호", minWidth:60,sortable: false, cellStyle:{textAlign: 'center'}},
	{field: "memberCode", headerName:"사번",minWidth:100, maxWidth:100},
	{field: "typeName", headerName:"유형",minWidth:100, maxWidth:100},
	{field: "memberName", headerName:"이름", minWidth:150, maxWidth:150, cellStyle:{cursor: 'pointer', color:'#3985EA'}},
	{field: "loginId", headerName:"아이디", minWidth:180, maxWidth:180},
	{field: "groupName", headerName:"조직",minWidth:120,maxWidth:120},
	{field: "dutyName", headerName:"직무",minWidth:100,maxWidth:100},
	{field: "email", headerName:"이메일",minWidth:270, maxWidth:270},
	{field: "phoneNumber", headerName:"연락처",minWidth:150, maxWidth:150, valueFormatter: fn_phoneFormatter},
	{field: "authName", headerName:"권한",minWidth:120, maxWidth:120},
	{field: "status", headerName:"상태",minWidth:100, maxWidth:100},
	{field: "writeDate", headerName:"작성일자",minWidth:123, maxWidth:123}
];

// let the grid know which columns and what data to use
let memberGridOptions = {
	suppressRowTransform: true,
	columnDefs: memberColumnDefs,
	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 : memberAgGridData,
	suppressRowClickSelection : true, // 로우 클릭시 체크박스 선택 true no, false yes
	localeText : {
		noRowsToShow : '조회 결과가 없습니다.'
	}, //데이터 없을 시 나오는 문구
	rowSelection : 'multiple',        // row 다중 선택
	debug : false,
	onCellClicked: function(event){   //셀 클릭 이벤트
		/* alert(event.column.colId); */
		if('memberName'==event.column.colId){
			fn_updateMemberIntro(event.data.muMemberId);
		}
	},
	onSelectionChanged: function(event){ //체크박스 선택
		let selectRows = [];
		selectRows = event.api.getSelectedRows();
		
		memberSelectId = '';
		for(let i=0; i<selectRows.length; i++){
			memberSelectId += selectRows[i].muMemberId + ",";
		}
		memberSelectId = memberSelectId.substring(0, memberSelectId.lastIndexOf(','));
	},
	onSortChanged: function(event){
		 //정렬
		memberSort = ''; //기존 정렬 초기화
		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){
					memberStart = 0;
					memberSort += gridSortModel+' '+ gridSort + ',';
				}
				else{
					nullCnt++;
					
					if(nullCnt == columnArr.length){
						memberSort  = '';
						memberDir   = '';
						memberStart = 0;
					}
				}
			}
		}
		memberSort = memberSort.substring(0,memberSort.lastIndexOf( ",")); //맨끝 콤마 지우기
		
		fn_memberSearch();
	}
};

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

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


/****************************************************************************
* 페이지 init
****************************************************************************/
function fn_pageInit(){
	// 조직
	fn_setGroupCombo();
	
	// 직무
	fn_setDutyCombo();
	
	// 권한
	fn_setAuthCombo();
	
	// 초기 페이징 처리
	if(!memberSearchGroupId){
		
	}else{
		$('#li_'+memberSearchGroupId).click();
	}
	
	if(!memberSearchDutyId){
		
	}else{
		$('#li_'+memberSearchDutyId).click();
	}
	
	if(!memberSearchAuthId){
		
	}else{
		$('#li_'+memberSearchAuthId).click();
	}
	
	$("#memberSearchKeyword").val(memberSearchKeywordParam);
	
	fn_memberSearch("A");
}

/****************************************************************************
* 페이지 event
****************************************************************************/
function fn_pageEvent(){
	// 검색 input
	$(document).on('keypress', '#memberSearchKeyword', function(e) {
		fn_memberEnter(e);
	});
	
	// 검색 조회 버튼
	$("#btnSearchMember").click(function () {
		fn_memberSearch();
	});
	
	// 직원등록 팝업 버튼
	$("#btnInsertMember").click(function () {
		fn_insertMemberPopup();
	});
	
	// 직원등록 팝업 버튼
	$("#btnDownloadMemberExcel").click(function () {
		fn_downloadMemberExcel();
	});
}

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