/* 페이징 관련 변수 */
let stockCloseDetailTotalCount   = 0;
let stockCloseDetailTotalPages   = 0;

/*aggird*/
let stockCloseDetailAgGridData = [];

let stockCloseDetailSelectId = "";

function fn_selectTotalStockSumCompany(){
	let formData = new FormData();
	formData.append("menuClass", menuClass);
	formData.append("muStockCloseId", muStockCloseId);
	$.ajax({
		url: encodeURI('/webstockclosedetail/selectTotalStockCloseDetail.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 = $("#stockCloseDetailTreatmentId").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 = $("#stockCloseDetailCompanyId").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_selectListStockCloseDetail(){
	let formData = new FormData();
	formData.append("menuClass", menuClass);
	formData.append("stockCloseDetailSearchKeywordParam", stockCloseDetailSearchKeywordParam);
	formData.append("stockCloseDetailSort", stockCloseDetailSort);
	formData.append("stockCloseDetailDir", stockCloseDetailDir);
	formData.append("stockCloseDetailStart", stockCloseDetailStart);
	formData.append("stockCloseDetailLimit", stockCloseDetailLimit);
	formData.append("stockCloseDetailTreatmentId", stockCloseDetailTreatmentId);
	formData.append("stockCloseDetailCompanyId", stockCloseDetailCompanyId);
	formData.append("muStockCloseId", muStockCloseId);

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

				stockCloseDetailTotalPages = Math.ceil(stockCloseDetailTotalCount/stockCloseDetailLimit);
				
				// 리스트 조회
				stockCloseDetailAgGridData = data.rows;
				stockCloseDetailGridOptions.api.setRowData(stockCloseDetailAgGridData);
				
				// if(0<data.rows.length){
				// 	//페이징 처리
				// 	window.pagObj = $('#stockCloseDetailPagination').twbsPagination({
				// 		startPage    : ((stockCloseDetailStart/stockCloseDetailLimit)+1),
				// 		totalPages   : (stockCloseDetailTotalPages==0)?1:stockCloseDetailTotalPages,
				// 		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_stockCloseDetailPagination(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(){
			// 로딩열기
			stockCloseDetailGridOptions.api.showLoadingOverlay();
		},
		complete:function(){
			
		}
	});
}

/****************************************************************************
* 검색하기
****************************************************************************/
function fn_stockCloseDetailSearch(param){
	if("A"!=param && "Y"!=selectUseYn){
		modalEvent.warning("", "조회 권한이 없습니다.");
		return false;
	}
	
	fn_stockCloseDetailPaginReset();
	
	stockCloseDetailTreatmentId   = $("#stockCloseDetailTreatmentId").val();
	stockCloseDetailCompanyId     = $("#stockCloseDetailCompanyId").val();
	
	stockCloseDetailSearchKeywordParam = $("#stockCloseDetailSearchKeyword").val();

	fn_selectListStockCloseDetail();
}


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

	fn_stockCloseDetailSearch();
}

/****************************************************************************
* 페이징 처리
****************************************************************************/
function fn_stockCloseDetailPagination(param){
	stockCloseDetailStart = (parseInt(param)-1)*stockCloseDetailLimit;
	
	fn_selectListStockCloseDetail();
}

/****************************************************************************
* 페이징 리셋
****************************************************************************/
function fn_stockCloseDetailPaginReset(){
	stockCloseDetailSearchKeywordParam = '';

	stockCloseDetailStart        = 0;
	stockCloseDetailLimit        = 100;
	stockCloseDetailTotalCount   = 0;
	stockCloseDetailTotalPages   = 0;
	
	//페이징 초기화
	if($("#stockCloseDetailPagination").data("twbs-pagination")){
		$("#stockCloseDetailPagination").twbsPagination("destroy");
	}
}


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

/****************************************************************************
* 완료
****************************************************************************/
function fn_stockCloseDetailOk(){
	fn_stockCloseDetailReset();
}

/****************************************************************************
* 엑셀 다운 다운로드
****************************************************************************/
function fn_downloadStockCloseDetailExcel(){
	if("Y"==downloadUseYn){
		let pagingParam = "?menuClass="+menuClass;
		pagingParam    += "&stockCloseDetailSearchKeywordParam="+stockCloseDetailSearchKeywordParam;
		pagingParam    += "&stockCloseDetailSort="+stockCloseDetailSort;
		pagingParam    += "&stockCloseDetailDir="+stockCloseDetailDir;
		pagingParam    += "&stockCloseDetailStart="+stockCloseDetailStart;
		pagingParam    += "&stockCloseDetailLimit="+stockCloseDetailLimit;
		pagingParam    += "&stockCloseDetailTreatmentId="+stockCloseDetailTreatmentId;
		pagingParam    += "&stockCloseDetailCompanyId="+stockCloseDetailCompanyId;
		pagingParam    += "&muStockCloseId="+muStockCloseId;
		
		let url = encodeURI("/webstockclosedetail/downloadStockCloseDetailExcel.do"+pagingParam);
		$("#stockCloseDetailSelectListForm").prop("action",url);
		$("#stockCloseDetailSelectListForm").submit();
	}
	else{
		modalEvent.warning("", "내려받기 권한이 없습니다.");
		return false;
	}
}

function fn_selectStockCloseDetailPopup(param, param2, param3){
	let reqParam =  {
		"muStockCloseId" : muStockCloseId,
		"muTreatmentId" : param,
		"muProductId"   : param2,
		"muCompanyId"   : param3
	};
	
	stockCloseDetailSelectModal.popup(function(obj, reqParam) {
		fn_stockCloseDetailOk();
	}, reqParam);
}

function fn_stockCloseDetailCancel(){
	let pagingParam = "?menuClass="+menuClass;
	pagingParam    += "&stockCloseSort="+stockCloseSort;
	pagingParam    += "&stockCloseDir="+stockCloseDir;
	pagingParam    += "&stockCloseStart="+stockCloseStart;
	pagingParam    += "&stockCloseLimit="+stockCloseLimit;
	pagingParam    += "&stockCloseSearchStartDate="+stockCloseSearchStartDate;
	pagingParam    += "&stockCloseSearchEndDate="+stockCloseSearchEndDate;
	pagingParam    += "&stockCloseSearchDateType="+stockCloseSearchDateType;
	
	fn_leftFormAction("/webstockclose/selectListStockCloseIntro.do"+pagingParam);
}

let stockCloseDetailColumnDefs = [
	/*{field: "checkbox", headerName:"", minWidth: columnWidth, maxWidth: columnWidth, headerCheckboxSelection: true, checkboxSelection: true},*/
	/* {field: "rowNum", headerName:"번호", minWidth: columnWidth, maxWidth: columnWidth, sortable: false}, */	
	{headerName : '번호', spanHeaderHeight: true, wrapHeaderText: true, autoHeaderHeight: true, field: "rowNum", minWidth:60, sortable: false, cellStyle:{textAlign: 'center'}, headerClass: "center-header"},
	{field: "companyName", spanHeaderHeight: true, wrapHeaderText: true, autoHeaderHeight: true, headerName:"거래처명", minWidth: 120},
	{field: "treatmentName", spanHeaderHeight: true, wrapHeaderText: true, autoHeaderHeight: true, headerName:"재고 구분", minWidth: 100, maxWidth: 100},
	{field: "productName", spanHeaderHeight: true, wrapHeaderText: true, autoHeaderHeight: true, headerName:"제품명", minWidth: 100/*, cellStyle:{cursor: 'pointer', color:'#3985EA'}*/},	
	{headerName : '이월', children: [
		{field: "r_price", headerName:"단가", minWidth: 90, maxWidth: 90, cellStyle:{textAlign: 'right'}},
		{field: "r_quantity", headerName:"수량", minWidth: 60, maxWidth: 60, cellStyle:{textAlign: 'right'}},
		{field: "r_totalAmount", headerName:"금액", minWidth: 90, maxWidth: 90, cellStyle:{textAlign: 'right'}}
	], cellStyle:{textAlign: 'right'}},
	{headerName : '입고', children: [
		{field: "i_price", headerName:"단가", minWidth: 90, maxWidth: 90, cellStyle:{textAlign: 'right'}},
		{field: "i_quantity", headerName:"수량", minWidth: 60, maxWidth: 60, cellStyle:{textAlign: 'right'}},
		{field: "i_totalAmount", headerName:"금액", minWidth: 90, maxWidth: 90, cellStyle:{textAlign: 'right'}}
	], cellStyle:{textAlign: 'right'}},
	{headerName : '실사용', children: [
		{field: "u_price", headerName:"단가", minWidth: 90, maxWidth: 90, cellStyle:{textAlign: 'right'}},
		{field: "u_quantity", headerName:"수량", minWidth: 60, maxWidth: 60, cellStyle:{textAlign: 'right'}},
		{field: "u_totalAmount", headerName:"금액", minWidth: 90, maxWidth: 90, cellStyle:{textAlign: 'right'}}
	], cellStyle:{textAlign: 'right'}},
	{headerName : '과부족', children: [
		{field: "m_price", headerName:"단가", minWidth: 90, maxWidth: 90, cellStyle:{textAlign: 'right'}},
		{field: "m_quantity", headerName:"수량", minWidth: 60, maxWidth: 60, cellStyle:{textAlign: 'right'}},
		{field: "m_totalAmount", headerName:"금액", minWidth: 90, maxWidth: 90, cellStyle:{textAlign: 'right'}}
	], cellStyle:{textAlign: 'right'}},
	{headerName : '실재 재고', children: [
		{field: "price", headerName:"단가", minWidth: 90, maxWidth: 90, cellStyle:{textAlign: 'right'}},
		{field: "quantity", headerName:"수량", minWidth: 60, maxWidth: 60, cellStyle:{textAlign: 'right'}},
		{field: "totalAmount", headerName:"금액", minWidth: 90, maxWidth: 90, cellStyle:{textAlign: 'right'}}
	], cellStyle:{textAlign: 'right'}},	
	{headerName : '사유', spanHeaderHeight: true, wrapHeaderText: true, autoHeaderHeight: true, field: "ETC", minWidth: 90, maxWidth: 90, cellStyle:{textAlign: 'right'}},	
	
];

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

		fn_stockCloseDetailSearch();
	}
};

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

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


/****************************************************************************
* 페이지 init
****************************************************************************/
function fn_pageInit(){
	// 뒤로가기 버튼 이벤트 및 노출
	$(".back").removeAttr("onclick");
	$(".back").attr("onclick", "fn_stockCloseDetailCancel();");
	$(".back").show();
	
	// 현재고 재고품목수, 품목별 재고수, 거래처수, 재고총액 조회
	fn_selectTotalStockSumCompany();
	
	// 재고구분(진료) 콤보
	fn_setTreatmentCombo();
	
	// 거래처 콤보
	fn_setCompanyCombo();
	
	// 초기 페이징 처리
	$("#stockCloseDetailSearchKeyword").val(stockCloseDetailSearchKeywordParam);
	
	fn_stockCloseDetailSearch("A");
	
}

/****************************************************************************
* 페이지 event
****************************************************************************/
function fn_pageEvent(){
	// 검색 input
	$(document).on('keypress', '#stockCloseDetailSearchKeyword', function(e) {
		fn_stockCloseDetailEnter(e);
	});
	
	// 검색 조회 버튼
	$("#btnSearchStockCloseDetail").click(function () {
		fn_stockCloseDetailSearch();
	});
	
	// 재고마감 상세 내려받기
	$("#btnDownloadStockCloseDetail").click(function () {
		fn_downloadStockCloseDetailExcel();
	});
}

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