require(['config'], function() {
	require([
		'jquery.bootstrap.fileUpload' //파일 업로드가 있는 페이지에서 로딩
	], function($) {
		pageObj.init();
	});
});

/********************************************************
 --------------------------------------------------------
 - Object 목록								            -
 --------------------------------------------------------
 * const gridColModel = {}	: 화면 Grid Object			*
 * let pageObj = {}			: 화면공통 Object			*
 * let listObj = {}			: 목록화면 Object			*
 * let viewObj = {}			: 상세화면 Object			*
 * let modifyObj = {}		: 수정화면 Object			*
 * let createObj = {}		: 신규화면 Object			*
 *******************************************************/

/*화면 변수*/
const STINFO07010_GRID_ID = '#ITP_STINFO07010_jqGrid';
const STINFO07010_GRID_LIST = '#ITP_STINFO07010_jqGrid_list';
const STINFO07010_GRID_PAGER = '#ITP_STINFO07010_jqGridPager';
const STINFO07010_GRID_EMPTY = '#ITP_STINFO07010_jqGridEmpty';

let ITP_FORM_STINFO07010_DETAIL_IS_DUPLICATE = false;
let ITP_FORM_STINFO07010_DETAIL_IS_WRITING = false;

/*API URL*/
let API_DETAIL_GRID_LIST 	= '/api/item/itemclass-grid-list';	    // 목록
let API_DETAIL_INFO 		= '/api/item/info-itemClassMng';		// 상세
let API_DETAIL_DELETE 		= '/api/item/del-itemClassMng';			// 삭제
let API_ITEM_CLASS_LEVEL	= '/api/item/class-level-list';			//품목분류 level 검색

/*화면 Grid ColModel*/
const gridColModel = {
	list: [
		{
			index: 'BRAND_ID', name: 'brandId',
			label: ITP_MSG_LOCALE.label.brandId, //브랜드ID
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: true
		},
		{
			index: 'ITEM_CLASS_MNG_NO', name: 'itemClassMgntNo',
			label: ITP_MSG_LOCALE.label.itemClassMgntNo, //품목분류번호
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'ITEM_CLASS_NM', name: 'itemClassNm',
			label: ITP_MSG_LOCALE.label.itemClassNm, //품목분류명
			width: '10', fixed: false, align: 'left',
			sortable: false, hidden: false, classes: 'ui-ellipsis'
		},
		{
			index: 'ITEM_CLASS_LEVEL1', name: 'itemClass1Nm',
			label: ITP_MSG_LOCALE.label.itemClassLevel1, //품목분류Level 1
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: false, classes: 'ui-ellipsis'
		},
		{
			index: 'ITEM_CLASS_LEVEL2', name: 'itemClass2Nm',
			label: ITP_MSG_LOCALE.label.itemClassLevel2, //품목분류Level 2
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: false, classes: 'ui-ellipsis'
		},
		{
			index: 'ITEM_CLASS_LEVEL3', name: 'itemClass3Nm',
			label: ITP_MSG_LOCALE.label.itemClassLevel3, //품목분류Level 3
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: false, classes: 'ui-ellipsis'
		},
		{
			index: 'ITEM_CLASS_LEVEL4', name: 'itemClass4Nm',
			label: ITP_MSG_LOCALE.label.itemClassLevel4, //품목분류Level 4
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: false, classes: 'ui-ellipsis'
		},
		{
			index: 'PRN_SEQ', name: 'prnSeq',
			label: ITP_MSG_LOCALE.label.prnSeq, //출력순번
			width: '15', fixed: false, align: 'center',
			sortable: false, hidden: true
		}
	]
};

/*화면공통 Object*/
let pageObj = {
	init: function () {
		this.ui.init();
		this.event.init();
	},
	ui: {
		init: function () {
			this.view();
			this.grid();
			this.ready();
		},
		view: function() {
			// 버튼 권한설정
			fn_proc_btn_auth('STINFO07010');

			// 공통코드 표시
			itemClassLevel.init('ITP_FORM_STINFO07010_SEARCH_ITEM_CLASS', 1);
		},
		grid: function() {
			itp_fn_jqgrid_resize(STINFO07010_GRID_ID, STINFO07010_GRID_LIST, 'lg');
			listObj.empty.init();
		},
		ready: function() {
			listObj.init();
		}
	},
	event: {
		init: function () {
			this.button();
		},
		button: function () {
			// 버튼 클릭 이벤트
			$('button').each(function() {
				var id = $(this).attr('id');
				$(this).on('click', function() {
					switch (id) {
						case 'ITP_BTN_STINFO07010_SRH'				: listObj.button.search();		break;	// 조회 버튼 클릭
						case 'ITP_BTN_STINFO07010_NEWREG'			: listObj.popup(); 				break;	// 신규등록 버튼
						case 'ITP_BTN_STINFO07010_MODIFY'			: modifyObj.button.modify();	break;	// 수정 버튼
						case 'ITP_BTN_STINFO07010_CANCELLIST'		: createObj.button.cancel(); 	break;	// 취소/목록 버튼
						case 'ITP_BTN_STINFO07010_DELETE'			: listObj.button.deleteObj();		break;	// 삭제 버튼
						case 'ITP_BTN_STINFO07010_SAVE'				: createObj.button.save(); 		break;	// 저장 버튼
					}
				});
			});

		}
	},
	switchScreen: function(mode) {
		$('.itp_det_head').find('button[id^="ITP_BTN_STINFO07010_"]').each(function(i) {
			$(this).hide();
		});
		$('#ITP_TAB_STINFO07010').find('div[id$="_CONTAINER"]').each(function(i) {
			$(this).hide();
		});
		if(mode == 'LIST') { // 목록
			itp_fn_fire_window_resize();
			$('#ITP_AJAX_STINFO07010_LIST_CONTAINER').show();
			fn_show_btn_auth_array(['#ITP_BTN_STINFO07010_SRH', '#ITP_BTN_STINFO07010_NEWREG', '#ITP_BTN_STINFO07010_DELETE']);
		} else if(mode == 'ADD') { // 등록
			$('#ITP_AJAX_STINFO07010_DETAIL_CONTAINER').show();
			fn_show_btn_auth_array(['#ITP_BTN_STINFO07010_CANCELLIST', '#ITP_BTN_STINFO07010_SAVE']);

			$('#ITP_FORM_STINFO07010_DETAIL').find('input, textarea, select, checkbox').each(function(i, elem) {
				$(this).attr('id') === 'ITP_FORM_STINFO07010_DETAIL_VIEW_CD' ? $(this).val('C') : $(this).val('');
				if(elem.type === 'select') {
					$(this).val('').prop('selected', true);
				}
			});

			// 브랜드그룹 정보 설정
			$('#ITP_FORM_STINFO07010_DETAIL_AFFL_SHOP_ID').val(fn_make_user_info.get('afflShopId'));
			$('#ITP_FORM_STINFO07010_DETAIL_BRAND_ID').val(fn_make_user_info.get('brandId'));

			$('#ITP_FORM_STINFO07010_DETAIL_STORE_ID').removeAttr('readonly');
			$('#ITP_FORM_STINFO07010_DETAIL_DUP').removeAttr('disabled');

			$('#ITP_FORM_STINFO07010_DETAIL .fnStoreNm').text('(자동부여)');
		} else if(mode == 'MODIFY') { // 수정
			$('#ITP_AJAX_STINFO07010_DETAIL_CONTAINER').show();
			fn_show_btn_auth_array(['#ITP_BTN_STINFO07010_CANCELLIST', '#ITP_BTN_STINFO07010_SAVE', '#ITP_BTN_STINFO07010_RESET_PW']);

			// 브랜드그룹 정보 설정
			$('#ITP_FORM_STINFO07010_DETAIL_AFFL_SHOP_ID').val(fn_make_user_info.get('afflShopId'));
			$('#ITP_FORM_STINFO07010_DETAIL_BRAND_ID').val(fn_make_user_info.get('brandId'));

			$('#ITP_FORM_STINFO07010_DETAIL_STORE_ID').attr('readonly', true);
			$('#ITP_FORM_STINFO07010_DETAIL_DUP').attr('disabled', true);
			$('#ITP_FORM_STINFO07010_DETAIL_SEARCH_AFFL_SHOP_NM').attr('readonly', true);

			$('#ITP_FORM_STINFO07010_DETAIL_SEARCH_AFFL_SHOP').hide();
			$('#ITP_FORM_STINFO07010_DETAIL_DELETE_AFFL_SHOP').hide();
		} else if(mode == 'VIEW') { // 보기
			$('#ITP_AJAX_STINFO07010_VIEW_CONTAINER').show();
			fn_show_btn_auth_array(['#ITP_BTN_STINFO07010_MODIFY', '#ITP_BTN_STINFO07010_CANCELLIST']);
		}
	}
};

/*목록화면 Object*/
let listObj = {
	init: function () {
		this.form();
		this.grid.init();
	},
	itp_STINFO07010_search: false,
	button: {
		search: function() {
			listObj.itp_STINFO07010_search = true;
			let param = $('#ITP_FORM_STINFO07010_SEARCH').serializeObject();
			param.gridSize = $.jgrid.defaults.rowNum;
			param.gridPage = $.jgrid.defaults.page;
			$(STINFO07010_GRID_ID).data('grid-param',param);
			$(STINFO07010_GRID_ID).setGridParam($.param(param)).trigger('reloadGrid');
			// $(STINFO07010_GRID_ID).setGridParam({'postData': JSON.stringify(param)}).trigger('reloadGrid');

			listObj.grid.search();
		},
		create: function() {
			if(!fn_make_user_info.isEmpty()) {
				createObj.init();
			}
		},
		deleteObj: function() {
			var selectedIds = $(STINFO07010_GRID_ID).getGridParam('selarrrow');
			if(selectedIds.length < 1) { // 1개만 선택
				return;
			}
			var deleteFn = {
				callBack: function(args) {
					var itemClassMgntNos = '';
					for (var i=0; i<selectedIds.length; i++) {
						itemClassMgntNos += $(STINFO07010_GRID_ID).jqGrid('getRowData', selectedIds[i]).itemClassMgntNo;
						if(i < selectedIds.length-1)  itemClassMgntNos += ',';
					}
					var searchFn = function() {
						listObj.grid.search();
					};
					var param = $.param({brandId:fn_make_user_info.get('brandId'), itemClassMgntNo:itemClassMgntNos});
					fn_ajax_call(API_DETAIL_DELETE,  param, searchFn, 'GET');
				}
			};
			itp_fn_modal_confirm(ITP_MSG_LOCALE.message.form.deleteData, deleteFn, null);
		}
	},
	form: function() {
		$('#ITP_FORM_STINFO07010_SEARCH_ITEM_CLASS1').on('change', function() {
			($(this).val() === '') ? itemClassLevel.clear(2): itemClassLevel.change(2);
		});
		$('#ITP_FORM_STINFO07010_SEARCH_ITEM_CLASS2').on('change', function() {
			($(this).val() === '') ? itemClassLevel.clear(3): itemClassLevel.change(3);
		});
		$('#ITP_FORM_STINFO07010_SEARCH_ITEM_CLASS3').on('change', function() {
			($(this).val() === '') ? itemClassLevel.clear(4): itemClassLevel.change(4);
		});
	},
	empty: {
		init: function() {
		},
		itp_STINFO07010_param: {},
		push: function() {
		},
		back: function() {
		}
	},
	grid: {
		init: function () {
			// 데이터 없을때
			listObj.empty.push();
			this.search();
		},
		search: function() {
			pageObj.switchScreen('LIST');
			this.unload();
			this.load();
		},
		load: function() {
			let param = $('#ITP_FORM_STINFO07010_SEARCH').serializeObject();
			param.gridSize = $.jgrid.defaults.rowNum;
			param.sbrandId = fn_make_user_info.get('brandId');

			var option = {
				gridId: STINFO07010_GRID_ID,
				colModel: gridColModel.list,
				param: param,
				url: DOMAIN + API_DETAIL_GRID_LIST,
				pager: STINFO07010_GRID_PAGER,
				multiselect: true,
				rownumbers: false,
				onCellSelect: function(rowId, cellIdx, cellValue) {
					var cm = $(this).jqGrid('getGridParam', 'colModel');
					var colNm = cm[cellIdx].name;
					if (colNm === 'itemClassNm') {
						const selectVal = $(this).jqGrid('getCell', rowId, 'itemClassMgntNo');
						const key = {brandId:fn_make_user_info.get('brandId'), itemClassMgntNo: selectVal, viewCd: 'R'};
						// var param = $.param(key);
						// viewObj.init(param);
						listObj.popup($(STINFO07010_GRID_ID).jqGrid('getRowData', rowId));
					}
				},
				loadComplete: function(data) {
					console.log(data);
					// itp_fn_grid_load_complete(data, STINFO07010_GRID_ID, true, '', 'STINFO07010', listObj.itp_STINFO07010_search, listObj.empty, true, data.gridRecords, true);
					itp_fn_grid_load_complete(data, STINFO07010_GRID_ID, true, undefined, 'STINFO07010', listObj.itp_STINFO07010_search, listObj.empty, true, data.gridRecords, false);
					var ids = $(STINFO07010_GRID_ID).getDataIDs();
					$.each(ids, function(idx, rowId) {
						$(STINFO07010_GRID_ID).jqGrid('setCell', rowId, 'itemClassNm', '', ITP_GRID_COL_STYLE.link);
					});
				},
				onPaging: function(action) {
					itp_fn_grid_paging(STINFO07010_GRID_ID, action, param);
				}
			};
			itp_fn_grid_make_remote(option);
		},
		clearData : function() {
			$(STINFO07010_GRID_ID).jqGrid('clearGridData', true);
			$(STINFO07010_GRID_LIST).find('.ui-jqgrid-bdiv').css('min-height', '100px');
			$(STINFO07010_GRID_EMPTY).html(ITP_MSG_LOCALE.message.grid.noData);
			$(STINFO07010_GRID_EMPTY).show();
		},
		unload : function() {
			$.jgrid.gridUnload(STINFO07010_GRID_ID);
		}
	},
	popup: function(param) {
		// 팝업
		var popFn = function(rowDataPop) {
			console.log(rowDataPop);
			if(rowDataPop)
				listObj.button.search();
		};
		fn_call_popup('biz', 'BIZPOP_ITEM_CLASS_MANAGE', '#ITP_ASIDE', popFn, param, 'S');
	}
};

/*수정화면 Object*/
let modifyObj = {
		init: function () {
	},
	button: {
		modify: function (param) {
			itp_fn_form_clear_validate(null, '#ITP_FORM_STINFO07010_DETAIL');
			const selectVal = $('#ITP_FORM_STINFO07010_VIEW_BRAND_UNIT_UNQ_NO').val();
			const key = {brandId:fn_make_user_info.get('brandId'), brandUnitUnqNo: selectVal, viewCd: 'R'};
			var param = $.param(key);
			modifyObj.load(param);
		}
	},
	load: function(param) {
		fn_ajax_call(API_DETAIL_INFO, param, this.callback, 'GET');
	},
	callback: function (result) {
		console.log(result);
		pageObj.switchScreen('MODIFY');

		$('#ITP_FORM_STINFO07010_DETAIL #ITP_FORM_STINFO07010_DETAIL_VIEW_CD').val('U');
		$('#ITP_FORM_STINFO07010_DETAIL #ITP_FORM_STINFO07010_DETAIL_ITEM_ID').val(result.itemId);
		$('#ITP_FORM_STINFO07010_DETAIL #ITP_FORM_STINFO07010_DETAIL_BRAND_UNIT_UNQ_NO').val(result.brandUnitUnqNo);
		$('#ITP_FORM_STINFO07010_DETAIL .fnBrandNm').text(result.brandId);
		$('#ITP_FORM_STINFO07010_DETAIL #ITP_FORM_STINFO07010_DETAIL_ST_CD').val(result.unitStCd);
		// $('#ITP_FORM_STINFO07010_DETAIL .fnItemClassMgntNo').text(result.itemId);
		$('#ITP_FORM_STINFO07010_DETAIL #ITP_FORM_STINFO07010_DETAIL_ITEM_CLASS_MGNT_NO').val(result.itemClassMgntNo);
		$('#ITP_FORM_STINFO07010_DETAIL #ITP_FORM_STINFO07010_DETAIL_ITEM_NM').val(result.itemClassNm);
		$('#ITP_FORM_STINFO07010_DETAIL #ITP_FORM_STINFO07010_DETAIL_SPPLY_ID').val(result.spplyId);
		$('#ITP_FORM_STINFO07010_DETAIL #ITP_FORM_STINFO07010_DETAIL_SPPLY_NM').val(result.spplyNm);
		$('#ITP_FORM_STINFO07010_DETAIL #ITP_FORM_STINFO07010_DETAIL_SPPLY_ITEM_ID').val(result.spplyItemId);
		$('#ITP_FORM_STINFO07010_DETAIL #ITP_FORM_STINFO07010_DETAIL_CONT_STT_DT').val(result.contSttDt);
		$('#ITP_FORM_STINFO07010_DETAIL #ITP_FORM_STINFO07010_DETAIL_CONT_END_DT').val(result.contEndDt);
		$('#ITP_FORM_STINFO07010_DETAIL #ITP_FORM_STINFO07010_DETAIL_LEAD_TIME').val(result.leadTime);
		$('#ITP_FORM_STINFO07010_DETAIL #ITP_FORM_STINFO07010_DETAIL_UNIT').val(result.unit);
		$('#ITP_FORM_STINFO07010_DETAIL #ITP_FORM_STINFO07010_DETAIL_STDD_QYT').val(result.stddQty);
		$('#ITP_FORM_STINFO07010_DETAIL #ITP_FORM_STINFO07010_DETAIL_CURR').val(result.curr);
		$('#ITP_FORM_STINFO07010_DETAIL #ITP_FORM_STINFO07010_DETAIL_UNIT_AMT').val(result.unitAmt);
		$('#ITP_FORM_STINFO07010_DETAIL #ITP_FORM_STINFO07010_DETAIL_STORE_SALE_STDD_QTY').val(result.storeSaleStddQty);
		$('#ITP_FORM_STINFO07010_DETAIL #ITP_FORM_STINFO07010_DETAIL_STORE_SALE_UNIT_AMT').val(result.storeSaleUnitAmt);
		$('#ITP_FORM_STINFO07010_DETAIL .fnRegId').text(result.regId);
		$('#ITP_FORM_STINFO07010_DETAIL .fnRegDt').text(result.regDt);
		$('#ITP_FORM_STINFO07010_DETAIL .fnChgId').text(result.chgId);
		$('#ITP_FORM_STINFO07010_DETAIL .fnChgDt').text(result.chgDt);
		$.each(result.imageFileNoList, function(index, item) {
			$('#ITP_FORM_STINFO07010_VIEW .ITEM_IMAGE').append('<img src=" + item.filePath +" />');
		});
	}
};

/*신규화면 Object*/
let createObj = {
	init: function () {
		pageObj.switchScreen('ADD');
		itp_fn_form_clear_validate(null, '#ITP_FORM_STINFO07010_DETAIL');
		$('#ITP_FORM_STINFO07010_DETAIL_BRAND_ID').val(fn_make_user_info.get('brandId'));
	},
	button: {
		cancel: function() {
			listObj.grid.search();
		},
		save: function() {
			const formId = '#ITP_FORM_STINFO07010_DETAIL';
			itp_fn_form_clear_validate(null, formId);
			if (createObj.isValid(formId)) {
				if (ITP_FORM_STINFO07010_DETAIL_IS_DUPLICATE) {
					itp_fn_modal_duplicate(ITP_MSG_LOCALE.label.userId, formId + '_USER_ID');
				} else {
					let param = $(formId).serializeObject();
					//console.log(JSON.stringify(param));
					var searhFn = function() {
						ITP_FORM_STINFO07010_DETAIL_IS_WRITING = false;
						listObj.button.search();
					};
					fn_ajax_call(API_DETAIL_SAVE, JSON.stringify(param), searhFn, 'POST');
				}
			}
		}
	},
	isValid: function(formId) {
		var isValid = false;
		$(formId).find('input, select, checkbox, textarea').each(function(k) {
			if($(this).data('check-required')) {
				var arry = $(this).data('check-required').split(',');
				isValid = itp_fn_form_validate(formId, '#' + $(this).attr('id'), arry, undefined);
				if(!isValid) return false;
			}
		});
		return isValid;
	}
};

var itemClassLevel = {
	levelID: '',
	init: function(id, level) {
		this.levelID = id;
		this.clear(level);
		this.make(level);
	},
	make: function(level) {
		this.call(level);
	},
	change: function(level) {
		this.clear(level);
		this.call(level);
	},
	call: function(level) {
		var _this = this;
		var callbackFn = function(result) {
			// console.log(result);
			fn_make_select_item_class(result.searchList, _this.levelID + level, true,'품목분류Level' + level);
		};
		var keys =  function() {
			var keys = {sBrandId:fn_make_user_info.get('brandId'), sItemLevel: level};
			for(var i=1; i<level; i++) {
				var key = 'sItemClass' + i;
				var id = '#' + this.levelID + i;
				keys[key] = $(id + ' option:selected').val();
			}
			// console.log(keys);
			return keys;
		};
		fn_ajax_call(API_ITEM_CLASS_LEVEL, $.param(keys(level)), callbackFn, 'GET');
	},
	clear: function(level) {
		for(var i=level; i<5; i++) {
			$('#' + (this.levelID + i)).find('option:not(:first)').remove();
		}
	}
};
