
const MAIN_NOTICE_GRID_ID = '#ITP_MAIN_NOTICE_jqGrid';
const MAIN_NOTICE_GRID_LIST = '#ITP_MAIN_NOTICE_jqGrid_list';
const MAIN_NOTICE_GRID_PAGER = '#ITP_MAIN_NOTICE_jqGridPager';
const MAIN_NOTICE_GRID_EMPTY = '#ITP_MAIN_NOTICE_jqGridEmpty';

let NTICE_DETAIL_GRID_LIST = '/api/ntice/main-detail-grid-list';
let MAIN_CHART_COUNT = '/api/main/chart/count';
let MAIN_CHART_PCH_REQ_CHART = '/api/main/chart/pch-req-chart';
let MAIN_CHART_PCH_ODR_CHART = '/api/main/chart/pch-odr-chart';
let MAIN_CHART_PR_RANK_CHART = '/api/main/chart/pr-rank-chart';
let MAIN_CHART_STL_CHART = '/api/main/chart/stl-chart';
let MAIN_CHART_SFT_STCK_CHART = '/api/main/chart/sft-stck-chart';
let MAIN_CHART_DELI_CHART = '/api/main/chart/deli-chart';

var chartCnt=0;
function loadJS(url, implementationCode ) {
	var scriptTag = document.createElement('script');
	scriptTag.src = url;
	scriptTag.onload = implementationCode;
	scriptTag.onreadystatechange = implementationCode;
	document.head.appendChild(scriptTag);
};

require(['config'], function() {
	require([
		'jquery', 
		'jquery.bootstrap.fileUpload' //파일 업로드가 있는 페이지에서 로딩
	], function($) {
		 
		setTimeout(function() {
			// 시간지정
			// $('#ITP_FORM_MAIN_NOTICE_SEARCH_SCH_DT').val(itp_fn_date_format(new Date(), 2));
			// $('#ITP_FORM_MAIN_NOTICE_SEARCH_USER_ID').val(fn_make_user_info.get('userId'));

			// 조회
	    	itp_fn_MAIN_NOTICE_search();
			itp_fn_MAIN_COUNT();
			
			$('#ITP_FORM_MAIN_SEARCH_PR_TYPE').on('change', function() {
				drawChartReq();
			});
			
			$('#ITP_FORM_MAIN_SEARCH_PO_TYPE').on('change', function() {
				drawChartPodr();
			});
			
			$('#ITP_FORM_MAIN_SEARCH_ITEM_CNT_TYPE').on('change', function() {
				drawChartReqUp();
			});
			
			$('#ITP_FORM_MAIN_SEARCH_DELI_TYPE').on('change', function() {
				drawChartDeli();
			});
			
			$('#ITP_FORM_MAIN_SEARCH_RELEASE_TYPE').on('change', function() {
				drawChartRelease();
			});
			
			$('#ITP_FORM_MAIN_SEARCH_ORDERS_TYPE').on('change', function() {
				drawChartOrders();
			});
			
			//그래프 
			google.charts.load('current', {'packages':['corechart']});
			google.charts.load('current', {'packages':['bar']});
			
			$('#ITP_MAIN_HEADER_BRAND').hide();
			$('#ITP_MAIN_HEADER_STORE').hide();
			$('#ITP_MAIN_HEADER_SPPLY').hide();
			
			$('#ITP_MAIN_DRAW_CHART_REQ').hide();
			$('#ITP_MAIN_DRAW_CHART_PODR').hide();
			$('#ITP_MAIN_DRAW_CHART_REQ_UP').hide();
			$('#ITP_MAIN_DRAW_CHART_CORE').hide();
			$('#ITP_MAIN_DRAW_LINE').hide();
			$('#ITP_MAIN_DRAW_DELI_CHART').hide(); 		// 입고
			$('#ITP_MAIN_DRAW_RELEASE_CHART').hide();	// 출고
			$('#ITP_MAIN_DRAW_ORDERS_CHART').hide();	// 수주내역
			
			var authTpCd = fn_make_user_info.get('authTpCd'); 
			// 10:관리자, 20:영업담당자, 30:가맹점, 40:브랜드, 50:매장, 60:공급사
			// console.log('>>>> authTpCd = ' + authTpCd);
			
			if( authTpCd == '40' || authTpCd == '10' ) { // 브랜드
				$('#ITP_MAIN_HEADER_BRAND').show();
			
				$('#ITP_MAIN_DRAW_CHART_REQ').show();  
				google.charts.setOnLoadCallback(drawChartReq); // 구매요청
				
				$('#ITP_MAIN_DRAW_CHART_PODR').show();
				google.charts.setOnLoadCallback(drawChartPodr); // 구매발주
			
				$('#ITP_MAIN_DRAW_CHART_REQ_UP').show();
				google.charts.setOnLoadCallback(drawChartReqUp); // 매출순위
				
				if(fn_make_user_info.get('brandId')) {
					$('#ITP_MAIN_DRAW_CHART_CORE').show();
					google.charts.setOnLoadCallback(drawChartcore); // 정산
					chartCnt=4;
				} else {
					chartCnt=3;
				}
			
				$('#ITP_MAIN_DRAW_LINE').show();	
				$('#ITP_MAIN_DRAW_LINE .itp_main_draw_line').show();	
				google.charts.setOnLoadCallback(drawLine); // 안전재고
			} else if( authTpCd == '50' ) { // 매장
				$('#ITP_MAIN_HEADER_STORE').show();
			
				$('#ITP_MAIN_DRAW_CHART_REQ').show();  
				google.charts.setOnLoadCallback(drawChartReq); // 구매요청
				
				$('#ITP_MAIN_DRAW_DELI_CHART').show();  
				google.charts.setOnLoadCallback(drawChartDeli); // 입고
				
				$('#ITP_MAIN_DRAW_CHART_REQ_UP').show();
				google.charts.setOnLoadCallback(drawChartReqUp); // 매출순위
				
				$('#ITP_MAIN_DRAW_CHART_CORE').show();
				google.charts.setOnLoadCallback(drawChartcore); // 정산
				chartCnt=4;
			} else if( authTpCd == '60' ) { // 공급사
				$('#ITP_MAIN_HEADER_SPPLY').show();
			
				$('#ITP_MAIN_DRAW_ORDERS_CHART').show();  
				google.charts.setOnLoadCallback(drawChartOrders); // 수주내역
				
				$('#ITP_MAIN_DRAW_RELEASE_CHART').show();  
				google.charts.setOnLoadCallback(drawChartRelease); // 출고
				
				$('#ITP_MAIN_DRAW_CHART_REQ_UP').show();
				google.charts.setOnLoadCallback(drawChartReqUp); // 매출순위
				
				$('#ITP_MAIN_DRAW_CHART_CORE').show();
				google.charts.setOnLoadCallback(drawChartcore); // 정산
				chartCnt=4;
			}
			
			if(chartCnt==3) {
				$('#ITP_MAIN_GRAPH_AREA').css('grid-template-columns','1fr 1fr 1fr');
			}	

		}, 300);
		
		loadJS('./js/cpexcel.js', function() {
			loadJS('./js/xlsx.js', function() {
				if(XLSX.version!=='0.18.5') {
					make_xlsx_lib(XLSX);
				}
				console.log("xxxxxx xlsx xxxxxx", XLSX);
			});
		});
	});
});

//구매요청 그래프
function drawChartReq() {
	
	const key = { brandId:fn_make_user_info.get('brandId'), storeId:fn_make_user_info.get('storeId'), prType: $('#ITP_FORM_MAIN_SEARCH_PR_TYPE').val() };
	var param = $.param(key); 
	fn_ajax_call(MAIN_CHART_PCH_REQ_CHART, param, function(result) {
		
		var data = google.visualization.arrayToDataTable( eval(result.chartData) );
	  	var options = {
			legend: { position: 'left' }, 
			bar: { groupWidth: "50%" },
			width: chartCnt==4? 245: 300,
	  	};	
	  	var chart = new google.charts.Bar(document.getElementById('ITP_PCH_REQ_GRAPH'));
	  	// chart.draw(data, options);
		console.log("xx draw char req xx", param, data, chart)
		chart.draw(data, google.charts.Bar.convertOptions(options));
		
	}, 'GET'); 
}

//수주내역 그래프
function drawChartOrders() {
	
	const key = { brandId:fn_make_user_info.get('brandId'), 
			      spplyId:fn_make_user_info.get('spplyId'), 
				  poType: $('#ITP_FORM_MAIN_SEARCH_ORDERS_TYPE').val() };
	var param = $.param(key);
	fn_ajax_call(MAIN_CHART_PCH_ODR_CHART, param, function(result) {
		
		var data = google.visualization.arrayToDataTable( eval(result.chartData) );
	  	var options = {
			legend: { position: 'left' },
			width: chartCnt==4? 245: 300,
		};	
	  	var chart = new google.charts.Bar(document.getElementById('ITP_ORDERS_GRAPH'));
	  	chart.draw(data, options);
		
	}, 'GET');
	
}

//입고 그래프
function drawChartDeli() {
	
	const key = { brandId:fn_make_user_info.get('brandId'), 
				  storeId:fn_make_user_info.get('storeId'), 
				  deliType: $('#ITP_FORM_MAIN_SEARCH_DELI_TYPE').val() };
	var param = $.param(key);
	fn_ajax_call(MAIN_CHART_DELI_CHART, param, function(result) {
		
		var data = google.visualization.arrayToDataTable( eval(result.chartData) );
	  	var options = {
			legend: { position: 'left' },
			width: chartCnt==4? 245: 300,
		};	
	  	var chart = new google.charts.Bar(document.getElementById('ITP_DELI_GRAPH'));
	  	chart.draw(data, options);
		
	}, 'GET');
	
}

//출고 그래프
function drawChartRelease() {
	
	const key = { brandId:fn_make_user_info.get('brandId'), 
				  spplyId:fn_make_user_info.get('spplyId'), 
				  deliType: $('#ITP_FORM_MAIN_SEARCH_RELEASE_TYPE').val() };
	var param = $.param(key);
	fn_ajax_call(MAIN_CHART_DELI_CHART, param, function(result) {
		
		var data = google.visualization.arrayToDataTable( eval(result.chartData) );
	  	var options = {
			legend: { position: 'left' },
			width: chartCnt==4? 245: 300,
	  	};	
	  	var chart = new google.charts.Bar(document.getElementById('ITP_RELEASE_GRAPH'));
	  	chart.draw(data, options);
		
	}, 'GET');
	
}

//구매발주 그래프
function drawChartPodr() {
	
	const key = { brandId:fn_make_user_info.get('brandId'), storeId:fn_make_user_info.get('storeId'), poType: $('#ITP_FORM_MAIN_SEARCH_PO_TYPE').val() };
	var param = $.param(key);
	fn_ajax_call(MAIN_CHART_PCH_ODR_CHART, param, function(result) {
		
		var data = google.visualization.arrayToDataTable( eval(result.chartData) );
	
		var options = {
			legend: { position: 'left' }, 
			bar: { groupWidth: "50%" },
			width: chartCnt==4? 245: 300,
		};	
		var chart = new google.charts.Bar(document.getElementById('ITP_PCH_PODR_GRAPH'));	
		// chart.draw(data, options);
		chart.draw(data, google.charts.Bar.convertOptions(options));
		
	}, 'GET');	
	  
}

//구매요청 상위 품목 그리드
function drawChartReqUp() {
	
	const key = { brandId:fn_make_user_info.get('brandId'), storeId:fn_make_user_info.get('storeId'), spplyId:fn_make_user_info.get('spplyId'), prType: $('#ITP_FORM_MAIN_SEARCH_ITEM_CNT_TYPE').val() };
	var param = $.param(key);
	fn_ajax_call(MAIN_CHART_PR_RANK_CHART, param, function(result) {
		
		var data = google.visualization.arrayToDataTable( eval(result.chartData) );

		var options = {
			title: '구매요청 상위 품목',
			legend: { position: 'left' },
			bars: 'horizontal',
			width: 300,
		};
		console.log("xxxxxxxxxxx drawChartReqUp xxxxxxxxxxx")
		
		var chart = new google.charts.Bar(document.getElementById('ITP_PCH_REQ_UP_ITEM_GRAPH'));		
		chart.draw(data, options);
		
	}, 'GET');
	
}

//정산 그래프
function drawChartcore() {
	
	const key = { brandId:fn_make_user_info.get('brandId'), storeId:fn_make_user_info.get('storeId'), spplyId:fn_make_user_info.get('spplyId') };
	var param = $.param(key);
	fn_ajax_call(MAIN_CHART_STL_CHART, param, function(result) {
		
		// var data = google.visualization.arrayToDataTable([ [' ', ' '], ['요청', 25], ['확인', 65], ['반려', 10] ]);
		var data = google.visualization.arrayToDataTable( eval(result.chartData) );
	
	    var options = {
			// title: '정산', 
			legend: { position: 'left' }, 
			width: 300,
	    }; 
	    var chart = new google.visualization.PieChart(document.getElementById('ITP_STTL_GRAPH'));	
		console.log("xxxxxxxxxxx drawChartcore xxxxxxxxxxx", data, options )
	    chart.draw(data, options);				
		
	}, 'GET');
    
}


function drawLine() {

	const key = { brandId:fn_make_user_info.get('brandId'), storeId:fn_make_user_info.get('storeId') };
	var param = $.param(key);
	fn_ajax_call(MAIN_CHART_SFT_STCK_CHART, param, function(result) {
		
		var data = google.visualization.arrayToDataTable( eval(result.chartData) );
		
		var options = {
		    title: '',
		    width: 900,
		    legend: { position: 'top' }
		};
		
		var chart = new google.visualization.LineChart(document.getElementById('ITP_SAFE_STCK_GRAPH'));		
		chart.draw(data, options);
		
	}, 'GET');	
  
}

var itp_fn_MAIN_COUNT = function() {
	
	var brandId = fn_make_user_info.get('brandId');
	var storeId = fn_make_user_info.get('storeId');
	var spplyId = fn_make_user_info.get('spplyId');
	
	if(brandId == '' && storeId == '' && spplyId == '') {
		return;
	}
	
	const key = { brandId:brandId, storeId:storeId, spplyId:spplyId };
	var param = $.param(key);
	fn_ajax_call(MAIN_CHART_COUNT, param, function(result) {
		
		$('#ITP_AJAX_SUMMARY_DETAIL_CONTAINER .fnPr20Count').text( itp_fn_number_comma( result.pr20Count ) + '건' );
		$('#ITP_AJAX_SUMMARY_DETAIL_CONTAINER .fnDp02Amt').text( itp_fn_number_comma( result.dp02Amt ) + '원' );
		$('#ITP_AJAX_SUMMARY_DETAIL_CONTAINER .fnUnpaidAmt').text( itp_fn_number_comma( result.unpaidAmt ) + '원' );
				
		$('#ITP_AJAX_SUMMARY_DETAIL_CONTAINER .fnPo30Count').text( itp_fn_number_comma( result.po30Count ) + '건' );		
		$('#ITP_AJAX_SUMMARY_DETAIL_CONTAINER .fnPoEndCount').text( itp_fn_number_comma( result.poEndCount ) + '건' );		
		$('#ITP_AJAX_SUMMARY_DETAIL_CONTAINER .fnPoPsblAmt').text( itp_fn_number_comma( result.poPsblAmt ) + '원' );
				
		$('#ITP_AJAX_SUMMARY_DETAIL_CONTAINER .fnOrdersCount').text( itp_fn_number_comma( result.ordersCount ) + '건' );		
		$('#ITP_AJAX_SUMMARY_DETAIL_CONTAINER .fnOrdersAmt').text( itp_fn_number_comma( result.ordersAmt ) + '원' );		
		$('#ITP_AJAX_SUMMARY_DETAIL_CONTAINER .fnSttlReqAmt').text( itp_fn_number_comma( result.sttlReqAmt ) + '원' );		
		
	}, 'GET');
	
}

var itp_fn_MAIN_NOTICE_search = function() {
	// itp_fn_MAIN_NOTICE_grid.unload();
	// itp_fn_MAIN_NOTICE_grid.callBack();
	// 공지사항 조회
	const formId = '#ITP_FORM_MAIN_SEARCH';
	let param = $(formId).serializeObject();
	var searhFn = function(result) {
		const tb=$('#ITP_NOTE_PANEL .rtable').find('tbody');
		if(Array.isArray(result.gridRows) && result.gridRows.length ) {
			var s='', idx=1;
			for(var c of result.gridRows ) {
				let title=c.nticeTitl;
				if(title.length>62) {
					title=title.substr(0,62)+'...';
				} 
				s+=`<tr>
					<td>${idx}</td><td>${c.brandNm}</td>
					<td style="text-align:left;"><a href="javascript:clickNotify('${c.nticeNo}')">${title}</a></td>
					<td>${c.nticeStatNm}</td><td>${c.addDt}</td>
				</tr>`;
				idx++;
			}
			tb.html(s);
		} else {
			tb.html('<tr><td colspan="5" style="text-align:center;">등록된 공지사항이 없습니다</td></tr>')
		} 
	};
	fn_ajax_call(NTICE_DETAIL_GRID_LIST, JSON.stringify(param), searhFn, 'POST');
};
function clickNotify(nticeNo) {
	fn_call_popup('comm', 'NOTICE_INFO_POPUP', '#ITP_ASIDE', function(rowDataPop) { 
		 console.log("rowDataPop ==> ", rowDataPop)
	}, {nticeNo}, 'S');
}
