
/* ##############################################################
	설  명 : [Modal]제품(약품) 검색 팝업
	작성일 : 2023. 01. 19.
	작성자 : NTsoft
	수정일 	        수정자 	 수정내용
	-------         -------- ---------------------------
	2023. 01. 19.	NTsoft 	 최초 생성
*/
/* 검색 관련 변수 */
let productSearchKeywordParam = "";
let productSort               = "";
let productDir                = "";
let productStart              = 0;
let productLimit              = 100;

/* 페이징 관련 변수 */
let productTotalCount   = 0;
let productTotalPages   = 0;

/*aggird*/
let productAgGridData  = [];
let productColumnDefs  = [];
let productGridOptions = {};

let productSearchModal = {
	callback : null,
	reqParam : null,
	dataList : null,
	/* 모달 초기화 작업 */
	init : function () {
		$('#productSearchModal').remove();
		$('body').append( this.HtmlTemplate);
		
		//그리드 설정
		this.setGrid();
		
		//그리드 이벤트
		this.setEvent();
	},
	/* 그리드 설정 */
	setGrid:function(){
		productSearchKeywordParam = "";
		productSort               = "";
		productDir                = "";

		productAgGridData  = [];
		productColumnDefs  = [];
		productGridOptions = {};

		productColumnDefs = [
			{field: "treatmentName", headerName:"재고구분",minWidth:100, maxWidth:100},
			{field: "companyName", headerName:"거래처명",minWidth:100},
			{field: "productName", headerName:"제품명", minWidth:100, cellStyle:{cursor: 'pointer', color:'#3985EA'}},
			{field: "volume", headerName:"용량",minWidth:60, maxWidth:100},
			{field: "unitName", headerName:"단위",minWidth:60, maxWidth:100},
			{field: "price", headerName:"단가(원)",minWidth:100, maxWidth:100},
			{field: "quantity", headerName:"재고수량",minWidth:60, maxWidth:100}
		];
		
		// let the grid know which columns and what data to use
		productGridOptions = {
			suppressRowTransform: true,
			columnDefs: productColumnDefs,
			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 : productAgGridData,
			suppressRowClickSelection : true, // 로우 클릭시 체크박스 선택 true no, false yes
			localeText : {
				noRowsToShow : '조회 결과가 없습니다.'
			}, //데이터 없을 시 나오는 문구
			rowSelection : 'multiple', // row 다중 선택
			debug : false,
			onCellClicked: function(event){ //셀 클릭 이벤트
				/* alert(event.column.colId); */
				if('productName'==event.column.colId){
					productSearchModal.setSelect(event.data);
				}
				
				productSearchModal.setSelect();
			},
			onSelectionChanged: function(event){ //체크박스 선택
			},
			onSortChanged: function(event){
				 //정렬
				productSort = ''; //기존 정렬 초기화
				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){
							productStart = 0;
							productSort += gridSortModel+' '+ gridSort + ',';
						}
						else{
							nullCnt++;
							if(nullCnt == columnArr.length){
								productSort = '';
								productDir = '';
								productStart = 0;
							}
						}
					}
				}
				productSort = productSort.substring(0,productSort.lastIndexOf( ",")); //맨끝 콤마 지우기
		
				fn_searchModal_procedureSearch();
			}
		};
		
		// lookup the container we want the Grid to use
		let productGridDiv = document.querySelector('#modalProductGrid');
		
		// create the grid passing in the div to use together with the columns & data we want to use
		new agGrid.Grid(productGridDiv, productGridOptions);
	},
	/* 그리드 이벤트 설정 */
	setEvent:function() {
		$('#productSearchModal .btnCancle').on("click", function(){
			productSearchModal.close();
		});
		
		$('#productSearchModal #modalSearchProductBtn').on("click", function(){
			fn_searchModal_procedureSearch();
		});
	},
	/* 데이터 선택 */
	setSelect:function(param) {
		let checkedData = param;
		if(dataList==null||checkedData==undefined){
			return ;
		}
		
		if( productSearchModal.callback )  {
			productSearchModal.callback(checkedData);
		}
		productSearchModal.close();
	},
	// 상세 조회
	search:function() {
		
		let muTreatmentId  = productSearchModal.reqParam.muTreatmentId;
			
		let formData = new FormData();
		formData.append("menuClass", menuClass);
		formData.append("productSearchKeywordParam", productSearchKeywordParam);
		formData.append("productSort", productSort);
		formData.append("productDir", productDir);

		$.ajax({
			url: encodeURI('/webproduct/selectListProductOption.do'),
			data: formData,
			dataType: "json",
			processData: false,
			contentType: false,
			type: 'POST',
			async: true,
			success: function(data){
				if('0'==data.msgCode){
					dataList = data.rows;
					
					productAgGridData = data.rows;
					productGridOptions.api.setRowData(productAgGridData);
				}
				else{
					modalEvent.danger("조회 오류", data.msgDesc);
				}
			},
			error : function(xhr, status, error) {
				modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
			},
			beforeSend:function(){
				// 로딩열기
				productGridOptions.api.showLoadingOverlay();
			},
			complete:function(){
				
			}
		});
	},
	/*
	 * 팝업
	 * callback : 콜백함수, reqParam: 팝업파라미터
	 */
	popup:function(callback, reqParam) {
		// 초기화 후 열기
		productSearchModal.init();
		
		//콜백함수 지정.
		productSearchModal.callback = callback;
		productSearchModal.reqParam = reqParam;
		productSearchModal.dataList = null;
		
		productSearchModal.search();
		
		setTimeout(function(){
			$('#productSearchModal').modal('show')
		}, 200);
	},
	/*
	 * 팝업 닫기
	 */
	close:function() {
		$('#productSearchModal').modal('hide');

		setTimeout(function(){
			$('#productSearchModal').remove();
		},500);
	},
	HtmlTemplate : `
	<div id="productSearchModal" 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 id="modalSearchKeyword" type="text" placeholder="제품명"/>
						</div>
						<button id="modalSearchProductBtn">검색</button>
					</div>
					
					<div id="modalProductGrid" class="modal_table_box ag-theme-balham"></div>
				</div>
				
				<div class="list1_modal_footer">
					<div class="btn_box">
						<button type="button" class="cancel_btn btnCancle">취소</button>
					</div>
				</div>
			</div>
		</div>
	</div>
    `
};

/****************************************************************************
* 페이징 처리
****************************************************************************/
function fn_searchModal_procedurePagination(param){
	procedureStart = (parseInt(param)-1)*procedureLimit;
	
	productSearchModal.search();
}

/****************************************************************************
* 페이징 리셋
****************************************************************************/
function fn_searchModal_procedurePaginReset(){
	productSearchKeywordParam = '';

	//페이징 초기화
	if($("#modalProductPagination").data("twbs-pagination")){
		$("#modalProductPagination").twbsPagination("destroy");
	}
}

/****************************************************************************
* 검색하기
****************************************************************************/
function fn_searchModal_procedureSearch(){
	
	fn_searchModal_procedurePaginReset();
	
	productSearchKeywordParam = $("#productSearchModal #modalSearchKeyword").val();
	
	productSearchModal.search();
}

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