
/* ##############################################################
	설  명 : [Modal]진료/시술 검색 필터 팝업 (페이징처리되는 팝업)
	작성일 : 2023. 01. 19.
	작성자 : NTsoft
	수정일 	        수정자 	 수정내용
	-------         -------- ---------------------------
	2023. 01. 19.	NTsoft 	 최초 생성
*/
let treatmentProcedureSearchModal = {
	callback : null,
	reqParam : null,
	dataList : null,
	/*aggrid 및 검색관련*/
	searchKeywordParam : "",
	searchSort         : "",
	searchDir          : "",
	searchStart        : 0,
	searchLimit        : 100,
	totalCount         : 0,
	totalPages         : 0,
	agGridData         : [],
	columnDefs         : [],
	gridOptions        : {},
	/* 모달 초기화 작업 */
	init : function () {
		$('#treatmentProcedureSearchModal').remove();
		$('body').append( this.HtmlTemplate);
		
		//그리드 설정
		this.setGrid();
		
		//그리드 이벤트
		this.setEvent();
	},
	/* 페이징 처리 */
	pagination:function(page){
		searchStart = (parseInt(page)-1)*searchLimit;
		treatmentProcedureSearchModal.search();
	},
	/* 페이징 리셋 */
	paginReset:function(){
		treatmentProcedureSearchModal.searchKeywordParam = '';

		treatmentProcedureSearchModal.searchStart  = 0;
		treatmentProcedureSearchModal.searchLimit  = 100;
		treatmentProcedureSearchModal.totalCount   = 0;
		treatmentProcedureSearchModal.totalPages   = 0;
		
		//페이징 초기화
		if($("#treatmentProcedureSearchModal .pagination").data("twbs-pagination")){
			$("#treatmentProcedureSearchModal .pagination").twbsPagination("destroy");
		}
	},
	/* 검색하기 (초기화 후 검색) */
	resetSearch:function(){
		treatmentProcedureSearchModal.paginReset();
		
		treatmentProcedureSearchModal.searchKeywordParam = $("#treatmentProcedureSearchModal .searchKeyword").val();
		
		treatmentProcedureSearchModal.search();
	},
	/* 그리드 설정 */
	setGrid:function(){
		treatmentProcedureSearchModal.columnDefs = [
			{field: "treatmentName", headerName:"진료구분",minWidth:200, maxWidth:200},
			{field: "treatmentProcedureName", headerName:"시술명", minWidth:200, cellStyle:{cursor: 'pointer', color:'#3985EA'}}
		];
		
		// let the grid know which columns and what data to use
		treatmentProcedureSearchModal.gridOptions = {
			suppressRowTransform: true,
			columnDefs: treatmentProcedureSearchModal.columnDefs,
			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 : treatmentProcedureSearchModal.agGridData,
			suppressRowClickSelection : true, // 로우 클릭시 체크박스 선택 true no, false yes
			localeText : {
				noRowsToShow : '조회 결과가 없습니다.'
			}, //데이터 없을 시 나오는 문구
			rowSelection : 'multiple', // row 다중 선택
			debug : false,
			onCellClicked: function(event){ //셀 클릭 이벤트
				/* alert(event.column.colId); */
				if('treatmentProcedureName'==event.column.colId){
					treatmentProcedureSearchModal.setSelect(event.node.rowIndex);
				}
				
				treatmentProcedureSearchModal.setSelect();
			},
			onSelectionChanged: function(event){ //체크박스 선택
			},
			onSortChanged: function(event){
				 //정렬
				treatmentProcedureSearchModal.searchSort = ''; //기존 정렬 초기화
				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){
							treatmentProcedureSearchModal.searchStart = 0;
							treatmentProcedureSearchModal.searchSort += gridSortModel+' '+ gridSort + ',';
						}
						else{
							nullCnt++;
							if(nullCnt == columnArr.length){
								treatmentProcedureSearchModal.searchSort  = '';
								treatmentProcedureSearchModal.searchDir   = '';
								treatmentProcedureSearchModal.searchStart = 0;
							}
						}
					}
				}
				treatmentProcedureSearchModal.searchSort = treatmentProcedureSearchModal.searchSort.substring(0,treatmentProcedureSearchModal.searchSort.lastIndexOf( ",")); //맨끝 콤마 지우기
		
				treatmentProcedureSearchModal.resetSearch();
			}
		};
		
		// lookup the container we want the Grid to use
		let gridDiv = document.querySelector('#treatmentProcedureSearchModal .dataGrid');
		
		// create the grid passing in the div to use together with the columns & data we want to use
		new agGrid.Grid(gridDiv, treatmentProcedureSearchModal.gridOptions);
	},
	/* 그리드 이벤트 설정 */
	setEvent:function() {
		$('#treatmentProcedureSearchModal .btnCancle').on("click", function(){
			treatmentProcedureSearchModal.close();
		});
		
		$('#treatmentProcedureSearchModal .btnSave').on("click", function(){
			treatmentProcedureSearchModal.save("I");
		});
		
		/* 검색 */
		$('#treatmentProcedureSearchModal .search_btn').on("click", function(){
			treatmentProcedureSearchModal.resetSearch();
		});
		
		// 엔터 이벤트
		$(document).on('keypress', '#treatmentProcedureSearchModal .searchKeyword', function(e) {
			if(e.which){
				// 파이어폭스
				if(13 == e.which) {
					//로그인 액션 스크립트
					treatmentProcedureSearchModal.resetSearch();
				}
			}
			else{
				// 윈도우, 사파리, 크롬
				if(13 == event.keyCode) {
					//로그인 액션 스크립트
					treatmentProcedureSearchModal.resetSearch();
				}
			}
		});
	},
	/* 데이터 선택 */
	setSelect:function(selectNumber) {
		let checkedData = treatmentProcedureSearchModal.dataList[selectNumber];
		if(treatmentProcedureSearchModal.dataList==null||checkedData==undefined){
			return ;
		}
		
		if( treatmentProcedureSearchModal.callback )  {
			treatmentProcedureSearchModal.callback(checkedData);
		}
		treatmentProcedureSearchModal.close();
	},
	// 상세 조회
	search:function(state) {
		let formData = new FormData();
		formData.append("menuClass", menuClass);
		formData.append("treatmentProcedureSearchKeywordParam", treatmentProcedureSearchModal.searchKeywordParam);
		formData.append("treatmentProcedureSort", treatmentProcedureSearchModal.searchSort);
		formData.append("treatmentProcedureDir", treatmentProcedureSearchModal.searchDir);
		formData.append("treatmentProcedureStart", treatmentProcedureSearchModal.searchStart);
		formData.append("treatmentProcedureLimit", treatmentProcedureSearchModal.searchLimit);
		
		$.ajax({
			url: encodeURI('/webtreatmentprocedure/selectListTreatmentProcedureOption.do'),
			data: formData,
			dataType: "json",
			processData: false,
			contentType: false,
			type: 'POST',
			async: true,
			success: function(data){
				if('0'==data.msgCode){
					// 페이징 처리
					treatmentProcedureSearchModal.totalCount  = data.totalCount;
					//$("#txt_treatmentProcedureSearchModal.totalCount").text(treatmentProcedureSearchModal.totalCount);
					
					treatmentProcedureSearchModal.totalPages = Math.ceil(treatmentProcedureSearchModal.totalCount/treatmentProcedureSearchModal.searchLimit);
					
					// 리스트 조회
					treatmentProcedureSearchModal.dataList = data.rows;
					
					treatmentProcedureSearchModal.agGridData = data.rows;
					treatmentProcedureSearchModal.gridOptions.api.setRowData(treatmentProcedureSearchModal.agGridData);
	
					if(0<data.rows.length){
						//페이징 처리
						window.pagObj = $('#treatmentProcedureSearchModal .pagination').twbsPagination({
							startPage    : ((treatmentProcedureSearchModal.searchStart/treatmentProcedureSearchModal.searchLimit)+1),
							totalPages   : (treatmentProcedureSearchModal.totalPages==0)?1:treatmentProcedureSearchModal.totalPages,
							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) {
								treatmentProcedureSearchModal.pagination(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(){
				// 로딩열기
				treatmentProcedureSearchModal.gridOptions.api.showLoadingOverlay();
			},
			complete:function(){
				
			}
		});
	},
	/*
	 * 팝업
	 * callback : 콜백함수, reqParam: 팝업파라미터
	 */
	popup:function(callback, reqParam) {
		// 초기화 후 열기
		treatmentProcedureSearchModal.init();
		
		//콜백함수 지정.
		treatmentProcedureSearchModal.callback = callback;
		treatmentProcedureSearchModal.reqParam = reqParam;
		treatmentProcedureSearchModal.dataList = null;
		
		treatmentProcedureSearchModal.resetSearch();
		
		setTimeout(function(){
			$('#treatmentProcedureSearchModal').modal('show')
		}, 200);
	},
	/*
	 * 팝업 닫기
	 */
	close:function() {
		$('#treatmentProcedureSearchModal').modal('hide');

		setTimeout(function(){
			$('#treatmentProcedureSearchModal').remove();
		},500);
	},
	HtmlTemplate : `
	<div id="treatmentProcedureSearchModal" class="modal product_modal fade" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="">
		<div class="modal-dialog">
			<div class="modal-content">
				<div class="list1_modal_header">
					<label class="title">진료/시술 검색</label>
				</div>
				
				<div class="list1_modal_body">
					<div class="input_box">
						<div class="search_box">
							<img src="/image/web/search_B.svg"/>
							<input class="searchKeyword" type="text" placeholder="시술명"/>
						</div>
						<button class="search_btn">검색</button>
					</div>
					
					<div class="dataGrid modal_table_box ag-theme-balham"></div>
					
					<!-- 페이지게이션 -->
					<div class="page_box">
						<nav ria-label="Page navigation" class="navigation">
							<ul class="pagination"></ul>
						</nav>
					</div>
				</div>
				
				<div class="list1_modal_footer">
					<div class="btn_box">
						<button type="button" class="cancel_btn btnCancle">취소</button>
					</div>
				</div>
			</div>
		</div>
	</div>
    `
};