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

/*API URL*/
const API_MOBILE_INIT_INFO	= '/api/rtnmng/init-rtnReq';
const API_MOBILE_SAVE		= '/api/rtnmng/save-rtnReq';
const API_POP_SEARCH_LIST	= '/api/whs/mng/pop-whs-search';
const API_POP_ITEM_LIST 	= '/api/item/pop-grid-list';

const ID_ITP_POP_MRTNMNG01010_REQ_AREA 		= "ITP_POP_MRTNMNG01010_REQ_AREA";
const ID_ITP_POP_MRTNMNG01010_WHS_AREA 		= "ITP_POP_MRTNMNG01010_WHS_AREA";
const ID_ITP_POP_MRTNMNG01010_ITEM_AREA 	= "ITP_POP_MRTNMNG01010_ITEM_AREA";

const RTN_REQ_ST_CD_TEMP_SAVE		="RR00";
const RTN_REQ_ST_CD_REQUEST_SAVE	="RR20";

let mobPageObj = {
	isPrevPage: false,
	pageParam: null,
	init: function () {
		this.ui.init();
		this.event.init();
		this.ready();
	},
	ui: {
		init: function () {
			this.info();
			this.view();
		},
		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'));
		},
		view: function() {
			// 조회일자 지정
			$('#ITP_MOBILE_MRTNMNG01010 .itp_input.date').datepicker(ITP_DATE_LANGUAGE);
			$('#ITP_FORM_MRTNMNG01010_DETAIL_DLV_REQ_DT').datepicker('setDate', itp_fn_date_add('M', 1));

			if(fn_make_user_info.get('authTpCd') === '50') {
				$('#ITP_FORM_MRTNMNG01010_DETAIL #ITP_BTN_MRTNMNG01010_DETAIL_SEARCH_WHS_NM').hide();
				$('#ITP_FORM_MRTNMNG01010_DETAIL #ITP_BTN_MRTNMNG01010_DETAIL_DELETE_WHS_NM').hide();
			}
		}
	},
	event: {
		init: function() {
			this.button();
		},
		button: function() {
			$('button[id^="ITP_BTN_MRTNMNG01010_DETAIL"]').on('click', function() {
				if($(this).is('[data-call-popup]')) {
					mobPopObj.show($(this).data('call-popup'), $(this).attr('id'));
				} else {
					var id = $(this).attr('id');
					switch (id) {
						case 'ITP_BTN_MRTNMNG01010_DETAIL_DELROW'			: mobContObj.list.delRow(); 		break;
						case 'ITP_BTN_MRTNMNG01010_DETAIL_SEARCH_WHS_NM'	: mobPopObj.popWhsNm.init(); 		break;
						case 'ITP_BTN_MRTNMNG01010_DETAIL_DELETE_WHS_NM'	: mobPopObj.popWhsNm.delete();		break;
						case 'ITP_BTN_MRTNMNG01010_DETAIL_CANCEL'			: mobContObj.cancel();				break;
					}
				}
				return false;
			});

			$(document).on('click', '#ITP_LIST_MRTNMNG01010_POP_WHS_ROWS li button', function() {
				mobPopObj.popWhsNm.choice($(this));
			});
		}
	},
	ready: function() {
		mobContObj.init();
	}
};

let mobContObj = {
	init: function() {
		this.button();
		this.data.load();
	},
	button: function() {
		var _this = this;
		$(document).on('click', '.DETAIL_ITEM_PLUS', function() {
			_this.list.actPlus($(this));
		});
		$(document).on('click', '.DETAIL_ITEM_MINUS', function() {
			_this.list.actMinus($(this));
		});
	},
	data: {
		initPchReq: null,
		load: function() {
			var _this = this;
			var callbackFn = function(result) {
				console.log(result);
				_this.initPchReq = result;
				$('#ITP_FORM_MRTNMNG01010_DETAIL #ITP_FORM_MRTNMNG01010_DETAIL_BRAND_ID').val(result.brandId);
				$('#ITP_FORM_MRTNMNG01010_DETAIL #ITP_FORM_MRTNMNG01010_DETAIL_STORE_ID').val(result.storeId);
				$('#ITP_FORM_MRTNMNG01010_DETAIL #ITP_FORM_MRTNMNG01010_DETAIL_WHS_ID').val(result.rtnWhsId);
				$('#ITP_FORM_MRTNMNG01010_DETAIL #ITP_FORM_MRTNMNG01010_DETAIL_WHS_NM').val(result.rtnWhsNm);
				$('#ITP_FORM_MRTNMNG01010_DETAIL #ITP_FORM_MRTNMNG01010_DETAIL_LOCATION').val(result.rtnLocation);
				$('#ITP_FORM_MRTNMNG01010_DETAIL #ITP_FORM_MRTNMNG01010_DETAIL_LOCATION_NM').val(result.rtnLocationNm);
				$('#ITP_FORM_MRTNMNG01010_DETAIL #ITP_FORM_MRTNMNG01010_DETAIL_WHS_DVSN').val(result.whsDvsn);
			};
			const param = {brandId:fn_make_user_info.get('brandId'), storeId:fn_make_user_info.get('storeId')};
			fn_ajax_call(API_MOBILE_INIT_INFO, param, callbackFn, 'GET');
		}
	},
	list: {
		rows: [],
		addRow: function() {
		},
		delRow: function() {
			this.detachRow();
		},
		attachRow: function (items) {
			var _this = this;
			var fnIsExist = function(rows, item) {
				var isExist = false;
				$.each(rows, function(i, row) {
					if(row.brandUnitUnqNo === item.brandUnitUnqNo) {
						isExist = true;
						return false;
					}
				});
				return isExist;
			};
			$.each(items, function(i, item) {
				if(!fnIsExist(_this.rows, item)) {
					_this.rows.push(item);
					$('#ITP_LIST_MRTNMNG01010_ITEM_AREA .panel-group').append($('#ITP_LIST_MRTNMNG01010_DETAIL_ROWCOPY').html());
					var $li = $('#ITP_LIST_MRTNMNG01010_ITEM_AREA .panel-group > .list-row:last');
					$li.find('.fnBrandUnitUnqNo').val(item.brandUnitUnqNo);
					$li.find('.fnItemNm').text(item.itemNm);
					$li.find('.fnPchReqQty').text(item.pchReqQty);
					$li.find('.fnUnitAmt').text(CommonObj.currency.add(item.unitAmt));
					_this.pchReqAmtTot();
				}
			});
		},
		detachRow: function () {
			if($('#ITP_LIST_MRTNMNG01010_ITEM_AREA input:checkbox[name=brandUnitUnqNo]:checked').length > 0) {
				var _this = this;
				$('#ITP_LIST_MRTNMNG01010_DETAIL_ROWS li').each(function(index, elem) {
					var __this = this;
					var isChecked = $(this).find('input[type="checkbox"]').is(':checked');
					if(isChecked) {
						$(this).remove();
						$.each(_this.rows, function(i, row){
							if(row.brandUnitUnqNo === $(__this).find('input[type="checkbox"]').val()) {
								_this.rows.splice(i, 1);
								return false;
							}
						});
					}
				});
				this.pchReqAmtTot();
			}
		},
		actPlus: function(elem) {
			var $div = $(elem).siblings('div');
			var num = Number($div.text());
			$($div).text((num + 1).toString());
			this.rows[$div.parents('li').index()]['pchReqQty'] = $($div).text();
			this.pchReqAmtTot();
		},
		actMinus: function(elem) {
			var $div = $(elem).siblings('div');
			var num = Number($div.text());
			if(num <= 1) {
				itp_fn_modal_alert('수량을 확인하세요.');
			} else {
				$($div).text((num - 1).toString());
				this.rows[$div.parents('li').index()]['pchReqQty'] = $($div).text();
				this.pchReqAmtTot();
			}
		},
		pchReqAmtTot: function() {
			var reqAmt = 0;
			$.each(this.rows, function(index, item) {
				var qty = item.pchReqQty;
				var amt = item.unitAmt;
				reqAmt += Number(qty) * amt;
			});
			$('#ITP_AJAX_MRTNMNG01010_DETAIL_CONTAINER').find('.fnRtnReqAmt').text(CommonObj.currency.add(reqAmt));
		}
	},
	cancel: function () {
		$(location).attr('href', MOBILE_CONTEXTPATH + '/app/main.html');
	}
};

let mobPopObj = {
	init: function(popId, parentId) {
		switch (popId) {
			case 'ITP_POP_MRTNMNG01010_RTN_AREA'		: this.popReqConfirm.init(parentId); 	break;
			case 'ITP_POP_MRTNMNG01010_WHS_AREA'		: this.popWhsNm.init(); 				break;
			case 'ITP_POP_MRTNMNG01010_ITEM_AREA'		: this.popItem.init();					break;
		}
		$('#' + popId).show();
	},
	popItem: {
		// rows: null,
		init: function() {
			this.search();
		},
		search: function() {
			$('#ITP_LIST_MRTNMNG01010_POP_ITEM_AREA .panel-group').empty();
			var callbackFn = function(result) {
				console.log(result);
				mobPopObj.popItem.rows = result.gridRows;
				$.each(mobPopObj.popItem.rows, function (i, item) {
					$('#ITP_LIST_MRTNMNG01010_POP_ITEM_AREA .panel-group').append($('#ITP_LIST_MRTNMNG01010_POP_ITEM_ROWCOPY').html());
					var $li = $('#ITP_LIST_MRTNMNG01010_POP_ITEM_AREA .panel-group > .row_2:last');
					$li.find('#ITP_FORM_MRTNMNG01010_POP_ITEM_CHECKBOX').val(item.itemId);
					$li.find('.fnItemNm').text(item.itemNm);
					$li.find('.fnUnitAmt').text(CommonObj.currency.add(item.unitAmt));
					$li.find('.fnOrdAmt').text(CommonObj.currency.add(item.unitAmt));
				});
				mobPopObj.popItem.addRow.init();
			};
			let param = $('#ITP_FORM_MRTNMNG01010_POPUP_ITEM').serializeObject();
			fn_ajax_call(API_POP_ITEM_LIST, JSON.stringify(param), callbackFn, 'POST');
		},
		addRow: {
			init: function() {
				this.button.init();
			},
			button: {
				init: function() {
					var _this = this;
					$('button[id^="ITP_BTN_MRTNMNG01010_POP_ITEM_"]').off('click').on('click', function() {
						var id = $(this).attr('id');
						switch (id) {
							case 'ITP_BTN_MRTNMNG01010_POP_ITEM_PLUS'	: _this.actPlus($(this)); 		break;
							case 'ITP_BTN_MRTNMNG01010_POP_ITEM_MINUS'	: _this.actMinus($(this)); 		break;
							case 'ITP_BTN_MRTNMNG01010_POP_ITEM_ADD'		: _this.addItems(); 			break;
							// case 'ITP_BTN_MRTNMNG01010_POP_ITEM_ADD'		: _this.actItemAdd($(this)); 	break;
							case 'ITP_BTN_MRTNMNG01010_POP_ITEM_SEARCH'	: mobPopObj.popItem.search(); 	break;
							case 'ITP_BTN_MRTNMNG01010_POP_ITEM_CLOSE'	: mobPopObj.hide(id); 			break;
						}
						return false;
					});
				},
				actPlus: function(elem) {
					var $div = $(elem).siblings('div');
					var num = Number($div.text());
					$($div).text((num + 1).toString());
					this.reqAmtUnit(elem, $($div).text());
				},
				actMinus: function(elem) {
					var $div = $(elem).siblings('div');
					var num = Number($div.text());
					if(num <= 1) {
						itp_fn_modal_alert('수량을 확인하세요.');
					} else {
						$($div).text((num - 1).toString());
						this.reqAmtUnit(elem, $($div).text());
					}
				},
				reqAmtUnit: function(elem, qty) {
					var $li = $(elem).closest('li');
					var unitAmt = CommonObj.onlyNumber($li.find('.fnUnitAmt').text());
					$li.find('.fnOrdAmt').text(CommonObj.currency.add(Number(unitAmt ? unitAmt : 0) * Number(qty)));
				},
				actItemAdd: function(elem) {
					var $li = $(elem).closest('li');
					var item = mobPopObj.popItem.rows[$li.index()];
					item['pchReqQty'] = $li.find('.fnPchReqQty').html();
					// var index = $(elem).closest('li').index();
					// var item = mobPopObj.popItem.rows[index];
					// item['pchReqQty'] = $(elem).closest('li').find('.fnPchReqQty').html();
					mobContObj.list.attachRow(item);
				},
				addItems: function() {
					var items = [];
					$('#ITP_LIST_MRTNMNG01010_POP_ITEM_ROWS').find('input:checkbox').each(function() {
						if($(this).is(':checked')) {
							var index = $(this).closest('li').index();
							var item = mobPopObj.popItem.rows[index];
							item['pchReqQty'] = $(this).closest('li').find('.fnPchReqQty').html();
							items.push(item);
						}
					});
					if(items.length > 0) {
						mobContObj.list.attachRow(items);
						mobPopObj.popItem.close();
					} else {
						itp_fn_modal_alert('품목을 선택하세요.');
					}
				}
			}
		},
		delRow: function() {

		},
		close: function() {
			this.rows.length = 0;
			$('#ITP_LIST_MRTNMNG01010_POP_ITEM_ROWS').children().remove();
			mobPopObj.hide('ITP_POP_MRTNMNG01010_ITEM_AREA');
		}
	},
	popWhsNm: {
		init: function () {
			this.rows.length = 0;
			this.search();
			this.action();
		},
		rows: [],
		search: function () {
			var _this = this;
			$('#ITP_LIST_MRTNMNG01010_POP_WHS_AREA .panel-group').empty();
			var callbackFn = function(result) {
				console.log(result);
				_this.view(result.gridRows);
			};
			const param = $('#ITP_FORM_MRTNMNG01010_POP_WHS').serializeObject();
			(fn_make_user_info.get('authTpCd') === '50') ? param.swhsDvsn = 'W02' : param.swhsDvsn = 'W01';
			fn_ajax_call(API_POP_SEARCH_LIST, JSON.stringify(param), callbackFn, 'POST');
		},
		view: function(gridRows) {
			this.rows = gridRows;
			$.each(gridRows, function (i, item) {
				$('#ITP_LIST_MRTNMNG01010_POP_WHS_AREA .panel-group').append($('#ITP_LIST_MRTNMNG01010_POP_WHS_ROWCOPY').html());
				var $li = $('#ITP_LIST_MRTNMNG01010_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);
			});
		},
		action: function() {
			var _this = this;
			$('button[id^="ITP_BTN_MPOMNG04010_POP_WHS"]').off('click').on('click', function() {
				var id = $(this).attr('id');
				switch (id) {
					case 'ITP_BTN_MRTNMNG01010_POP_WHS_SEARCH'	: _this.search();			break;
					case 'ITP_BTN_MRTNMNG01010_POP_WHS_CHOICE'	: _this.choice($(this)); 	break;
					case 'ITP_BTN_MRTNMNG01010_POP_WHS_CLOSE'	: _this.close(); 			break;
				}
				return false;
			});
		},
		choice: function(elem) {
			var _this = this;
			var whsId = $(elem).data('whs-id');
			$.each(this.rows, function (i, item) {
				if(whsId === item.whsId) {
					console.log(item);
					$('#ITP_FORM_MRTNMNG01010_DETAIL #ITP_FORM_MRTNMNG01010_DETAIL_WHS_ID').val(item.whsId);
					$('#ITP_FORM_MRTNMNG01010_DETAIL #ITP_FORM_MRTNMNG01010_DETAIL_WHS_NM').val(item.whsNm);
					$('#ITP_FORM_MRTNMNG01010_DETAIL #ITP_FORM_MRTNMNG01010_DETAIL_LOCATION').val(item.location);
					mobPopObj.hide(ID_ITP_POP_MRTNMNG01010_WHS_AREA);
					itp_fn_form_clear_validate(null, '#ITP_FORM_MRTNMNG01010_DETAIL');
					return false;
				}
			});
		},
		delete: function() {
			$('#ITP_FORM_MRTNMNG01010_DETAIL #ITP_FORM_MRTNMNG01010_DETAIL_WHS_ID').val('');
			$('#ITP_FORM_MRTNMNG01010_DETAIL #ITP_FORM_MRTNMNG01010_DETAIL_WHS_NM').val('');
			$('#ITP_FORM_MRTNMNG01010_DETAIL #ITP_FORM_MRTNMNG01010_DETAIL_LOCATION').val('');
		},
		close: function() {
			this.rows.length = 0;
			$('#ITP_LIST_MRTNMNG01010_POP_WHS_AREA .panel-group').empty();
			$('#ITP_POP_MRTNMNG01010_WHS_AREA #ITP_FORM_MRTNMNG01010_POP_WHS_KEYWORD').val('');
			mobPopObj.hide(this.popId);
		}
	},
	popReqConfirm: {
		init: function (parentId) {
			this.rtnReqStCd = (parentId === 'ITP_BTN_MRTNMNG01010_DETAIL_RTN_ORDER') ? RTN_REQ_ST_CD_REQUEST_SAVE : RTN_REQ_ST_CD_TEMP_SAVE;
			this.view();
			this.action();
		},
		view: function() {
			if(this.rtnReqStCd === RTN_REQ_ST_CD_REQUEST_SAVE) {
				$('#ITP_POP_MRTNMNG01010_RTN_AREA .msg_save').text('빈품요청 하시겠습니까?');
			} else {
				$('#ITP_POP_MRTNMNG01010_RTN_AREA .msg_save').text('임시저장 하시겠습니까?');
			}
			$('#ITP_POP_MRTNMNG01010_RTN_AREA .fnRtnReqDt').text($('#ITP_FORM_MRTNMNG01010_DETAIL #ITP_FORM_MRTNMNG01010_DETAIL_DLV_REQ_DT').val());
			$('#ITP_POP_MRTNMNG01010_RTN_AREA .fnItemQty').text(CommonObj.currency.add(mobContObj.list.rows.length, '개'));
			$('#ITP_POP_MRTNMNG01010_RTN_AREA .fnRtnAmt').text($('#ITP_FORM_MRTNMNG01010_DETAIL .fnRtnReqAmt').text());
			$('#ITP_FORM_MRTNMNG01010_DETAIL #ITP_FORM_MRTNMNG01010_DETAIL_RTN_REQ_ST_CD').val(this.rtnReqStCd);
		},
		action: function() {
			var _this = this;
			$('#ITP_POP_MRTNMNG01010_RTN_AREA button[id="ITP_BTN_MRTNMNG01010_POP_RTN_CONFIRM"]').off('click').on('click', function() {
				_this.save('#ITP_FORM_MRTNMNG01010_DETAIL');
			});
		},
		save: function(formId) {
			let param = $(formId).serializeObject();
			var gridInsertData = [];
			$.each(mobContObj.list.rows, function(index, row) {
				row['viewCd'] 			= 'C';
				row['rtnQty']			= row.pchReqQty;
				row['rtnAmt']			= parseInt(row.unitAmt) * parseInt(row.pchReqQty);
				gridInsertData.push(row);
			});
			param.gridInsertData = gridInsertData;
			param['colReqDt'] = param.colReqDt.replace(/[^0-9]/g, "");
			// console.log(JSON.stringify(param));
			var saveFn = function (result) {
				console.log(result);
				mobPopObj.hide('ITP_POP_MRTNMNG01010_RTN_AREA');
				$('#ITP_LIST_MRTNMNG01010_DETAIL_ROWS').empty();
				mobContObj.list.rows.length = 0;
				$('#ITP_AJAX_MRTNMNG01010_DETAIL_CONTAINER').find('.fnRtnReqAmt').text('');
			};
			fn_ajax_call(API_MOBILE_SAVE, JSON.stringify(param), saveFn, 'POST');
		}
	},
	show: function(popId, parentId) {
		var _this = this;
		$('button[id$="CLOSE"]').off('click').on('click', function() {
			var id = $(this).attr('id');
			if($(this).hasClass('btn-pop-close')) {
				_this.hide(id);
			}
		});
		if(parentId === 'ITP_BTN_MRTNMNG01010_DETAIL_RTN_ORDER' || parentId === 'ITP_BTN_MRTNMNG01010_DETAIL_TEMP_SAVE') {
			var formId = '#ITP_FORM_MRTNMNG01010_DETAIL';
			itp_fn_form_clear_validate(null, formId);
			if (itp_fn_form_event.isValid(formId)) {
				if($('#ITP_LIST_MRTNMNG01010_DETAIL_ROWS li').length < 1) {
					itp_fn_modal_alert('품목추가 버튼을 이용하여 품목을 추가해 주세요.');
				} else {
					mobPopObj.init(popId, parentId);
				}
			}
		} else {
			mobPopObj.init(popId, parentId);
		}
	},
	hide: function(id) {
		$('#' + id).closest('.mobile-pop-close').hide();
	}
};
