
const SYSTEM01010_GRID_ID = '#ITP_SYSTEM01010_jqGrid';	
const SYSTEM01010_GRID_LIST = SYSTEM01010_GRID_ID + '_list';
const SYSTEM01010_GRID_PAGER = SYSTEM01010_GRID_ID + 'Pager';
const SYSTEM01010_GRID_EMPTY = SYSTEM01010_GRID_ID + 'Empty';

let ITP_FORM_SYSTEM01010_IS_WRITING = false;
let ITP_FORM_SYSTEM01010_IS_DUPLICATE = false;
let SYSTEM01010_GRID_LAST_ROW_ID;
let SYSTEM01010_SCH_CODE_CD; //

let CODE_CODE_SEARCH = '/api/code/code-search'; 
let CODE_SAVE_CODE = '/api/code/save-code'; 
let CODE_INFO_CODE = '/api/code/info-code'; 
let CODE_CHECK_DUPLICATE = '/api/code/check-duplicate'; 
let CODE_DETAIL_GRID_LIST = '/api/code/detail-grid-list'; 

require(['config'], function() {
	require([
		'jquery'
	], function($) {
		// 버튼 권한설정
		fn_proc_btn_auth('SYSTEM01010');
		
		// 공통코드 표시
		fn_make_select(CODE_LIST, 'CODE_TP_CD', 'ITP_SYSTEM01010_ADV_SRH_FORM_CODE_TP_CD', true, '전체');
		fn_make_select(CODE_LIST, 'CODE_TP_CD', 'ITP_FORM_SYSTEM01010_CODE_TYPE', true, '선택');		
		fn_make_select(CODE_LIST, 'USE_YN', 'ITP_SYSTEM01010_ADV_SRH_FORM_USE_YN', true, '전체');
		fn_make_select(CODE_LIST, 'USE_YN', 'ITP_FORM_SYSTEM01010_USE_YN', true, '선택');

		itp_fn_SYSTEM01010_search();
		itp_fn_jqgrid_resize(SYSTEM01010_GRID_ID, SYSTEM01010_GRID_LIST, 'sm');
		itp_fn_SYSTEM01010_detail_grid.init();
    	itp_fn_fire_window_resize();

		$('#ITP_BTN_SYSTEM01010_SRH').on('click', function() {
			itp_fn_SYSTEM01010_search();
		});

		$('#ITP_AJAX_SYSTEM01010_SRH_CONTAINER').on('click', '.list-group .list-group-item', function() {
			const $this = $(this);
			var itemFn = {
				callBack: function() {
					itp_fn_form_clear_validate(null, '#ITP_FORM_SYSTEM01010_DETAIL');
					$('#ITP_AJAX_SYSTEM01010_SRH_CONTAINER .list-group .list-group-item').removeClass('active');
					$this.addClass('active');
					const codeCd = $this.find('.itp_param_key').text();
					itp_fn_SYSTEM01010_detail(codeCd);
				}
			};
			if (ITP_FORM_SYSTEM01010_IS_WRITING || itp_fn_check_grid_is_writing(SYSTEM01010_GRID_ID)) {
				itp_fn_modal_confirm(ITP_MSG_LOCALE.message.ajax.cancelData, itemFn, null);
			} else {
				itemFn.callBack();
			}
		});

		$('#ITP_BTN_SYSTEM01010_NEW').on('click', function() {
			var newFn = {
    			callBack: function(args) {
					itp_fn_form_clear_validate(null, '#ITP_FORM_SYSTEM01010_DETAIL');
    				const item = $('#ITP_AJAX_SYSTEM01010_SRH_CONTAINER .list-group .list-group-item');
    				item.removeClass('active');

					// 코드정보 초기화
					$('#ITP_FORM_SYSTEM01010_DETAIL input[name=viewCd]').val('C');
					$('#ITP_FORM_SYSTEM01010_CODE_CD').val('');
					$('#ITP_FORM_SYSTEM01010_CODE_NM_KR').val('');
					$('#ITP_FORM_SYSTEM01010_USE_YN').val('');
					$('#ITP_FORM_SYSTEM01010_CODE_TYPE').val('');
					$('#ITP_FORM_SYSTEM01010_CODE_CD').removeAttr('readonly');
					$('#ITP_BTN_SYSTEM01010_DUP').removeAttr('disabled');
					
					// 그리드 초기화
					itp_fn_SYSTEM01010_detail_grid.clearData();
    			}
    		};
			if (ITP_FORM_SYSTEM01010_IS_WRITING || itp_fn_check_grid_is_writing(SYSTEM01010_GRID_ID)) {
				itp_fn_modal_confirm(ITP_MSG_LOCALE.message.ajax.cancelData, newFn, null);
			} else {
				newFn.callBack();
			}
		});

		$('#ITP_BTN_SYSTEM01010_SAVE').on('click', function() {
			const formId = '#ITP_FORM_SYSTEM01010';
			itp_fn_form_clear_validate(null, formId + '_DETAIL');
			var vali_codeCd = itp_fn_form_validate(formId + '_DETAIL', formId + '_CODE_CD', ['empty'], undefined);
			var vali_useYn = itp_fn_form_validate(formId + '_DETAIL', formId + '_USE_YN', ['empty'], undefined);
			var vali_codeNmKr = itp_fn_form_validate(formId + '_DETAIL', formId + '_CODE_NM_KR', ['empty'], undefined);
			var vali_codeTypeCd = itp_fn_form_validate(formId + '_DETAIL', formId + '_CODE_TYPE', ['empty'], undefined);

			if (vali_codeCd && vali_useYn && vali_codeNmKr && vali_codeTypeCd) {
				if (ITP_FORM_SYSTEM01010_IS_DUPLICATE) {
					itp_fn_modal_duplicate(ITP_MSG_LOCALE.label.code, formId + '_CODE_CD');
				} else {
					if (itp_fn_grid_validate_row(SYSTEM01010_GRID_ID)) {
						let gridInsertData = [];
						let gridUpdateData = [];
						let gridDeleteData = [];
						const rowData = $(SYSTEM01010_GRID_ID).getRowData();
						const keyValue = $(formId + '_CODE_CD').val();
						$.each(rowData, function(key, value) {
							if (value.viewCd != 'R') {
								value.codeCd = keyValue;
								if (value.viewCd == 'C') {
									gridInsertData.push(value);
								} else if (value.viewCd == 'U') {
									gridUpdateData.push(value);
								} else if (value.viewCd == 'D') {
									gridDeleteData.push(value);
								}
							}
						});
						let param = $(formId + '_DETAIL').serializeObject();
						param.gridInsertData = gridInsertData;
						param.gridUpdateData = gridUpdateData;
						param.gridDeleteData = gridDeleteData;
						//console.log(JSON.stringify(param)); 						
						var searhFn = function() {
							SYSTEM01010_SCH_CODE_CD = keyValue;
							ITP_FORM_SYSTEM01010_IS_WRITING = false;
							var keyword = {sCodeNm: $('#ITP_KEYWORD_SYSTEM01010_INPUT').val()};
							var param = $('#ITP_SYSTEM01010_ADV_SRH_FORM').serialize() + '&' + $.param(keyword);
							fn_ajax_call(CODE_CODE_SEARCH, param, itp_fn_SYSTEM01010_search_callback, 'GET');
						};
						fn_ajax_call(CODE_SAVE_CODE, JSON.stringify(param), searhFn, 'POST');						
					};
				}
			}
		});
	});
});

var itp_fn_SYSTEM01010_search = function() {
	var searhFn = {
		callBack: function(args) {			
			var sCodeNm = {sCodeNm: $('#ITP_KEYWORD_SYSTEM01010_INPUT').val()};
			var param = $('#ITP_SYSTEM01010_ADV_SRH_FORM').serialize() + '&' + $.param(sCodeNm);						
			fn_ajax_call(CODE_CODE_SEARCH, param, itp_fn_SYSTEM01010_search_callback, 'GET');
		}
	};
	if (ITP_FORM_SYSTEM01010_IS_WRITING || itp_fn_check_grid_is_writing(SYSTEM01010_GRID_ID)) {
		itp_fn_modal_confirm(ITP_MSG_LOCALE.message.ajax.cancelData, searhFn, null);
	} else {
		searhFn.callBack();
	}
};

var itp_fn_SYSTEM01010_search_callback = function(result) {
	
	$('#ITP_AJAX_SYSTEM01010_SRH_CONTAINER > .list-group').empty(); // 초기화
	
	$.each(result.searchList, function(index, item) {
		$('#ITP_AJAX_SYSTEM01010_SRH_CONTAINER > .list-group').append($('#ITP_AJAX_SYSTEM01010_SRH_CONTAINER_ROWCOPY').val());
		$('#ITP_AJAX_SYSTEM01010_SRH_CONTAINER > .list-group > .list-group-item:last').find('.fnCodeCd').text(item.codeCd);
		$('#ITP_AJAX_SYSTEM01010_SRH_CONTAINER > .list-group > .list-group-item:last').find('.fnCodeNm').text(item.codeNm);
		$('#ITP_AJAX_SYSTEM01010_SRH_CONTAINER > .list-group > .list-group-item:last').find('.fnCodeTpNm').text(item.codeTpNm);
		if(SYSTEM01010_SCH_CODE_CD && SYSTEM01010_SCH_CODE_CD == item.codeCd) {
			$('#ITP_AJAX_SYSTEM01010_SRH_CONTAINER > .list-group > .list-group-item:last').addClass('active');	
		}		
	});
	
	// 첫번째 데이터 상세조회
	if($('#ITP_AJAX_SYSTEM01010_SRH_CONTAINER .list-group .list-group-item').length > 0) {
		if(SYSTEM01010_SCH_CODE_CD && SYSTEM01010_SCH_CODE_CD !== undefined) {
			itp_fn_SYSTEM01010_detail(SYSTEM01010_SCH_CODE_CD);	
		} else {
			const item = $('#ITP_AJAX_SYSTEM01010_SRH_CONTAINER .list-group .list-group-item').first();
			const codeCd = item.find('.itp_param_key').text();
			item.addClass('active');
			itp_fn_SYSTEM01010_detail(codeCd);	
		}	
	}	
};

var itp_fn_SYSTEM01010_detail = function(key) {
	var codeCd  = {codeCd: key};
	var param = $.param(codeCd);						
	fn_ajax_call(CODE_INFO_CODE, param, itp_fn_SYSTEM01010_detail_callback, 'GET');	
};

var itp_fn_SYSTEM01010_detail_callback = function(result) {
	// 코드정보 지정
	$('#ITP_FORM_SYSTEM01010_DETAIL input[name=viewCd]').val('U');
	$('#ITP_FORM_SYSTEM01010_CODE_CD').val(result.codeCd);
	$('#ITP_FORM_SYSTEM01010_CODE_NM_KR').val(result.codeNm);
	$('#ITP_FORM_SYSTEM01010_USE_YN').val(result.useYn);
	$('#ITP_FORM_SYSTEM01010_CODE_TYPE').val(result.codeTpCd);
	$('#ITP_FORM_SYSTEM01010_CODE_CD').attr('readonly', true);
	$('#ITP_BTN_SYSTEM01010_DUP').attr('disabled', true);

	// 코드 상세리스트 조회	
	const key = {codeCd: result.codeCd, gridSize: $.jgrid.defaults.rowNum};
	itp_fn_SYSTEM01010_detail_grid.unload();
	itp_fn_SYSTEM01010_detail_grid.callBack(key);
};
		
var itp_fn_SYSTEM01010_detail_grid = {
	init: function() {
		ITP_FORM_SYSTEM01010_IS_WRITING = false;
		ITP_FORM_SYSTEM01010_IS_DUPLICATE = false;
		
		$('#ITP_FORM_SYSTEM01010_DETAIL').on('change', 'input, select, textarea', function() {
    		if (!ITP_FORM_SYSTEM01010_IS_WRITING) {
    			ITP_FORM_SYSTEM01010_IS_WRITING = true;
    		}
    		if ($(this).attr('id') == 'ITP_FORM_SYSTEM01010_CODE_CD') {
				ITP_FORM_SYSTEM01010_IS_DUPLICATE = true;
			}
    	});

		$('body').on('click', function(e) {
			var gridId = SYSTEM01010_GRID_ID.replace('#', '');
			itp_fn_grid_reset_selection(e, SYSTEM01010_GRID_LAST_ROW_ID, gridId, 'SYSTEM01010');
		});

		$('#ITP_BTN_SYSTEM01010_DUP').on('click', function() {
			const formId = '#ITP_FORM_SYSTEM01010';
			itp_fn_form_clear_validate(null, formId + '_DETAIL');
			var vali_codeCd = itp_fn_form_validate(formId + '_DETAIL', formId + '_CODE_CD', ['empty'], undefined);
			if (vali_codeCd) {
				var dupFn = function(result) {
					if (result.code == 'N') {
						ITP_FORM_SYSTEM01010_IS_DUPLICATE = false;
					} else {
						ITP_FORM_SYSTEM01010_IS_DUPLICATE = true;
					}
				};
				const key = {'codeCd':  $(formId + '_CODE_CD').val()};
				const param = $.param(key);
				fn_ajax_call(CODE_CHECK_DUPLICATE, param, dupFn, 'GET');
			}
		});

		$('#ITP_BTN_SYSTEM01010_ADDROW').on('click', function() {
			SYSTEM01010_GRID_LAST_ROW_ID = itp_fn_grid_add_row(SYSTEM01010_GRID_ID, undefined, ['codeDtlCd'], 'SYSTEM01010');
		});

		$('#ITP_BTN_SYSTEM01010_DELROW').on('click', function() {
		    itp_fn_grid_del_row(SYSTEM01010_GRID_ID);
		});
	},
	callBack: function(args) {
		$(SYSTEM01010_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: 'CODE_CD', name: 'codeCd',
					label: ITP_MSG_LOCALE.label.code,
					width: '10', fixed: false, align: 'center',
					sortable: false, hidden: true
				},
				{
					index: 'CODE_DTL_CD', name: 'codeDtlCd',
					label: ITP_MSG_LOCALE.label.codeDtl,
					width: '10', fixed: false, align: 'center',
					sortable: false, editable: false, edittype: 'text',
					editrules: {required: true},
					editoptions: {maxlength: 10}
				},
				{
					index: 'VIEW_NUM', name: 'viewNum',
					label: ITP_MSG_LOCALE.label.orderNo,
					width: '10', fixed: false, align: 'center',
					sortable: true, editable: true, edittype: 'text',
					editrules: {required: true, number: true}
				},
				{
					index: 'CODE_DTL_NM', name: 'codeDtlNm',
					label: ITP_MSG_LOCALE.label.codeNmKo,
					width: '30', fixed: false, align: 'center',
					sortable: false, editable: true, edittype: 'text',
					editrules: {required: true},
					editoptions: {maxlength: 40}
				},
				{
					index: 'CODE_DESC', name: 'codeDesc',
					label: ITP_MSG_LOCALE.label.remark,
					width: '20', fixed: false, align: 'center',
					sortable: false, editable: true, edittype: 'text'
				},
				{
					index: 'USE_YN', name: 'useYn',
					label: ITP_MSG_LOCALE.label.useYn,
					width: '10', fixed: false, align: 'center',
					sortable: false, editable: true, formatter: 'checkbox', edittype: 'checkbox',
					editoptions: {value: 'Y:N', defaultValue: 'Y'},
					editrules: {required: true}
				}
			],
			loadBeforeSend: function(jqXHR) {
			    jqXHR.setRequestHeader('X-AUTH-TOKEN', CONN_KEY);
			},
			postData: JSON.stringify(args),
			url: DOMAIN + CODE_DETAIL_GRID_LIST,
			pager: SYSTEM01010_GRID_PAGER,
			onCellSelect: function(rowId, cellIdx, cellValue) {
				SYSTEM01010_GRID_LAST_ROW_ID = itp_fn_set_data_editable(rowId, cellIdx, SYSTEM01010_GRID_LAST_ROW_ID, SYSTEM01010_GRID_ID, ['codeDtlCd']);
		   	},
			loadComplete: function(data) {
				itp_fn_grid_load_complete(data, SYSTEM01010_GRID_ID, true, undefined, 'SYSTEM01010');
		    },
		    loadError: function(jqXHR, textStatus, errorThrown) {
		    	itp_fn_grid_load_error(jqXHR, textStatus, errorThrown);
		    },
		    onPaging: function(action) {
		    	var pagingFn = {
	    			callBack: function(args) {
	    				$(args).trigger('reloadGrid');
	    			}
	    		};
		    	if (itp_fn_check_grid_is_writing(SYSTEM01010_GRID_ID)) {
		    		itp_fn_modal_confirm(ITP_MSG_LOCALE.message.ajax.cancelData, pagingFn, SYSTEM01010_GRID_ID);
		    		return 'stop';
		    	} else {
		    		itp_fn_grid_paging(SYSTEM01010_GRID_ID, action, args);
		    	}
		    },
		    onSortCol: function(index, columnIndex, sortOrder) {
		    	var sortingFn = {
	    			callBack: function(args) {
	    				$(args).trigger('reloadGrid');
	    			}
	    		};
		    	if (itp_fn_check_grid_is_writing(SYSTEM01010_GRID_ID)) {
		    		itp_fn_modal_confirm(ITP_MSG_LOCALE.message.ajax.cancelData, sortingFn, SYSTEM01010_GRID_ID);
		    		return 'stop';
		    	} else {
		    		itp_fn_grid_sorting(SYSTEM01010_GRID_ID, index, sortOrder);
		    	}
		    }
		}).navGrid(SYSTEM01010_GRID_PAGER, ITP_GRID_NAV_DEFAULTS.navGrid);
	},
	clearData : function() {
		$(SYSTEM01010_GRID_ID).jqGrid('clearGridData', true);
		$(SYSTEM01010_GRID_LIST).find('.ui-jqgrid-bdiv').css('min-height', '100px');
		$(SYSTEM01010_GRID_EMPTY).html(ITP_MSG_LOCALE.message.grid.noData);
		$(SYSTEM01010_GRID_EMPTY).show();
	}, 
	unload : function() {
		$.jgrid.gridUnload(SYSTEM01010_GRID_ID); 
	}
};