/********************************************************
 --------------------------------------------------------
 - Object 목록								            -
 --------------------------------------------------------
 * const gridColModel = {}	: 화면 Grid Object			*
 * let pageObj = {}			: 화면공통 Object			*
 * let listObj = {}			: 목록화면 Object			*
 * let modifyObj = {}			: 상세화면 Object			*
 *******************************************************/

/*화면 변수*/
const SALESMNG01010_GRID_ID = '#ITP_SALESMNG01010_jqGrid';
const SALESMNG01010_GRID_LIST = '#ITP_SALESMNG01010_jqGrid_list';
const SALESMNG01010_GRID_PAGER = '#ITP_SALESMNG01010_jqGridPager';
const SALESMNG01010_GRID_EMPTY = '#ITP_SALESMNG01010_jqGridEmpty';

let ITP_FORM_SALESMNG01010_DETAIL_IS_DUPLICATE = false;
let ITP_FORM_SALESMNG01010_DETAIL_IS_WRITING = false;
let SALESMNG01010_DETAIL_GRID_LAST_ROW_ID;

/*API URL*/
let API_GRID_LIST = '/api/sale/mng/store-grid-list';

let LOGIN_AUTH_TYPE_CD;

/*화면 Grid ColModel*/
const gridColModel = {
	list: [
		{
			index: 'VIEW_CD', name: 'viewCd',
			label: ITP_MSG_LOCALE.label.viewCd,
			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: 'left',
			sortable: false, hidden: false, classes: 'ui-ellipsis'
		},
		{
			index: 'WHS_QTY', name: 'whsQty',
			label: "구매수량",
			width: '10', fixed: false, align: 'right',
			sortable: false, editable: false, edittype: 'text', 
			formatter:'integer',formatoptions: { defaultValue: '', thousandsSeparator: ',' }
		}, 
		{
			index: 'SUPPLY_AMT', name: 'supplyAmt',
			label: "공급가액",
			width: '10', fixed: false, align: 'right',
			sortable: false, editable: false, edittype: 'text', 
			formatter:'integer',formatoptions: { defaultValue: '', thousandsSeparator: ',' }
		},
		{
			index: 'STORE_AMT', name: 'storeAmt',
			label: "판매금액",
			width: '10', fixed: false, align: 'right',
			sortable: false, editable: false, edittype: 'text', 
			formatter:'integer',formatoptions: { defaultValue: '', thousandsSeparator: ',' }
		},		
		{
			index: 'INCOME_AMT', name: 'incomeAmt',
			label: "수입금액",
			width: '10', fixed: false, align: 'right',
			sortable: false, editable: false, edittype: 'text', 
			formatter:'integer',formatoptions: { defaultValue: '', thousandsSeparator: ',' }
		},
		{
			index: 'WHS_QTY1', name: 'whsQty1',
			label: "반품수량",
			width: '10', fixed: false, align: 'right',
			sortable: false, editable: false, edittype: 'text', 
			formatter:'integer',formatoptions: { defaultValue: '', thousandsSeparator: ',' }
		}, 
		{
			index: 'SUPPLY_AMT1', name: 'supplyAmt1',
			label: "반품공급가액",
			width: '10', fixed: false, align: 'right',
			sortable: false, editable: false, edittype: 'text', 
			formatter:'integer',formatoptions: { defaultValue: '', thousandsSeparator: ',' }
		},
		{
			index: 'STORE_AMT1', name: 'storeAmt1',
			label: "판품금액",
			width: '10', fixed: false, align: 'right',
			sortable: false, editable: false, edittype: 'text', 
			formatter:'integer',formatoptions: { defaultValue: '', thousandsSeparator: ',' }
		},		
		{
			index: 'INCOME_AMT1', name: 'incomeAmt1',
			label: "판품손실",
			width: '10', fixed: false, align: 'right',
			sortable: false, editable: false, edittype: 'text', 
			formatter:'integer',formatoptions: { defaultValue: '', thousandsSeparator: ',' }
		},		
		{
			index: 'TOT_INCOME_AMT', name: 'totIncomeAmt',
			label: "총매출금액",
			width: '10', fixed: false, align: 'right',
			sortable: false, editable: false, edittype: 'text', 
			formatter:'integer',formatoptions: { defaultValue: '', thousandsSeparator: ',' }
		}
	]
};

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('SALESMNG01010');
			
			// 공통코드 표시
			$('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_SALESMNG01010 .input-group.date').datepicker(ITP_DATE_LANGUAGE);			
			$('#ITP_FORM_SALESMNG01010_SEARCH_FROM_DT').datepicker('setDate', new Date(now.setMonth(now.getMonth() - 1)));
			$('#ITP_FORM_SALESMNG01010_SEARCH_TO_DT').datepicker('setDate', new Date());
			
			// 권한에 따라 매장값 설정
			$('#ITP_FORM_SALESMNG01010_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_SALESMNG01010_SEARCH_STORE_ID').val(fn_make_user_info.get('storeId'));
			}
			
		},
		grid: function() {
			itp_fn_jqgrid_resize(SALESMNG01010_GRID_ID, SALESMNG01010_GRID_LIST, 'lg');
			listObj.empty.init();
			itp_fn_fire_window_resize();
		},
		ready: function() {
			listObj.init();
		}
	},
	event: {
		init: function () {
			this.button();
			this.change();
		},
		button: function () {
			// 버튼 클릭 이벤트
			$('button').each(function() {
				var id = $(this).attr('id');
				$(this).on('click', function() {
					switch (id) {
						case 'ITP_BTN_SALESMNG01010_SRH'				: listObj.button.search();		break;	// 조회 버튼 클릭
						case 'ITP_BTN_SALESMNG01010_SEARCH_STORE_POP'	: listObj.button.storePop();	break;	// 매장검색 팝업
						case 'ITP_BTN_SALESMNG01010_SEARCH_ERASE'		: listObj.button.storeErase();	break;	// 매장 지움
						case 'ITP_BTN_SALESMNG01010_EXCEL'			: listObj.excelDown();	break;	// 엑셀 다운로드
					}
				});
			});

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

		}, 
		change: function() {
			$('#ITP_FORM_SALESMNG01010_SEARCH_STORE_SPPLY_GUBUN').on('change', function() {
				var gubunVal = $('#ITP_FORM_SALESMNG01010_SEARCH_STORE_SPPLY_GUBUN').val();
				if(gubunVal == '1') { // 매장
					$('#ITP_FORM_SALESMNG01010_SEARCH_STORE_SPPLY_NM').attr('placeholder', '매장명');
					
					$(SALESMNG01010_GRID_ID).jqGrid('hideCol', ["spplyNm"]);
					$(SALESMNG01010_GRID_ID).jqGrid('showCol', ["storeNm"]);		
					// $(SALESMNG01010_GRID_ID).setColProp('spplyNm', {hidden: true});
					// $(SALESMNG01010_GRID_ID).setColProp('storeNm', {hidden: false});								
				} 
				listObj.button.search();	
				// itp_fn_jqgrid_resize(SALESMNG01010_GRID_ID, SALESMNG01010_GRID_LIST, 'lg');							
			});			
		}
	},
	switchScreen: function(mode) {
		if(mode == 'LIST') { // 목록
			$('#ITP_BTN_SALESMNG01010_MODIFY').hide();
			$('#ITP_BTN_SALESMNG01010_CANCELLIST').hide();
			$('#ITP_BTN_SALESMNG01010_DELETE').hide();
			$('#ITP_BTN_SALESMNG01010_STTL_END').hide();
			
			if(LOGIN_AUTH_TYPE_CD == '50') { // 매장관리자
				$('#ITP_BTN_SALESMNG01010_SEARCH_STORE_POP').hide();
				$('#ITP_BTN_SALESMNG01010_SEARCH_ERASE').hide();
			} else {
				$('#ITP_BTN_SALESMNG01010_SEARCH_STORE_POP').show();
				$('#ITP_BTN_SALESMNG01010_SEARCH_ERASE').show();
			}
			
			fn_show_btn_auth('#ITP_BTN_SALESMNG01010_SRH');
			
			$('#ITP_AJAX_SALESMNG01010_LIST_CONTAINER').show();			
			$('#ITP_BTN_SALESMNG01010_EXCEL').show();
			
		} 
	}
};

/*목록화면 Object*/
let listObj = {
	init: function () {
		this.grid.init();
	},
	itp_SALESMNG01010_search: false,
	button: {
		search: function() {
			listObj.itp_SALESMNG01010_search = true;
			let param = $('#ITP_FORM_SALESMNG01010_SEARCH').serializeObject();
			param.gridSize = $.jgrid.defaults.rowNum;
			param.gridPage = $.jgrid.defaults.page;
			$(SALESMNG01010_GRID_ID).setGridParam({'postData': JSON.stringify(param)}).trigger('reloadGrid');
		}, 
		storePop: function() {
			fn_call_popup('biz', 'BIZPOP_BRAND_STORE', '#ITP_ASIDE', function(result) {
				// alert(JSON.stringify(result));
				$('#ITP_FORM_SALESMNG01010_SEARCH_STORE_ID').val(result[0].storeId);
				$('#ITP_FORM_SALESMNG01010_SEARCH_STORE_SPPLY_NM').val(result[0].storeNm);				
				listObj.button.search();
			}, null, 'S');
		}, 
		storeErase: function() {
			$('#ITP_FORM_SALESMNG01010_SEARCH_STORE_ID').val('');
			$('#ITP_FORM_SALESMNG01010_SEARCH_STORE_SPPLY_NM').val('');
			listObj.button.search();
		}
	},
	empty: {
		init: function() {
			var _this = this;
			this.push();
			$(SALESMNG01010_GRID_EMPTY).on('click', function() {
				_this.back();
				_this.itp_SALESMNG01010_param.gridSize = $.jgrid.defaults.rowNum;
				$(SALESMNG01010_GRID_ID).setGridParam({'postData': JSON.stringify(_this.itp_SALESMNG01010_param)}).trigger('reloadGrid');
			});
		},
		itp_SALESMNG01010_param: {},
		push: function() {
			let param = $('#ITP_FORM_SALESMNG01010_SEARCH').serializeObject();
			listObj.itp_SALESMNG01010_param = param;
		},
		back: function() {
			$('#ITP_FORM_SALESMNG01010_SEARCH_STORE_ID').val(listObj.itp_SALESMNG01010_param.sstoreId);
			$('#ITP_FORM_SALESMNG01010_SEARCH_STORE_NM').val(listObj.itp_SALESMNG01010_param.sstoreNm);
			$('#ITP_FORM_SALESMNG01010_SEARCH_FROM_DT').val(listObj.itp_SALESMNG01010_param.fromDt);
			$('#ITP_FORM_SALESMNG01010_SEARCH_TO_DT').val(listObj.itp_SALESMNG01010_param.toDt);
			$('#ITP_FORM_SALESMNG01010_SEARCH_ITEM_NM').val(listObj.itp_SALESMNG01010_param.sitemNm);
		}
	},
	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_SALESMNG01010_SEARCH').serializeObject();
			param.gridSize = $.jgrid.defaults.rowNum;

			var option = {
				gridId: SALESMNG01010_GRID_ID,
				colModel: gridColModel.list,
				param: param,
				url: DOMAIN + API_GRID_LIST,
				pager: SALESMNG01010_GRID_PAGER,
				onCellSelect: function(rowId, cellIdx, cellValue) {
					var cm = $(this).jqGrid('getGridParam', 'colModel');
					var colNm = cm[cellIdx].name;
					if (colNm == 'sttlMgntUnqNo') {
						const sttlMgntUnqNoVal = $(this).jqGrid('getCell', rowId, 'sttlMgntUnqNo');
						
						const key = {sttlMgntUnqNo: sttlMgntUnqNoVal, viewCd: 'R'};
						var param = $.param(key);
						modifyObj.init(param);
					}
				},
				loadComplete: function(data) {
					console.log(data);
					itp_fn_grid_load_complete(data, SALESMNG01010_GRID_ID, true, 'number', 'SALESMNG01010', listObj.itp_SALESMNG01010_search, listObj.empty, true, data.gridRecords, true);
					var ids = $(SALESMNG01010_GRID_ID).getDataIDs();
					$.each(ids, function(idx, rowId) {
						$(SALESMNG01010_GRID_ID).jqGrid('setCell', rowId, 'sttlMgntUnqNo', '', ITP_GRID_COL_STYLE.link);
					});
				},
				onPaging: function(action) {
					itp_fn_grid_paging(SALESMNG01010_GRID_ID, action, param);
				}
			};
			itp_fn_grid_make_remote(option);
			
			$(SALESMNG01010_GRID_ID).jqGrid('setGroupHeaders', {
				useColSpanStyle: true,
			  	groupHeaders:[
					{ startColumnName: 'whsQty', numberOfColumns: 4, titleText: '구매' }, 
					{ startColumnName: 'whsQty1', numberOfColumns: 4, titleText: '반품' }
			  	]
	    	});
		},
		clearData : function() {
			$(SALESMNG01010_GRID_ID).jqGrid('clearGridData', true);
			$(SALESMNG01010_GRID_LIST).find('.ui-jqgrid-bdiv').css('min-height', '100px');
			$(SALESMNG01010_GRID_EMPTY).html(ITP_MSG_LOCALE.message.grid.noData);
			$(SALESMNG01010_GRID_EMPTY).show();
		},
		unload : function() {
			$.jgrid.gridUnload(SALESMNG01010_GRID_ID);
		}
	},
	excelDown: function() {
		var param = {
			'url': API_GRID_LIST,
			'param': $('#ITP_FORM_SALESMNG01010_SEARCH').serializeObject(),
			'gridColumns': $(SALESMNG01010_GRID_ID).jqGrid('getGridParam', 'colModel'),
			'fileName': '매장별_매출현황.xlsx',
			'sheetName': '매장별매출현황'
		};
		itp_fn_remote_to_excel(param);
	}
};
