/* 페이징 관련 변수 */
let stockSumAdjustmentTotalCount   = 0;
let stockSumAdjustmentTotalPages   = 0;

/*aggird*/
let stockSumAdjustmentAgGridData = [];

let stockSumAdjustmentSelectId = "";

/****************************************************************************
* 현재고 품목수, 품목별재고수, 거래처수, 재고총액 조회 (현재고 상단)
****************************************************************************/
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 = $("#stockSumAdjustmentTreatmentId").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.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_setCompanyCombo(){
	// 대상
	const target = $("#stockSumAdjustmentCompanyId").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_selectListStockSumAdjustment(){
	let formData = new FormData();
	formData.append("menuClass", menuClass);
	formData.append("stockSumAdjustmentSearchKeywordParam", stockSumAdjustmentSearchKeywordParam);
	formData.append("stockSumAdjustmentSort", stockSumAdjustmentSort);
	formData.append("stockSumAdjustmentDir", stockSumAdjustmentDir);
	formData.append("stockSumAdjustmentStart", stockSumAdjustmentStart);
	formData.append("stockSumAdjustmentLimit", stockSumAdjustmentLimit);
	formData.append("stockSumAdjustmentTreatmentId", stockSumAdjustmentTreatmentId);
	formData.append("stockSumAdjustmentCompanyId", stockSumAdjustmentCompanyId);

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

				stockSumAdjustmentTotalPages = Math.ceil(stockSumAdjustmentTotalCount/stockSumAdjustmentLimit);
				
				// 리스트 조회
				stockSumAdjustmentAgGridData = data.rows;
				stockSumAdjustmentGridOptions.api.setRowData(stockSumAdjustmentAgGridData);
				
				// if(0<data.rows.length){
				// 	//페이징 처리
				// 	window.pagObj = $('#stockSumAdjustmentPagination').twbsPagination({
				// 		startPage    : ((stockSumAdjustmentStart/stockSumAdjustmentLimit)+1),
				// 		totalPages   : (stockSumAdjustmentTotalPages==0)?1:stockSumAdjustmentTotalPages,
				// 		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_stockSumAdjustmentPagination(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(){
			// 로딩열기
			stockSumAdjustmentGridOptions.api.showLoadingOverlay();
		},
		complete:function(){
			
		}
	});
}

/****************************************************************************
* 검색하기
****************************************************************************/
function fn_stockSumAdjustmentSearch(param){
	if("A"!=param && "Y"!=selectUseYn){
		modalEvent.warning("", "조회 권한이 없습니다.");
		return false;
	}
	
	fn_stockSumAdjustmentPaginReset();
	
	stockSumAdjustmentTreatmentId  = $("#stockSumAdjustmentTreatmentId").val();
	stockSumAdjustmentCompanyId    = $("#stockSumAdjustmentCompanyId").val();
	
	stockSumAdjustmentSearchKeywordParam = $("#stockSumAdjustmentSearchKeyword").val();

	fn_selectListStockSumAdjustment();
}


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

	fn_stockSumAdjustmentSearch();
}

/****************************************************************************
* 페이징 처리
****************************************************************************/
function fn_stockSumAdjustmentPagination(param){
	stockSumAdjustmentStart = (parseInt(param)-1)*stockSumAdjustmentLimit;
	
	fn_selectListStockSumAdjustment();
}

/****************************************************************************
* 페이징 리셋
****************************************************************************/
function fn_stockSumAdjustmentPaginReset(){
	stockSumAdjustmentSearchKeywordParam = '';

	stockSumAdjustmentStart        = 0;
	stockSumAdjustmentLimit        = 100;
	stockSumAdjustmentTotalCount   = 0;
	stockSumAdjustmentTotalPages   = 0;
	
	//페이징 초기화
	if($("#stockSumAdjustmentPagination").data("twbs-pagination")){
		$("#stockSumAdjustmentPagination").twbsPagination("destroy");
	}
}


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

/****************************************************************************
* 완료
****************************************************************************/
function fn_stockSumAdjustmentOk(){
	fn_stockSumAdjustmentReset();
}

function fn_updateStockSumAdjustmentDetailPopup(param, param2, param3){
	let reqParam =  {
		"muTreatmentId" : param,
		"muProductId" : param2,
		"muCompanyId" : param3
	};
	
	if("Y"==updateUseYn){
		// 수정가능
		stockSumAdjustmentDetailUpdateModal.popup(function(obj, reqParam) {
			fn_stockSumAdjustmentOk();
		}, reqParam);
	}
}


/****************************************************************************
* 엑셀 다운 다운로드
****************************************************************************/
function fn_downloadStockSumAdjustmentExcel(){
	if("Y"==downloadUseYn){
		let pagingParam = "?menuClass="+menuClass;
		pagingParam    += "&stockSumAdjustmentSearchKeywordParam="+stockSumAdjustmentSearchKeywordParam;
		pagingParam    += "&stockSumAdjustmentSort="+stockSumAdjustmentSort;
		pagingParam    += "&stockSumAdjustmentDir="+stockSumAdjustmentDir;
		pagingParam    += "&stockSumAdjustmentStart="+stockSumAdjustmentStart;
		pagingParam    += "&stockSumAdjustmentLimit="+stockSumAdjustmentLimit;
		pagingParam    += "&stockSumAdjustmentTreatmentId="+stockSumAdjustmentTreatmentId;
		pagingParam    += "&stockSumAdjustmentCompanyId="+stockSumAdjustmentCompanyId;
		
		let url = encodeURI("/webstocksumadjustment/downloadStockSumAdjustmentExcel.do"+pagingParam);
		$("#stockSumAdjustmentSelectListForm").prop("action",url);
		$("#stockSumAdjustmentSelectListForm").submit();
	}
	else{
		modalEvent.warning("", "내려받기 권한이 없습니다.");
		return false;
	}
}

let stockSumAdjustmentColumnDefs = [
	/*{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:150, maxWidth:150},
	{field: "productName", headerName:"제품명", minWidth:380, cellStyle:{cursor: 'pointer', color:'#3985EA'}},
	{field: "companyName", headerName:"거래처명", minWidth:375},
	{field: "avgPrice", headerName:"평균단가", minWidth:230, maxWidth:230, cellStyle:{textAlign: 'right'}},
	{field: "quantity", headerName:"재고수량", minWidth:150, maxWidth:150, cellStyle:{textAlign: 'right'}},
	{field: "amount", headerName:"재고금액",minWidth:230, maxWidth:230, cellStyle:{textAlign: 'right'}}
];

// let the grid know which columns and what data to use
let stockSumAdjustmentGridOptions = {
	suppressRowTransform: true,
	columnDefs: stockSumAdjustmentColumnDefs,
	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 : stockSumAdjustmentAgGridData,
	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_updateStockSumAdjustmentDetailPopup(event.data.muTreatmentId, event.data.muProductId, event.data.muCompanyId);
		}
	},
	onSelectionChanged: function(event){ //체크박스 선택
		let selectRows = [];
		selectRows = event.api.getSelectedRows();
		
		stockSumAdjustmentSelectId = '';
		for(let i=0; i<selectRows.length; i++){
			stockSumAdjustmentSelectId += selectRows[i].muStockSumId + ",";
		}
		stockSumAdjustmentSelectId = stockSumAdjustmentSelectId.substring(0, stockSumAdjustmentSelectId.lastIndexOf(','));
	},
	onSortChanged: function(event){
		 //정렬
		stockSumAdjustmentSort = ''; //기존 정렬 초기화
		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){
					stockSumAdjustmentStart = 0;
					stockSumAdjustmentSort += gridSortModel+' '+ gridSort + ',';
				}
				else{
					nullCnt++;
					if(nullCnt == columnArr.length){
						stockSumAdjustmentSort = '';
						stockSumAdjustmentDir = '';
						stockSumAdjustmentStart = 0;
					}
				}
			}
		}
		stockSumAdjustmentSort = stockSumAdjustmentSort.substring(0,stockSumAdjustmentSort.lastIndexOf( ",")); //맨끝 콤마 지우기

		fn_stockSumAdjustmentSearch();
	}
};

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

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


/****************************************************************************
* 페이지 init
****************************************************************************/
function fn_pageInit(){

	// 현재고 재고품목수, 품목별 재고수, 거래처수, 재고총액 조회
	fn_selectTotalStockSumCompany();
	
	// 재고구분(진료) 콤보
	fn_setTreatmentCombo();
	
	// 거래처 콤보
	fn_setCompanyCombo();
	
	// 초기 페이징 처리
	$("#stockSumAdjustmentSearchKeyword").val(stockSumAdjustmentSearchKeywordParam);

	//재고조정 페이지 메뉴 위치조정(재고마감상세페이지 css 동일)
	$(".sub_menu_list").css('margin-top','0px');

	fn_stockSumAdjustmentSearch("A");
	
}

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

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