require(['config'], function() {
	require([
		'jquery'
	], function($) {

		setTimeout(function() {
			// mobMainObj.init();
		}, 100);

	});
});

let MOBILE_APP_VERSION = '';

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;
var chartWidth=window.offsetWidth-16;
function clickNotify(nticeNo) {
	mobPopObj.popNotice.open(nticeNo);
}
 
var mobMainObj = {
	init: function () {
		this.ui();
		this.notice.init();
		this.count.init();
		this.chart.init();
		
	},
	ui: function() { 
		var authTpCd = fn_make_user_info.get('authTpCd');
		if(authTpCd === '40' ) {
			$('#ITP_MAIN_HEADER_BRAND').show();
		} else if(authTpCd === '50') {
			$('#ITP_MAIN_HEADER_STORE').show();
		} else if(authTpCd === '60') {
			$('#ITP_MAIN_HEADER_SPPLY').show();
		} 
	},
	notice: {
		init: function () {
			this.load();
		},
		load: function () {
			var searhFn = function(result) { 
				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+=`<li>
							<div class="itp_note_info">
								<label>공지제목</label>
								<span>:</span>
								<div class="under fnNoteTitle"><a href="javascript:clickNotify('${c.nticeNo}')">${title}</a></div>
							</div>
							<div class="itp_note_info">
								<label>공지일</label>
								<span>:</span>
								<div class="fnNoteDt">${c.addDt}</div>
							</div>
						</li>`; 
					}
					$('#ITP_NOTE_ROW').html(s);
				} else {
					$('#ITP_NOTE_ROW').html('<div class="itp_note_bar" style="display: block;"> <h1>등록된 게시물이 없습니다.</h1> </div>')
				} 
			};
			fn_ajax_call(NTICE_DETAIL_GRID_LIST, "{}", searhFn, 'POST');
		}
	},
	count: {
		init: function () {
			this.load();
		},
		load: 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) {
				console.log(result);

				$('#ITP_MAIN_CONTAINER .fnPr20Count').text( CommonObj.currency.add( result.pr20Count, '건' ));
				$('#ITP_MAIN_CONTAINER .fnDp02Amt').text( CommonObj.currency.add( result.dp02Amt ));
				$('#ITP_MAIN_CONTAINER .fnUnpaidAmt').text( CommonObj.currency.add( result.unpaidAmt ));

				$('#ITP_MAIN_CONTAINER .fnPo30Count').text( CommonObj.currency.add( result.po30Count, '건' ));
				$('#ITP_MAIN_CONTAINER .fnPoEndCount').text( CommonObj.currency.add( result.poEndCount, '건' ));
				$('#ITP_MAIN_CONTAINER .fnPoPsblAmt').text( CommonObj.currency.add( result.poPsblAmt ));

				$('#ITP_MAIN_CONTAINER .fnOrdersCount').text( CommonObj.currency.add( result.ordersCount, '건' ) );
				$('#ITP_MAIN_CONTAINER .fnOrdersAmt').text( CommonObj.currency.add( result.ordersAmt ));
				$('#ITP_MAIN_CONTAINER .fnSttlReqAmt').text( CommonObj.currency.add( result.sttlReqAmt ));

			}, 'GET');
		}
	},
	chart: {
		init: function () {
			//그래프
			google.charts.load('current', {'packages':['corechart']});
			google.charts.load('current', {'packages':['bar']});
			this.view();
		},
		view:function() {
			$('div[id^="ITP_MAIN_DRAW"]').hide();
			var authTpCd = fn_make_user_info.get('authTpCd');
			if(authTpCd === '40' || authTpCd === '10') {
				this.brand.init();
			} else if(authTpCd === '50') {
				this.store.init();
			} else if(authTpCd === '60') {
				this.spply.init();
			}
		},
		brand: {
			init: function() {
				$('#ITP_MAIN_DRAW_CHART_REQ').show();
				google.charts.setOnLoadCallback(this.drawChartReq); // 구매요청

				$('#ITP_MAIN_DRAW_CHART_PODR').show();
				google.charts.setOnLoadCallback(this.drawChartPodr); // 구매발주

				$('#ITP_MAIN_DRAW_CHART_REQ_UP').show();
				google.charts.setOnLoadCallback(this.drawChartReqUp); // 매출순위

				if(fn_make_user_info.get('brandId')) {
					$('#ITP_MAIN_DRAW_CHART_CORE').show();
					google.charts.setOnLoadCallback(this.drawChartcore); // 정산
					chartCnt=4;
				} else {
					chartCnt=3;
				}
				const me=this;
				$('#ITP_FORM_MAIN_SEARCH_PR_TYPE').on('change', function() {
					me.drawChartReq();
				});
				
				$('#ITP_FORM_MAIN_SEARCH_PO_TYPE').on('change', function() {
					me.drawChartPodr();
				});
				
				$('#ITP_FORM_MAIN_SEARCH_ITEM_CNT_TYPE').on('change', function() {
					me.drawChartReqUp();
				});
				
				$('#ITP_FORM_MAIN_SEARCH_DELI_TYPE').on('change', function() {
					// this.drawChartDeli();
				});
				
				$('#ITP_FORM_MAIN_SEARCH_RELEASE_TYPE').on('change', function() {
					// this.drawChartRelease();
				});
				
				$('#ITP_FORM_MAIN_SEARCH_ORDERS_TYPE').on('change', function() {
					// this.drawChartOrders();
				});

				$('#ITP_MAIN_DRAW_LINE').show();
				$('#ITP_MAIN_DRAW_LINE .itp_main_draw_line').show();
				google.charts.setOnLoadCallback(this.drawLine); // 안전재고
			},
			drawChartReq: function() {
				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: chartWidth,
					};
					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');
			},
			drawChartPodr: function() {
				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: chartWidth,
					};
					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');
			},
			drawChartReqUp: function() {
				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: chartWidth,
					};
					console.log("xxxxxxxxxxx drawChartReqUp xxxxxxxxxxx")

					var chart = new google.charts.Bar(document.getElementById('ITP_PCH_REQ_UP_ITEM_GRAPH'));
					chart.draw(data, options);

				}, 'GET');
			},
			drawChartcore: function() {
				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: chartWidth,
					};
					var chart = new google.visualization.PieChart(document.getElementById('ITP_STTL_GRAPH'));
					console.log("xxxxxxxxxxx drawChartcore xxxxxxxxxxx", data, options )
					chart.draw(data, options);

				}, 'GET');
			},
			drawLine: function() {
				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: chartWidth + 100,
						legend: { position: 'top' }
					};

					var chart = new google.visualization.LineChart(document.getElementById('ITP_SAFE_STCK_GRAPH'));
					chart.draw(data, options);

				}, 'GET');
			}
		},
		store: {
			init: function() {

			}
		},
		spply: {
			init: function() {

			}
		}
	}
};

function appCallFnVersion(version) {
	MOBILE_APP_VERSION = version;
	console.log(MOBILE_APP_VERSION);
}

let mobPopObj = {
	popNotice: {
		popId: 'ITP_POP_NOTICE',
		open: function (nticeNo) {
			mobPopObj.show(this.popId);
			this.search(nticeNo);
		},
		close: function() {
			mobPopObj.hide(this.popId);
		},
		search: function (nticeNo) { 
			fn_ajax_call('/api/ntice/info-ntice', {nticeNo}, function(result) {
				// 브랜드그룹 셋팅
				$('#ITP_POP_NOTICE_AREA .fnNoteNm').html(result.nticeTitl);
				$('#ITP_POP_NOTICE_AREA .fnNote').html(result.nticeDesc);
				$('#ITP_POP_NOTICE_AREA .fnNoteFromTo').html(result.notiStDay+' ~ '+result.notiEdDay); 
				/*
				$('#ITP_FORM_NOTICE_INFO_POPUP_AFFL_SHOP_NM').html(result.afflShopNm);
				$('#ITP_FORM_NOTICE_INFO_POPUP_BRAND_NM').html(result.brandNm);
				*/ 
			}, 'GET');
		},
		
	},
	show: function(popId) {
		 console.log("popup show id=="+popId)
		$('#' + popId+' .btn-pop-close').on('click', function() {
			mobPopObj.hide(popId);
		});
		$('#' + popId).show();
	},
	hide: function(popId) {
		$('#' + popId).closest('.mobile-pop-close').hide();
	}
};

function appCallFnConnKey(connKey) {
	if(connKey) {
		sessionStorage.setItem('itp_login_info', JSON.stringify({
			timestamp: new Date(),
			connKey: connKey
		}));
		itp_fn_session_data(connKey);
	} else {
		location.replace('app:logout');
	}
}
