/* 페이징 관련 변수 */
let stockSumTotalCount   = 0;
let stockSumTotalPages   = 0;

/*aggird*/
let stockSumAgGridData = [];

let stockSumSelectId = "";

/****************************************************************************
* 현재고 품목수, 품목별재고수, 거래처수, 재고총액 조회 (현재고 상단)
****************************************************************************/
function fn_selectTotalStockSumCompany(){
	let formData = new FormData();
	formData.append("menuClass", menuClass);

	$.ajax({
		url: encodeURI('/webstocksum/selectTotalStockSumCompany.do'),
		data: formData,
		dataType: "json",
		processData: false,
		contentType: false,
		type: 'POST',
		async: true,
		success: function(data){
			if('0'==data.msgCode){
				$("#treatmentCount").text(data.rows[0].treatmentCount);
				$("#groupTreatmentCount").text(data.rows[0].groupTreatmentCount);
				$("#companyCount").text(data.rows[0].companyCount);
				$("#stockAmount").text(fn_numberFormat(data.rows[0].stockAmount));
			}
			else{
				modalEvent.danger("조회 오류", data.msgDesc);
			}
		},
		error : function(xhr, status, error) {
			modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
		},
		beforeSend:function(){
		},
		complete:function(){
		}
	});
}

/****************************************************************************
* 재고구분(진료) 콤보데이타 설정
****************************************************************************/
function fn_setTreatmentCombo(){
	// 대상
	const target = $("#stockSumTreatmentId").siblings("ul.select_option_list");
	let comboHTML = '<li id="li_treatmentAll" class="option_list_item">재고구분 전체</li>';
	target.empty().html(comboHTML).trigger("create");

	let category = fn_selectCategoryList2();
	let reservationCategory = category.find(cat => cat.categoryName === '재고구분');

	if (reservationCategory) {
		fn_selectModalOtherOption2(reservationCategory.categoryCode);
	}

	// 콤보 이벤트
	target.on("click","li.option_list_item",function () {
		// 1. 선택값 셋팅
		// let selectIdArr = $(this).prop("id").split('_');
		let selectId    = $(this).prop("id");
		let selectName  = $(this).text();

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

/****************************************************************************
* 거래처 콤보데이타 설정
****************************************************************************/
function fn_setCompanyCombo(){
	// 대상
	const target = $("#stockSumCompanyId").siblings("ul.select_option_list");

	// 데이터 조회
	let comboData = fn_selectListCompanyOption();
	
	// 조회 데이터 셋팅
	let comboHTML = '<li id="li_companyAll" class="option_list_item">거래처 전체</li>';
	
	for(let i = 0; i < comboData.length; i++){
		let muCompanyId     = comboData[i].muCompanyId;
		let companyName     = comboData[i].companyName;
		
		comboHTML += '<li id="li_'+muCompanyId+'" class="option_list_item">';
		comboHTML += '	<span>'+companyName+'</span>';
		comboHTML += '</li>';
	}
	target.empty().html(comboHTML).trigger("create");
	
	// 콤보 이벤트
	target.find("li.option_list_item").click(function () {
		// 1. 선택값 셋팅
		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_selectListStockSumCompany(){
	let formData = new FormData();
	formData.append("menuClass", menuClass);
	formData.append("stockSumSearchKeywordParam", stockSumSearchKeywordParam);
	formData.append("stockSumSort", stockSumSort);
	formData.append("stockSumDir", stockSumDir);
	formData.append("stockSumStart", stockSumStart);
	formData.append("stockSumLimit", stockSumLimit);
	formData.append("stockSumTreatmentId", stockSumTreatmentId);
	formData.append("stockSumCompanyId", stockSumCompanyId);

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

				stockSumTotalPages = Math.ceil(stockSumTotalCount/stockSumLimit);
				
				// 리스트 조회
				stockSumAgGridData = data.rows;
				stockSumGridOptions.api.setRowData(stockSumAgGridData);
				
				// if(0<data.rows.length){
				// 	//페이징 처리
				// 	window.pagObj = $('#stockSumPagination').twbsPagination({
				// 		startPage    : ((stockSumStart/stockSumLimit)+1),
				// 		totalPages   : (stockSumTotalPages==0)?1:stockSumTotalPages,
				// 		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_stockSumPagination(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(){
			// 로딩열기
			stockSumGridOptions.api.showLoadingOverlay();
		},
		complete:function(){
			
		}
	});
}

/****************************************************************************
* 검색하기
****************************************************************************/
function fn_stockSumSearch(param){
	if("A"!=param && "Y"!=selectUseYn){
		modalEvent.warning("", "조회 권한이 없습니다.");
		return false;
	}
	
	fn_stockSumPaginReset();
	
	stockSumTreatmentId   = $("#stockSumTreatmentId").val().split('_')[1]||'';
	stockSumCompanyId     = $("#stockSumCompanyId").val();
	
	stockSumSearchKeywordParam = $("#stockSumSearchKeyword").val();

	fn_selectListStockSumCompany();
}


/****************************************************************************
* 초기화하기
****************************************************************************/
function fn_stockSumReset(){
	
	$("#stockSumSearchKeyword").val("");

	fn_stockSumSearch();
}

/****************************************************************************
* 페이징 처리
****************************************************************************/
function fn_stockSumPagination(param){
	stockSumStart = (parseInt(param)-1)*stockSumLimit;
	
	fn_selectListStockSumCompany();
}

/****************************************************************************
* 페이징 리셋
****************************************************************************/
function fn_stockSumPaginReset(){
	stockSumSearchKeywordParam = '';

	stockSumStart        = 0;
	stockSumLimit        = 100;
	stockSumTotalCount   = 0;
	stockSumTotalPages   = 0;
	
	//페이징 초기화
	if($("#stockSumPagination").data("twbs-pagination")){
		$("#stockSumPagination").twbsPagination("destroy");
	}
}


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

/****************************************************************************
* 완료
****************************************************************************/
function fn_stockSumOk(){
	fn_stockSumReset();
}

/****************************************************************************
* 상세 리스트 화면으로 이동.
****************************************************************************/
function fn_selectListStockSumCompanyHistoryIntro(param, param2, param3){
	if("Y"==updateUseYn){
		// 수정가능
		let pagingParam = "?menuClass="+menuClass;
		pagingParam    += "&stockSumSearchKeywordParam="+stockSumSearchKeywordParam;
		pagingParam    += "&stockSumSort="+stockSumSort;
		pagingParam    += "&stockSumDir="+stockSumDir;
		pagingParam    += "&stockSumStart="+stockSumStart;
		pagingParam    += "&stockSumLimit="+stockSumLimit;
		pagingParam    += "&stockSumTreatmentId="+stockSumTreatmentId;
		pagingParam    += "&stockSumCompanyId="+stockSumCompanyId;
		pagingParam    += "&muTreatmentId="+param;
		pagingParam    += "&muProductId="+param2;
		pagingParam    += "&muCompanyId="+param3;
		
		fn_leftFormAction("/webstocksumhistory/selectListStockSumCompanyHistoryIntro.do"+pagingParam);
	}
	else{
		modalEvent.warning("", "수정 권한이 없습니다.");
		return false;
	}
	
}

/****************************************************************************
* 엑셀 다운 다운로드
****************************************************************************/
function fn_downloadStockSumExcel(){
	if("Y"==downloadUseYn){
		let pagingParam = "?menuClass="+menuClass;
		pagingParam    += "&stockSumSearchKeywordParam="+stockSumSearchKeywordParam;
		pagingParam    += "&stockSumSort="+stockSumSort;
		pagingParam    += "&stockSumDir="+stockSumDir;
		pagingParam    += "&stockSumStart="+stockSumStart;
		pagingParam    += "&stockSumLimit="+stockSumLimit;
		pagingParam    += "&stockSumTreatmentId="+stockSumTreatmentId;
		pagingParam    += "&stockSumCompanyId="+stockSumCompanyId;
		
		let url = encodeURI("/webstocksum/downloadStockSumCompanyExcel.do"+pagingParam);
		$("#stockSumSelectListForm").prop("action",url);
		$("#stockSumSelectListForm").submit();
	}
	else{
		modalEvent.warning("", "내려받기 권한이 없습니다.");
		return false;
	}
}

let stockSumColumnDefs = [
	/*{field: "checkbox", headerName:"", minWidth:55, maxWidth:55, headerCheckboxSelection: true, checkboxSelection: true},*/
	/* {field: "rowNum", headerName:"번호", minWidth:80,maxWidth:80, sortable: false}, */
	{field: "rowNum", headerName:"번호", minWidth:60,sortable: false, cellStyle:{textAlign: 'center'}},
	{field: "treatmentName", headerName:"재고구분", minWidth:180, maxWidth:180},
	{field: "productName", headerName:"제품명", minWidth:330,maxWidth:330, cellStyle:{cursor: 'pointer', color:'#3985EA'}},
	{field: "companyName", headerName:"거래처명",minWidth:330,maxWidth: 330},
	{field: "totalAvgPrice", headerName:"평균 단가",minWidth:330,maxWidth:330, cellStyle:{textAlign: 'right'}},
	{field: "totalQuantity", headerName:"재고 수량",minWidth:330,maxWidth:330, cellStyle:{textAlign: 'right'}}
];

// let the grid know which columns and what data to use
let stockSumGridOptions = {
	suppressRowTransform: true,
	columnDefs: stockSumColumnDefs,
	defaultColDef: {		// 리스트 기본 설정
		flex: 1,
		sortable: true,		//정렬 여부
		resizable: true,	//리사이즈
		editable: false,	// 그리드에서 데이터 수정
		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 : stockSumAgGridData,
	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){
			fn_selectListStockSumCompanyHistoryIntro(event.data.muTreatmentId, event.data.muProductId, event.data.muCompanyId);
		}
	},
	onSelectionChanged: function(event){ //체크박스 선택
		let selectRows = [];
		selectRows = event.api.getSelectedRows();
		
		stockSumSelectId = '';
		for(let i=0; i<selectRows.length; i++){
			stockSumSelectId += selectRows[i].muStockSumId + ",";
		}
		stockSumSelectId = stockSumSelectId.substring(0, stockSumSelectId.lastIndexOf(','));
	},
	onSortChanged: function(event){
		 //정렬
		stockSumSort = ''; //기존 정렬 초기화
		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){
					stockSumStart = 0;
					stockSumSort += gridSortModel+' '+ gridSort + ',';
				}
				else{
					nullCnt++;
					if(nullCnt == columnArr.length){
						stockSumSort = '';
						stockSumDir = '';
						stockSumStart = 0;
					}
				}
			}
		}
		stockSumSort = stockSumSort.substring(0,stockSumSort.lastIndexOf( ",")); //맨끝 콤마 지우기

		fn_stockSumSearch();
	}
};

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

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


/****************************************************************************
* 페이지 init
****************************************************************************/
function fn_pageInit(){
	// 현재고 재고품목수, 품목별 재고수, 거래처수, 재고총액 조회
	fn_selectTotalStockSumCompany();
	
	// 재고구분(진료) 콤보
	fn_setTreatmentCombo();
	
	// 거래처 콤보
	fn_setCompanyCombo();
	
	if(!stockSumTreatmentId){
		
	}else{
		$('#li_'+stockSumTreatmentId).click();
	}
	
	if(!stockSumCompanyId){
		
	}else{
		$('#li_'+stockSumCompanyId).click();
	}
	
	// 초기 페이징 처리
	$("#stockSumSearchKeyword").val(stockSumSearchKeywordParam);
	
	fn_stockSumSearch("A");
	
}

/****************************************************************************
* 페이지 event
****************************************************************************/
function fn_pageEvent(){
	// 검색 input
	$(document).on('keypress', '#stockSumSearchKeyword', function(e) {
		fn_stockSumEnter(e);
	});
	
	// 검색 조회 버튼
	$("#btnSearchStockSum").click(function () {
		fn_stockSumSearch();
	});
	
	// 입출고 현황 내려받기
	$("#btnDownloadStockSum").click(function () {
		fn_downloadStockSumExcel();
	});
}

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