/* 페이징 관련 변수 */
let stockCloseTotalCount   = 0;
let stockCloseTotalPages   = 0;

/*aggird*/
let stockCloseAgGridData = [];

let stockCloseSelectId = "";


/****************************************************************************
* 재고마감 리스트
****************************************************************************/
function fn_selectListStockClose(){
	let formData = new FormData();
	formData.append("menuClass", menuClass);
	formData.append("stockCloseSearchKeywordParam", stockCloseSearchKeywordParam);
	formData.append("stockCloseSort", stockCloseSort);
	formData.append("stockCloseDir", stockCloseDir);
	formData.append("stockCloseStart", stockCloseStart);
	formData.append("stockCloseLimit", stockCloseLimit);
	formData.append("stockCloseSearchStartDate", stockCloseSearchStartDate);
	formData.append("stockCloseSearchEndDate", stockCloseSearchEndDate);
	formData.append("stockCloseSearchDateType", stockCloseSearchDateType);

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

				stockCloseTotalPages = Math.ceil(stockCloseTotalCount/stockCloseLimit);
				
				// 리스트 조회
				stockCloseAgGridData = data.rows;
				stockCloseGridOptions.api.setRowData(stockCloseAgGridData);
				
				// if(0<data.rows.length){
				// 	//페이징 처리
				// 	window.pagObj = $('#stockClosePagination').twbsPagination({
				// 		startPage    : ((stockCloseStart/stockCloseLimit)+1),
				// 		totalPages   : (stockCloseTotalPages==0)?1:stockCloseTotalPages,
				// 		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_stockClosePagination(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(){
			// 로딩열기
			stockCloseGridOptions.api.showLoadingOverlay();
		},
		complete:function(){
			
		}
	});
}

/****************************************************************************
* 검색 날짜 설정
//(A:오늘, B:3일, C:7일, D:최근30일, E:최근90일, F:이번달, G:올해, H:지난주, I:지난달)
****************************************************************************/
function fn_stockCloseSetDate(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;
		
		stockCloseSearchStartDate = year+'-'+month+'-'+day;
		stockCloseSearchEndDate   = 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;
		
		stockCloseSearchEndDate   = 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;
		
		stockCloseSearchStartDate = 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;
		
		stockCloseSearchEndDate   = 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;
		
		stockCloseSearchStartDate = 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;
		
		stockCloseSearchStartDate = startYear+'-'+startMonth+'-'+startDay;
		stockCloseSearchEndDate   = 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;
		
		stockCloseSearchEndDate   = 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;
		
		stockCloseSearchStartDate = 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;
		
		stockCloseSearchEndDate   = year+'-'+month+'-'+day;
		
		// 검색 시작일자
		stockCloseSearchStartDate = 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;
		
		stockCloseSearchEndDate   = year+'-'+month+'-'+day;
		
		// 검색 시작일자
		stockCloseSearchStartDate = year+'-01-01';
	}
	else if("H"==param){
		// H:지난주, I:지난달
		// 검색 종료일자
		let toDate = new Date();

		let startDate = new Date(toDate.getFullYear(), toDate.getMonth(), toDate.getDate() - toDate.getDay() - 6); // 지난주 월요일
		let endDate = new Date(toDate.getFullYear(), toDate.getMonth(), toDate.getDate() - toDate.getDay()); // 지난주 일요일

        let year = endDate.getFullYear();
        let month = endDate.getMonth() + 1; // JS의 getMonth()는 0부터 시작하므로 +1
        let day = endDate.getDate();

		if(month < 10) month = "0" + month;
		if(day < 10) day = "0" + day;
		
		stockCloseSearchEndDate   = year+'-'+month+'-'+day;

		// 시작일자 설정
		year = startDate.getFullYear();
		month = startDate.getMonth() + 1;
		day = startDate.getDate();

		month = month < 10 ? '0' + month : month;
		day = day < 10 ? '0' + day : day;

		stockCloseSearchStartDate = year + '-' + month + '-' + day;
	}
	else if("I"==param){
		// I:지난달
		// 검색 종료일자
		let toDate = new Date();
		let currentYear = toDate.getFullYear();
		let currentMonth = toDate.getMonth();

		// 지난달의 첫째 날
		let firstDayOfLastMonth = new Date(currentYear, currentMonth - 1, 1);
		let year = firstDayOfLastMonth.getFullYear();
		let month = firstDayOfLastMonth.getMonth() + 1; // JS는 월을 0부터 시작하므로 +1
		let day = firstDayOfLastMonth.getDate();

		if(month < 10) month = "0" + month;
		if(day < 10) day = "0" + day;

		// 검색 시작일자
		stockCloseSearchStartDate = year + '-' + month + '-' + day;

		// 지난달의 마지막 날
		let lastDayOfLastMonth = new Date(currentYear, currentMonth, 0);
		year = lastDayOfLastMonth.getFullYear();
		month = lastDayOfLastMonth.getMonth() + 1;
		day = lastDayOfLastMonth.getDate();

		if(month < 10) month = "0" + month;
		if(day < 10) day = "0" + day;

		stockCloseSearchEndDate = year + '-' + month + '-' + day;
	}
	
	$("#stockCloseSearchStartDate").val(stockCloseSearchStartDate).trigger("change");
	$("#stockCloseSearchEndDate").val(stockCloseSearchEndDate).trigger("change");
}

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

	stockCloseSearchDateType  = $("#stockCloseSearchDateType").val();
	stockCloseSearchStartDate = $("#stockCloseSearchStartDate").val();
	stockCloseSearchEndDate   = $("#stockCloseSearchEndDate").val();
	stockCloseSearchType      = $("#stockCloseSearchType").val();

	fn_selectListStockClose();
}


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

	fn_stockCloseSearch();
}

/****************************************************************************
* 페이징 처리
****************************************************************************/
function fn_stockClosePagination(param){
	stockCloseStart = (parseInt(param)-1)*stockCloseLimit;
	
	fn_selectListStockClose();
}

/****************************************************************************
* 페이징 리셋
****************************************************************************/
function fn_stockClosePaginReset(){
	stockCloseSearchKeywordParam = '';

	stockCloseStart        = 0;
	stockCloseLimit        = 100;
	stockCloseTotalCount   = 0;
	stockCloseTotalPages   = 0;
	
	//페이징 초기화
	if($("#stockClosePagination").data("twbs-pagination")){
		$("#stockClosePagination").twbsPagination("destroy");
	}
}


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

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

/****************************************************************************
* 완료
****************************************************************************/
function fn_stockCloseOk(){
	fn_stockCloseReset();
}

function fn_insertStockClosePopup(){
	if("Y"!=insertUseYn){
		modalEvent.warning("", "등록 권한이 없습니다.");
		return false;
	}
	
	let reqParam =  {};
	stockCloseInsertModal.popup(function(obj, reqParam) {
		fn_stockCloseOk();
	}, reqParam);
}


/****************************************************************************
* 엑셀 다운 다운로드
****************************************************************************/
function fn_downloadStockCloseExcel(){
	if("Y"==downloadUseYn){
		let pagingParam = "?menuClass="+menuClass;
		pagingParam    += "&stockCloseSearchKeywordParam="+stockCloseSearchKeywordParam;
		pagingParam    += "&stockCloseSort="+stockCloseSort;
		pagingParam    += "&stockCloseDir="+stockCloseDir;
		pagingParam    += "&stockCloseStart="+stockCloseStart;
		pagingParam    += "&stockCloseLimit="+stockCloseLimit;
		pagingParam    += "&stockCloseSearchStartDate="+stockCloseSearchStartDate;
		pagingParam    += "&stockCloseSearchEndDate="+stockCloseSearchEndDate;
		pagingParam    += "&stockCloseSearchDateType="+stockCloseSearchDateType;
		
		let url = encodeURI("/webstockclose/downloadStockCloseExcel.do"+pagingParam);
		$("#stockCloseSelectListForm").prop("action",url);
		$("#stockCloseSelectListForm").submit();
	}
	else{
		modalEvent.warning("", "내려받기 권한이 없습니다.");
		return false;
	}
}

/****************************************************************************
* 재고마감 상세 화면으로 이동.
****************************************************************************/
function fn_selectListStockCloseDetailIntro(param){
	if("Y"==updateUseYn){
		// 수정가능
		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;
		pagingParam    += "&muStockCloseId="+param;
		
		fn_leftFormAction("/webstockclosedetail/selectListStockCloseDetailIntro.do"+pagingParam);
	}
	else{
		modalEvent.warning("", "수정 권한이 없습니다.");
		return false;
	}
	
}
let columnWidth = 1519/5;

let stockCloseColumnDefs = [
	/*{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: "closeDate", headerName:"최종수행일자", minWidth: columnWidth, maxWidth: columnWidth, cellStyle:{cursor: 'pointer', color:'#3985EA'}},
	{field: "endDate", headerName:"마감월", minWidth: columnWidth, maxWidth: columnWidth},
	{field: "companyCount", headerName:"거래처 수", minWidth: columnWidth, maxWidth: columnWidth, cellStyle:{textAlign: 'right'}},
	{field: "productCount", headerName:"품목 수", minWidth: columnWidth, maxWidth: columnWidth, cellStyle:{textAlign: 'right'}},
	{field: "totalAmount", headerName:"재고총액", minWidth: columnWidth, maxWidth: columnWidth, cellStyle:{textAlign: 'right'}}
];

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

		fn_stockCloseSearch();
	}
};

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

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


/****************************************************************************
* 페이지 init
****************************************************************************/
function fn_pageInit(){
	// 날짜 datepicker
	fn_searchDatePicker("#divStockCloseSearchStartDate", "#divStockCloseSearchEndDate");
	
	if(!stockCloseSearchStartDate&&!stockCloseSearchEndDate){
		// 검색 오늘날짜 셋팅
		fn_stockCloseSetDate('D');
	}else{
		$("#stockCloseSearchStartDate").val(stockCloseSearchStartDate).trigger("change");
		$("#stockCloseSearchEndDate").val(stockCloseSearchEndDate).trigger("change");
	}
	
	fn_stockCloseSearch("A");
	
}

/****************************************************************************
* 페이지 event
****************************************************************************/
function fn_pageEvent(){
	// 검색 input
	$(document).on('keypress', '#stockCloseSearchKeyword', function(e) {
		fn_stockCloseEnter(e);
	});
	
	// 검색 조회 버튼
	$("#btnSearchStockClose").click(function () {
		fn_stockCloseSearch();
	});
	
	// 재고마감 등록 버튼
	$("#btnInsertStockClose").click(function () {
		fn_insertStockClosePopup();
	});
	
	// 재고마감 내려받기
	$("#btnDownloadStockClose").click(function () {
		fn_downloadStockCloseExcel();
	});

	// 기간 선택 콤보 이벤트
	const target = $("#stockCloseSearchDateType").siblings("ul.select_option_list");
	target.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);
	});
}

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