/* 페이징 관련 변수 */
let stockHistoryTotalCount   = 0;
let stockHistoryTotalPages   = 0;

/*aggird*/
let stockHistoryAgGridData = [];

let stockHistorySelectId = "";



/****************************************************************************
* 입출고내역 상단 거래처정보 및 각 타입별 수량/금액 조회
****************************************************************************/
function fn_selectStockHistory(){
	let formData = new FormData();
	formData.append("menuClass", menuClass);
	formData.append("stockHistorySearchStartDate", stockHistorySearchStartDate);
	formData.append("stockHistorySearchEndDate", stockHistorySearchEndDate);
	formData.append("stockHistorySearchDateType", stockHistorySearchDateType);
	formData.append("muTreatmentId", muTreatmentId);
	formData.append("muProductId", muProductId);
	formData.append("muCompanyId", muCompanyId);

	$.ajax({
		url: encodeURI('/webstockhistory/selectStockHistory.do'),
		data: formData,
		dataType: "json",
		processData: false,
		contentType: false,
		type: 'POST',
		async: true,
		success: function(data){
			if('0'==data.msgCode){
				// 입출고내역 상단 거래처정보
				$("#productName").text(data.companyRows[0].productName);
				$("#volumeUnitName").text('('+data.companyRows[0].volume+data.companyRows[0].unitName+')');
				$("#companyName").text(data.companyRows[0].companyName);
				$("#businessNumber").text(data.companyRows[0].businessNumber);
				$("#userName").text(data.companyRows[0].userName);
				$("#phoneNumber").text(fn_setFormatPhone(data.companyRows[0].phoneNumber));
				$("#email").text(data.companyRows[0].email);
				
				// 각 타입별 수량/금액 조회
				$("#inTotalQuantity").text(data.rows[0].inTotalQuantity);
				$("#inTotalAmount").text(data.rows[0].inTotalAmount);
				$("#uOutTotalQuantity").text(data.rows[0].uOutTotalQuantity);
				$("#uOutTotalAmount").text(data.rows[0].uOutTotalAmount);
				$("#sOutTotalQuantity").text(data.rows[0].sOutTotalQuantity);
				$("#sOutTotalAmount").text(data.rows[0].sOutTotalAmount);
				$("#rOutTotalQuantity").text(data.rows[0].rOutTotalQuantity);
				$("#rOutTotalAmount").text(data.rows[0].rOutTotalAmount);
				$("#dOutTotalQuantity").text(data.rows[0].dOutTotalQuantity);
				$("#dOutTotalAmount").text(data.rows[0].dOutTotalAmount);
				$("#eOutTotalQuantity").text(data.rows[0].eOutTotalQuantity);
				$("#eOutTotalAmount").text(data.rows[0].eOutTotalAmount);
				$("#aaInTotalQuantity").text(data.rows[0].aaInTotalQuantity);
				$("#aaInTotalAmount").text(data.rows[0].aaInTotalAmount);
				$("#adOutTotalQuantity").text(data.rows[0].adOutTotalQuantity);
				$("#adOutTotalAmount").text(data.rows[0].adOutTotalAmount);
			}
			else{
				modalEvent.danger("조회 오류", data.msgDesc);
			}
		},
		error : function(xhr, status, error) {
			modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
		},
		beforeSend:function(){
			
		},
		complete:function(){
			
		}
	});
}

/****************************************************************************
* 검색 날짜 설정
//(A:오늘, B:3일, C:7일, D:최근30일, E:최근90일, F:이번달, G:올해, H:지난주, I:지난달)
****************************************************************************/
function fn_stockHistorySetDate(param){
	if("A"==param){
		// 오늘
		let toDate = new Date();
		let year  = toDate.getFullYear();
		let month = toDate.getMonth() + 1;
		let day   = toDate.getDate();
		
		if(month < 10) month = "0" + month;
		if(day < 10) day = "0" + day;
		
		stockHistorySearchStartDate = year+'-'+month+'-'+day;
		stockHistorySearchEndDate   = year+'-'+month+'-'+day;
	}
	else if("B"==param){
		// 3일
		// 검색 종료일자
		let toDate = new Date();
		let year  = toDate.getFullYear();
		let month = toDate.getMonth() + 1;
		let day   = toDate.getDate();
		
		if(month < 10) month = "0" + month;
		if(day < 10) day = "0" + day;
		
		stockHistorySearchEndDate   = year+'-'+month+'-'+day;
		
		// 검색 시작일자
		toDate.setDate(toDate.getDate() - 3);
		year  = toDate.getFullYear();
		month = toDate.getMonth() + 1;
		day   = toDate.getDate();
		
		if(month < 10) month = "0" + month;
		if(day < 10) day = "0" + day;
		
		stockHistorySearchStartDate = year+'-'+month+'-'+day;
	}
	else if("C"==param){
		// 이번주
		// 검색 종료일자
		let toDate = new Date();
		let year  = toDate.getFullYear();
		let month = toDate.getMonth() + 1;
		let day   = toDate.getDate();
		
		if(month < 10) month = "0" + month;
		if(day < 10) day = "0" + day;
		
		stockHistorySearchEndDate   = year+'-'+month+'-'+day;
		
		// 검색 시작일자
		toDate.setDate(toDate.getDate() - 7);
		year  = toDate.getFullYear();
		month = toDate.getMonth() + 1;
		day   = toDate.getDate();
		
		if(month < 10) month = "0" + month;
		if(day < 10) day = "0" + day;
		
		stockHistorySearchStartDate = year+'-'+month+'-'+day;
	}
	else if("D"==param){
		// 최근30일
		let toDate = new Date();
		let year  = toDate.getFullYear();
		let month = toDate.getMonth() + 1;
		let day   = toDate.getDate();
		
		if(month < 10) month = "0" + month;
		if(day < 10) day = "0" + day;
		
		//최근30일
		toDate.setDate(toDate.getDate() - 30);
		startYear  = toDate.getFullYear();
		startMonth = toDate.getMonth() + 1;
		startDay   = toDate.getDate();
		
		if(startMonth < 10) startMonth = "0" + startMonth;
		if(startDay < 10) startDay = "0" + startDay;
		
		stockHistorySearchStartDate = startYear+'-'+startMonth+'-'+startDay;
		stockHistorySearchEndDate   = year+'-'+month+'-'+day;
		
	}
	else if("E"==param){
		// 최근90일
		// 검색 종료일자
		let toDate = new Date();
		let year  = toDate.getFullYear();
		let month = toDate.getMonth() + 1;
		let day   = toDate.getDate();
		
		if(month < 10) month = "0" + month;
		if(day < 10) day = "0" + day;
		
		stockHistorySearchEndDate   = year+'-'+month+'-'+day;
		
		// 검색 시작일자
		toDate.setDate(toDate.getDate() - 90);
		year  = toDate.getFullYear();
		month = toDate.getMonth() + 1;
		day   = toDate.getDate();
		
		if(month < 10) month = "0" + month;
		if(day < 10) day = "0" + day;
		
		stockHistorySearchStartDate = year+'-'+month+'-'+day;
	}
	else if("F"==param){
		//F:이번달
		// 검색 종료일자
		let toDate = new Date();
		let year  = toDate.getFullYear();
		let month = toDate.getMonth() + 1;
		let day   = toDate.getDate();
		
		if(month < 10) month = "0" + month;
		if(day < 10) day = "0" + day;
		
		stockHistorySearchEndDate   = year+'-'+month+'-'+day;
		
		// 검색 시작일자
		stockHistorySearchStartDate = year+'-'+month+'-01';
	}
	else if("G"==param){
		// G:올해
		// 검색 종료일자
		let toDate = new Date();
		let year  = toDate.getFullYear();
		let month = toDate.getMonth() + 1;
		let day   = toDate.getDate();
		
		if(month < 10) month = "0" + month;
		if(day < 10) day = "0" + day;
		
		stockHistorySearchEndDate   = year+'-'+month+'-'+day;
		
		// 검색 시작일자
		stockHistorySearchStartDate = year+'-01-01';
	}
	else if("H"==param){
		// H:지난주, I:지난달
		// 검색 종료일자
		let toDate = new Date();
		let year  = toDate.getFullYear();
		let month = toDate.getMonth() + 1;
		let day   = toDate.getDate();
		
		if(month < 10) month = "0" + month;
		if(day < 10) day = "0" + day;
		
		stockHistorySearchEndDate   = year+'-'+month+'-'+day;
		
		// 검색 시작일자
		stockHistorySearchStartDate = year+'-01-01';
	}
	else if("I"==param){
		// I:지난달
		// 검색 종료일자
		let toDate = new Date();
		let year  = toDate.getFullYear();
		let month = toDate.getMonth() + 1;
		let day   = toDate.getDate();
		
		if(month < 10) month = "0" + month;
		if(day < 10) day = "0" + day;
		
		stockHistorySearchEndDate   = year+'-'+month+'-'+day;
		
		// 검색 시작일자
		stockHistorySearchStartDate = year+'-01-01';
	}
	
	$("#stockHistorySearchStartDate").val(stockHistorySearchStartDate).trigger("change");
	$("#stockHistorySearchEndDate").val(stockHistorySearchEndDate).trigger("change");
}


/****************************************************************************
* 입출고 내역 정보 리스트 조회
****************************************************************************/
function fn_selectListStockHistoryJson(){
	let formData = new FormData();
	formData.append("menuClass", menuClass);
	formData.append("stockHistorySort", stockHistorySort);
	formData.append("stockHistoryDir", stockHistoryDir);
	formData.append("stockHistoryStart", stockHistoryStart);
	formData.append("stockHistoryLimit", stockHistoryLimit);
	formData.append("stockHistorySearchStartDate", stockHistorySearchStartDate);
	formData.append("stockHistorySearchEndDate", stockHistorySearchEndDate);
	formData.append("stockHistorySearchDateType", stockHistorySearchDateType);
	formData.append("stockHistorySearchType", stockHistorySearchType);
	formData.append("muTreatmentId", muTreatmentId);
	formData.append("muProductId", muProductId);
	formData.append("muCompanyId", muCompanyId);

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

				stockHistoryTotalPages = Math.ceil(stockHistoryTotalCount/stockHistoryLimit);
				
				// 리스트 조회
				stockHistoryAgGridData = data.rows;
				stockHistoryGridOptions.api.setRowData(stockHistoryAgGridData);
				
				// if(0<data.rows.length){
				// 	//페이징 처리
				// 	window.pagObj = $('#stockHistoryPagination').twbsPagination({
				// 		startPage    : ((stockHistoryStart/stockHistoryLimit)+1),
				// 		totalPages   : (stockHistoryTotalPages==0)?1:stockHistoryTotalPages,
				// 		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_stockHistoryPagination(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(){
			// 로딩열기
			stockHistoryGridOptions.api.showLoadingOverlay();
		},
		complete:function(){
			
		}
	});
}

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

	stockHistorySearchDateType  = $("#stockHistorySearchDateType").val();
	stockHistorySearchStartDate = $("#stockHistorySearchStartDate").val();
	stockHistorySearchEndDate   = $("#stockHistorySearchEndDate").val();
	stockHistorySearchType      = $("#stockHistorySearchType").val();

	fn_selectStockHistory();
	fn_selectListStockHistoryJson();
}


/****************************************************************************
* 초기화하기
****************************************************************************/
function fn_stockHistoryReset(){
	fn_stockHistorySetDate('D');
	$("#stockHistorySearchDateType option:eq(0)").prop("selected", true);

	fn_stockHistorySearch();
}

/****************************************************************************
* 페이징 처리
****************************************************************************/
function fn_stockHistoryPagination(param){
	stockHistoryStart = (parseInt(param)-1)*stockHistoryLimit;
	
	fn_selectListStockHistoryJson();
}

/****************************************************************************
* 페이징 리셋
****************************************************************************/
function fn_stockHistoryPaginReset(){

	stockHistoryStart        = 0;
	stockHistoryLimit        = 100;
	stockHistoryTotalCount   = 0;
	stockHistoryTotalPages   = 0;
	
	//페이징 초기화
	if($("#stockHistoryPagination").data("twbs-pagination")){
		$("#stockHistoryPagination").twbsPagination("destroy");
	}
}


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

/****************************************************************************
* 정렬 이벤트
****************************************************************************/
function fn_alignEvent(param, param2){
	let align = "";
	
	if("A"==param){
		align = "오늘";
		
		fn_stockHistorySetDate('A');
	}
	else if("B"==param){
		align = "최근30일";
		
		fn_stockHistorySetDate('D');
	}
	else if("C"==param){
		align = "최근90일";
		
		fn_stockHistorySetDate('E');
	}
	else if("D"==param){
		align = "이번주";
		
		fn_stockHistorySetDate('C');
	}
	else if("E"==param){
		align = "이번달";
		
		fn_stockHistorySetDate('F');
	}
	else if("F"==param){
		align = "올해";
		
		fn_stockHistorySetDate('G');
	}
	else if("G"==param){
		align = "지난주";
		
		fn_stockHistorySetDate('H');
	}
	else if("H"==param){
		align = "지난달";
		
		fn_stockHistorySetDate('I');
	}
	else{
		align = "";
	}
	$("#stockHistorySearchDateType").val(param);
	$("#stockHistorySearchDateType").siblings("button").text(align);
}

/****************************************************************************
* 완료
****************************************************************************/
function fn_stockHistoryOk(){
	fn_stockHistoryReset();
}

function fn_insertStockHistoryInPopup(){
	if("Y"!=insertUseYn){
		modalEvent.warning("", "등록 권한이 없습니다.");
		return false;
	}
	
	let reqParam =  {
		"muTreatmentId" : muTreatmentId,
		"muProductId"   : muProductId,
		"muCompanyId"   : muCompanyId
	};
	stockHistoryInInsertModal.popup(function(obj, reqParam) {
		fn_stockHistoryOk();
	}, reqParam);
}

function fn_insertStockHistoryOutPopup(){
	if("Y"!=insertUseYn){
		modalEvent.warning("", "등록 권한이 없습니다.");
		return false;
	}
	
	let reqParam =  {
		"muTreatmentId" : muTreatmentId,
		"muProductId"   : muProductId,
		"muCompanyId"   : muCompanyId
	};
	stockHistoryOutInsertModal.popup(function(obj, reqParam) {
		fn_stockHistoryOk();
	}, reqParam);
}


/****************************************************************************
* 엑셀 다운 다운로드
****************************************************************************/
function fn_downloadStockHistoryExcel(){
	if("Y"==downloadUseYn){
		// 수정가능
		let pagingParam = "?menuClass="+menuClass;
		pagingParam    += "&stockHistorySort="+stockHistorySort;
		pagingParam    += "&stockHistoryDir="+stockHistoryDir;
		pagingParam    += "&stockHistoryStart="+stockHistoryStart;
		pagingParam    += "&stockHistoryLimit="+stockHistoryLimit;
		pagingParam    += "&stockHistorySearchStartDate="+stockHistorySearchStartDate;
		pagingParam    += "&stockHistorySearchEndDate="+stockHistorySearchEndDate;
		pagingParam    += "&stockHistorySearchDateType="+stockHistorySearchDateType;
		pagingParam    += "&stockHistorySearchType="+stockHistorySearchType;
		pagingParam    += "&muTreatmentId="+muTreatmentId;
		pagingParam    += "&muProductId="+muProductId;
		pagingParam    += "&muCompanyId="+muCompanyId;
		
		let url = encodeURI("/webstockhistory/downloadStockHistoryExcel.do"+pagingParam);
		$("#stockHistorySelectListForm").prop("action",url);
		$("#stockHistorySelectListForm").submit();
	}
	else{
		modalEvent.warning("", "내려받기 권한이 없습니다.");
		return false;
	}
}
function formatUseCount(data){
	if(data.data.type==='U'||data.data.type==='S'||data.data.type==='D'||data.data.type==='U'||data.data.type==='AD'){
		return '-'+data.value;
	}
	return data.value;
}
function fn_stockHistoryCancel(){
	let pagingParam = "?menuClass="+menuClass;
	pagingParam    += "&stockStatusSearchKeywordParam="+stockStatusSearchKeywordParam;
	pagingParam    += "&stockStatusSort="+stockStatusSort;
	pagingParam    += "&stockStatusDir="+stockStatusDir;
	pagingParam    += "&stockStatusStart="+stockStatusStart;
	pagingParam    += "&stockStatusLimit="+stockStatusLimit;
	pagingParam    += "&stockStatusSearchStartDate="+stockStatusSearchStartDate;
	pagingParam    += "&stockStatusSearchEndDate="+stockStatusSearchEndDate;
	pagingParam    += "&stockStatusSearchDateType="+stockStatusSearchDateType;
	pagingParam    += "&stockStatusTreatmentId="+stockStatusTreatmentId;
	pagingParam    += "&stockStatusCompanyId="+stockStatusCompanyId;
	
	fn_leftFormAction("/webstockstatus/selectListStockStautsIntro.do"+pagingParam);
}


let stockHistoryColumnDefs = [
	/*{field: "checkbox", headerName:"", minWidth: columnWidth, maxWidth: columnWidth, headerCheckboxSelection: true, checkboxSelection: true},*/
	/* {field: "rowNum", headerName:"번호", minWidth: columnWidth, maxWidth: columnWidth, sortable: false}, */
	{field: "rowNum", headerName:"번호", minWidth:60,sortable: false, cellStyle:{textAlign: 'center'}},
	{field: "inDate", headerName:"날짜", minWidth: 100, maxWidth: 100},
	{field: "typeName", headerName:"구분", minWidth: 150, maxWidth: 150},
	{field: "productName", headerName:"제품명", minWidth: 150, maxWidth: 150},
	{field: "companyName", headerName:"거래처명", minWidth: 150, maxWidth: 150},
	{field: "price", headerName:"단가", minWidth: 130, maxWidth: 130, cellStyle:{textAlign: 'right'}},
	{field: "quantity", headerName:"수량", minWidth: 70, maxWidth: 70,valueFormatter: formatUseCount, cellStyle:{textAlign: 'right'}},
	{field: "totalAmount", headerName:"금액", minWidth: 130, maxWidth: 130, cellStyle:{textAlign: 'right'}},
	{field: "originalFileName", headerName:"첨부파일", minWidth: 200, maxWidth: 200, cellStyle:{cursor: 'pointer', color:'#3985EA'}},
	{field: "filePath", hide:true},
	{field: "etc", headerName:"메모", minWidth: 439}
];
// let the grid know which columns and what data to use
let stockHistoryGridOptions = {
	suppressRowTransform: true,
	columnDefs: stockHistoryColumnDefs,
	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 : stockHistoryAgGridData,
	suppressRowClickSelection : true, // 로우 클릭시 체크박스 선택 true no, false yes
	localeText : {
		noRowsToShow : '조회 결과가 없습니다.'
	}, //데이터 없을 시 나오는 문구
	rowSelection : 'multiple', // row 다중 선택
	debug : false,
	onCellClicked: function(event){ //셀 클릭 이벤트
		if(event.column.colId=='originalFileName'){
			const fileName = event.data.filename;  // Assuming filePath is stored in each row's data
			// const modal = document.getElementById('fileModal');
			// const file = document.getElementById('file');
			// const downloadLink = document.getElementById('downloadLink');
			// downloadLink.href = filePath; // Set the href attribute to the filePath
			// modal.style.display = 'block'; // Show the modal
			// file.src = filePath.replace("C:", "");
			// location.href = filePath.replace("C:", "");
			let url = encodeURI(`/webstockhistory/downloadFile.do?fileName=${fileName}`);

			let newForm = $("<form><form/>");
			newForm.attr("name", "excelForm");
			newForm.attr("method", "POST");
			newForm.attr("target", "_blank");
			newForm.attr("action", url);
			newForm.appendTo('body');
			newForm.submit();
		}
	},
	onSelectionChanged: function(event){ //체크박스 선택
		let selectRows = [];
		selectRows = event.api.getSelectedRows();
		
		stockHistorySelectId = '';
		for(let i=0; i<selectRows.length; i++){
			stockHistorySelectId += selectRows[i].muStockHistoryId + ",";
		}
		stockHistorySelectId = stockHistorySelectId.substring(0, stockHistorySelectId.lastIndexOf(','));
	},
	onSortChanged: function(event){
		 //정렬
		stockHistorySort = ''; //기존 정렬 초기화
		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){
					stockHistoryStart = 0;
					stockHistorySort += gridSortModel+' '+ gridSort + ',';
				}
				else{
					nullCnt++;
					if(nullCnt == columnArr.length){
						stockHistorySort = '';
						stockHistoryDir = '';
						stockHistoryStart = 0;
					}
				}
			}
		}
		stockHistorySort = stockHistorySort.substring(0,stockHistorySort.lastIndexOf( ",")); //맨끝 콤마 지우기

		fn_stockHistorySearch();
	}
};

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

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


/****************************************************************************
* 페이지 init
****************************************************************************/
function fn_pageInit(){
	// 뒤로가기 버튼 이벤트 및 노출
	$(".back").removeAttr("onclick");
	$(".back").attr("onclick", "fn_stockHistoryCancel();");
	$(".back").show();
	
	// 날짜 datepicker
	fn_searchDatePicker("#divStockHistorySearchStartDate", "#divStockHistorySearchEndDate");
	
	stockHistorySearchStartDate = stockStatusSearchStartDate;
	stockHistorySearchEndDate   = stockStatusSearchEndDate;
	
	if(!stockHistorySearchStartDate&&!stockHistorySearchEndDate){
		// 검색 오늘날짜 셋팅
		fn_stockHistorySetDate('D');
	}else{
		$("#stockHistorySearchStartDate").val(stockHistorySearchStartDate).trigger("change");;
		$("#stockHistorySearchEndDate").val(stockHistorySearchEndDate).trigger("change");;
	}
	
	if(!stockHistorySearchType){
		
	}else{
		$('#li_'+stockHistorySearchType).click();
	}
	
	
	// 입출고내역 상단 거래처정보 및 각 타입별 수량/금액 조회
	fn_selectStockHistory();
	
	fn_stockHistorySearch("A");
}

/****************************************************************************
* 페이지 event
****************************************************************************/
function fn_pageEvent(){
	
	// 검색 조회 버튼
	$("#btnSearchStockHistory").click(function () {
		fn_stockHistorySearch();
	});
	
	// 입고 팝업 버튼
	$("#btnInStockHistory").click(function () {
		fn_insertStockHistoryInPopup();
	});
	
	// 출고 팝업 버튼
	$("#btnOutStockHistory").click(function () {
		fn_insertStockHistoryOutPopup();
	});
	
	// 입출고 내역 내려받기
	$("#btnDownloadStockHistory").click(function () {
		fn_downloadStockHistoryExcel();
	});
	
	// 기간 선택 콤보 이벤트
	$("#stockHistorySearchDateType").siblings("ul.select_option_list").find("li.option_list_item").click(function () {
		let selectIdArr = $(this).prop("id").split('_');
		let selectId    = selectIdArr[1];
		let selectName  = $(this).text();
		
		$(this).parent().siblings("button").text(selectName);
		$(this).parent().siblings("input").val(selectId);
		
		fn_alignEvent(selectId);
	});
	
	// 구분 선택 콤보 이벤트
	$("#stockHistorySearchType").siblings("ul.select_option_list").find("li.option_list_item").click(function () {
		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(){
	// 페이지 init
	fn_pageInit();
	
	// 페이지 event
	fn_pageEvent();
});