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


//화면변수
const LOANMNG04010_VIEW_GRID_ID = '#ITP_LOANMNG04010_VIEW_jqGrid';
const LOANMNG04010_VIEW_GRID_LIST = '#ITP_LOANMNG04010_VIEW_jqGrid_list';
const LOANMNG04010_VIEW_GRID_PAGER = '#ITP_LOANMNG04010_VIEW_jqGridPager';
const LOANMNG04010_VIEW_GRID_EMPTY = '#ITP_LOANMNG04010_VIEW_jqGridEmpty';


//API URL
let API_LOAN_STATE_INFO_LOAN_STORE = '/api/loan/state/info-loan-store';		// 매장 여신관리 정보
let API_LOAN_STATE_HIST_GRID_LIST = '/api/loan/state/hist-grid-list';		// 여신이력 그리드 리스트


//화면 grid ColModel
const gridColModel = {
	list:[],
	view: [
		{
			index: 'VIEW_CD', name: 'viewCd',
			label: ITP_MSG_LOCALE.label.viewCd,
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: true
		},
		{
			index: 'LOAN_MGNT_UNQ_NO', name: 'loanMgntUnqNo',
			label: ITP_MSG_LOCALE.label.loanMgntUnqNo,			// 여신관리고유번호
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: true
		},
		{
			index: 'LOAN_REG_DT', name: 'loanRegDt',
			label: ITP_MSG_LOCALE.label.loanRegDt,				// 발행일자
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'DPST_PAY_DVSN_NM', name: 'dpstPayDvsnNm',
			label: ITP_MSG_LOCALE.label.dpstPayDvsnNm,			// 입지구분
			width: '7', fixed: false, align: 'left',
			sortable: false, hidden: false
		},
		{
			index: 'MEDIA_DVSN_NM', name: 'mediaDvsnNm',
			label: ITP_MSG_LOCALE.label.mediaDvsnNm,			// 매체구분
			width: '7', fixed: false, align: 'left',
			sortable: false, hidden: false
		},
		{
			index: 'DPST_AMT', name: 'dpstAmt',
			label: ITP_MSG_LOCALE.label.dpstAmt,				// 입금
			width: '7', fixed: false, align: 'right',
			sortable: false, hidden: false,
			formatter:'integer', formatoptions: {defaultValue: '', thousandsSeparator: ',' }
		},
		{
			index: 'PAYM_AMT', name: 'paymAmt',
			label: ITP_MSG_LOCALE.label.paymAmt,				// 지급
			width: '7', fixed: false, align: 'right',
			sortable: false, hidden: false,
			formatter:'integer', formatoptions: {defaultValue: '', thousandsSeparator: ',' }
		},
		{
			index: 'TRSC_AF_BAL', name: 'trscAfBal',
			label: '잔액'	,										// 거래 후 잔액
			width: '7', fixed: false, align: 'right',
			sortable: false, hidden: false,
			formatter:'integer', formatoptions: {defaultValue: '', thousandsSeparator: ',' }
		},
		{
			index: 'USER', name: 'user',
			label: '사용자',										// 사용자
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'NO', name: 'no',
			label: '관련번호',										// 관련번호
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
	],
	detail: []
}


/*화면공통 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('LOANMNG04010');
			// 공통코드 표시
			$('select').each(function() {
				if($(this).data('select-code')) {
					fn_make_select(CODE_LIST, $(this).data('select-code'), $(this).attr('id'));
				}
			});
			// 조회일자 지정	
			var now = new Date();
			var defaultToDate = new Date(now);
			defaultToDate.setDate(now.getDate() - 30);
			$('#ITP_TAB_LOANMNG04010 .input-group.date').datepicker(ITP_DATE_LANGUAGE);
			$('#ITP_FORM_LOANMNG04010_SEARCH_FROM_DT').datepicker('setDate', defaultToDate);
			$('#ITP_FORM_LOANMNG04010_SEARCH_TO_DT').datepicker('setDate', now);
		},
		grid: function() {
			//itp_fn_jqgrid_resize(LOANMNG04010_VIEW_GRID_ID, LOANMNG04010_VIEW_GRID_LIST, 'lg');
			itp_fn_fire_window_resize();
		},
		ready: function() {
			viewObj.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_LOANMNG04010_SRH'				: listObj.button.search();		break;	// 조회 버튼 클릭
						case 'ITP_BTN_LOANMNG04010_NEWREG'			: listObj.button.create(); 		break;	// 신규등록 버튼
						case 'ITP_BTN_LOANMNG04010_VIEW_SEARCH_SRH'	: viewObj.button.history();		break;	// 이력조회
						case 'ITP_BTN_LOANMNG04010_EXCEL'			: viewObj.excelDown();			break;	// 엑셀 다운로드
					}
				});
			});
		}
	},
	switchScreen: function(mode) {
        $('.itp_det_head').find('button[id^="ITP_BTN_LOANMNG04010_"]').each(function(i) {
            $(this).hide();
        });
        $('#ITP_TAB_LOANMNG04010').find('div[id$="_CONTAINER"]').each(function(i) {
            $(this).hide();
        });
        if(mode == 'VIEW') { // 목록
            fn_show_btn_auth_array(['#ITP_BTN_LOANMNG04010_SRH', '#ITP_BTN_LOANMNG04010_NEWREG']);
            $('#ITP_AJAX_LOANMNG04010_VIEW_CONTAINER').show();
            $('#ITP_AJAX_LOANMNG04010_VIEW_LIST_CONTAINER').show();
            $('#ITP_FORM_LOANMNG04010_SEARCH #ITP_FORM_LOANMNG04010_VIEW_BRAND_ID').val(fn_make_user_info.get('brandId'));
            if(fn_make_user_info.get('spplyId').length != 0){
            	$('#ITP_FORM_LOANMNG04010_SEARCH #ITP_FORM_LOANMNG04010_VIEW_STORE_ID').val(fn_make_user_info.get('spplyId'));
            } else {
            	$('#ITP_FORM_LOANMNG04010_SEARCH #ITP_FORM_LOANMNG04010_VIEW_STORE_ID').val(fn_make_user_info.get('userId'));
            }
            $('#ITP_BTN_LOANMNG04010_SRH').show();
            $('#ITP_BTN_LOANMNG04010_PRINT').show();
            $('#ITP_BTN_LOANMNG04010_SEARCH_WHS_ID').show();
            $('#ITP_BTN_LOANMNG04010_DELETE_WHS_ID').show();
            $('#ITP_BTN_LOANMNG04010_VIEW_SEARCH_SRH').show();

			$('#ITP_BTN_LOANMNG04010_EXCEL').show();
        }
    }
};


/*상세화면 Object*/
let viewObj = {
	init: function() {
		this.load();
	},
	itp_LOANMNG04010_param: {},
	itp_LOANMNG04010_search: false,
	button: {
		history: function() {
			let param = $('#ITP_FORM_LOANMNG04010_VIEW_SEARCH').serializeObject();
			param.gridSize = $.jgrid.defaults.rowNum;
			param.gridPage = $.jgrid.defaults.page;
			$(LOANMNG04010_VIEW_GRID_ID).setGridParam({'postData': JSON.stringify(param)}).trigger('reloadGrid'); 
		}
	},
	load: function() {
		fn_ajax_call(API_LOAN_STATE_INFO_LOAN_STORE, null, this.callback, 'GET');
	},
	callback: function(result) {
		pageObj.switchScreen('VIEW');
		$('#ITP_FORM_LOANMNG04010_VIEW_BRAND_ID').val(result.brandId);
		$('#ITP_FORM_LOANMNG04010_VIEW_STORE_ID').val(result.storeId);
		$('#ITP_FORM_LOANMNG04010_VIEW_LOAN_MGNT_UNQ_NO').val(result.loanMgntUnqNo);
		$('#ITP_FORM_LOANMNG04010_VIEW_SEARCH_LOAN_MGNT_UNQ_NO').val(result.loanMgntUnqNo);
		$('#ITP_FORM_LOANMNG04010_VIEW .fnBrandNm').text(result.brandNm);
		$('#ITP_FORM_LOANMNG04010_VIEW .fnStoreNm').text(result.storeNm);
		$('#ITP_FORM_LOANMNG04010_VIEW .fnLoanDvsn').text(result.loanDvsnNm);
		var limitAmt;
		if(result.loanDvsn == 'LD01') { // 선불(충전)
			limitAmt = result.chrgeLimitAmt;
		} else if(result.loanDvsn == 'LD02') { // 후불(신용)
			limitAmt = result.credtLimitAmt;				
		}
		
		if(result.loanDvsn == 'LD01') { // 선불(충전)
			limitAmt = result.chrgeLimitAmt;
			$('#ITP_FORM_LOANMNG04010_VIEW .fnPosbLimitAmt').text(itp_fn_number_comma(result.chrgeLimitAmt)); // TODO 가용한도금액
		} else if(result.loanDvsn == 'LD02') { // 후불(신용)
			limitAmt = result.credtLimitAmt;
			$('#ITP_FORM_LOANMNG04010_VIEW .fnPosbLimitAmt').text(itp_fn_number_comma(result.credtLimitAmt)); // TODO 가용한도금액
		}
		$('#ITP_FORM_LOANMNG04010_VIEW .fnCredtLimitAmt').text(itp_fn_number_comma(limitAmt));
		$('#ITP_FORM_LOANMNG04010_VIEW .fnContDt').text(''); // TODO 계약기간
		$('#ITP_FORM_LOANMNG04010_VIEW .fnUseYn').text(result.useYnNm);		
		$('#ITP_FORM_LOANMNG04010_VIEW .fnPosbLimitAmt').text(itp_fn_number_comma(result.acctBal + limitAmt - result.useAmtTotal)); // TODO 가용한도금액
		$('#ITP_FORM_LOANMNG04010_VIEW .fnTmpRcvAcctTotal').text(itp_fn_number_comma(result.acctBal));
		$('#ITP_FORM_LOANMNG04010_VIEW .fnUseAmtTotal').text(itp_fn_number_comma(result.useAmtTotal));
		$('#ITP_FORM_LOANMNG04010_VIEW .fnLastModify').text(result.sysChgNm + ' / ' + result.sysChgDttm);
		
		viewObj.grid.init();
	},
	grid: {
		init: function() {
			this.unload();
			this.load();
		},
		load: function() {
			let param = $('#ITP_FORM_LOANMNG04010_VIEW_SEARCH').serializeObject();
			param.gridSize = $.jgrid.defaults.rowNum;
			param.pagingYn = false; // 페이징안함
			var option = {
				gridId: LOANMNG04010_VIEW_GRID_ID,
				colModel: gridColModel.view,
				param: param,
				url: DOMAIN + API_LOAN_STATE_HIST_GRID_LIST,
				pager: LOANMNG04010_VIEW_GRID_PAGER,
				loadComplete: function(data) {
					itp_fn_grid_load_complete(data, LOANMNG04010_VIEW_GRID_ID, true, undefined, 'LOANMNG04010_VIEW');
				},
				onPaging: function(action) {
					var pagingFn = {
						callBack: function(args) {
							$(args).trigger('reloadGrid');
						}
					};
					if (itp_fn_check_grid_is_writing(LOANMNG04010_VIEW_GRID_ID)) {
						itp_fn_modal_confirm(ITP_MSG_LOCALE.message.ajax.cancelData, pagingFn, LOANMNG04010_VIEW_GRID_ID);
						return 'stop';
					} else {
						itp_fn_grid_paging(LOANMNG04010_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(LOANMNG04010_VIEW_GRID_ID)) {
						itp_fn_modal_confirm(ITP_MSG_LOCALE.message.ajax.cancelData, sortingFn, LOANMNG04010_VIEW_GRID_ID);
						return 'stop';
					} else {
						itp_fn_grid_sorting(LOANMNG04010_VIEW_GRID_ID, index, sortOrder);
					}
				}
			};
			itp_fn_grid_make_remote(option);
		},
		clearData : function() {
			$(LOANMNG04010_VIEW_GRID_ID).jqGrid('clearGridData', true);
			$(LOANMNG04010_VIEW_GRID_LIST).find('.ui-jqgrid-bdiv').css('min-height', '100px');
			$(LOANMNG04010_VIEW_GRID_EMPTY).html(ITP_MSG_LOCALE.message.grid.noData);
			$(LOANMNG04010_VIEW_GRID_EMPTY).show();
		},
		unload : function() {
			$.jgrid.gridUnload(LOANMNG04010_VIEW_GRID_ID);
		}
	},
	excelDown: function() {
		var param = {
			'url': API_LOAN_STATE_HIST_GRID_LIST,
			'param': $('#ITP_FORM_LOANMNG04010_VIEW_SEARCH').serializeObject(),
			'gridColumns': $(LOANMNG04010_VIEW_GRID_ID).jqGrid('getGridParam', 'colModel'),
			'fileName': '매장여신이력.xlsx',
			'sheetName': '여신이력리스트'
		};
		itp_fn_remote_to_excel(param);
	}
}
