/********************************************************
 --------------------------------------------------------
 - Object 목록								            -
 --------------------------------------------------------
 * const gridColModel = {}	: 화면 Grid Object			*
 * let pageObj = {}			: 화면공통 Object			*
 * let listObj = {}			: 목록화면 Object			*
 * let viewObj = {}			: 상세화면 Object			*
 * let modifyObj = {}		: 수정화면 Object			*
 * let locInfoObj = {}		: 로케이션정보 Object				*
 *******************************************************/

/*화면 변수*/
const LOANMNG01010_GRID_ID = '#ITP_LOANMNG01010_jqGrid';
const LOANMNG01010_GRID_LIST = '#ITP_LOANMNG01010_jqGrid_list';
const LOANMNG01010_GRID_PAGER = '#ITP_LOANMNG01010_jqGridPager';
const LOANMNG01010_GRID_EMPTY = '#ITP_LOANMNG01010_jqGridEmpty';

const LOANMNG01010_VIEW_GRID_ID = '#ITP_LOANMNG01010_VIEW_jqGrid';
const LOANMNG01010_VIEW_GRID_LIST = '#ITP_LOANMNG01010_VIEW_jqGrid_list';
const LOANMNG01010_VIEW_GRID_PAGER = '#ITP_LOANMNG01010_VIEW_jqGridPager';
const LOANMNG01010_VIEW_GRID_EMPTY = '#ITP_LOANMNG01010_VIEW_jqGridEmpty';

let ITP_FORM_LOANMNG01010_DETAIL_IS_DUPLICATE = false;
let ITP_FORM_LOANMNG01010_DETAIL_IS_WRITING = false;
let LOANMNG01010_DETAIL_GRID_LAST_ROW_ID;

/*API URL*/
let LOAN_STATE_DETAIL_GRID_LIST = '/api/loan/state/detail-grid-list';
let LOAN_STATE_INFO_LOAN_MNG = '/api/loan/state/info-loan-mng';
let LOAN_STATE_HIST_GRID_LIST = '/api/loan/state/hist-grid-list';

/* 로그인 권한타입 */
let LOGIN_AUTH_TYPE_CD;

/*화면 Grid ColModel*/
const gridColModel = {
	list: [
		{
			index: 'BRAND_ID', name: 'brandId',
			label: "브랜드ID", 
			width: '0', fixed: false, align: 'center',
			sortable: false, hidden: true
		},
		{
			index: 'STORE_ID', name: 'storeId',
			label: "매장ID", 
			width: '0', fixed: false, align: 'center',
			sortable: false, hidden: true
		},
		{
			index: 'BRAND_NM', name: 'brandNm',
			label: ITP_MSG_LOCALE.label.brandNm, //브랜드
			width: '13', fixed: false, align: 'center',
			sortable: false, hidden: true
		},
		{
			index: 'STORE_NM', name: 'storeNm',
			label: "매장명", 
			width: '13', fixed: false, align: 'left',
			sortable: false, hidden: false, classes: 'ui-ellipsis'
		},
		{
			index: 'LOAN_MGNT_UNQ_NO', name: 'loanMgntUnqNo',
			label: "여신관리번호", 
			minwidth: 120,
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'LOAN_DVSN_NM', name: 'loanDvsnNm',
			label: "정산타입", 
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'LIMIT_AMT', name: 'limitAmt',
			label: "한도금액", 
			width: '10', fixed: false, align: 'right',
			sortable: false, hidden: false, 
			formatter:'integer',formatoptions: { defaultValue: '', thousandsSeparator: ',' }
		},
		{
			index: 'ACCT_BAL', name: 'acctBal',
			label: "잔액", 
			width: '10', fixed: false, align: 'right',
			sortable: false, hidden: false, 
			formatter:'integer',formatoptions: { defaultValue: '', thousandsSeparator: ',' }
		},		
		{
			index: 'POSB_LIMIT_AMT', name: 'posbLimitAmt',
			label: "사용가능금액", 
			width: '10', fixed: false, align: 'right',
			sortable: false, hidden: false, 
			formatter:'integer',formatoptions: { defaultValue: '', thousandsSeparator: ',' }
		},
		{
			index: 'USE_AMT_TOTAL', name: 'useAmtTotal',
			label: '사용한금액', 
			width: '10', fixed: false, align: 'right',
			sortable: false, hidden: false, 
			formatter:'integer',formatoptions: { defaultValue: '', thousandsSeparator: ',' }
		},
		{
			index: 'USE_YN_NM', name: 'useYnNm',
			label: "사용여부", 
			width: '8', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'SYS_CHG_NM', name: 'sysChgNm',
			label: "최종수정자", 
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: false, classes: 'ui-ellipsis'
		}
	],
	view: [
		{
			index: 'VIEW_CD', name: 'viewCd',
			label: ITP_MSG_LOCALE.label.viewCd,
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: true
		},		
		{
			index: 'LOAN_REG_DT', name: 'loanRegDt',
			label: "발생일자",
			width: '10', fixed: false, align: 'center',
			sortable: false, editable: false, edittype: 'text'
		},
		{
			index: 'DPST_PAY_DVSN_NM', name: 'dpstPayDvsnNm',
			label: "입지구분",
			width: '10', fixed: false, align: 'center',
			sortable: false, editable: false, edittype: 'text'
		},
		{
			index: 'MEDIA_DVSN_NM', name: 'mediaDvsnNm',
			label: "매체구분",
			width: '10', fixed: false, align: 'center',
			sortable: false, editable: false, edittype: 'text'
		},
		{
			index: 'DPST_AMT', name: 'dpstAmt',
			label: "입금",
			width: '10', fixed: false, align: 'right',
			sortable: false, editable: false, edittype: 'text', 
			formatter:'integer',formatoptions: { defaultValue: '', thousandsSeparator: ',' }
		},
		{
			index: 'PAYM_AMT', name: 'paymAmt',
			label: "지급",
			width: '10', fixed: false, align: 'right',
			sortable: false, editable: false, edittype: 'text', 
			formatter:'integer',formatoptions: { defaultValue: '', thousandsSeparator: ',' }
		},
		{
			index: 'TRSC_AF_BAL', name: 'trscAfBal',
			label: "잔액",
			width: '10', fixed: false, align: 'right',
			sortable: false, editable: false, edittype: 'text', 
			formatter:'integer',formatoptions: { defaultValue: '', thousandsSeparator: ',' }
		},
		{
			index: 'USER', name: 'user',
			label: "사용자",
			width: '10', fixed: false, align: 'center',
			sortable: false, editable: false, edittype: 'text'
		},
		{
			index: 'NO', name: 'no',
			label: "관련번호",
			width: '10', fixed: false, align: 'center',
			sortable: false, editable: false, edittype: 'text'
		}
	]
};

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

/*화면공통 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('LOANMNG01010');
			
			// 공통코드 표시
			$('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_LOANMNG01010 .input-group.date').datepicker(ITP_DATE_LANGUAGE);			
			$('#ITP_FORM_LOANMNG01010_SEARCH_FROM').datepicker('setDate', new Date(now.setMonth(now.getMonth() - 1)));
			$('#ITP_FORM_LOANMNG01010_SEARCH_TO').datepicker('setDate', new Date());
			
			// 권한에 따라 매장값 설정
			$('#ITP_FORM_LOANMNG01010_SEARCH_BRAND_ID').val(fn_make_user_info.get('brandId'));
			LOGIN_AUTH_TYPE_CD = fn_make_user_info.get('authTpCd'); // 권한타입
			if(LOGIN_AUTH_TYPE_CD == '50') {
				$('#ITP_FORM_LOANMNG01010_SEARCH_STORE_ID').val(fn_make_user_info.get('storeId'));
				$('#ITP_FORM_LOANMNG01010_SEARCH_STORE_NM').val(fn_make_user_info.get('storeNm'));	
			}
			
		},
		grid: function() {
			itp_fn_jqgrid_resize(LOANMNG01010_GRID_ID, LOANMNG01010_GRID_LIST, 'lg');
			listObj.empty.init();
			itp_fn_fire_window_resize();
		},
		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_LOANMNG01010_SRH'					: listObj.button.search();		break;	// 조회 버튼 클릭
						case 'ITP_BTN_LOANMNG01010_CANCELLIST'			: viewObj.button.cancel(); 	break;	// 취소/목록 버튼
						case 'ITP_BTN_LOANMNG01010_VIEW_SEARCH_SRH'		: viewObj.button.history();		break;	// 이력조회
						case 'ITP_BTN_LOANMNG01010_STORE_SEARCH'		: listObj.button.popupStore();	break;	// 매장선택 팝업
						case 'ITP_BTN_LOANMNG01010_STORE_ERASE'			: listObj.button.eraseStore();	break;	// 매장선택 삭제
						case 'ITP_BTN_LOANMNG01010_EXCEL'			: listObj.excelDown();	break;	// 엑셀다운로드
						case 'ITP_BTN_LOANMNG01010_VIEW_EXCEL'		: viewObj.histexcelDown();		break;	// 이력 엑셀 다운로드
					}
				});
			});

			$('body').on('click', function(e) {
			});

		}
	},
	switchScreen: function(mode) {
		if(mode == 'LIST') { // 목록
			$('#ITP_BTN_LOANMNG01010_MODIFY').hide();
			$('#ITP_BTN_LOANMNG01010_CANCELLIST').hide();
			$('#ITP_BTN_LOANMNG01010_DELETE').hide();
			$('#ITP_BTN_LOANMNG01010_SAVE').hide();
			
			if(LOGIN_AUTH_TYPE_CD == '50') {
				$('#ITP_BTN_LOANMNG01010_STORE_SEARCH').hide();
				$('#ITP_BTN_LOANMNG01010_STORE_ERASE').hide();
			} else {
				$('#ITP_BTN_LOANMNG01010_STORE_SEARCH').show();
				$('#ITP_BTN_LOANMNG01010_STORE_ERASE').show();
			}
			
			fn_show_btn_auth('#ITP_BTN_LOANMNG01010_SRH');

			$('#ITP_AJAX_LOANMNG01010_LIST_CONTAINER').show();
			$('#ITP_AJAX_LOANMNG01010_DETAIL_CONTAINER').hide();
			$('#ITP_AJAX_LOANMNG01010_VIEW_CONTAINER').hide();
			
			$('#ITP_BTN_LOANMNG01010_EXCEL').show();
		} else if(mode == 'VIEW') { // 보기
			$('#ITP_BTN_LOANMNG01010_SRH').hide();
			$('#ITP_BTN_LOANMNG01010_DELETE').hide();
			$('#ITP_BTN_LOANMNG01010_SAVE').hide();
			
			fn_show_btn_auth('#ITP_BTN_LOANMNG01010_MODIFY');
			fn_show_btn_auth('#ITP_BTN_LOANMNG01010_CANCELLIST');

			$('#ITP_AJAX_LOANMNG01010_LIST_CONTAINER').hide();
			$('#ITP_AJAX_LOANMNG01010_DETAIL_CONTAINER').hide();
			$('#ITP_AJAX_LOANMNG01010_VIEW_CONTAINER').show();
			
			$('#ITP_BTN_LOANMNG01010_VIEW_EXCEL').show();
		}
	}
};

/*목록화면 Object*/
let listObj = {
	init: function () {
		this.grid.init();
	},
	itp_LOANMNG01010_search: false,
	button: {
		search: function() {
			listObj.itp_LOANMNG01010_search = true;
			let param = $('#ITP_FORM_LOANMNG01010_SEARCH').serializeObject();
			param.gridSize = $.jgrid.defaults.rowNum;
			param.gridPage = $.jgrid.defaults.page;
			$(LOANMNG01010_GRID_ID).setGridParam({'postData': JSON.stringify(param)}).trigger('reloadGrid');
		},
		popupStore: function() { // 매장선택 팝업
			fn_call_popup('biz', 'BIZPOP_BRAND_STORE', '#ITP_ASIDE', function(result) {
				// alert(JSON.stringify(result));
				$('#ITP_FORM_LOANMNG01010_SEARCH_STORE_ID').val(result[0].storeId);
				$('#ITP_FORM_LOANMNG01010_SEARCH_STORE_NM').val(result[0].storeNm);				
				listObj.button.search();
			}, null, 'S');
		}, 
		eraseStore: function() { // 매장선택 삭제
			$('#ITP_FORM_LOANMNG01010_SEARCH_STORE_ID').val('');
			$('#ITP_FORM_LOANMNG01010_SEARCH_STORE_NM').val('');
			listObj.button.search();
		}
	},
	empty: {
		init: function() {
			var _this = this;
			this.push();
			$(LOANMNG01010_GRID_EMPTY).on('click', function() {
				_this.back();
				_this.itp_LOANMNG01010_param.gridSize = $.jgrid.defaults.rowNum;
				$(LOANMNG01010_GRID_ID).setGridParam({'postData': JSON.stringify(_this.itp_LOANMNG01010_param)}).trigger('reloadGrid');
			});
		},
		itp_LOANMNG01010_param: {},
		push: function() {
			let param = $('#ITP_FORM_LOANMNG01010_SEARCH').serializeObject();
			listObj.itp_LOANMNG01010_param = param;
		},
		back: function() {
			$('#ITP_FORM_LOANMNG01010_WHS_DVSN').val(listObj.itp_LOANMNG01010_param.swhsDvsn);
			$('#ITP_FORM_LOANMNG01010_WHS_ST_CD').val(listObj.itp_LOANMNG01010_param.swhsStCd);
			$('#ITP_FORM_LOANMNG01010_SEARCH_WHS_NM').val(listObj.itp_LOANMNG01010_param.swhsNm);
		}
	},
	grid: {
		init: function () {
			// 데이터 없을때
			listObj.empty.push();
			this.search();
		},
		colModel: gridColModel.list,
		search: function() {
			pageObj.switchScreen('LIST');
			this.unload();
			this.load();
		},
		load: function() {
			let param = $('#ITP_FORM_LOANMNG01010_SEARCH').serializeObject();
			param.gridSize = $.jgrid.defaults.rowNum;

			var option = {
				gridId: LOANMNG01010_GRID_ID,
				colModel: gridColModel.list,
				param: param,
				url: DOMAIN + LOAN_STATE_DETAIL_GRID_LIST,
				pager: LOANMNG01010_GRID_PAGER,
				onCellSelect: function(rowId, cellIdx, cellValue) {
					var cm = $(this).jqGrid('getGridParam', 'colModel');
					var colNm = cm[cellIdx].name;
					if (colNm == 'loanDvsnNm') {
						const loanMgntUnqNoVal = $(this).jqGrid('getCell', rowId, 'loanMgntUnqNo');
						
						const key = {loanMgntUnqNo: loanMgntUnqNoVal, viewCd: 'R'};
						var param = $.param(key);
						viewObj.init(param);
					}
				},
				loadComplete: function(data) {
					// console.log(data);
					itp_fn_grid_load_complete(data, LOANMNG01010_GRID_ID, true, 'number', 'LOANMNG01010', listObj.itp_LOANMNG01010_search, listObj.empty, true, data.gridRecords, true);
					var ids = $(LOANMNG01010_GRID_ID).getDataIDs();
					$.each(ids, function(idx, rowId) {
						$(LOANMNG01010_GRID_ID).jqGrid('setCell', rowId, 'loanDvsnNm', '', ITP_GRID_COL_STYLE.link);
					});
				},
				onPaging: function(action) {
					itp_fn_grid_paging(LOANMNG01010_GRID_ID, action, param);
				}
			};
			itp_fn_grid_make_remote(option);
		},
		clearData : function() {
			$(LOANMNG01010_GRID_ID).jqGrid('clearGridData', true);
			$(LOANMNG01010_GRID_LIST).find('.ui-jqgrid-bdiv').css('min-height', '100px');
			$(LOANMNG01010_GRID_EMPTY).html(ITP_MSG_LOCALE.message.grid.noData);
			$(LOANMNG01010_GRID_EMPTY).show();
		},
		unload : function() {
			$.jgrid.gridUnload(LOANMNG01010_GRID_ID);
		}
	},
	excelDown: function() {
		var param = {
			'url': LOAN_STATE_DETAIL_GRID_LIST,
			'param': $('#ITP_FORM_LOANMNG01010_SEARCH').serializeObject(),
			'gridColumns': $(LOANMNG01010_GRID_ID).jqGrid('getGridParam', 'colModel'),
			'fileName': '여신현황.xlsx',
			'sheetName': '여신현황리스트'
		};
		itp_fn_remote_to_excel(param);
	}
};

/*상세화면 Object*/
let viewObj = {
	init: function (param) {
		this.load(param);
	},
	button: {
		cancel: function() {
			listObj.grid.search();
		},
		history: function() {
			let param = $('#ITP_FORM_LOANMNG01010_VIEW_SEARCH').serializeObject();
			param.gridSize = $.jgrid.defaults.rowNum;
			param.gridPage = $.jgrid.defaults.page;
			$(LOANMNG01010_VIEW_GRID_ID).setGridParam({'postData': JSON.stringify(param)}).trigger('reloadGrid');
		},
	},
	load: function(param) {
		fn_ajax_call(LOAN_STATE_INFO_LOAN_MNG, param, this.callback, 'GET');
	},
	callback: function (result) {
		// console.log(result);
		pageObj.switchScreen('VIEW');
		$('#ITP_FORM_LOANMNG01010_VIEW_BRAND_ID').val(result.brandId);
		$('#ITP_FORM_LOANMNG01010_VIEW_STORE_ID').val(result.storeId);
		$('#ITP_FORM_LOANMNG01010_VIEW_LOAN_MGNT_UNQ_NO').val(result.loanMgntUnqNo);
		$('#ITP_FORM_LOANMNG01010_VIEW_SEARCH_LOAN_MGNT_UNQ_NO').val(result.loanMgntUnqNo);
		
		$('#ITP_FORM_LOANMNG01010_VIEW .fnBrandNm').text(result.brandNm);
		$('#ITP_FORM_LOANMNG01010_VIEW .fnStoreNm').text(result.storeNm);
		$('#ITP_FORM_LOANMNG01010_VIEW .fnLoanDvsn').text(result.loanDvsnNm);
		var limitAmt;
		if(result.loanDvsn == 'LD01') { // 선불(충전)
			limitAmt = result.chrgeLimitAmt;
		} else if(result.loanDvsn == 'LD02') { // 후불(신용)
			limitAmt = result.credtLimitAmt;				
		}
		$('#ITP_FORM_LOANMNG01010_VIEW .fnCredtLimitAmt').text(itp_fn_number_comma(limitAmt));
		$('#ITP_FORM_LOANMNG01010_VIEW .fnContDt').text(''); // TODO 계약기간
		$('#ITP_FORM_LOANMNG01010_VIEW .fnUseYn').text(result.useYnNm);		
		$('#ITP_FORM_LOANMNG01010_VIEW .fnPosbLimitAmt').text(itp_fn_number_comma(limitAmt + result.acctBal - result.useAmtTotal)); // TODO 가용한도금액
		$('#ITP_FORM_LOANMNG01010_VIEW .fnTmpRcvAcctTotal').text(itp_fn_number_comma(result.acctBal));
		$('#ITP_FORM_LOANMNG01010_VIEW .fnUseAmtTotal').text(itp_fn_number_comma(result.useAmtTotal));
		$('#ITP_FORM_LOANMNG01010_VIEW .fnLastModify').text(result.sysChgNm + ' / ' + result.sysChgDttm);

		// 여신이력 리스트 조회
		viewObj.grid.init();
	},
	grid: {
		init: function() {
			this.unload();
			this.load();
		},
		load : function() {
			let param = $('#ITP_FORM_LOANMNG01010_VIEW_SEARCH').serializeObject();
			param.gridSize = $.jgrid.defaults.rowNum;
			param.pagingYn = false; // 페이징안함

			var option = {
				gridId: LOANMNG01010_VIEW_GRID_ID,
				colModel: gridColModel.view,
				param: param,
				url: DOMAIN + LOAN_STATE_HIST_GRID_LIST,
				pager: LOANMNG01010_VIEW_GRID_PAGER,
				loadComplete: function(data) {
					itp_fn_grid_load_complete(data, LOANMNG01010_VIEW_GRID_ID, true, undefined, 'LOANMNG01010_VIEW');
				},
				onPaging: function(action) {
					var pagingFn = {
						callBack: function(args) {
							$(args).trigger('reloadGrid');
						}
					};
					if (itp_fn_check_grid_is_writing(LOANMNG01010_VIEW_GRID_ID)) {
						itp_fn_modal_confirm(ITP_MSG_LOCALE.message.ajax.cancelData, pagingFn, LOANMNG01010_VIEW_GRID_ID);
						return 'stop';
					} else {
						itp_fn_grid_paging(LOANMNG01010_VIEW_GRID_ID, action, param);
					}
				},
				onSortCol: function(index, columnIndex, sortOrder) {
					var sortingFn = {
						callBack: function(args) {
							$(args).trigger('reloadGrid');
						}
					};
					if (itp_fn_check_grid_is_writing(LOANMNG01010_VIEW_GRID_ID)) {
						itp_fn_modal_confirm(ITP_MSG_LOCALE.message.ajax.cancelData, sortingFn, LOANMNG01010_VIEW_GRID_ID);
						return 'stop';
					} else {
						itp_fn_grid_sorting(LOANMNG01010_VIEW_GRID_ID, index, sortOrder);
					}
				}
			};
			itp_fn_grid_make_remote(option);
		},
		clearData : function() {
			$(LOANMNG01010_VIEW_GRID_ID).jqGrid('clearGridData', true);
			$(LOANMNG01010_VIEW_GRID_LIST).find('.ui-jqgrid-bdiv').css('min-height', '100px');
			$(LOANMNG01010_VIEW_GRID_EMPTY).html(ITP_MSG_LOCALE.message.grid.noData);
			$(LOANMNG01010_VIEW_GRID_EMPTY).show();
		},
		unload : function() {
			$.jgrid.gridUnload(LOANMNG01010_VIEW_GRID_ID);
		}
	},
	histexcelDown: function() {
		var param = {
			'url': LOAN_STATE_HIST_GRID_LIST,
			'param': $('#ITP_FORM_LOANMNG01010_VIEW_SEARCH').serializeObject(),
			'gridColumns': $(LOANMNG01010_VIEW_GRID_ID).jqGrid('getGridParam', 'colModel'),
			'fileName': '여신이력.xlsx',
			'sheetName': '여신이력리스트'
		};
		itp_fn_remote_to_excel(param);
	}
};
