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

/*화면 변수*/
const STOCKMNG01010_GRID_ID = '#ITP_STOCKMNG01010_jqGrid';
const STOCKMNG01010_GRID_LIST = '#ITP_STOCKMNG01010_jqGrid_list';
const STOCKMNG01010_GRID_PAGER = '#ITP_STOCKMNG01010_jqGridPager';
const STOCKMNG01010_GRID_EMPTY = '#ITP_STOCKMNG01010_jqGridEmpty';

let ITP_FORM_STOCKMNG01010_DETAIL_IS_DUPLICATE = false;
let ITP_FORM_STOCKMNG01010_DETAIL_IS_WRITING = false;
let STOCKMNG01010_DETAIL_GRID_LAST_ROW_ID;

/*API URL*/
let STOCK_MNG_DETAIL_GRID_LIST = '/api/stock/mng/detail-grid-list';
let WHS_MNG_DETAIL_GRID_LIST = '/api/whs/mng/detail-grid-list';
let WHS_MNG_LOCATION_GRID_LIST = '/api/whs/mng/location-grid-list';
let API_ITEM_CLASS_LEVEL = '/api/item/class-level-list';		//품목분류 level 검색

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: 'LOCATION', name: 'location',
			label: "로케이션", 
			width: '0', fixed: false, align: 'center',
			sortable: false, hidden: true
		},
		{
			index: 'BRAND_NM', name: 'brandNm',
			label: ITP_MSG_LOCALE.label.brandNm, //브랜드
			width: '10', fixed: false, align: 'left',
			minwidth: 120,
			sortable: false, hidden: false, classes: 'ui-ellipsis'
		},
		{
			index: 'STORE_NM', name: 'storeNm',
			label: "매장명", 
			width: '10', fixed: false, align: 'left',
			minwidth: 100,
			sortable: false, hidden: false, classes: 'ui-ellipsis'
		},
		{
			index: 'WHS_ID', name: 'whsId',
			label: "창고번호", 
			width: '8', fixed: false, align: 'center',
			minwidth: 100,
			sortable: false, hidden: false
		},
		{
			index: 'WHS_NM', name: 'whsNm',
			label: "창고명", 
			width: '13', fixed: false, align: 'left',
			minwidth: 120,
			sortable: false, hidden: false, classes: 'ui-ellipsis'
		},
		{
			index: 'LOCATION_NM', name: 'locationNm',
			label: "로케이션명", 
			width: '10', fixed: false, align: 'left',
			minwidth: 140,
			sortable: false, hidden: false, classes: 'ui-ellipsis'
		},
		{
			index: 'ITEM_ID', name: 'itemId',
			label: "품목번호", 
			width: '15', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'ITEM_NM', name: 'itemNm',
			label: "품목명", 
			width: '10', fixed: false, align: 'left',
			minwidth: 110,
			sortable: false, hidden: false, classes: 'ui-ellipsis'
		},
		{
			index: 'UNIT', name: 'unit',
			label: "단위", 
			width: '5', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'STCK_QTY', name: 'stckQty',
			label: "현재고수량", 
			width: '12', fixed: false, align: 'right',
			sortable: false, hidden: false,
			formatter: 'integer', formatoptions: {thousandsSeparator: ','}
		},
		{
			index: 'PRP_STCK_QTY', name: 'prpStckQty',
			label: "적정재고수량", 
			width: '12', fixed: false, align: 'right',
			sortable: false, hidden: false,
			formatter: 'integer', formatoptions: {thousandsSeparator: ','}
		},
		{
			index: 'SFT_STCK_RT', name: 'sftStckRt',
			label: "안전재고비율(%)", 
			width: '10', fixed: false, align: 'right',
			minwidth: 120,
			sortable: false, hidden: false
		},
		{
			index: 'CUR_STCK_RT', name: 'curStckRt',
			label: "현재고비율(%)", 
			width: '10', fixed: false, align: 'right',
			minwidth: 100,
			sortable: false, hidden: false
		}		
	]
};

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('STOCKMNG01010');
			
			// 브랜드ID 지정
			$('#ITP_FORM_STOCKMNG01010_SEARCH_BRAND_ID').val(fn_make_user_info.get('brandId'));
			$('#ITP_FORM_STOCKMNG01010_SEARCH_STORE_ID').val(fn_make_user_info.get('storeId'));
			LOGIN_AUTH_TYPE_CD = fn_make_user_info.get('authTpCd'); // 권한타입
			
			pageObj.fnWhsList(function() {
				pageObj.fnLocationList();
			}); // 창고리스트
			
			// 공통코드 표시
			// fn_make_select(CODE_LIST, 'WHS_DVSN', 'ITP_FORM_STOCKMNG01010_WHS_DVSN');			

			// 조회일자 지정
			$('#ITP_TAB_STOCKMNG01010 .input-group.date').datepicker(ITP_DATE_LANGUAGE);	
			
			// 분류
			itemClassLevel.list(1, true);		
		},
		grid: function() {
			itp_fn_jqgrid_resize(STOCKMNG01010_GRID_ID, STOCKMNG01010_GRID_LIST, 'lg');
			listObj.empty.init();
			
		},
		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_STOCKMNG01010_SRH'		: listObj.button.search();		break;	// 조회 버튼
						case 'ITP_BTN_STOCKMNG01010_ADDROW'		: listObj.button.clickStockProc();	break;	// 재고처리 버튼
						case 'ITP_BTN_STOCKMNG01010_DELROW'		: listObj.button.clickStockHist();	break;	// 재고이력 버튼
						case 'ITP_BTN_STOCKMNG01010_EXCEL'		: listObj.excelDown();	break;	// 엑셀다운로드
					}
				});
			});

			$('body').on('click', function(e) {
				
			});
		}, 
		change: function () {
			// 창고 변경
			$('#ITP_FORM_STOCKMNG01010_SEARCH_WHS_ID').on('change', function() {
				pageObj.fnLocationList(function() {
					listObj.button.search(); // 조회	
				}); // 로케이션 리스트
			});
			$('#ITP_FORM_STOCKMNG01010_SEARCH_LOCATION').on('change', function() {
				listObj.button.search(); // 조회
			});
			
		}
	},
	switchScreen: function(mode) {
		if(mode == 'LIST') { // 목록
			itp_fn_fire_window_resize();			
			fn_show_btn_auth('#ITP_BTN_STOCKMNG01010_SRH');

			$('#ITP_AJAX_STOCKMNG01010_LIST_CONTAINER').show();
			
			$('#ITP_BTN_STOCKMNG01010_EXCEL').show();
		}
	}, 
	fnWhsList: function(fnCall) {
		const brandIdVal = $('#ITP_FORM_STOCKMNG01010_SEARCH_BRAND_ID').val();	
		const storeIdVal = $('#ITP_FORM_STOCKMNG01010_SEARCH_STORE_ID').val();	
		const whsDvsnVal = LOGIN_AUTH_TYPE_CD == '50' ? 'W02' : 'W01'; // 본사/매장 구분
		
		const param = {swhsDvsn: whsDvsnVal, sbrandId: brandIdVal, sstoreId: storeIdVal, pagingYn: false};
		
		fn_ajax_call(WHS_MNG_DETAIL_GRID_LIST, JSON.stringify(param), function(result) {
			
			fn_make_select_whs(result.gridRows, 'ITP_FORM_STOCKMNG01010_SEARCH_WHS_ID');
			
			if (fnCall !== undefined || typeof fnCall !== 'undefined') fnCall();
					
		}, 'POST');
	}, 
	fnLocationList: function(fnCall) {
		const brandIdVal = $('#ITP_FORM_STOCKMNG01010_SEARCH_BRAND_ID').val();
		const storeIdVal = $('#ITP_FORM_STOCKMNG01010_SEARCH_STORE_ID').val();	
		const whsIdVal = $('#ITP_FORM_STOCKMNG01010_SEARCH_WHS_ID').val();	
		const param = {brandId: brandIdVal, storeId: storeIdVal, whsId: whsIdVal, pagingYn: false};
		
		fn_ajax_call(WHS_MNG_LOCATION_GRID_LIST, JSON.stringify(param), function(result) {
			
			fn_make_select_location(result.gridRows, 'ITP_FORM_STOCKMNG01010_SEARCH_LOCATION');
			
			if (fnCall !== undefined || typeof fnCall !== 'undefined') fnCall();
					
		}, 'POST');
	}
};

/*목록화면 Object*/
let listObj = {
	init: function () {
		this.form();
		this.grid.init();
	},
	itp_STOCKMNG01010_search: false,
	button: {
		search: function() {
			listObj.itp_STOCKMNG01010_search = true;
			let param = $('#ITP_FORM_STOCKMNG01010_SEARCH').serializeObject();
			param.gridSize = $.jgrid.defaults.rowNum;
			param.gridPage = $.jgrid.defaults.page;
			$(STOCKMNG01010_GRID_ID).setGridParam({'postData': JSON.stringify(param)}).trigger('reloadGrid');
		}, 
		clickStockProc: function() {
			// 그리드에서 최소1개는 선택해야 함
			const rowKey = $(STOCKMNG01010_GRID_ID).getGridParam('selrow');
		    if (!rowKey) {
				itp_fn_modal_alert_ajax(ITP_MSG_LOCALE.message.ajax.noData);
		    	return;
		    }
			var selectedIds = $(STOCKMNG01010_GRID_ID).getGridParam('selarrrow');
			if (selectedIds.length > 1) {
				itp_fn_modal_alert_ajax(ITP_MSG_LOCALE.message.ajax.noSingleData);
		    	return;
			}
			var brandId = $(STOCKMNG01010_GRID_ID).jqGrid('getRowData', selectedIds[0]).brandId;
			var storeIdVal = $('#ITP_FORM_STOCKMNG01010_SEARCH_STORE_ID').val();
			var whsId = $(STOCKMNG01010_GRID_ID).jqGrid('getRowData', selectedIds[0]).whsId;
			var location = $(STOCKMNG01010_GRID_ID).jqGrid('getRowData', selectedIds[0]).location;
			var itemId = $(STOCKMNG01010_GRID_ID).jqGrid('getRowData', selectedIds[0]).itemId;
			
			var args = {'brandId': brandId, 'storeId': storeIdVal, 'whsId': whsId, 'location': location, 'itemId': itemId};			
			fn_call_popup('biz', 'BIZPOP_PO_STOCK_PROC', '#ITP_ASIDE', function() {
				listObj.button.search(); // 조회
			}, args, 'S');
		}, 
		clickStockHist: function() {
			// 그리드에서 최소1개는 선택해야 함
			const rowKey = $(STOCKMNG01010_GRID_ID).getGridParam('selrow');
		    if (!rowKey) {
				itp_fn_modal_alert_ajax(ITP_MSG_LOCALE.message.ajax.noData);
		    	return;
		    }
			var selectedIds = $(STOCKMNG01010_GRID_ID).getGridParam('selarrrow');
			if (selectedIds.length > 1) {
				itp_fn_modal_alert_ajax(ITP_MSG_LOCALE.message.ajax.noSingleData);
		    	return;
			}
			var brandId = $(STOCKMNG01010_GRID_ID).jqGrid('getRowData', selectedIds[0]).brandId;
			var whsId = $(STOCKMNG01010_GRID_ID).jqGrid('getRowData', selectedIds[0]).whsId;
			var location = $(STOCKMNG01010_GRID_ID).jqGrid('getRowData', selectedIds[0]).location;
			var itemId = $(STOCKMNG01010_GRID_ID).jqGrid('getRowData', selectedIds[0]).itemId;
			
			var args = {'brandId': brandId, 'whsId': whsId, 'location': location, 'itemId': itemId};			
			fn_call_popup('biz', 'BIZPOP_PO_STOCK_HIST', '#ITP_ASIDE', null, args, 'S');
		}
	},
	form: function() {
        $('#ITP_FORM_STOCKMNG01010_SEARCH_ITEM_CLASS1').on('change', function() {
            ($(this).val() === '') ? itemClassLevel.clear(2, true): itemClassLevel.list(2, true);
        });
        $('#ITP_FORM_STOCKMNG01010_SEARCH_ITEM_CLASS2').on('change', function() {
            ($(this).val() === '') ? itemClassLevel.clear(3, true): itemClassLevel.list(3, true);
        });
        $('#ITP_FORM_STOCKMNG01010_SEARCH_ITEM_CLASS3').on('change', function() {
            ($(this).val() === '') ? itemClassLevel.clear(4, true): itemClassLevel.list(4, true);
        });
    },
	empty: {
		init: function() {
			var _this = this;
			this.push();
			$(STOCKMNG01010_GRID_EMPTY).on('click', function() {
				_this.back();
				_this.itp_STOCKMNG01010_param.gridSize = $.jgrid.defaults.rowNum;
				$(STOCKMNG01010_GRID_ID).setGridParam({'postData': JSON.stringify(_this.itp_STOCKMNG01010_param)}).trigger('reloadGrid');
			});
		},
		itp_STOCKMNG01010_param: {},
		push: function() {
			let param = $('#ITP_FORM_STOCKMNG01010_SEARCH').serializeObject();
			listObj.itp_STOCKMNG01010_param = param;
		},
		back: function() {
			$('#ITP_FORM_STOCKMNG01010_SEARCH_WHS_ID').val(listObj.itp_STOCKMNG01010_param.swhsId);
			$('#ITP_FORM_STOCKMNG01010_SEARCH_LOCATION').val(listObj.itp_STOCKMNG01010_param.slocation);
			$('#ITP_FORM_STOCKMNG01010_SEARCH_ITEM_CLASS1').val(listObj.itp_STOCKMNG01010_param.sitemClass1);
			$('#ITP_FORM_STOCKMNG01010_SEARCH_ITEM_CLASS2').val(listObj.itp_STOCKMNG01010_param.sitemClass2);
			$('#ITP_FORM_STOCKMNG01010_SEARCH_ITEM_CLASS3').val(listObj.itp_STOCKMNG01010_param.sitemClass3);
			$('#ITP_FORM_STOCKMNG01010_SEARCH_ITEM_CLASS4').val(listObj.itp_STOCKMNG01010_param.sitemClass4);
			$('#ITP_FORM_STOCKMNG01010_SEARCH_ITEM_NM').val(listObj.itp_STOCKMNG01010_param.sitemNm);
		}
	},
	grid: {
		init: function () {
			// 데이터 없을때
			listObj.empty.push();
			this.search();
		},
		colModel: gridColModel.list,
		search: function() {
			pageObj.switchScreen('LIST');
			this.unload();
			this.load();
		},
		load: function() {
			$('#ITP_FORM_STOCKMNG01010_SEARCH_BRAND_ID').val(fn_make_user_info.get('brandId'));
			
			let param = $('#ITP_FORM_STOCKMNG01010_SEARCH').serializeObject(); 
			param.gridSize = $.jgrid.defaults.rowNum;
			$(STOCKMNG01010_GRID_ID).data('grid-param',param);
			var option = {
				gridId: STOCKMNG01010_GRID_ID,
				colModel: gridColModel.list,
				param: param,
				url: DOMAIN + STOCK_MNG_DETAIL_GRID_LIST,
				pager: STOCKMNG01010_GRID_PAGER,
				multiselect: true,
				rownumbers: false,
				onCellSelect: function(rowId, cellIdx, cellValue) {
					var cm = $(this).jqGrid('getGridParam', 'colModel');
					var colNm = cm[cellIdx].name;
					if (colNm == 'whsNm') {
						
					}
				},
				loadComplete: function(data) {
					console.log(data);
					itp_fn_grid_load_complete(data, STOCKMNG01010_GRID_ID, true, 'number', 'STOCKMNG01010', listObj.itp_STOCKMNG01010_search, listObj.empty, true, data.gridRecords, true);
					var ids = $(STOCKMNG01010_GRID_ID).getDataIDs();
					$.each(ids, function(idx, rowId) {
						// $(STOCKMNG01010_GRID_ID).jqGrid('setCell', rowId, 'whsNm', '', ITP_GRID_COL_STYLE.link);
					});
				},
				onPaging: function(action) {
					itp_fn_grid_paging(STOCKMNG01010_GRID_ID, action, param);
				}
			};
			itp_fn_grid_make_remote(option);
		},
		clearData : function() {
			$(STOCKMNG01010_GRID_ID).jqGrid('clearGridData', true);
			$(STOCKMNG01010_GRID_LIST).find('.ui-jqgrid-bdiv').css('min-height', '100px');
			$(STOCKMNG01010_GRID_EMPTY).html(ITP_MSG_LOCALE.message.grid.noData);
			$(STOCKMNG01010_GRID_EMPTY).show();
		},
		unload : function() {
			$.jgrid.gridUnload(STOCKMNG01010_GRID_ID);
		}
	},
	excelDown: function() {
		var param = {
			'url': STOCK_MNG_DETAIL_GRID_LIST,
			'param': $('#ITP_FORM_STOCKMNG01010_SEARCH').serializeObject(),
			'gridColumns': $(STOCKMNG01010_GRID_ID).jqGrid('getGridParam', 'colModel'),
			'fileName': '재고정보.xlsx',
			'sheetName': '재고리스트'
		};
		itp_fn_remote_to_excel(param);
	}
};

var itemClassLevel = {
    isList: true,
    level: 1,
    keys: function() {
        var keys = {sBrandId:fn_make_user_info.get('brandId'), sItemLevel: this.level};
        for(var i=1; i<this.level; i++) {
            var key = 'sItemClass' + i;
            var id = (this.isList ? '#ITP_FORM_STOCKMNG01010_SEARCH_ITEM_CLASS' : '#ITP_FORM_STOCKMNG01010_DETAIL_ITEM_CLASS') + i;
            keys[key] = $(id + ' option:selected').val();
        }
        return keys;
    },
    list: function(level, isList) {
        this.level = level;
        this.isList = isList;
        this.clear(level, isList);
        this.call( $.param(this.keys()));
    },
    detail: {
        data: [],
        make: function() {
            itemClassLevel.isList = false;
            itemClassLevel.call( $.param(itemClassLevel.keys()));
        }
    },
    call: function(param) {
        fn_ajax_call(API_ITEM_CLASS_LEVEL, param, this.callback, 'GET');
    },
    callback: function(result) {
        var id = 'ITP_FORM_STOCKMNG01010_SEARCH_ITEM_CLASS' + itemClassLevel.level;
        fn_make_select_item_class(result.searchList, id, true, '선택');
        if(!itemClassLevel.isList) {
            $('#' + id).val(itemClassLevel.detail.data[ itemClassLevel.level - 1]);
            if(itemClassLevel.level < itemClassLevel.detail.data.length) {
                if(itemClassLevel.detail.data[itemClassLevel.level] !== '') {
                    itemClassLevel.level++;
                    itemClassLevel.call( $.param(itemClassLevel.keys()));
                }
            }
        }
    },
    clear: function(level, isList) {
        for(var i=level; i<5; i++) {
            var id = 'ITP_FORM_STOCKMNG01010_SEARCH_ITEM_CLASS' + i;
            $('#' + id).find('option').remove();
        }
    }
};

