
const KOPER07010_GRID_ID = '#ITP_KOPER07010_jqGrid';
const KOPER07010_GRID_LIST = '#ITP_KOPER07010_jqGrid_list';
const KOPER07010_GRID_PAGER = '#ITP_KOPER07010_jqGridPager';
const KOPER07010_GRID_EMPTY = '#ITP_KOPER07010_jqGridEmpty';

let ITP_FORM_KOPER07010_DETAIL_IS_WRITING = false;
let KOPER07010_GRID_LAST_ROW_ID;

let NK_APPTYPE_CFG_GRID_LIST = '/api/nk/apptype/cfg/grid-list';
let NK_SAVE_APPTYPE_CFG = '/api/nk/apptype/cfg/save-apptype-cfg'; 
let BRAND_LIST_BRAND = '/api/nk/brand/list-brand'; // 브랜드리스트
let CORNER_LIST_CORNER = '/api/nk/corner/list-corner'; // 코너리스트

require(['config'], function() {
	require([
		'jquery',
		'check'
	], function($) {
		
		// 버튼 권한설정
		fn_proc_btn_auth('KOPER07010');
		// 공통코드 표시
		fn_make_select(CODE_LIST, 'APP_TYPE_CD', 'ITP_FORM_KOPER07010_SEARCH_APP_TYPE_CD');
		fn_make_select(CODE_LIST, 'CFG_TYPE_CD', 'ITP_FORM_KOPER07010_SEARCH_CFG_TYPE_CD');
		fn_make_input_common_cd(CODE_LIST, 'YN', 'ITP_FORM_KOPER07010_SEARCH_YN', false);

		// 그리드
		itp_fn_jqgrid_resize(KOPER07010_GRID_ID, KOPER07010_GRID_LIST, 'lg');
		itp_fn_KOPER07010_grid.init();
    	itp_fn_fire_window_resize();

		// 조회
		itp_fn_KOPER07010_search();
		
		$('#ITP_FORM_KOPER07010_SEARCH_APP_TYPE_CD,#ITP_FORM_KOPER07010_SEARCH_CFG_TYPE_CD').on('change', function() {
			// 조회
			itp_fn_KOPER07010_search();
		});

		// 조회 버튼 클릭
		$('#ITP_BTN_KOPER07010_SRH').on('click', function() {
			itp_KOPER07010_search = true;
			let param = $('#ITP_FORM_KOPER07010_SEARCH').serializeObject();
			param.gridSize = $.jgrid.defaults.rowNum;
			param.gridPage = $.jgrid.defaults.page;
			$(KOPER07010_GRID_ID).setGridParam({'postData': JSON.stringify(param)}).trigger('reloadGrid');
		});

		// 추가 버튼
		$('#ITP_BTN_KOPER07010_ADD').on('click', function() {
			if($('#ITP_FORM_KOPER07010_SEARCH_APP_TYPE_CD').val() == '') {
				itp_fn_modal_alert('어플리케이션유형코드를 선택하세요.');
				return;
			}
			if($('#ITP_FORM_KOPER07010_SEARCH_CFG_TYPE_CD').val() == '') {
				itp_fn_modal_alert('환경설정구분코드를 선택하세요.');
				return;
			}
			KOPER07010_GRID_LAST_ROW_ID = itp_fn_grid_add_row(KOPER07010_GRID_ID, function(last_row_id, row_count) {
				
				const cfgTypeNm = $('#ITP_FORM_KOPER07010_SEARCH_CFG_TYPE_CD option:selected').text();
				$(KOPER07010_GRID_ID).jqGrid('setCell', last_row_id, 'cfgTypeNm', cfgTypeNm);
				
			}, ['cfgKey'], 'KOPER07010');
		});
		
		// 삭제 버튼
		$('#ITP_BTN_KOPER07010_DEL').on('click', function() {
			if($('#ITP_FORM_KOPER07010_SEARCH_APP_TYPE_CD').val() == '') {
				itp_fn_modal_alert('어플리케이션유형코드를 선택하세요.');
				return;
			}
			if($('#ITP_FORM_KOPER07010_SEARCH_CFG_TYPE_CD').val() == '') {
				itp_fn_modal_alert('환경설정구분코드를 선택하세요.');
				return;
			}
			itp_fn_grid_del_row(KOPER07010_GRID_ID);			
		});
		
		// 저장 버튼
		$('#ITP_BTN_KOPER07010_SAVE').on('click', function() {
			if($('#ITP_FORM_KOPER07010_SEARCH_APP_TYPE_CD').val() == '') {
				itp_fn_modal_alert('어플리케이션유형코드를 선택하세요.');
				return;
			}
			if($('#ITP_FORM_KOPER07010_SEARCH_CFG_TYPE_CD').val() == '') {
				itp_fn_modal_alert('환경설정구분코드를 선택하세요.');
				return;
			}
			
			let gridInsertData = [];
			let gridUpdateData = [];
			let gridDeleteData = [];
			const rowData = $(KOPER07010_GRID_ID).getRowData();
			$.each(rowData, function(key, value) {
				if (value.viewCd != 'R') {
					if (value.viewCd == 'C') {
						gridInsertData.push(value);
					} else if (value.viewCd == 'U') {
						gridUpdateData.push(value);
					} else if (value.viewCd == 'D') {
						gridDeleteData.push(value);
					}
				}
			});
			
			$('#ITP_FORM_KOPER07010_SAVE_VIEW_CD').val('U');
			$('#ITP_FORM_KOPER07010_SAVE_APP_TYPE_CD').val($('#ITP_FORM_KOPER07010_SEARCH_APP_TYPE_CD').val());
			$('#ITP_FORM_KOPER07010_SAVE_CFG_TYPE_CD').val($('#ITP_FORM_KOPER07010_SEARCH_CFG_TYPE_CD').val());
			
			let param = $('#ITP_FORM_KOPER07010_SAVE').serializeObject();
			param.gridInsertData = gridInsertData;
			param.gridUpdateData = gridUpdateData;
			param.gridDeleteData = gridDeleteData;
			
			fn_ajax_call(NK_SAVE_APPTYPE_CFG, JSON.stringify(param), function() {			
				// 조회
    			itp_fn_KOPER07010_search();
			}, 'POST');
		});

		$('body').on('click', function(e) {			
			var gridId = KOPER07010_GRID_ID.replace('#', '');
			var rids = $(KOPER07010_GRID_ID).jqGrid('getDataIDs');			
			var last_row_id = rids[rids.length - 1];
			itp_fn_grid_reset_selection(e, last_row_id, gridId, 'KOPER07010_DETAIL');
		});
	});
});

var itp_fn_KOPER07010_grid = {
	init: function() {
		// 데이터 없을때
		itp_fn_KOPER07010_empty.push();
		$(KOPER07010_GRID_EMPTY).on('click', function() {
			itp_fn_KOPER07010_empty.back();
			itp_KOPER07010_param.gridSize = $.jgrid.defaults.rowNum;
			$(KOPER07010_GRID_ID).setGridParam({'postData': JSON.stringify(itp_KOPER07010_param)}).trigger('reloadGrid');
		});
	},
	callBack: function() {
		let param = $('#ITP_FORM_KOPER07010_SEARCH').serializeObject();
		param.gridSize = $.jgrid.defaults.rowNum;
		$(KOPER07010_GRID_ID).jqGrid({
			colModel: [
				{
					index: 'VIEW_CD', name: 'viewCd',
					label: ITP_MSG_LOCALE.label.viewCd,
					width: '10', fixed: false, align: 'center',
					sortable: false, hidden: true
				},
				{
					index: 'CFG_TYPE_NM', name: 'cfgTypeNm',
					label: '환경설정구분', 
					width: '10', fixed: false, align: 'center',
					sortable: false, hidden: false
				},
				{
					index: 'CFG_KEY', name: 'cfgKey',
					label: '환경설정키', 
					width: '10', fixed: false, align: 'center',
					sortable: false, editable: false, edittype: 'text',
					editrules: {required: true}, 
					editoptions: {maxlength: 100}
				},
				{
					index: 'CFG_NM', name: 'cfgNm',
					label: '환경설정명', 
					width: '10', fixed: false, align: 'center',
					sortable: false, editable: true, edittype: 'text', 
					editrules: {required: true},
					editoptions: {maxlength: 25}
				},
				{
					index: 'MUST_YN', name: 'mustYn',
					label: '필수여부', 
					width: '7', fixed: false, align: 'center',
					sortable: false, editable: true, formatter: 'select', edittype: 'select',
					editoptions: {value: $('#ITP_FORM_KOPER07010_SEARCH_YN').val()},
					editrules: {required: true}
				},
				{
					index: 'CFG_VALUE', name: 'cfgValue',
					label: '기본값', 
					width: '10', fixed: false, align: 'center',
					sortable: false, editable: true, edittype: 'text', 
					editrules: {required: true}
				},
				{
					index: 'CFG_DESC', name: 'cfgDesc',
					label: '설명', 
					width: '15', fixed: false, align: 'center',
					sortable: false, editable: true, edittype: 'text', 
					editrules: {required: false}
				}
			],
			loadBeforeSend: function(jqXHR) {
			    jqXHR.setRequestHeader('X-AUTH-TOKEN', CONN_KEY);
			},
			postData: JSON.stringify(param),
			url: DOMAIN + NK_APPTYPE_CFG_GRID_LIST,
			pager: KOPER07010_GRID_PAGER,
			multiselect: true,
			rownumbers: false,
			onCellSelect: function(rowId, cellIdx, cellValue) {
				KOPER07010_GRID_LAST_ROW_ID = itp_fn_set_data_editable(rowId, cellIdx, KOPER07010_GRID_LAST_ROW_ID, KOPER07010_GRID_ID, ['cfgKey']);
		   	},
			loadComplete: function(data) {
				itp_fn_grid_load_complete(data, KOPER07010_GRID_ID, true, 'number', 'KOPER07010', itp_KOPER07010_search, itp_fn_KOPER07010_empty, false, data.gridRecords, true);
				var ids = $(KOPER07010_GRID_ID).getDataIDs();
				$.each(ids, function(idx, rowId) {
					$(KOPER07010_GRID_ID).jqGrid('setCell', rowId, 'cornerNm', '', ITP_GRID_COL_STYLE.link);
				});
		    },
		    loadError: function(jqXHR, textStatus, errorThrown) {
		    	itp_fn_grid_load_error(jqXHR, textStatus, errorThrown);
		    },
		    onPaging: function(action) {
		    	itp_fn_grid_paging(KOPER07010_GRID_ID, action, param);
		    }
		}).navGrid(KOPER07010_GRID_PAGER, ITP_GRID_NAV_DEFAULTS.navGrid);
	},
	clearData : function() {
		$(KOPER07010_GRID_ID).jqGrid('clearGridData', true);
		$(KOPER07010_GRID_LIST).find('.ui-jqgrid-bdiv').css('min-height', '100px');
		$(KOPER07010_GRID_EMPTY).html(ITP_MSG_LOCALE.message.grid.noData);
		$(KOPER07010_GRID_EMPTY).show();
	},
	unload : function() {
		$.jgrid.gridUnload(KOPER07010_GRID_ID);
	}
};

var itp_fn_KOPER07010_search = function() {	
	itp_fn_KOPER07010_grid.unload();
	itp_fn_KOPER07010_grid.callBack();
};

let itp_KOPER07010_param = {};
let itp_KOPER07010_search = false;
var itp_fn_KOPER07010_empty = {
	push: function() {
		let param = $('#ITP_FORM_KOPER07010_SEARCH').serializeObject();
		itp_KOPER07010_param = param;
	},
	back: function() {
		$('#ITP_FORM_KOPER07010_SEARCH_APP_TYPE_CD').val(itp_KOPER07010_param.sappTypeCd);
		$('#ITP_FORM_KOPER07010_SEARCH_CFG_TYPE_CD').val(itp_KOPER07010_param.scfgTypeCd);
	}
};

var itp_fn_KOPER07010_brand_list = function(fnCall) {
	const cmpyCdVal = $('#ITP_TXT_KOPER07010_SHR_CMPY').attr('data-cmpy-cd');	
	const key = {cmpyCd: cmpyCdVal, userTypeCd: USER_TYPE_CD, userId: USER_ID};
	var param = $.param(key);
	fn_ajax_call(BRAND_LIST_BRAND, param, function(result) {
		
		fn_make_select_brand(result, 'ITP_FORM_KOPER07010_SEARCH_BRAND_CD');
		fn_make_select_brand(result, 'ITP_FORM_KOPER07010_DETAIL_BRAND_CD');
		
		if (fnCall !== undefined || typeof fnCall !== 'undefined') fnCall();
				
	}, 'GET');
};

var itp_fn_KFRGD02010_corner_list = function(brandCdVal, storeNoVal, fnCall) {
	const key = {brandCd: brandCdVal, storeNo: storeNoVal};
	var param = $.param(key);
	fn_ajax_call(CORNER_LIST_CORNER, param, function(result) {
	
		fn_make_select_corner(result, 'ITP_FORM_KOPER07010_SEARCH_CORNER_CD');
		
		if (fnCall !== undefined || typeof fnCall !== 'undefined') fnCall();
	
	}, 'GET');
};

