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

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

/*화면 변수*/
const STINFO06010_GRID_ID = '#ITP_STINFO06010_jqGrid';
const STINFO06010_GRID_LIST = '#ITP_STINFO06010_jqGrid_list';
const STINFO06010_GRID_PAGER = '#ITP_STINFO06010_jqGridPager';
const STINFO06010_GRID_EMPTY = '#ITP_STINFO06010_jqGridEmpty';

const STINFO06010_DETAIL_GRID_ID = '#ITP_STINFO06010_DETAIL_jqGrid';
const STINFO06010_DETAIL_GRID_LIST = '#ITP_STINFO06010_DETAIL_jqGrid_list';
const STINFO06010_DETAIL_GRID_PAGER = '#ITP_STINFO06010_DETAIL_jqGridPager';
const STINFO06010_DETAIL_GRID_EMPTY = '#ITP_STINFO06010_DETAIL_jqGridEmpty';

let STINFO06010_GRID_LAST_ROW_ID;

/* 공통코드 리스트 */
let ITP_COMMON_CD_DSTRBT_COST_UNIT = fn_make_common_cd_list(CODE_LIST, 'DSTRBT_COST_UNIT', true, '기본단위');
let ITP_COMMON_CD_CURR = fn_make_common_cd_list(CODE_LIST, 'CURR', true, '통화');
let ITP_COMMON_CD_UNIT_TARGET_CD = fn_make_common_cd_list(CODE_LIST, 'UNIT_TARGET_CD', true, '대상여부');

/*API URL*/
let API_DETAIL_GRID_LIST 	= '/api/itemunit/store-unit-grid-list';		// 목록
let API_DETAIL_INFO 		= '/api/itemunit/info-storeitemunit';		// 상세
let API_DETAIL_NEW	 		= '/api/itemunit/new-info-storeitemunit';	// 신규
let API_DETAIL_SAVE 		= '/api/itemunit/save-store-itemunit';		// 저장

/*화면 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: 'STORE_ID', name: 'storeId',
			label: ITP_MSG_LOCALE.label.storeId, //매장ID
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: true
		},
		{
			index: 'STORE_NM', name: 'storeNm',
			label: ITP_MSG_LOCALE.label.storeNm, //매장명
			width: '10', fixed: false, align: 'left',
			sortable: false, hidden: false, classes: 'ui-ellipsis'
		},
		{
			index: 'CONT_STT_DT', name: 'contSttDt',
			label: ITP_MSG_LOCALE.label.contSttDt, //계약시작일
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'CONT_END_DT', name: 'contEndDt',
			label: ITP_MSG_LOCALE.label.contEndDt, //계약종료일
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'SYS_REG_DTTM', name: 'sysRegDttm',
			label: ITP_MSG_LOCALE.label.sysRegDt, //계약생성일
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'ITEM_CNT', name: 'itemCnt',
			label: ITP_MSG_LOCALE.label.itemCnt, //계약품목수
			width: '10', fixed: false, align: 'right',
			sortable: false, hidden: false
		}
	],
	detail: [
		{
			index: 'VIEW_CD', name: 'viewCd',
			label: ITP_MSG_LOCALE.label.viewCd, //공급단가
			width: '6', fixed: false, align: 'center',
			sortable: false, hidden: true
		},
		{
			index: 'VIEW_NM', name: 'viewNm',
			label: ITP_MSG_LOCALE.label.viewNm, //공급단가
			width: '6', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'BRAND_ID', name: 'brandId',
			label: ITP_MSG_LOCALE.label.brandId, //브랜드ID
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: true
		},
		{
			index: 'BRAND_UNIT_UNQ_NO', name: 'brandUnitUnqNo',
			label: ITP_MSG_LOCALE.label.brandId, //브랜드ID
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: true
		},
		{
			index: 'STORE_UNIT_UNQ_NO', name: 'storeUnitUnqNo',
			label: ITP_MSG_LOCALE.label.storeId, //브랜드ID
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: true
		},
		{
			index: 'ITEM_ID', name: 'itemId',
			label: ITP_MSG_LOCALE.label.itemId, //품목번호
			width: '12', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'ITEM_NM', name: 'itemNm',
			label: ITP_MSG_LOCALE.label.itemNm, //품목명
			width: '11', fixed: false, align: 'left',
			sortable: false, hidden: false
		},
		{
			index: 'CONT_STT_DT', name: 'contSttDt',
			label: ITP_MSG_LOCALE.label.contSttDt, //계약시작일
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'CONT_END_DT', name: 'contEndDt',
			label: ITP_MSG_LOCALE.label.contEndDt, //계약종료일
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'UNIT', name: 'unit',
			label: ITP_MSG_LOCALE.label.unit, //기본단위
			width: '8', fixed: false, align: 'center',
			sortable: false, editable: false, formatter: 'select', edittype: 'select',
			editoptions: {value: ITP_COMMON_CD_DSTRBT_COST_UNIT}
		},
		{
			index: 'CURR', name: 'curr',
			label: ITP_MSG_LOCALE.label.curr, //통화
			width: '7', fixed: false, align: 'center',
			sortable: false, editable: true, formatter: 'select', edittype: 'select',
			editoptions: {value: ITP_COMMON_CD_CURR},
			classes: 'input_color',
			editrules: {required: true}
		},
		{
			index: 'UNIT_AMT', name: 'unitAmt',
			label: ITP_MSG_LOCALE.label.unitAmt, //단가
			width: '10', fixed: false, align: 'right',
			sortable: true, editable: true, edittype: 'text',
			classes: 'input_color',
			editrules: {required: true},
			editoptions: {"onKeyup": "this.value=this.value.replace(/[^0-9]/g,'');",  maxlength: 10},
			formatter: 'integer', formatoptions: { defaultValue: '', thousandsSeparator: ',' }
		},
		{
			index: 'UNIT_TARGET_CD', name: 'unitTargetCd',
			label: ITP_MSG_LOCALE.label.unitTargetCd, //대상여부
			width: '7', fixed: false, align: 'center',
			classes: 'input_color',
			sortable: false, editable: true, formatter: 'select', edittype: 'select',
			editoptions: {value: ITP_COMMON_CD_UNIT_TARGET_CD},
			editrules: {required: true}
		},
		{
			index: 'SPPLY_UNIT_AMT', name: 'spplyUnitAmt',
			label: ITP_MSG_LOCALE.label.spplyUnitAmt, //공급단가
			width: '6', fixed: false, align: 'right',
			sortable: false, hidden: false,
			formatter: 'integer', formatoptions: { defaultValue: '', thousandsSeparator: ',' }
			
		},
		{
			index: 'SPPLY_NM', name: 'spplyNm',
			label: ITP_MSG_LOCALE.label.spplyNm, //공급업체명
			width: '6', fixed: false, align: 'left',
			minwidth: 240,
			sortable: false, hidden: false
		}
	],
	sdetail: [
		{
			index: 'VIEW_CD', name: 'viewCd',
			label: ITP_MSG_LOCALE.label.viewCd, //공급단가
			width: '6', fixed: false, align: 'center',
			sortable: false, hidden: true
		},
		{
			index: 'VIEW_NM', name: 'viewNm',
			label: ITP_MSG_LOCALE.label.viewNm, //공급단가
			width: '6', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'BRAND_ID', name: 'brandId',
			label: ITP_MSG_LOCALE.label.brandId, //브랜드ID
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: true
		},
		{
			index: 'BRAND_UNIT_UNQ_NO', name: 'brandUnitUnqNo',
			label: ITP_MSG_LOCALE.label.brandId, //브랜드ID
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: true
		},
		{
			index: 'STORE_UNIT_UNQ_NO', name: 'storeUnitUnqNo',
			label: ITP_MSG_LOCALE.label.storeId, //브랜드ID
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: true
		},
		{
			index: 'ITEM_ID', name: 'itemId',
			label: ITP_MSG_LOCALE.label.itemId, //품목번호
			minwidth: 160,
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'ITEM_NM', name: 'itemNm',
			label: ITP_MSG_LOCALE.label.itemNm, //품목명
			width: '13', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'CONT_STT_DT', name: 'contSttDt',
			label: ITP_MSG_LOCALE.label.contSttDt, //계약시작일
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'CONT_END_DT', name: 'contEndDt',
			label: ITP_MSG_LOCALE.label.contEndDt, //계약종료일
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'UNIT', name: 'unit',
			label: ITP_MSG_LOCALE.label.unit, //기본단위
			width: '9', fixed: false, align: 'center',
			sortable: false, editable: false, formatter: 'select', edittype: 'select',
			editoptions: {value: ITP_COMMON_CD_DSTRBT_COST_UNIT}
		},
		{
			index: 'CURR', name: 'curr',
			label: ITP_MSG_LOCALE.label.curr, //통화
			width: '9', fixed: false, align: 'center',
			sortable: false, editable: false, formatter: 'select', edittype: 'select',
			editoptions: {value: ITP_COMMON_CD_CURR}
		},
		{
			index: 'UNIT_AMT', name: 'unitAmt',
			label: ITP_MSG_LOCALE.label.unitAmt, //단가
			width: '10', fixed: false, align: 'center',
			sortable: true, editable: false, edittype: 'text',
			formatter: 'integer', formatoptions: { defaultValue: '', thousandsSeparator: ',' }
		},
		{
			index: 'UNIT_TARGET_CD', name: 'unitTargetCd',
			label: ITP_MSG_LOCALE.label.unitTargetCd, //대상여부
			width: '10', fixed: false, align: 'center',
			sortable: false, editable: false, formatter: 'select', edittype: 'select',
			editoptions: {value: ITP_COMMON_CD_UNIT_TARGET_CD}
		}
	]
};

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

			// 공통코드 표시
			$('select').each(function() {
				if($(this).data('select-code')) {
					fn_make_select(CODE_LIST, $(this).data('select-code'), $(this).attr('id'));
				}
			});

			// 조회일자 지정
			var now = new Date();
			$('#ITP_TAB_STINFO06010 .input-group.date').datepicker(ITP_DATE_LANGUAGE);
			$('#ITP_FORM_STINFO06010_DETAIL_FROM_DT').datepicker('setDate', new Date(now.setMonth(now.getMonth() - 1)));
			$('#ITP_FORM_STINFO06010_DETAIL_TO_DT').datepicker('setDate', new Date());
			
			
		},
		grid: function() {
			itp_fn_jqgrid_resize(STINFO06010_GRID_ID, STINFO06010_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_STINFO06010_SRH'				: listObj.button.search();		break;	// 조회 버튼 클릭
						case 'ITP_BTN_STINFO06010_NEWREG'			: listObj.button.create(); 		break;	// 신규등록 버튼
						case 'ITP_BTN_STINFO06010_CANCELLIST'		: listObj.grid.search(); 		break;	// 취소/목록 버튼
						case 'ITP_BTN_STINFO06010_SAVE'				: createObj.button.save(); 		break;	// 저장 버튼
						case 'ITP_BTN_STINFO06010_EXCEL'			: pageObj.excelDown(); 			break;	// 엑셀 다운로드 버튼
						case 'ITP_BTN_STINFO06010_DETAIL_EXCEL'			: pageObj.excelDtlDown(); 			break;	// 엑셀 다운로드 버튼
					}
				});
			});

			var fnDateChange = function(cellname, data) {
				var cnt = $(STINFO06010_DETAIL_GRID_ID).getGridParam("reccount");
				for (var i=1; i<=cnt; i++) {
					$(STINFO06010_DETAIL_GRID_ID).jqGrid('setCell', i, cellname, data);
				}
			};
			$('#ITP_FORM_STINFO06010_DETAIL_FROM_DT').datepicker().on('changeDate', function () {
				fnDateChange('contSttDt', $(this).val());
			});

			$('#ITP_FORM_STINFO06010_DETAIL_TO_DT').datepicker().on('changeDate', function () {
				fnDateChange('contEndDt', $(this).val());
			});

			$('body').on('click', function(e) {
				var gridId = STINFO06010_DETAIL_GRID_ID.replace('#', '');
				itp_fn_grid_reset_selection(e, STINFO06010_GRID_LAST_ROW_ID, gridId, 'STINFO06010');
				
				var preItemId = $(STINFO06010_DETAIL_GRID_ID).jqGrid('getCell', STINFO06010_GRID_LAST_ROW_ID, 'itemId');
				
				if(preItemId !== undefined) {										
					var preUnitAmt = $(STINFO06010_DETAIL_GRID_ID).jqGrid('getCell', STINFO06010_GRID_LAST_ROW_ID, 'unitAmt');
					
					var cnt = $(STINFO06010_DETAIL_GRID_ID).getGridParam("reccount");
					var itemId;
					var viewCd ;
					for (var i = 1; i <= cnt ; i++) {
						itemId = $(STINFO06010_DETAIL_GRID_ID).jqGrid('getCell', i, 'itemId');
						viewCd = $(STINFO06010_DETAIL_GRID_ID).jqGrid('getCell', i, 'viewCd');
						
						if(preItemId == itemId) {
							if (viewCd != "C") {
								$(STINFO06010_DETAIL_GRID_ID).jqGrid('setCell', i, 'viewCd', 'U');	
							}
							$(STINFO06010_DETAIL_GRID_ID).jqGrid('setCell', i, 'unitAmt', preUnitAmt);
						}
					}	
				}
			});

		}
	},
	action: function () {
		var _this = this;
		
		//시작일자 변경시
		$('#ITP_FORM_STINFO06010_DETAIL_FROM_DT').focusin(function() {
			$(this).data('pre', $(this).val());
		});
		
		$('#ITP_FORM_STINFO06010_DETAIL_TO_DT').focusin(function() {
			$('#ITP_FORM_STINFO06010_DETAIL_TO_DT').data('pre', $(this).val());
		});
		
		$('#ITP_FORM_STINFO06010_DETAIL_FROM_DT').change(function() {
			if(pageObj.screenMode === 'MODIFY') {
				var preDate = $(this).data('pre');
				var topreDate = $('#ITP_FORM_STINFO06010_DETAIL_TO_DT').data('pre');
				var chgDate = $(this).val();
				
				var endDt = $('#ITP_FORM_STINFO06010_DETAIL_TO_DT').val();
				
				if (preDate > endDt) {
					if ( preDate != chgDate) {
						alert("계약 종료일은 시작일보다 이전일수 없습니다.");
						$('#ITP_FORM_STINFO06010_DETAIL #ITP_FORM_STINFO06010_DETAIL_FROM_DT').datepicker('setDate', new Date(preDate));
						$('#ITP_FORM_STINFO06010_DETAIL #ITP_FORM_STINFO06010_DETAIL_TO_DT').datepicker('setDate', new Date(topreDate));
						
						return;
					}
				} else {
					if ( preDate != chgDate) {
						alert("계약 시작일은 변경할 수 없습니다.");
						$('#ITP_FORM_STINFO06010_DETAIL #ITP_FORM_STINFO06010_DETAIL_FROM_DT').datepicker('setDate', new Date(preDate));
						return;
					}
				}
			}			
		});
	},
	switchScreen: function(mode) {
		this.screenMode = mode;
		$('.itp_det_head').find('button[id^="ITP_BTN_STINFO06010_"]').each(function(i) {
			$(this).hide();
		});
		$('#ITP_TAB_STINFO06010').find('div[id$="_CONTAINER"]').each(function(i) {
			$(this).hide();
		});
		$('#ITP_FORM_STINFO06010_DETAIL_FROM_DT').val('');
		$('#ITP_FORM_STINFO06010_DETAIL_TO_DT').val('');
		/*
		if(mode == 'ADD') {			
			$("#ITP_FORM_STINFO06010_DETAIL_FROM_DT").removeAttr('readonly');
		} else {
			//$('#ITP_FORM_STINFO06010_DETAIL .contDt').hide();
			//$('#ITP_FORM_STINFO06010_DETAIL_FROM_DT').attr('readonly','true');
			document.getElementById('ITP_FORM_STINFO06010_DETAIL_FROM_DT').readOnly = true; 
		}
		*/
		$('#ITP_FORM_STINFO06010_DETAIL .contDt').show();
		
		//if(pageObj.screenMode === 'ADD')
		
		if(mode == 'LIST') { // 목록
			itp_fn_fire_window_resize();
			$('#ITP_AJAX_STINFO06010_LIST_CONTAINER').show();
			if(fn_make_user_info.get('authTpCd') === '50') {
				fn_show_btn_auth_array(['#ITP_BTN_STINFO06010_SRH']);
				$('#ITP_FORM_STINFO06010_SEARCH_STORE_ID').val(fn_make_user_info.get('storeId'));
				$('#ITP_FORM_STINFO06010_SEARCH_STORE').hide();
			} else {
				fn_show_btn_auth_array(['#ITP_BTN_STINFO06010_SRH', '#ITP_BTN_STINFO06010_NEWREG']);
				$('#ITP_BTN_STINFO06010_EXCEL').show();
				$('#ITP_BTN_STINFO06010_DETAIL_DELETE_STORE').show();
			}
			$('#ITP_FORM_STINFO06010_SEARCH_BRAND_ID').val(fn_make_user_info.get('brandId'));
		} else if(mode == 'ADD') { // 등록
			itp_fn_form_clear_validate(null, '#ITP_FORM_STINFO07010_DETAIL');

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

			$('#ITP_AJAX_STINFO06010_DETAIL_CONTAINER').show();
			$('#ITP_BTN_STINFO06010_SRH').show();
			fn_show_btn_auth_array(['#ITP_BTN_STINFO06010_CANCELLIST', '#ITP_BTN_STINFO06010_SAVE']);

			$('#ITP_BTN_STINFO06010_DETAIL_SEARCH_STORE').removeAttr('disabled');
			$('#ITP_BTN_STINFO06010_DETAIL_DELETE_STORE').removeAttr('disabled');
			// 브랜드그룹 정보 설정
			$('#ITP_FORM_STINFO06010_DETAIL_BRAND_ID').val(fn_make_user_info.get('brandId'));
			$('#ITP_FORM_STINFO06010_DETAIL #ITP_FORM_STINFO06010_DETAIL_FROM_DT').datepicker('setDate', new Date());
			$('#ITP_FORM_STINFO06010_DETAIL #ITP_FORM_STINFO06010_DETAIL_TO_DT').datepicker('setDate', itp_fn_date_add('Y', 1));
			
			
			//return itp_fn_date_format(date.setDate(-1), 2);
		} else if(mode == 'MODIFY') { // 수정
			$('#ITP_AJAX_STINFO06010_DETAIL_CONTAINER').show();
			if(fn_make_user_info.get('authTpCd') === '50') {
				fn_show_btn_auth_array(['#ITP_BTN_STINFO06010_CANCELLIST']);
			} else {
				fn_show_btn_auth_array(['#ITP_BTN_STINFO06010_CANCELLIST', '#ITP_BTN_STINFO06010_SAVE']);
			}
			$('#ITP_BTN_STINFO06010_DETAIL_SEARCH_STORE').attr('disabled', true);
			$('#ITP_BTN_STINFO06010_DETAIL_DELETE_STORE').attr('disabled', true);
			// $('#ITP_BTN_STINFO06010_SRH').show();
			$('#ITP_BTN_STINFO06010_DETAIL_EXCEL').show();

			// 브랜드그룹 정보 설정
			$('#ITP_FORM_STINFO06010_DETAIL_BRAND_ID').val(fn_make_user_info.get('brandId'));
		} else if(mode == 'VIEW') { // 보기
			$('#ITP_AJAX_STINFO06010_VIEW_CONTAINER').show();
			fn_show_btn_auth_array(['#ITP_BTN_STINFO06010_MODIFY', '#ITP_BTN_STINFO06010_CANCELLIST']);
			
		}
		this.screenMode = mode;
	},
	excelDown: function() {
		var param = {
			'url': API_DETAIL_GRID_LIST,
			'param': $('#ITP_FORM_STINFO06010_SEARCH').serializeObject(),
			'gridColumns': $(STINFO06010_GRID_ID).jqGrid('getGridParam', 'colModel'),
			'fileName': '매장단가관리.xlsx',
			'sheetName': '매장단가관리'
		};
		itp_fn_remote_to_excel(param);
	},
	excelDtlDown: function() {
		var storeId = $('#ITP_FORM_STINFO06010_DETAIL_STORE_ID').val();
		var contSttDt = $('#ITP_FORM_STINFO06010_DETAIL_FROM_DT').val();
		var contEndDt = $('#ITP_FORM_STINFO06010_DETAIL_FROM_DT').val();
		const key = {brandId:fn_make_user_info.get('brandId'), storeId: storeId, contSttDt: contSttDt, contEndDt: contEndDt, viewCd: 'R'};
		
		var param = {
			'url': API_DETAIL_INFO,
			'param': key,
			'gridColumns': $(STINFO06010_DETAIL_GRID_ID).jqGrid('getGridParam', 'colModel'),
			'fileName': '매장단가정보.xlsx',
			'sheetName': '매장단가상세정보'
		};
		itp_fn_remote_to_excel(param);
	}
	
	
};

/*목록화면 Object*/
let listObj = {
	init: function () {
		this.grid.init();
	},
	itp_STINFO06010_search: false,
	button: {
		search: function() {
			listObj.itp_STINFO06010_search = true;
			let param = $('#ITP_FORM_STINFO06010_SEARCH').serializeObject();
			param.gridSize = $.jgrid.defaults.rowNum;
			param.gridPage = $.jgrid.defaults.page;
			$(STINFO06010_GRID_ID).data('grid-param',param);
			$(STINFO06010_GRID_ID).setGridParam({'postData': JSON.stringify(param)}).trigger('reloadGrid');
		},
		create: function() {
			var param = {'brandId':fn_make_user_info.get('brandId')};
			createObj.init(param);
		}
	},
	empty: {
		init: function() {
		},
		itp_STINFO06010_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_STINFO06010_SEARCH').serializeObject();
			param.gridSize = $.jgrid.defaults.rowNum;
			param.sbrandId = fn_make_user_info.get('brandId');
			param.sstoreId = fn_make_user_info.get('storeId');

			var option = {
				gridId: STINFO06010_GRID_ID,
				colModel: gridColModel.list,
				param: param,
				url: DOMAIN + API_DETAIL_GRID_LIST,
				pager: STINFO06010_GRID_PAGER,
				onCellSelect: function(rowId, cellIdx, cellValue) {
					var cm = $(this).jqGrid('getGridParam', 'colModel');
					var colNm = cm[cellIdx].name;
					if (colNm === 'contSttDt') {
						const storeId = $(this).jqGrid('getCell', rowId, 'storeId');
						const storeNm = $(this).jqGrid('getCell', rowId, 'storeNm');
						const contSttDt = $(this).jqGrid('getCell', rowId, 'contSttDt');
						const contEndDt = $(this).jqGrid('getCell', rowId, 'contEndDt');
						$('#ITP_FORM_STINFO06010_DETAIL_STORE_ID').val(storeId);
						$('#ITP_FORM_STINFO06010_DETAIL_STORE_NM').val(storeNm);
						const key = {brandId:fn_make_user_info.get('brandId'), storeId: storeId, contSttDt: contSttDt, contEndDt: contEndDt, viewCd: 'R'};
						// var param = $.param(key);
						modifyObj.init(key);
					}
				},
				loadComplete: function(data) {
					console.log(data);
					itp_fn_grid_load_complete(data, STINFO06010_GRID_ID, true, 'number', 'STINFO06010', listObj.itp_STINFO06010_search, listObj.empty, true, data.gridRecords, true);
					var ids = $(STINFO06010_GRID_ID).getDataIDs();
					$.each(ids, function(idx, rowId) {
						$(STINFO06010_GRID_ID).jqGrid('setCell', rowId, 'contSttDt', '', ITP_GRID_COL_STYLE.link);
					});
				},
				onPaging: function(action) {
					itp_fn_grid_paging(STINFO06010_GRID_ID, action, param);
				}
			};
			itp_fn_grid_make_remote(option);
		},
		clearData : function() {
			$(STINFO06010_GRID_ID).jqGrid('clearGridData', true);
			$(STINFO06010_GRID_LIST).find('.ui-jqgrid-bdiv').css('min-height', '100px');
			$(STINFO06010_GRID_EMPTY).html(ITP_MSG_LOCALE.message.grid.noData);
			$(STINFO06010_GRID_EMPTY).show();
		},
		unload : function() {
			$.jgrid.gridUnload(STINFO06010_GRID_ID);
		}
	}
};

/*수정화면 Object*/
let modifyObj = {
	init: function (param) {
		pageObj.switchScreen('MODIFY');
		// var param = $.param($('#ITP_FORM_STINFO06010_DETAIL').serializeObject());
		this.grid.init(param);
	},
	itp_STINFO06010_search: false,
	search: function() {
		listObj.itp_STINFO06010_search = true;
		let param = $('#ITP_FORM_STINFO06010_DETAIL').serializeObject();
		param.gridSize = 100 ; //$.jgrid.defaults.rowNum;
		param.gridPage = $.jgrid.defaults.page;
		$(STINFO06010_DETAIL_GRID_ID).setGridParam({'postData': JSON.stringify(param)}).trigger('reloadGrid');
	},
	button: {
	},
	empty: {
		init: function() {
			var _this = this;
			this.push();
			$(STINFO06010_DETAIL_GRID_EMPTY).on('click', function() {
				_this.back();
				_this.itp_STINFO06010_param.gridSize = 100 ; // $.jgrid.defaults.rowNum;
				$(STINFO06010_DETAIL_GRID_ID).setGridParam($.param(_this.itp_STINFO06010_param)).trigger('reloadGrid');
			});
		},
		itp_STINFO06010_param: {},
		push: function() {
			let param = $('#ITP_FORM_STINFO06010_DETAIL').serializeObject();
			listObj.itp_STINFO06010_param = param;
		},
		back: function() {
		}
	},
	grid: {
		init: function (param) {
			// 데이터 없을때
			listObj.empty.push();
			this.unload();
			this.load(param);
		},
		prevRowId: null,
		load: function(param) {
			var _this = this;
			$('#ITP_FORM_STINFO06010_DETAIL_FROM_DT').val(param.contSttDt);
			$('#ITP_FORM_STINFO06010_DETAIL_TO_DT').val(param.contEndDt);
			
			var option = {
				gridId: STINFO06010_DETAIL_GRID_ID,
				colModel: fn_make_user_info.get('authTpCd') === '50' ?  gridColModel.sdetail : gridColModel.detail,
				param: param,
				height : 'auto',
				rowNum: '',
				url: DOMAIN + API_DETAIL_INFO,
				loadComplete: function(data) {
					//console.log("12121212121212");
					//$(STINFO06010_DETAIL_GRID_LIST).jqGrid('hideCol',["spplyNm","spplyUnitAmt"]);
					createObj.rows = data.gridRows;
					itp_fn_grid_load_complete(data, STINFO06010_DETAIL_GRID_ID, false, 'number', 'STINFO06010', modifyObj.itp_STINFO06010_search, modifyObj.empty, true, data.gridRecords, true);
				},
				onCellSelect: function(rowid, cellIdx, cellValue) {
					if(fn_make_user_info.get('authTpCd') !== '50') {
						STINFO06010_GRID_LAST_ROW_ID = itp_fn_set_data_editable(rowid, cellIdx, STINFO06010_GRID_LAST_ROW_ID, STINFO06010_DETAIL_GRID_ID, ['actionId']);
					}
				},
				onPaging: function(action) {
					itp_fn_grid_paging(STINFO06010_GRID_ID, action, param);
				}
			};
			//itp_fn_grid_make_remote(option);
			itp_fn_grid_make_not_paging(option);
		},
		clearData : function() {
			$(STINFO06010_DETAIL_GRID_ID).jqGrid('clearGridData', true);
			$(STINFO06010_DETAIL_GRID_LIST).find('.ui-jqgrid-bdiv').css('min-height', '100px');
			$(STINFO06010_DETAIL_GRID_EMPTY).html(ITP_MSG_LOCALE.message.grid.noData);
			$(STINFO06010_DETAIL_GRID_EMPTY).show();
		},
		unload : function() {
			$.jgrid.gridUnload(STINFO06010_DETAIL_GRID_ID);
		}
	}
};

/*신규화면 Object*/
function fn_grid_new(option) {
	var options = $.extend({
		mtype: 'POST',
		multiselect: false,
		rownumbers: true,
		ondblClickRow: null,
		loadBeforeSend: function(jqXHR) {
			jqXHR.setRequestHeader('X-AUTH-TOKEN', CONN_KEY);
		},
		loadError: function(jqXHR, textStatus, errorThrown) {
			itp_fn_grid_load_error(jqXHR, textStatus, errorThrown);
		}
	}, option); 
	$(options.gridId).jqGrid({
		colModel: options.colModel,
		postData: JSON.stringify(options.param),
		mtype: options.mtype,
		url: options.url, 
		rowNum: 10000,
		multiselect: options.multiselect, 
		loadBeforeSend: options.loadBeforeSend,
		onCellSelect: options.onCellSelect,
		ondblClickRow: options.ondblClickRow,
		loadComplete: options.loadComplete,
		loadError: options.loadError,
		gridComplete: function () {
			$(STINFO06010_DETAIL_GRID_ID+'View').html("전체: "+$(options.gridId).getGridParam('records')+'건')
		}
	});
}

let createObj = {
	init: function (param) {
		pageObj.switchScreen('ADD');
		this.grid.init(param);
		this.button.init();
	},
	button: {
		init: function() {
			// 브랜드그룹 조회 버튼 클릭
			$('#ITP_BTN_STINFO06010_DETAIL_SEARCH_STORE').on('click', function() {
				
				createObj.popup();
			});
			// 브랜드그룹 텍스트 삭제 버튼 클릭
			$('#ITP_BTN_STINFO06010_DETAIL_DELETE_STORE').one('click', function() {
				$('#ITP_FORM_STINFO06010_DETAIL_BRAND_ID').val('');
				$('#ITP_FORM_STINFO06010_DETAIL_STORE_ID').val('');
				$('#ITP_FORM_STINFO06010_DETAIL_STORE_NM').val('');
			});
		},
		cancel: function() {
			listObj.grid.search();
		},
		save: function() {
			const formId = '#ITP_FORM_STINFO06010_DETAIL';
			var isValid = true;
			if(pageObj.screenMode === 'ADD') {
				//isValid = itp_fn_form_event.isValid(formId);
				//매장 아이디 존재 여부 확인
				var storeChk = $('#ITP_FORM_STINFO06010_DETAIL_STORE_ID').val();
				if (storeChk == '') {
					alert("계약할 매장을 선택해주세요!");
					return;
				}
			}
			if (isValid) {
				itp_fn_grid_save_rows(STINFO06010_DETAIL_GRID_ID);

				var rows = $(STINFO06010_DETAIL_GRID_ID).getRowData();
				let param = {};
				var gridInsertData = [];
				var gridUpdateData = [];
				var changeRows = createObj.changeRows(rows);
				$.each(changeRows, function (index, item) {
					if(item.viewCd === 'C') {
						gridInsertData.push(item);
					} else if(item.viewCd === 'U') {
						gridUpdateData.push(item);
					}
					// if(pageObj.screenMode === 'ADD') {
					// 	gridInsertData.push(item);
					// } else {
					// 	if(item.viewCd === 'C') {
					// 		gridInsertData.push(item);
					// 	} else if(item.viewCd === 'U') {
					// 		gridUpdateData.push(item);
					// 	}
					// }
				});
				param['viewCd'] = 'U';
				param['brandId'] = fn_make_user_info.get('brandId');
				param['storeId'] = $('#ITP_FORM_STINFO06010_DETAIL_STORE_ID').val();
				param['contSttDt'] = $('#ITP_FORM_STINFO06010_DETAIL_FROM_DT').val();
				param['contEndDt'] = $('#ITP_FORM_STINFO06010_DETAIL_TO_DT').val();
				
				if(pageObj.screenMode === 'ADD')
				{
					//param['contSttDt'] = $('#ITP_FORM_STINFO06010_DETAIL_FROM_DT').val();
					//param['contEndDt'] = $('#ITP_FORM_STINFO06010_DETAIL_TO_DT').val();
					param['viewCd'] = "C";
				} else {
					param['viewCd'] = "U";
				}
				param['gridInsertData'] = gridInsertData;
				param['gridUpdateData'] = gridUpdateData;
				console.log(JSON.stringify(param));
				
				var searhFn = function() {
					listObj.grid.search();
				};
				fn_ajax_call(API_DETAIL_SAVE, JSON.stringify(param), searhFn, 'POST');
			}
		}
	},
	grid: {
		init: function (param) {
			// 데이터 없을때
			listObj.empty.push();
			this.unload();
			this.load(param);
		},
		rows: [],
		prevRowId: null,
		load: function(param) {
			var _this = this;
			console.log(param);
			var option = {
				gridId: STINFO06010_DETAIL_GRID_ID,
				colModel: fn_make_user_info.get('authTpCd') === '50' ?  gridColModel.sdetail : gridColModel.detail,
				mtype: 'POST',
				param: param,
				url: DOMAIN + API_DETAIL_NEW,
				loadComplete: function(data) {
					console.log(data);
					createObj.rows = data.gridRows;
					itp_fn_grid_load_complete(data, STINFO06010_DETAIL_GRID_ID, false, 'number', 'STINFO06010', modifyObj.itp_STINFO06010_search, modifyObj.empty, true, data.gridRecords, true);
					$('#ITP_FORM_STINFO06010_DETAIL_FROM_DT').datepicker().trigger('changeDate');
					$('#ITP_FORM_STINFO06010_DETAIL_TO_DT').datepicker().trigger('changeDate');
				},
				onCellSelect: function(rowid, cellIdx, cellValue) {
					STINFO06010_GRID_LAST_ROW_ID = itp_fn_set_data_editable(rowid, cellIdx, STINFO06010_GRID_LAST_ROW_ID, STINFO06010_DETAIL_GRID_ID, ['actionId']);
				},
				onPaging: function(action) {
					itp_fn_grid_paging(STINFO06010_GRID_ID, action, param);
				}
			};
			fn_grid_new(option);
		},
		clearData : function() {
			$(STINFO06010_DETAIL_GRID_ID).jqGrid('clearGridData', true);
			$(STINFO06010_DETAIL_GRID_LIST).find('.ui-jqgrid-bdiv').css('min-height', '100px');
			$(STINFO06010_DETAIL_GRID_EMPTY).html(ITP_MSG_LOCALE.message.grid.noData);
			$(STINFO06010_DETAIL_GRID_EMPTY).show();
		},
		unload : function() {
			$.jgrid.gridUnload(STINFO06010_DETAIL_GRID_ID);
		}
	},
	popup: function() {
		var popFn = function(rowDataPop) {
			console.log(rowDataPop);
			if(rowDataPop && rowDataPop.length > 0) {
				console.log(rowDataPop[0].storeNm);
				$('#ITP_FORM_STINFO06010_DETAIL_BRAND_ID').val(rowDataPop[0].brandId);
				$('#ITP_FORM_STINFO06010_DETAIL_STORE_ID').val(rowDataPop[0].storeId);
				$('#ITP_FORM_STINFO06010_DETAIL_STORE_NM').val(rowDataPop[0].storeNm);
			}
			// 강제로 팝업 창닫기 실행
			setTimeout(function() {
				$('.modal-backdrop').hide();
			}, 500);
		};
		fn_call_popup('biz', 'BIZPOP_BRAND_STORE', '#ITP_ASIDE', popFn, null, 'S');
	},
	rows: [],
	changeRows: function(gridRows) {
		var modifyRows = [];
		var chkColumns = ['unit', 'curr', 'unitAmt', 'unitTargetCd'];
		$.each(this.rows, function(index, item) {
			var row = gridRows[index];
			if(row.viewCd === 'C') {
				modifyRows.push(item);
			} else {
				if(row.itemId === item.itemId) {
					$.each(chkColumns, function(index, column) {
						if(row[column].toString() !== item[column].toString()) {
							row.viewCd = 'U';
							modifyRows.push(row);
							return false;
						}
					});
				}
			}
		});
		return modifyRows;
	}
};
