require(['config'], function() {
	require([
	], function($) {
		mobPageObj.init();
	});
});

/*API URL*/
const API_MOBILE_GRID_LIST 			= '/api/stock/cdd/detail-grid-list';	// 목록
const API_MOBILE_SAVE 				= '/api/stock/cdd/save-stock-cdd';		// 저장
const API_MOBILE_BARCODE			= '/api/stock/mng/info-barcode-stock';	// 바코드
const API_MOBILE_WHS_GRID_LIST 		= '/api/whs/mng/detail-grid-list';
const API_MOBILE_LOCATION_LIST 		= '/api/whs/mng/location-grid-list';
const API_POP_STOCK_MNG_LIST 		= '/api/stock/mng/detail-grid-list';

const PAGE_MODE_LIST				= "LIST";
const PAGE_MODE_VIEW				= "VIEW";

let mobPageObj = {
	viewMode: PAGE_MODE_LIST,
	init: function () {
		this.ui.init();
		this.event.init();
		this.ready();
	},
	ui: {
		init: function () {
			this.view();
			this.info();
		},
		view: function() {
			// 공통코드 표시
			$('select').each(function() {
				if($(this).data('select-code')) {
					fn_make_select(CODE_LIST, $(this).data('select-code'), $(this).attr('id'));
				}
			});

			// 조회일자 지정
			$('#ITP_MOBILE_MSTOCKMNG02010 .itp_input.date').datepicker(ITP_DATE_LANGUAGE);
			$('#ITP_FORM_MSTOCKMNG02010_LIST_SEARCH_STCK_DT').datepicker('setDate', itp_fn_date_add('D', 1));
		},
		info: function() {
			$('input:hidden[id$="_BRAND_ID"]').val(fn_make_user_info.get('brandId'));
			$('input:hidden[id$="_STORE_ID"]').val(fn_make_user_info.get('storeId'));
		}
	},
	event: {
		init: function() {
			this.button();
		},
		button: function() {
			$('button[id^="ITP_BTN_MSTOCKMNG02010_LIST"]').on('click', function() {
				var id = $(this).attr('id');
				switch (id) {
					case 'ITP_BTN_MSTOCKMNG02010_LIST_SEARCH_WHS_NM'	: mobPopObj.popWhsNm.init(); 		break;
					case 'ITP_BTN_MSTOCKMNG02010_LIST_DELETE_WHS_NM'	: mobPopObj.popWhsNm.delete(); 		break;
					case 'ITP_BTN_MSTOCKMNG02010_LIST_SEARCH'			: mobContObj.list.search();			break;
					case 'ITP_BTN_MSTOCKMNG02010_LIST_BARCODE'			: mobContObj.barcode.callApp();		break;
					case 'ITP_BTN_MSTOCKMNG02010_LIST_SAVE'				: mobContObj.list.save();			break;
					case 'ITP_BTN_MSTOCKMNG02010_LIST_CANCEL'			: mobContObj.list.cancel();			break;
				}
				return false;
			});

			$(document).off('click', '#ITP_LIST_MSTOCKMNG02010_LIST_ITEM_ROWS li button');
			$(document).on('click', '#ITP_LIST_MSTOCKMNG02010_LIST_ITEM_ROWS li button', function() {
				if($(this).hasClass('DETAIL_ITEM_PLUS')) {
					mobContObj.list.actPlus($(this));
				} else if($(this).hasClass('DETAIL_ITEM_MINUS')) {
					mobContObj.list.actMinus($(this));
				}
			});

		}
	},
	switchScreen: function(mode) {
		$('#ITP_MOBILE_MSTOCKMNG02010').find('div[id$="_CONTAINER"]').each(function(i) {
			$(this).hide();
		});
		if(mode === PAGE_MODE_LIST) {
			$('#ITP_AJAX_MSTOCKMNG02010_LIST_CONTAINER').show();
		} else if(mode === PAGE_MODE_VIEW) {
			$('#ITP_AJAX_MSTOCKMNG02010_VIEW_CONTAINER').show();
		}
		this.viewMode = mode;
	},
	ready: function() {
		mobContObj.list.init();
	}
};

let mobContObj = {
	list: {
		rows: [],
		init: function() {
			mobPageObj.switchScreen(PAGE_MODE_LIST);
		},
		search: function() {
			var formId = '#ITP_FORM_MSTOCKMNG02010_LIST_SEARCH';
			itp_fn_form_clear_validate(null, formId);
			if (itp_fn_form_event.isValid(formId)) {
				mobPopObj.popItemNm.init();
			}
		},
		itemAdd: function(rows) {
			var _this = this;
			$.each(rows, function(index, item) {
				$('#ITP_LIST_MSTOCKMNG02010_LIST_ITEM_ROWS').append($('#ITP_LIST_MSTOCKMNG02010_LIST_ITEM_ROWCOPY').html());
				var $li = $('#ITP_LIST_MSTOCKMNG02010_LIST_ITEM_ROWS > .item-row:last');
				$li.find('.fnItemId').text(item.itemId);
				$li.find('.fnItemNm').text(item.itemNm);
				$li.find('.fnUnit').text(item.unit);
				$li.find('.fnCddQty').text(item.cddQty);
				$li.find('.fnStckQty').text(CommonObj.currency.add(item.stckQty, '개'));
				item['cddQty'] = 1;
				item['normalYn'] = (item.itemId && item.itemId !== '') ? 'Y' : 'N';
				mobContObj.list.rows.push(item);
			});
		},
		actPlus: function(elem) {
			var $div = $(elem).siblings('div');
			var index = $div.parents('li').index();
			var num = Number($div.text());
			$($div).text((num + 1).toString());
			this.rows[index]['cddQty'] = $($div).text();
		},
		actMinus: function(elem) {
			var $div = $(elem).siblings('div');
			var num = Number($div.text());
			if(num <= 1) {
				itp_fn_modal_alert('수량을 확인하세요.');
			} else {
				var index = $div.parents('li').index();
				$($div).text((num - 1).toString());
				this.rows[index]['cddQty'] = $($div).text();
			}
		},
		validClear: function() {
			var formId = '#ITP_FORM_MSTOCKMNG02010_LIST_SEARCH';
			itp_fn_form_clear_validate(null, formId);
		},
		save: function() {
			if($('#ITP_LIST_MSTOCKMNG02010_LIST_ITEM_ROWS').children().length === 0) {
				itp_fn_modal_alert(ITP_MSG_LOCALE.message.grid.noData);
				return;
			}
			var formId = '#ITP_FORM_MSTOCKMNG02010_LIST_SEARCH';
			itp_fn_form_clear_validate(null, formId);
			if (itp_fn_form_event.isValid(formId)) {
				var normalYnCheck = true;
				let gridInsertData = [];
				$.each(this.rows, function(key, value) {
					if (value.normalYn === 'N') {
						normalYnCheck = false;
					}
					gridInsertData.push({
						'cddQty': value.cddQty,
						'itemId': value.itemId
					});
				});
				if(!normalYnCheck) {
					itp_fn_modal_alert_ajax('정상여부 값이 N인 데이터가 있습니다.\n품목번호를 확인하세요.');
					return;
				}
				let param = $(formId).serializeObject();
				param['viewCd'] = 'C';
				param.whsId = $('#ITP_FORM_MSTOCKMNG02010_LIST_SEARCH_WHS_ID').val();
				param.location = $('#ITP_FORM_MSTOCKMNG02010_LIST_SEARCH_LOCATION').val();
				param.gridInsertData = gridInsertData;
				console.log(JSON.stringify(param));
				var searhFn = function() {
					$('#ITP_LIST_MSTOCKMNG02010_LIST_ITEM_ROWS').empty();
				};
				fn_ajax_call(API_MOBILE_SAVE, JSON.stringify(param), searhFn, 'POST');
			}
		},
		cancel: function() {
			$(location).attr('href', MOBILE_CONTEXTPATH + '/app/main.html');
		}
	},
	barcode: {
		callApp: function() {
			var formId = '#ITP_FORM_MSTOCKMNG02010_LIST_SEARCH';
			itp_fn_form_clear_validate(null, formId);
			if (itp_fn_form_event.isValid(formId)) {
				location.replace('app:scan');
				// appCallFnBarcode('ITEM221217000006BRD221200038');
			}
		}
	}
};

function appCallFnBarcode(barcode) {
	var infoFn = function(result) {
		console.log(JSON.stringify(result));
		if(result) {
			mobContObj.list.itemAdd([result]);
		}
	};
	const param = {
		'sBrandId': $('#ITP_FORM_MSTOCKMNG02010_LIST_SEARCH #ITP_FORM_MSTOCKMNG02010_LIST_SEARCH_BRAND_ID').val(),
		'sWhsId': $('#ITP_FORM_MSTOCKMNG02010_LIST_SEARCH #ITP_FORM_MSTOCKMNG02010_LIST_SEARCH_WHS_ID').val(),
		'sLocation': $('#ITP_FORM_MSTOCKMNG02010_LIST_SEARCH #ITP_FORM_MSTOCKMNG02010_LIST_SEARCH_LOCATION').val(),
		'sBarcode': barcode
	};
	// console.log(JSON.stringify(param));
	fn_ajax_call(API_MOBILE_BARCODE, param, infoFn, 'GET');
}

let mobPopObj = {
	popWhsNm: {
		popId: 'ITP_POP_MSTOCKMNG02010_WHS_AREA',
		rows: [],
		init: function () {
			this.rows.length = 0;
			mobPopObj.show(this.popId);
			this.search();
			this.action();
		},
		search: function () {
			var _this = this;
			$('#ITP_LIST_MSTOCKMNG02010_POP_WHS_AREA .panel-group').empty();
			var callbackFn = function(result) {
				console.log(result);
				_this.view(result.gridRows);
			};
			const param = $('#ITP_FORM_MSTOCKMNG02010_POP_WHS').serializeObject();
			(fn_make_user_info.get('authTpCd') === '50') ? param.swhsDvsn = 'W02' : param.swhsDvsn = 'W01';
			console.log(JSON.stringify(param));
			fn_ajax_call(API_MOBILE_WHS_GRID_LIST, JSON.stringify(param), callbackFn, 'POST');
		},
		view: function(gridRows) {
			this.rows = gridRows;
			$.each(gridRows, function (i, item) {
				$('#ITP_LIST_MSTOCKMNG02010_POP_WHS_AREA .panel-group').append($('#ITP_LIST_MSTOCKMNG02010_POP_WHS_ROWCOPY').html());
				var $li = $('#ITP_LIST_MSTOCKMNG02010_POP_WHS_AREA .panel-group > .row_2:last');
				$li.find('.fnWhsNm').text(item.whsNm);
				$li.find('.fnLocationNm').text(item.locationNm);
				$li.find('.fnWhsId').data('whs-id', item.whsId);
			});
		},
		choice: function(elem) {
			var _this = this;
			var whsId = $(elem).data('whs-id');
			$.each(this.rows, function (i, item) {
				if(whsId === item.whsId) {
					$('#ITP_FORM_MSTOCKMNG02010_LIST_SEARCH #ITP_FORM_MSTOCKMNG02010_LIST_SEARCH_WHS_ID').val(item.whsId);
					$('#ITP_FORM_MSTOCKMNG02010_LIST_SEARCH #ITP_FORM_MSTOCKMNG02010_LIST_SEARCH_WHS_NM').val(item.whsNm);
					_this.close();
					_this.location(item.whsId);
					return false;
				}
			});
		},
		location: function(whsId) {
			var callbackFn = function(result) {
				fn_make_select_location(result.gridRows, 'ITP_FORM_MSTOCKMNG02010_LIST_SEARCH_LOCATION');
			};
			var param = {
				'brandId': fn_make_user_info.get('brandId'),
				'storeId': fn_make_user_info.get('storeId'),
				'whsId': whsId
			};
			fn_ajax_call(API_MOBILE_LOCATION_LIST, JSON.stringify(param), callbackFn, 'POST');
		},
		action: function() {
			var _this = this;
			$('button[id^="ITP_BTN_MSTOCKMNG02010_POP_WHS"]').off('click').on('click', function() {
				var id = $(this).attr('id');
				switch (id) {
					case 'ITP_BTN_MSTOCKMNG02010_POP_WHS_SEARCH'	: _this.search();			break;
					case 'ITP_BTN_MSTOCKMNG02010_POP_WHS_CHOICE'	: _this.choice($(this)); 	break;
					case 'ITP_BTN_MSTOCKMNG02010_POP_WHS_CLOSE'		: _this.close(); 			break;
				}
				return false;
			});
		},
		delete: function() {
			$('#ITP_FORM_MSTOCKMNG02010_LIST_SEARCH #ITP_FORM_MSTOCKMNG02010_LIST_SEARCH_WHS_ID').val('');
			$('#ITP_FORM_MSTOCKMNG02010_LIST_SEARCH #ITP_FORM_MSTOCKMNG02010_LIST_SEARCH_WHS_NM').val('');
			$('#ITP_FORM_MSTOCKMNG02010_LIST_SEARCH #ITP_FORM_MSTOCKMNG02010_LIST_SEARCH_LOCATION option').remove();
		},
		close: function() {
			this.rows.length = 0;
			$('#ITP_POP_MSTOCKMNG02010_LIST_WHS_AREA .panel-group').empty();
			$('#ITP_FORM_MSTOCKMNG02010_POP_WHS #ITP_FORM_MSTOCKMNG02010_POP_WHS_KEYWORD').val('');
			mobPopObj.hide(this.popId);
		}
	},
	popItemNm: {
		popId: 'ITP_POP_MSTOCKMNG02010_ITEM_AREA',
		rows: [],
		init: function () {
			this.rows.length = 0;
			mobPopObj.show(this.popId);
			this.reset();
			this.search();
			this.action();
		},
		search: function () {
			var _this = this;
			$('#ITP_POP_MSTOCKMNG02010_TABLE_AREA .table_body').remove();
			var callbackFn = function(result) {
				console.log(result);
				_this.rows = result.gridRows;
				$.each(result.gridRows, function (i, item) {
					$('#ITP_POP_MSTOCKMNG02010_TABLE_AREA .m_table_body').append($('#ITP_POP_MSTOCKMNG02010_TABLE_TR').html());
					var $li = $('#ITP_POP_MSTOCKMNG02010_TABLE_AREA .m_table_body > .table_body:last');
					$li.find('.fnItemId').text(item.itemId);
					$li.find('.fnItemNm').text(item.itemNm);
					$li.find('.fnUnit').text(item.unit);
					$li.find('.fnStckQty').text(CommonObj.currency.add(item.stckQty, '개'));
				});
			};
			var param = $('#ITP_FORM_MSTOCKMNG02010_POPUP_ITEM').serializeObject();
			console.log(JSON.stringify(param));
			fn_ajax_call(API_POP_STOCK_MNG_LIST, JSON.stringify(param), callbackFn, 'POST');
		},
		action: function() {
			var _this = this;
			$('button[id="ITP_BTN_MSTOCKMNG02010_POP_ITEM_SEARCH"]').off('click').on('click', function() {
				_this.search();
			});
			$('button[id="ITP_BTN_MSTOCKMNG02010_POP_ITEM_CHOICE"]').off('click').on('click', function() {
				_this.choice();
			});
			$('#ITP_POP_MSTOCKMNG02010_TABLE_AREA input:checkbox').off('click').on('click', function() {
				_this.checked($(this));
			});
		},
		checked: function(elem) {
			var clsNm = '.table_body';
			if($(elem).hasClass('chkAll')) {
				$(clsNm).find('input:checkbox').prop('checked', $(elem).is(':checked'));
			} else {
				var isChkAll = true;
				$(clsNm).find('input:checkbox').each(function() {
					if(!$(this).hasClass('chkAll') && !$(this).is(':checked')) {
						isChkAll = false;
						return false;
					}
				});
				$(clsNm).find('.chkAll').prop('checked', isChkAll);
			}
		},
		choice: function() {
			var _this = this;
			var items = [];
			$('#ITP_POP_MSTOCKMNG02010_TABLE_AREA input:checkbox').each(function(i) {
				if(!$(this).hasClass('chkAll') && $(this).is(':checked')) {
					items.push(_this.rows[i-1]);
				}
			});
			mobContObj.list.itemAdd(items);
			mobPopObj.hide(this.popId);
		},
		reset: function() {
			this.rows.length = 0;
			$('#ITP_FORM_MSTOCKMNG02010_POPUP_ITEM select').find('option:first').prop('selected', true);
			$('#ITP_FORM_MSTOCKMNG02010_POP_ITEM_KEYWORD').val('');
			$('#ITP_POP_MSTOCKMNG02010_TABLE_AREA .table_body').remove();
		}
	},
	show: function(popId) {
		$('button[id$="_CLOSE"]').off('click').on('click', function() {
			if($(this).hasClass('btn-pop-close')) {
				mobPopObj.hide(popId);
			}
		});
		$('#' + popId).show();
	},
	hide: function(popId) {
		$('#' + popId).closest('.mobile-pop-close').hide();
	}
};
