
const SYSTEM04010_GRID_ID = '#ITP_SYSTEM04010_jqGrid';
const SYSTEM04010_GRID_LIST = SYSTEM04010_GRID_ID + '_list';
const SYSTEM04010_GRID_PAGER = SYSTEM04010_GRID_ID + 'Pager';
const SYSTEM04010_GRID_EMPTY = SYSTEM04010_GRID_ID + 'Empty';

let SYSTEM04010_GRID_LAST_ROW_ID;
let ITP_FORM_SYSTEM04010_IS_WRITING = false;
let ITP_FORM_SYSTEM04010_IS_DUPLICATE = false;
let SYSTEM04010_SCH_AUTH_NO; //

let API_AUTH_DETAIL_GRID_LIST = '/api/menu/list-authmenu';
let API_MENU_LIST_AUTHMENU = '/api/menu/list-authmenu';
let AUTH_AUTH_SEARCH = '/api/auth/auth-search';
let AUTH_SAVE_AUTH = '/api/auth/save-auth';
let MENU_MENU_SEARCH = '/api/menu/menu-search';
let AUTH_INFO_AUTH = '/api/auth/info-auth';
let AUTH_CHECK_DUPLICATE = '/api/auth/check-duplicate';

require(['config'], function() {
	require([
		'jquery'
	], function($) {
		// 버튼 권한설정
		fn_proc_btn_auth('SYSTEM04010');		
		// 공통코드 표시
		fn_make_select(CODE_LIST, 'AUTH_TP_CD', 'ITP_SYSTEM04010_ADV_SRH_FORM_AUTH_TP_CD', true, '전체');
		fn_make_select(CODE_LIST, 'AUTH_TP_CD', 'ITP_FORM_SYSTEM04010_AUTH_TYPE_CD', true, '선택');
		fn_make_select(CODE_LIST, 'USE_YN', 'ITP_SYSTEM04010_ADV_SRH_FORM_USE_YN', true, '전체');
		fn_make_select(CODE_LIST, 'USE_YN', 'ITP_FORM_SYSTEM04010_USE_YN', true, '선택');
		
		// 상위메뉴조회
		itp_fn_SYSTEM04010_menu_search();
				
		itp_fn_SYSTEM04010_search();
		itp_fn_jqgrid_resize(SYSTEM04010_GRID_ID, SYSTEM04010_GRID_LIST, 'sm');
		itp_fn_SYSTEM04010_detail_grid.init();
    	itp_fn_fire_window_resize();

		// 팝업 조회
		// fn_proc_popup_view('SYSTEM04010');

		$('#ITP_BTN_SYSTEM04010_SRH').on('click', function() {
			itp_fn_SYSTEM04010_search();
		});

		$('#ITP_AJAX_SYSTEM04010_SRH_CONTAINER').on('click', '.list-group .list-group-item', function() {
			const $this = $(this);
			var itemFn = {
				callBack: function(args) {
					itp_fn_form_clear_validate(null, '#ITP_FORM_SYSTEM04010_DETAIL');
					$('#ITP_AJAX_SYSTEM04010_SRH_CONTAINER .list-group .list-group-item').removeClass('active');
					$this.addClass('active');
					const txt = $this.find('.itp_param_key').text();
					// SYSTEM04010_SCH_TOP_MENU_NO = item.find('.itp_param_key').data('topMenuNo');
					itp_fn_SYSTEM04010_detail(txt);					
				}
			};
			if (ITP_FORM_SYSTEM04010_IS_WRITING || itp_fn_check_grid_is_writing(SYSTEM04010_GRID_ID)) {
				itp_fn_modal_confirm(ITP_MSG_LOCALE.message.ajax.cancelData, itemFn, $this);
			} else {
				itemFn.callBack($this);
			}
		});

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

					// 정보 초기화					
					$('#ITP_FORM_SYSTEM04010_DETAIL input[name=viewCd]').val('C');
					$('#ITP_FORM_SYSTEM04010_AUTH_NO').val('');
					$('#ITP_FORM_SYSTEM04010_USE_YN').val('');
					$('#ITP_FORM_SYSTEM04010_AUTH_NM').val('');
					$('#ITP_FORM_SYSTEM04010_AUTH_TYPE_CD').val('');
					$('#ITP_FORM_SYSTEM04010_TOP_MENU_NO').val('');
					$('#ITP_FORM_SYSTEM04010_AUTH_NO').removeAttr('readonly');
					$('#ITP_FORM_SYSTEM04010_TOP_MENU_NO').removeAttr('disabled');
					$('#ITP_BTN_SYSTEM04010_DUP').removeAttr('disabled');
					
					// 그리드 초기화
					itp_fn_SYSTEM04010_detail_grid.clearData();	
    			}
    		};
			if (ITP_FORM_SYSTEM04010_IS_WRITING || itp_fn_check_grid_is_writing(SYSTEM04010_GRID_ID)) {
				itp_fn_modal_confirm(ITP_MSG_LOCALE.message.ajax.cancelData, newFn, null);
			} else {
				newFn.callBack();
			}
		});

		$('#ITP_BTN_SYSTEM04010_SAVE').on('click', function() {
			const formId = '#ITP_FORM_SYSTEM04010';
			itp_fn_form_clear_validate(null, formId + '_DETAIL');
			var vali_authNo = itp_fn_form_validate(formId + '_DETAIL', formId + '_AUTH_NO', ['empty'], undefined);
			var vali_useYn = itp_fn_form_validate(formId + '_DETAIL', formId + '_USE_YN', ['empty'], undefined);
			var vali_authNmKr = itp_fn_form_validate(formId + '_DETAIL', formId + '_AUTH_NM_KR', ['empty'], undefined);
			var vali_authTypeCd = itp_fn_form_validate(formId + '_DETAIL', formId + '_AUTH_TYPE_CD', ['empty'], undefined);
			var vali_topMenuNo = itp_fn_form_validate(formId + '_DETAIL', formId + '_TOP_MENU_NO', ['empty'], undefined);

			if (vali_authNo && vali_useYn && vali_authNmKr && vali_authTypeCd && vali_topMenuNo) {
				if (ITP_FORM_SYSTEM04010_IS_DUPLICATE) {
					itp_fn_modal_duplicate(ITP_MSG_LOCALE.label.permitCd, formId + '_AUTH_NO');
				} else {
					//if (itp_fn_grid_validate_row(SYSTEM04010_GRID_ID)) {
						let gridInsertData = [];
						let gridUpdateData = [];
						let gridDeleteData = [];
						const rowData = $(SYSTEM04010_GRID_ID).getRowData();
						const keyValue = $(formId + '_AUTH_NO').val();
						$.each(rowData, function(key, value) {
							if (value.viewCd != 'R') {
								value.authNo = keyValue;
								
								if (value.readYn == 'N' && value.writeYn == 'Y') {
									value.readYn = 'Y';
								}
								
								if (value.viewCd == 'C') {
									gridInsertData.push(value);
								} else if (value.viewCd == 'U') {
									
									if (value.readYn == 'N' && value.writeYn == 'N') {
										value.viewCd = 'D';
										gridDeleteData.push(value);
									} else {
										gridUpdateData.push(value);
									}
									
								}
							}
						});
						let param = $(formId + '_DETAIL').serializeObject();
						param.topMenuNo = $(formId + '_TOP_MENU_NO').val();
						param.gridInsertData = gridInsertData;
						param.gridUpdateData = gridUpdateData;
						param.gridDeleteData = gridDeleteData;
						console.log(JSON.stringify(param)); 
						var searhFn = function() {			
							SYSTEM04010_SCH_AUTH_NO = keyValue;
							var keyword = {keyword: $('#ITP_KEYWORD_SYSTEM04010_INPUT').val()};
							var param = $('#ITP_SYSTEM04010_ADV_SRH_FORM').serialize() + '&' + $.param(keyword);
							fn_ajax_call(AUTH_AUTH_SEARCH, param, itp_fn_SYSTEM04010_search_callback, 'GET');
						};
						fn_ajax_call(AUTH_SAVE_AUTH, JSON.stringify(param), searhFn, 'POST');
					//};
				}
			}
		});
	});
});

var itp_fn_SYSTEM04010_menu_search = function() {
	fn_ajax_call(MENU_MENU_SEARCH, null, itp_fn_SYSTEM04010_menu_search_callback, 'GET');
};

var itp_fn_SYSTEM04010_menu_search_callback = function(result) {
	fn_make_select_upper_menu(result.searchList, 'ITP_SYSTEM04010_ADV_SRH_FORM_TOP_MENU_NO', true, '전체');
	fn_make_select_upper_menu(result.searchList, 'ITP_FORM_SYSTEM04010_TOP_MENU_NO', true, '선택');
};

var itp_fn_SYSTEM04010_search = function() {
	var searhFn = {
		callBack: function(args) {
			var keyword = {keyword: $('#ITP_KEYWORD_SYSTEM04010_INPUT').val()};
			var param = $('#ITP_SYSTEM04010_ADV_SRH_FORM').serialize() + '&' + $.param(keyword);
			fn_ajax_call(AUTH_AUTH_SEARCH, param, itp_fn_SYSTEM04010_search_callback, 'GET');
		}
	};
	if (ITP_FORM_SYSTEM04010_IS_WRITING || itp_fn_check_grid_is_writing(SYSTEM04010_GRID_ID)) {
		itp_fn_modal_confirm(ITP_MSG_LOCALE.message.ajax.cancelData, searhFn, null);
	} else {
		searhFn.callBack();
	}
};

var itp_fn_SYSTEM04010_search_callback = function(result) {
	
	$('#ITP_AJAX_SYSTEM04010_SRH_CONTAINER > .list-group').empty(); // 초기화
	
	$.each(result.searchList, function(index, item) {
		$('#ITP_AJAX_SYSTEM04010_SRH_CONTAINER > .list-group').append($('#ITP_AJAX_SYSTEM04010_SRH_CONTAINER_ROWCOPY').val());
		$('#ITP_AJAX_SYSTEM04010_SRH_CONTAINER > .list-group > .list-group-item:last').find('.fnAuthNo').text(item.authNo);
		$('#ITP_AJAX_SYSTEM04010_SRH_CONTAINER > .list-group > .list-group-item:last').find('.fnAuthNo').attr('data-top-menu-no', item.topMenuNo);
		$('#ITP_AJAX_SYSTEM04010_SRH_CONTAINER > .list-group > .list-group-item:last').find('.fnAuthNm').text(item.authNm);
		$('#ITP_AJAX_SYSTEM04010_SRH_CONTAINER > .list-group > .list-group-item:last').find('.fnAuthTpNm').text(item.authTpNm);
		if(SYSTEM04010_SCH_AUTH_NO && SYSTEM04010_SCH_AUTH_NO == item.authNo) {
			$('#ITP_AJAX_SYSTEM04010_SRH_CONTAINER > .list-group > .list-group-item:last').addClass('active');	
		}		
	});
	
	// 첫번째 데이터 상세조회
	if($('#ITP_AJAX_SYSTEM04010_SRH_CONTAINER .list-group .list-group-item').length > 0) {
		if(SYSTEM04010_SCH_AUTH_NO && SYSTEM04010_SCH_AUTH_NO !== undefined) {
			itp_fn_SYSTEM04010_detail(SYSTEM04010_SCH_AUTH_NO);	
		} else {
			const item = $('#ITP_AJAX_SYSTEM04010_SRH_CONTAINER .list-group .list-group-item').first();
			const authNo = item.find('.itp_param_key').text();
			// SYSTEM04010_SCH_TOP_MENU_NO = item.find('.itp_param_key').data('topMenuNo');
			item.addClass('active');
			itp_fn_SYSTEM04010_detail(authNo);	
		}	
	}	
};

var itp_fn_SYSTEM04010_detail = function(key) {
	var authNo  = {authNo: key};
	var param = $.param(authNo);						
	fn_ajax_call(AUTH_INFO_AUTH, param, itp_fn_SYSTEM04010_detail_callback, 'GET');	
};

var itp_fn_SYSTEM04010_detail_callback = function(result) {
	ITP_FORM_SYSTEM04010_IS_WRITING = false;
	
	// 상세정보 지정
	$('#ITP_FORM_SYSTEM04010_DETAIL input[name=viewCd]').val('U');
	$('#ITP_FORM_SYSTEM04010_AUTH_NO').val(result.authNo);
	$('#ITP_FORM_SYSTEM04010_USE_YN').val(result.useYn);
	$('#ITP_FORM_SYSTEM04010_AUTH_NM').val(result.authNm);
	$('#ITP_FORM_SYSTEM04010_AUTH_TYPE_CD').val(result.authTpCd);
	$('#ITP_FORM_SYSTEM04010_TOP_MENU_NO').val(result.topMenuNo);
	$('#ITP_FORM_SYSTEM04010_AUTH_NO').attr('readonly', true);
	$('#ITP_FORM_SYSTEM04010_TOP_MENU_NO').attr('disabled', true);
	$('#ITP_BTN_SYSTEM04010_DUP').attr('disabled', true);
	
	// 상세리스트 조회	
	$(SYSTEM04010_GRID_ID).setGridParam({'url':DOMAIN + API_AUTH_DETAIL_GRID_LIST})
	const key = {authNo: result.authNo, topMenuNo: result.topMenuNo, gridSize: $.jgrid.defaults.rowNum};
	itp_fn_SYSTEM04010_detail_grid.unload();
	itp_fn_SYSTEM04010_detail_grid.callBack(key);
};

var itp_fn_SYSTEM04010_detail_grid = {
	init: function() {
		ITP_FORM_SYSTEM04010_IS_WRITING = false;
		ITP_FORM_SYSTEM04010_IS_DUPLICATE = false;		

		$('#ITP_FORM_SYSTEM04010_DETAIL').on('change', 'input, select, textarea', function() {
    		if (!ITP_FORM_SYSTEM04010_IS_WRITING) {
    			ITP_FORM_SYSTEM04010_IS_WRITING = true;
    		}
    		if ($(this).attr('id') == 'ITP_FORM_SYSTEM04010_AUTH_NO') {
				ITP_FORM_SYSTEM04010_IS_DUPLICATE = true;
			} else if ($(this).attr('id') == 'ITP_FORM_SYSTEM04010_TOP_MENU_NO') {
				var changeFn = {
					callBack: function(args) {
						const key = {topMenuNo: args, viewCd: 'C'};
						$(SYSTEM04010_GRID_ID).setGridParam({'url':DOMAIN + API_MENU_LIST_AUTHMENU, 'postData': JSON.stringify(key)}).trigger('reloadGrid');
					}
				};
				const topMenu = $(this).val();
				const viewCd = $('#ITP_FORM_SYSTEM04010_VIEW_CD').val();
				if (viewCd != 'C') {
					itp_fn_modal_confirm(ITP_MSG_LOCALE.message.ajax.resetData, changeFn, topMenu);
				} else {
					changeFn.callBack(topMenu);					
				}
			}
    	});

		$('body').on('click', function(e) {
			var gridId = SYSTEM04010_GRID_ID.replace('#', '');
			itp_fn_grid_reset_selection(e, SYSTEM04010_GRID_LAST_ROW_ID, gridId, 'SYSTEM04010');
		});

		$('#ITP_BTN_SYSTEM04010_DUP').on('click', function() {
			const formId = '#ITP_FORM_SYSTEM04010';
			itp_fn_form_clear_validate(null, formId + '_DETAIL');
			var vali_authNo = itp_fn_form_validate(formId + '_DETAIL', formId + '_AUTH_NO', ['empty'], undefined);
			if (vali_authNo) {
				var dupFn = function(result) {
					if (result.code == 'N') {
						ITP_FORM_SYSTEM04010_IS_DUPLICATE = false;
					} else {
						ITP_FORM_SYSTEM04010_IS_DUPLICATE = true;
					}
				};
				const param = {'authNo':  $(formId + '_AUTH_NO').val()};
				fn_ajax_call(AUTH_CHECK_DUPLICATE, param, dupFn, 'GET');
			}
		});
	}, 
	callBack: function(args) {
		$(SYSTEM04010_GRID_ID).jqGrid({
			colModel: [
				{
					index: 'VIEW_CD', name: 'viewCd',
					label: ITP_MSG_LOCALE.label.viewCd,
					width: '9', fixed: false, align: 'center',
					sortable: false, hidden: true
				},
				{
					index: 'AUTH_NO', name: 'authNo',
					label: ITP_MSG_LOCALE.label.permitCd,
					width: '9', fixed: false, align: 'center',
					sortable: false, hidden: true
				},
				{
					index: 'ACT_ID', name: 'actId',
					label: ITP_MSG_LOCALE.label.actionId,
					width: '9', fixed: false, align: 'center',
					sortable: false, hidden: true
				},
				{
					index: 'TOP_MENU_NO', name: 'topMenuNo',
					label: ITP_MSG_LOCALE.label.topMenu,
					width: '9', fixed: false, align: 'center',
					sortable: false, hidden: true
				},
				{
					index: 'MENU_NO', name: 'menuNo',
					label: ITP_MSG_LOCALE.label.subMenu,
					width: '9', fixed: false, align: 'center',
					sortable: false, hidden: true
				},
				{
					index: 'TOP_MENU_NM', name: 'topMenuNm',
					label: ITP_MSG_LOCALE.label.topMenu,
					width: '9', fixed: false, align: 'center',
					sortable: false, hidden: true
				},
				{
					index: 'MENU_NM', name: 'menuNm',
					label: ITP_MSG_LOCALE.label.menuName,
					width: '12', fixed: false, align: 'center',
					sortable: true, editable: false
				},
				{
					index: 'ACT_TP_NM', name: 'actTpNm',
					label: ITP_MSG_LOCALE.label.actionType,
					width: '9', fixed: false, align: 'center',
					sortable: false, hidden: true
				},
				{
					index: 'ACT_NM', name: 'actNm',
					label: ITP_MSG_LOCALE.label.menuDetail,
					width: '12', fixed: false, align: 'center',
					sortable: false, editable: false
				},
				{
					index: 'READ_YN', name: 'readYn', 
					label: ITP_MSG_LOCALE.label.readPermit,
					width: '6', fixed: false, align: 'center',
					sortable: false, editable: true, formatter: 'checkbox', edittype: 'checkbox',
					editoptions: {value: 'Y:N', defaultValue: 'Y'},
					editrules: {required: true}
				},
				{
					index: 'WRITE_YN', name: 'writeYn',
					label: ITP_MSG_LOCALE.label.writePermit,
					width: '6', 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 + API_AUTH_DETAIL_GRID_LIST,
			pager: SYSTEM04010_GRID_PAGER,			
			multiselect: false,
			rowNum: '',
			onCellSelect: function(rowId, cellIdx, cellValue) {
				SYSTEM04010_GRID_LAST_ROW_ID = itp_fn_set_data_editable(rowId, cellIdx, SYSTEM04010_GRID_LAST_ROW_ID, SYSTEM04010_GRID_ID);
		   	},
			loadComplete: function(data) {
				itp_fn_grid_load_complete(data, SYSTEM04010_GRID_ID, false, undefined, 'SYSTEM04010');				
		    },
		    loadError: function(jqXHR, textStatus, errorThrown) {
		    	itp_fn_grid_load_error(jqXHR, textStatus, errorThrown);
		    }
		}).navGrid(SYSTEM04010_GRID_PAGER, ITP_GRID_NAV_DEFAULTS.navGrid);
	}, 
	clearData : function() {
		$(SYSTEM04010_GRID_ID).jqGrid('clearGridData', true);
		$(SYSTEM04010_GRID_LIST).find('.ui-jqgrid-bdiv').css('min-height', '100px');
		$(SYSTEM04010_GRID_EMPTY).html(ITP_MSG_LOCALE.message.grid.noData);
		$(SYSTEM04010_GRID_EMPTY).show();
	},
	unload : function() {
		$.jgrid.gridUnload(SYSTEM04010_GRID_ID); 
	}
};
