/* 페이징 관련 변수 */
let stockSumHistoryTotalCount   = 0;
let stockSumHistoryTotalPages   = 0;

/*aggird*/
let stockSumHistoryAgGridData = [];

let stockSumHistorySelectId = "";

/****************************************************************************
* 현재고 상세 리스트 상단 - 제품명, 거래처, 평균입고단가, 재고수량, 재고금액 조회
****************************************************************************/
function fn_selectTotalStockSumCompanyHistory(){
	let formData = new FormData();
	formData.append("menuClass", menuClass);
	formData.append("muTreatmentId", muTreatmentId);
	formData.append("muCompanyId", muCompanyId);
	formData.append("muProductId", muProductId);

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

/****************************************************************************
* 현재 재고 제품별 거래처 - 상세 리스트
****************************************************************************/
function fn_selectListStockSumCompany(){
	let formData = new FormData();
	formData.append("menuClass", menuClass);
	formData.append("stockSumHistorySearchKeywordParam", stockSumHistorySearchKeywordParam);
	formData.append("stockSumHistorySort", stockSumHistorySort);
	formData.append("stockSumHistoryDir", stockSumHistoryDir);
	formData.append("stockSumHistoryStart", stockSumHistoryStart);
	formData.append("stockSumHistoryLimit", stockSumHistoryLimit);
	formData.append("muTreatmentId", muTreatmentId);
	formData.append("muCompanyId", muCompanyId);
	formData.append("muProductId", muProductId);

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

				stockSumHistoryTotalPages = Math.ceil(stockSumHistoryTotalCount/stockSumHistoryLimit);
				
				// 리스트 조회
				stockSumHistoryAgGridData = data.rows;
				stockSumHistoryGridOptions.api.setRowData(stockSumHistoryAgGridData);
				
				// if(0<data.rows.length){
				// 	//페이징 처리
				// 	window.pagObj = $('#stockSumHistoryPagination').twbsPagination({
				// 		startPage    : ((stockSumHistoryStart/stockSumHistoryLimit)+1),
				// 		totalPages   : (stockSumHistoryTotalPages==0)?1:stockSumHistoryTotalPages,
				// 		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_stockSumHistoryPagination(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(){
			// 로딩열기
			stockSumHistoryGridOptions.api.showLoadingOverlay();
		},
		complete:function(){
			
		}
	});
}

/****************************************************************************
* 검색하기
****************************************************************************/
function fn_stockSumHistorySearch(param){
	if("A"!=param && "Y"!=selectUseYn){
		modalEvent.warning("", "조회 권한이 없습니다.");
		return false;
	}
	
	fn_stockSumHistoryPaginReset();
	
	stockSumHistorySearchKeywordParam = $("#stockSumHistorySearchKeyword").val();

	fn_selectListStockSumCompany();
}


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

	fn_stockSumHistorySearch();
}

/****************************************************************************
* 페이징 처리
****************************************************************************/
function fn_stockSumHistoryPagination(param){
	stockSumHistoryStart = (parseInt(param)-1)*stockSumHistoryLimit;
	
	fn_selectListStockSumCompany();
}

/****************************************************************************
* 페이징 리셋
****************************************************************************/
function fn_stockSumHistoryPaginReset(){
	stockSumHistorySearchKeywordParam = '';

	stockSumHistoryStart        = 0;
	stockSumHistoryLimit        = 100;
	stockSumHistoryTotalCount   = 0;
	stockSumHistoryTotalPages   = 0;
	
	//페이징 초기화
	if($("#stockSumHistoryPagination").data("twbs-pagination")){
		$("#stockSumHistoryPagination").twbsPagination("destroy");
	}
}


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

function fn_stockSumHistoryCancel(){
	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;
	
	fn_leftFormAction("/webstocksum/selectListStockSumCompanyIntro.do"+pagingParam);
}


let stockSumHistoryColumnDefs = [
	/*{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: "inDate", headerName:"입고 날짜", minWidth:120, maxWidth:120},
	{field: "productName", headerName:"제품명", minWidth:215},
	{field: "companyName", headerName:"거래처명",minWidth:215},
	{field: "price", headerName:"단가",minWidth:130, maxWidth:130, cellStyle:{textAlign: 'right'}},
	{field: "quantity", headerName:"수량",minWidth:90, maxWidth:90, cellStyle:{textAlign: 'right'}},
	{field: "amount", headerName:"금액",minWidth:130, maxWidth:130, cellStyle:{textAlign: 'right'}},
	{field: "etc", headerName:"메모",minWidth:619}
];

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

		fn_stockSumHistorySearch();
	}
};

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

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


/****************************************************************************
* 페이지 init
****************************************************************************/
function fn_pageInit(){
	// 뒤로가기 버튼 이벤트 및 노출
	$(".back").removeAttr("onclick");
	$(".back").attr("onclick", "fn_stockSumHistoryCancel();");
	$(".back").show();
	
	// 현재고 상세 제품명, 거래처, 평균 입고단가, 재고수량, 재고총액 조회
	fn_selectTotalStockSumCompanyHistory();
	
	// 초기 페이징 처리
	$("#stockSumHistorySearchKeyword").val(stockSumHistorySearchKeywordParam);
	
	fn_stockSumHistorySearch("A");
	
}

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

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