/********************************************************
 --------------------------------------------------------
 - Object 목록								            -
 --------------------------------------------------------
 * const gridColModel = {}	: 화면 Grid Object			*
 * let pageObj = {}			: 화면공통 Object			*
 * let listObj = {}			: 목록화면 Object			*
 * let viewObj = {}			: 상세화면 Object			*
 * let modifyObj = {}		: 수정화면 Object			*
 * let createObj = {}		: 신규화면 Object			*
 *******************************************************/

/*화면 변수*/
const LOANMNG03010_GRID_ID = '#ITP_LOANMNG03010_jqGrid';
const LOANMNG03010_GRID_LIST = '#ITP_LOANMNG03010_jqGrid_list';
const LOANMNG03010_GRID_PAGER = '#ITP_LOANMNG03010_jqGridPager';
const LOANMNG03010_GRID_EMPTY = '#ITP_LOANMNG03010_jqGridEmpty';

const LOANMNG03010_VIEW_GRID_ID = '#ITP_LOANMNG03010_VIEW_jqGrid';
const LOANMNG03010_VIEW_GRID_LIST = '#ITP_LOANMNG03010_VIEW_jqGrid_list';
const LOANMNG03010_VIEW_GRID_PAGER = '#ITP_LOANMNG03010_VIEW_jqGridPager';
const LOANMNG03010_VIEW_GRID_EMPTY = '#ITP_LOANMNG03010_VIEW_jqGridEmpty';

const LOANMNG03010_DETAIL_GRID_ID = '#ITP_LOANMNG03010_DETAIL_jqGrid';
const LOANMNG03010_DETAIL_GRID_LIST = '#ITP_LOANMNG03010_DETAIL_jqGrid_list';
const LOANMNG03010_DETAIL_GRID_PAGER = '#ITP_LOANMNG03010_DETAIL_jqGridPager';
const LOANMNG03010_DETAIL_GRID_EMPTY = '#ITP_LOANMNG03010_DETAIL_jqGridEmpty';

let ITP_FORM_LOANMNG03010_DETAIL_IS_DUPLICATE = false;
let ITP_FORM_LOANMNG03010_DETAIL_IS_WRITING = false;
let LOANMNG03010_DETAIL_GRID_LAST_ROW_ID;

/*API URL*/
let UNPAID_MNG_DETAIL_GRID_LIST = '/api/unpaid/mng/detail-grid-list';
let UNPAID_MNG_STL_GRID_LIST = '/api/unpaid/mng/stl-grid-list';
let UNPAID_MNG_INFO_UNPAID = '/api/unpaid/mng/info-unpaid';

let WHS_MNG_ADD_WHS = '/api/whs/mng/add-whs';
let WHS_MNG_MIDIFY_WHS = '/api/whs/mng/modify-whs';
let WHS_MNG_REMOVE_WHS = '/api/whs/mng/remove-whs'; 

let LOGIN_AUTH_TYPE_CD;

/*화면 Grid ColModel*/
const gridColModel = {
	list: [
		{
			index: 'STTL_MGNT_UNQ_NO', name: 'sttlMgntUnqNo',
			label: "정산관리고유번호", 
			width: '0', fixed: false, align: 'center',
			sortable: false, hidden: true
		},
		{
			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: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'LOAN_DVSN_NM', name: 'loanDvsnNm',
			label: "정산타입", 
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: false
		},		
		{
			index: 'STTL_ST_NM', name: 'sttlStNm',
			label: "상태", 
			width: '8', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'STTL_REQ_DT', name: 'sttlReqDt',
			label: "정산요청일", 
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'STTL_DT', name: 'sttlDt',
			label: "정산일", 
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: false
		},		
		{
			index: 'STTL_REQ_AMT', name: 'sttlReqAmt',
			label: '정산요청금액', 
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: false, 
			formatter:'integer',formatoptions: { defaultValue: '', thousandsSeparator: ',' }
		},
		{
			index: 'STTL_AMT', name: 'sttlAmt',
			label: '정산금액', 
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: false, 
			formatter:'integer',formatoptions: { defaultValue: '', thousandsSeparator: ',' }
		},
		{
			index: 'ACCT_BAL', name: 'acctBal',
			label: '잔액', 
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: false, 
			formatter:'integer',formatoptions: { defaultValue: '', thousandsSeparator: ',' }
		}		
	],
	view: [
		{
			index: 'VIEW_CD', name: 'viewCd',
			label: ITP_MSG_LOCALE.label.viewCd,
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: true
		},
		{
			index: 'STTL_MGNT_DTL_NO', name: 'sttlMgntDtlNo',
			label: '정산관리상세번호',
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: true
		},		
		{
			index: 'BRAND_NM', name: 'brandNm',
			label: "브랜드",
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: true
		},
		{
			index: 'STORE_NM', name: 'storeNm',
			label: "매장명",
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: true
		},
		{
			index: 'ITEM_ID', name: 'itemId',
			label: "품목코드",
			width: '10', fixed: false, align: 'center',
			sortable: false, editable: false, edittype: 'text'
		},
		{
			index: 'ITEM_NM', name: 'itemNm',
			label: "품목명",
			width: '10', fixed: false, align: 'center',
			sortable: false, editable: false, edittype: 'text'
		},
		{
			index: 'UNIT', name: 'unit',
			label: "단위",
			width: '8', fixed: false, align: 'center',
			sortable: false, editable: false, edittype: 'text'
		},
		{
			index: 'UNIT_AMT', name: 'unitAmt',
			label: "단가",
			width: '8', fixed: false, align: 'center',
			sortable: false, editable: false, edittype: 'text', 
			formatter:'integer',formatoptions: { defaultValue: '', thousandsSeparator: ',' }
		},
		{
			index: 'PODR_QTY', name: 'podrQty',
			label: "발주수량",
			width: '8', fixed: false, align: 'center',
			sortable: false, editable: false, edittype: 'text', 
			formatter:'integer',formatoptions: { defaultValue: '', thousandsSeparator: ',' }
		},
		{
			index: 'DLV_QTY', name: 'dlvQty',
			label: "납품수량",
			width: '8', fixed: false, align: 'center',
			sortable: false, editable: false, edittype: 'text', 
			formatter:'integer',formatoptions: { defaultValue: '', thousandsSeparator: ',' }
		},
		{
			index: 'WHS_COL_QTY', name: 'whsColQty',
			label: "입고/수거수량",
			width: '8', fixed: false, align: 'center',
			sortable: false, editable: false, edittype: 'text', 
			formatter:'integer',formatoptions: { defaultValue: '', thousandsSeparator: ',' }
		}, 
		{
			index: 'WHS_COL_DT', name: 'whsColDt',
			label: "입고/수거일자",
			width: '8', fixed: false, align: 'center',
			sortable: false, editable: false, edittype: 'text'
		},
		{
			index: 'WHS_COL_AMT', name: 'whsColAmt',
			label: "입고/수거금액",
			width: '8', fixed: false, align: 'center',
			sortable: false, editable: false, edittype: 'text', 
			formatter:'integer',formatoptions: { defaultValue: '', thousandsSeparator: ',' }
		},
		{
			index: 'STTL_REQ_AMT', name: 'sttlReqAmt',
			label: "정산금액",
			width: '8', fixed: false, align: 'center',
			sortable: false, editable: false, edittype: 'text', 
			formatter:'integer',formatoptions: { defaultValue: '', thousandsSeparator: ',' }
		},
		{
			index: 'STTL_DVSN_NM', name: 'sttlDvsnNm',
			label: "정산구분",
			width: '8', fixed: false, align: 'center',
			sortable: false, editable: false, edittype: 'text'
		},
		{
			index: 'PODR_UNQ_NO', name: 'podrUnqNo',
			label: "발주번호",
			width: '8', fixed: false, align: 'center',
			sortable: false, editable: false, edittype: 'text'
		},
		{
			index: 'PODR_DTL_NO', name: 'podrDtlNo',
			label: "발주항번",
			width: '8', fixed: false, align: 'center',
			sortable: false, editable: false, edittype: 'text'
		}
	]
};

require(['config'], function() {
	require([
		'kakao.map.util'
	], 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('LOANMNG03010');
			
			// 공통코드 표시
			$('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_LOANMNG03010 .input-group.date').datepicker(ITP_DATE_LANGUAGE);			
			$('#ITP_FORM_LOANMNG03010_SEARCH_FROM_DT').datepicker('setDate', new Date(now.setMonth(now.getMonth() - 1)));
			$('#ITP_FORM_LOANMNG03010_SEARCH_TO_DT').datepicker('setDate', new Date());
			
			// 권한에 따라 매장값 설정
			$('#ITP_FORM_LOANMNG03010_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_LOANMNG03010_SEARCH_STORE_ID').val(fn_make_user_info.get('storeId'));
				$('#ITP_FORM_LOANMNG03010_SEARCH_STORE_NM').val(fn_make_user_info.get('storeNm'));	
			}
			
		},
		grid: function() {
			itp_fn_jqgrid_resize(LOANMNG03010_GRID_ID, LOANMNG03010_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_LOANMNG03010_SRH'				: listObj.button.search();		break;	// 조회 버튼 클릭
						case 'ITP_BTN_LOANMNG03010_CANCELLIST'		: viewObj.button.cancel(); 	break;	// 취소/목록 버튼
						case 'ITP_BTN_LOANMNG03010_PAYMENT'			: viewObj.button.payment();	break;	// 결제 버튼
					}
				});
			});

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

		}
	},
	switchScreen: function(mode) {
		if(mode == 'LIST') { // 목록
			$('#ITP_BTN_LOANMNG03010_MODIFY').hide();
			$('#ITP_BTN_LOANMNG03010_CANCELLIST').hide();
			$('#ITP_BTN_LOANMNG03010_DELETE').hide();
			$('#ITP_BTN_LOANMNG03010_PAYMENT').hide();
			
			if(LOGIN_AUTH_TYPE_CD == '50') { // 매장관리자
				$('#ITP_BTN_LOANMNG03010_STORE_SEARCH').hide();
				$('#ITP_BTN_LOANMNG03010_STORE_ERASE').hide();
			} else {
				$('#ITP_BTN_LOANMNG03010_STORE_SEARCH').show();
				$('#ITP_BTN_LOANMNG03010_STORE_ERASE').show();
			}
			
			fn_show_btn_auth('#ITP_BTN_LOANMNG03010_SRH');
			fn_show_btn_auth('#ITP_BTN_LOANMNG03010_NEWREG');
			
			$('#ITP_AJAX_LOANMNG03010_LIST_CONTAINER').show();
			$('#ITP_AJAX_LOANMNG03010_DETAIL_CONTAINER').hide();
			$('#ITP_AJAX_LOANMNG03010_VIEW_CONTAINER').hide();
			
		} else if(mode == 'VIEW') { // 보기
			$('#ITP_BTN_LOANMNG03010_SRH').hide();
			$('#ITP_BTN_LOANMNG03010_NEWREG').hide();
			$('#ITP_BTN_LOANMNG03010_DELETE').hide();
			
			fn_show_btn_auth('#ITP_BTN_LOANMNG03010_PAYMENT');
			fn_show_btn_auth('#ITP_BTN_LOANMNG03010_CANCELLIST');

			$('#ITP_AJAX_LOANMNG03010_LIST_CONTAINER').hide();
			$('#ITP_AJAX_LOANMNG03010_DETAIL_CONTAINER').hide();
			$('#ITP_AJAX_LOANMNG03010_VIEW_CONTAINER').show();
		}
	}
};

/*목록화면 Object*/
let listObj = {
	init: function () {
		this.grid.init();
	},
	itp_LOANMNG03010_search: false,
	button: {
		search: function() {
			listObj.itp_LOANMNG03010_search = true;
			let param = $('#ITP_FORM_LOANMNG03010_SEARCH').serializeObject();
			param.gridSize = $.jgrid.defaults.rowNum;
			param.gridPage = $.jgrid.defaults.page;
			$(LOANMNG03010_GRID_ID).setGridParam({'postData': JSON.stringify(param)}).trigger('reloadGrid');
		},
		create: function() {
			pageObj.switchScreen('ADD');			
			itp_fn_form_clear_validate(null, '#ITP_FORM_LOANMNG03010_DETAIL');						
			// 로케이션 리스트 조회
			createObj.init();
		}
	},
	empty: {
		init: function() {
			var _this = this;
			this.push();
			$(LOANMNG03010_GRID_EMPTY).on('click', function() {
				_this.back();
				_this.itp_LOANMNG03010_param.gridSize = $.jgrid.defaults.rowNum;
				$(LOANMNG03010_GRID_ID).setGridParam({'postData': JSON.stringify(_this.itp_LOANMNG03010_param)}).trigger('reloadGrid');
			});
		},
		itp_LOANMNG03010_param: {},
		push: function() {
			let param = $('#ITP_FORM_LOANMNG03010_SEARCH').serializeObject();
			listObj.itp_LOANMNG03010_param = param;
		},
		back: function() {
			$('#ITP_FORM_LOANMNG03010_SEARCH_STORE_ID').val(listObj.itp_LOANMNG03010_param.sstoreId);
			$('#ITP_FORM_LOANMNG03010_SEARCH_STORE_NM').val(listObj.itp_LOANMNG03010_param.sstoreNm);
			$('#ITP_FORM_LOANMNG03010_SEARCH_FROM_DT').val(listObj.itp_LOANMNG03010_param.fromDt);
			$('#ITP_FORM_LOANMNG03010_SEARCH_TO_DT').val(listObj.itp_LOANMNG03010_param.toDt);
		}
	},
	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_LOANMNG03010_SEARCH').serializeObject();
			param.gridSize = $.jgrid.defaults.rowNum;

			var option = {
				gridId: LOANMNG03010_GRID_ID,
				colModel: gridColModel.list,
				param: JSON.stringify(param),
				url: DOMAIN + UNPAID_MNG_DETAIL_GRID_LIST,
				pager: LOANMNG03010_GRID_PAGER,
				onCellSelect: function(rowId, cellIdx, cellValue) {
					var cm = $(this).jqGrid('getGridParam', 'colModel');
					var colNm = cm[cellIdx].name;
					if (colNm == 'sttlReqDt') {
						const sttlMgntUnqNoVal = $(this).jqGrid('getCell', rowId, 'sttlMgntUnqNo');
						
						const key = {sttlMgntUnqNo: sttlMgntUnqNoVal, viewCd: 'R'};
						var param = $.param(key);
						viewObj.init(param);
					}
				},
				loadComplete: function(data) {
					console.log(data);
					itp_fn_grid_load_complete(data, LOANMNG03010_GRID_ID, true, 'number', 'LOANMNG03010', listObj.itp_LOANMNG03010_search, listObj.empty, true, data.gridRecords, true);
					var ids = $(LOANMNG03010_GRID_ID).getDataIDs();
					$.each(ids, function(idx, rowId) {
						$(LOANMNG03010_GRID_ID).jqGrid('setCell', rowId, 'sttlReqDt', '', ITP_GRID_COL_STYLE.link);
					});
				},
				onPaging: function(action) {
					itp_fn_grid_paging(LOANMNG03010_GRID_ID, action, param);
				}
			};
			itp_fn_grid_make_remote(option);
		},
		clearData : function() {
			$(LOANMNG03010_GRID_ID).jqGrid('clearGridData', true);
			$(LOANMNG03010_GRID_LIST).find('.ui-jqgrid-bdiv').css('min-height', '100px');
			$(LOANMNG03010_GRID_EMPTY).html(ITP_MSG_LOCALE.message.grid.noData);
			$(LOANMNG03010_GRID_EMPTY).show();
		},
		unload : function() {
			$.jgrid.gridUnload(LOANMNG03010_GRID_ID);
		}
	}
};

/*상세화면 Object*/
let viewObj = {
	init: function (param) {
		this.load(param);
	},
	button: {
		cancel: function() {
			listObj.grid.search();
		},
		payment: function() {
			var confirmFn= {
				callBack: function() {
					// TODO PG결제 진행	
				}
			};
			itp_fn_modal_confirm(ITP_MSG_LOCALE.message.form.procData, confirmFn, null);
		}
	}, 
	load: function(param) {
		fn_ajax_call(UNPAID_MNG_INFO_UNPAID, param, this.callback, 'GET');
	},
	callback: function (result) {
		// console.log(result);
		pageObj.switchScreen('VIEW');
		$('#ITP_FORM_LOANMNG03010_VIEW #ITP_FORM_LOANMNG03010_VIEW_BRAND_ID').val(result.brandId);
		$('#ITP_FORM_LOANMNG03010_VIEW #ITP_FORM_LOANMNG03010_VIEW_STORE_ID').val(result.storeId);
		$('#ITP_FORM_LOANMNG03010_VIEW #ITP_FORM_LOANMNG03010_VIEW_STTL_MGNT_UNQ_NO').val(result.sttlMgntUnqNo);
		
		$('#ITP_FORM_LOANMNG03010_VIEW .fnBrandNm').text(result.brandNm);
		$('#ITP_FORM_LOANMNG03010_VIEW .fnStoreNm').text(result.storeNm);
		$('#ITP_FORM_LOANMNG03010_VIEW .fnSttlReqDt').text(result.sttlReqDt);
		$('#ITP_FORM_LOANMNG03010_VIEW .fnSttlStNm').text(result.sttlStNm);
		$('#ITP_FORM_LOANMNG03010_VIEW .fnSysRegDttm').text(result.sysRegDttm);
		$('#ITP_FORM_LOANMNG03010_VIEW .fnSysRegNm').text(result.sysRegNm);
		$('#ITP_FORM_LOANMNG03010_VIEW .fnSttlReqAmt').text(itp_fn_number_comma(result.sttlReqAmt));
		$('#ITP_FORM_LOANMNG03010_VIEW .fnAcctBal').text(itp_fn_number_comma(result.acctBal));

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

			var option = {
				gridId: LOANMNG03010_VIEW_GRID_ID,
				colModel: gridColModel.view,
				param: JSON.stringify(param),
				url: DOMAIN + UNPAID_MNG_STL_GRID_LIST,
				pager: LOANMNG03010_VIEW_GRID_PAGER,
				loadComplete: function(data) {
					itp_fn_grid_load_complete(data, LOANMNG03010_VIEW_GRID_ID, true, undefined, 'LOANMNG03010_VIEW');
				},
				onPaging: function(action) {
					var pagingFn = {
						callBack: function(args) {
							$(args).trigger('reloadGrid');
						}
					};
					if (itp_fn_check_grid_is_writing(LOANMNG03010_VIEW_GRID_ID)) {
						itp_fn_modal_confirm(ITP_MSG_LOCALE.message.ajax.cancelData, pagingFn, LOANMNG03010_VIEW_GRID_ID);
						return 'stop';
					} else {
						itp_fn_grid_paging(LOANMNG03010_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(LOANMNG03010_VIEW_GRID_ID)) {
						itp_fn_modal_confirm(ITP_MSG_LOCALE.message.ajax.cancelData, sortingFn, LOANMNG03010_VIEW_GRID_ID);
						return 'stop';
					} else {
						itp_fn_grid_sorting(LOANMNG03010_VIEW_GRID_ID, index, sortOrder);
					}
				}
			};
			itp_fn_grid_make_remote(option);
		},
		clearData : function() {
			$(LOANMNG03010_VIEW_GRID_ID).jqGrid('clearGridData', true);
			$(LOANMNG03010_VIEW_GRID_LIST).find('.ui-jqgrid-bdiv').css('min-height', '100px');
			$(LOANMNG03010_VIEW_GRID_EMPTY).html(ITP_MSG_LOCALE.message.grid.noData);
			$(LOANMNG03010_VIEW_GRID_EMPTY).show();
		},
		unload : function() {
			$.jgrid.gridUnload(LOANMNG03010_VIEW_GRID_ID);
		}
	}
};
