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


//화면변수
const POMNG07010_GRID_ID = '#ITP_POMNG07010_jqGrid';
const POMNG07010_GRID_LIST = '#ITP_POMNG07010_jqGrid_list';
const POMNG07010_GRID_PAGER = '#ITP_POMNG07010_jqGridPager';
const POMNG07010_GRID_EMPTY = '#ITP_POMNG07010_jqGridEmpty';


//API URL
let API_POMNG_INOUTMNG_WAREHOUSE_GRID_LIST = '/api/pomng/inoutmng/warehouse-grid-list';


//화면 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: 'PCH_PODR_UNQ_NO', name: 'pchPodrUnqNo',
			label: ITP_MSG_LOCALE.label.pchPodrUnqNo, 		// 발주번호
			width: '10', fixed: false, align: 'center',
			minwidth: 140,
			sortable: false, hidden: false
		},
		{
			index: 'PCH_PODR_DTL_NO', name: 'pchPodrDtlNo',
			label: ITP_MSG_LOCALE.label.pchPodrDtlNo, 		// 발주항번
			width: '5', fixed: false, align: 'center',
			minwidth: 80,
			sortable: false, hidden: false
		},
		{
			index: 'DLV_STTMT_UNQ_NO', name: 'dlvSttmtUnqNo',
			label: ITP_MSG_LOCALE.label.dlvSttmtUnqNo, 		// 납품번호
			width: '10', fixed: false, align: 'center',
			minwidth: 140,
			sortable: false, hidden: false
		},
		{
			index: 'DLV_STTMT_DTL_NO', name: 'dlvSttmtDtlNo',
			label: ITP_MSG_LOCALE.label.dlvSttmtDtlNo, 		// 납품항번
			width: '5', fixed: false, align: 'center',
			minwidth: 80,
			sortable: false, hidden: false
		},
		{
			index: 'PODR_QTY', name: 'podrQty',
			label: ITP_MSG_LOCALE.label.podrQty, 			// 발주수량
			width: '13', fixed: false, align: 'right',
			minwidth: 80,
			sortable: false, hidden: false
		},
		{
			index: 'DLV_QTY', name: 'dlvQty',
			label: ITP_MSG_LOCALE.label.dlvQty, 			// 납품수량
			width: '13', fixed: false, align: 'right',
			minwidth: 80,
			sortable: false, hidden: false
		},
		{
			index: 'WHS_QTY', name: 'whsQty',
			label: ITP_MSG_LOCALE.label.whsQty, 			// 입고수량
			width: '13', fixed: false, align: 'right',
			minwidth: 80,
			sortable: false, hidden: false
		},
		{
			index: 'DIV_REQ_DT', name: 'dlvReqDt',
			label: ITP_MSG_LOCALE.label.dlvReqDt, 			// 납품요청일
			width: '8', fixed: false, align: 'center',
			minwidth: 100,
			sortable: false, hidden: false
		},
		
		{
			index: 'DLV_SCH_DT', name: 'dlvSchDt',
			label: ITP_MSG_LOCALE.label.dlvSchDt, 			// 납품예정일
			width: '8', fixed: false, align: 'center',
			minwidth: 100,
			sortable: false, hidden: false
		},
		{
			index: 'DLV_CMPLT_DT', name: 'dlvCmpltDt',
			label: ITP_MSG_LOCALE.label.dlvCmpltDt, 		// 납품일자
			width: '8', fixed: false, align: 'center',
			minwidth: 100,
			sortable: false, hidden: false
		},
		{
			index: 'WHS_CNFM_NM', name: 'whsCnfmNm',
			label: ITP_MSG_LOCALE.label.whsCnfmNm, 			// 입고확인자
			width: '8', fixed: false, align: 'center',
			minwidth: 100,
			sortable: false, hidden: false
		},
		{
			index: 'DLV_MGR_NM', name: 'dlvMgrNm',
			label: ITP_MSG_LOCALE.label.dlvMgrNm, 			// 납품자명
			width: '8', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'DLV_MGR_TEL_NO', name: 'dlvMgrTelNo',
			label: ITP_MSG_LOCALE.label.dlvMgrTelNo, 		// 납품자전화번호
			width: '8', fixed: false, align: 'center',
			minwidth: 140,
			sortable: false, hidden: false
		},
		{
			index: 'ITEM_ID', name: 'itemId',
			label: ITP_MSG_LOCALE.label.itemId, 			// 품목번호
			width: '8', fixed: false, align: 'left',
			minwidth: 140,
			sortable: false, hidden: false
		},
		{
			index: 'ITEM_NM', name: 'itemNm',
			label: ITP_MSG_LOCALE.label.itemNm, 			// 품목명
			width: '8', fixed: false, align: 'left',
			minwidth: 100,
			sortable: false, hidden: false, classes: 'ui-ellipsis'
		},
		{
			index: 'UNIT', name: 'unit',
			label: ITP_MSG_LOCALE.label.unit, 				// 기본단위
			width: '5', fixed: false, align: 'center',
			minwidth: 80,
			sortable: false, hidden: false
		},
		{
			index: 'WHS_AMT', name: 'whsAmt',
			label: ITP_MSG_LOCALE.label.whsAmt, 			// 입고금액
			width: '13', fixed: false, align: 'right',
			sortable: false, hidden: false,
			formatter: 'integer', formatoptions: {thousandsSeparator: ','}
		}
	],
	view: [],
	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('POMNG07010');
			// 공통코드 표시
			$('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() + 5);
			$('#ITP_TAB_POMNG07010 .input-group.date').datepicker(ITP_DATE_LANGUAGE);
			$('#ITP_FORM_POMNG07010_SEARCH_FROM_DT').datepicker('setDate', now);
			$('#ITP_FORM_POMNG07010_SEARCH_TO_DT').datepicker('setDate', defaultToDate);
			
			$('#ITP_BTN_POMNG07010_EXCEL').show();
			
			if (fn_make_user_info.get('storeId') != '') {
				$('.brandSearchCond').hide();	
			}
			
		},
		grid: function() {
			itp_fn_jqgrid_resize(POMNG07010_GRID_ID, POMNG07010_GRID_LIST, 'lg');
			listObj.empty.init();
		},
		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_POMNG07010_SRH'				: listObj.button.search();		break;	// 조회 버튼 클릭
						case 'ITP_BTN_POMNG07010_NEWREG'			: listObj.button.create(); 		break;	// 신규등록 버튼
						case 'ITP_BTN_POMNG07010_MODIFY'			: modifyObj.button.modify();	break;	// 수정 버튼
						case 'ITP_BTN_POMNG07010_CANCELLIST'		: viewObj.button.cancel(); 		break;	// 취소/목록 버튼
						case 'ITP_BTN_POMNG07010_DELETE'			: 								break;	// 삭제 버튼
						case 'ITP_BTN_POMNG07010_EXCEL'				: listObj.excelDown(); break;	// excel 버튼
					}
				});
			});
		}
	},
	switchScreen: function(mode) {
        $('.itp_det_head').find('button[id^="ITP_BTN_POMNG07010_"]').each(function(i) {
            $(this).hide();
        });
        $('#ITP_TAB_POMNG07010').find('div[id$="_CONTAINER"]').each(function(i) {
            $(this).hide();
        });
        if(mode == 'LIST') { // 목록
			itp_fn_fire_window_resize();
            fn_show_btn_auth_array(['#ITP_BTN_POMNG07010_SRH', '#ITP_BTN_POMNG07010_NEWREG']);
            $('#ITP_AJAX_POMNG07010_LIST_CONTAINER').show();
            $('#ITP_FORM_POMNG07010_SEARCH #ITP_FORM_POMNG07010_SEARCH_BRAND_ID').val(fn_make_user_info.get('brandId'));
			$('#ITP_FORM_POMNG07010_SEARCH #ITP_FORM_POMNG07010_SEARCH_STORE_ID').val(fn_make_user_info.get('storeId'));
            $('#ITP_BTN_POMNG07010_SEARCH_SPPLY_ID').show();
            $('#ITP_BTN_POMNG07010_DELETE_SPPLY_ID').show();
            $('#ITP_BTN_POMNG07010_SEARCH_WHS_ID').show();
            $('#ITP_BTN_POMNG07010_DELETE_WHS_ID').show();
        }
    }
}


/*목록화면 Object*/
let listObj = {
	init: function() {
		this.grid.init();
		this.action();
	},
	itp_POMNG07010_param: {},
	itp_POMNG07010_search: false,
	button: {
		search: function() {
			listObj.itp_POMNG07010_search = true;
			let param = $('#ITP_FORM_POMNG07010_SEARCH').serializeObject();
			param.gridSize = $.jgrid.defaults.rowNum;
            param.gridPage = $.jgrid.defaults.page;
            //console.log(JSON.stringify(param));
			$(POMNG07010_GRID_ID).data('grid-param',param);
            $(POMNG07010_GRID_ID).setGridParam({'postData': JSON.stringify(param)}).trigger('reloadGrid');
        }
	},
	empty: {
		init: function() {
			var _this = this;
            this.push();
            $(POMNG07010_GRID_EMPTY).on('click', function() {
                _this.back();
                listObj.itp_POMNG07010_param.gridSize = $.jgrid.defaults.rowNum;
                $(POMNG07010_GRID_ID).setGridParam({'postData': JSON.stringify(listObj.itp_POMNG07010_param)}).trigger('reloadGrid');
            });
		},
		push: function() {
            let param = $('#ITP_FORM_POMNG07010_SEARCH').serializeObject();
            listObj.itp_POMNG07010_param = param;
        },
        back: function() {
            $('#ITP_FORM_POMNG07010_SERVICE_BRAND_TYPE').val(listObj.itp_POMNG07010_param.brandType);
            $('#ITP_FORM_POMNG07010_SERVICE_ST_CD').val(listObj.itp_POMNG07010_param.stCd);
            $('#ITP_FORM_POMNG07010_SEARCH_BRAND_NM').val(listObj.itp_POMNG07010_param.brandNm);
        }
	},
	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_POMNG07010_SEARCH').serializeObject();
            param.gridSize = $.jgrid.defaults.rowNum;
            console.log(JSON.stringify(param));
            var option = {
            	gridId: POMNG07010_GRID_ID,
            	colModel: gridColModel.list,
            	param: param,
            	url: DOMAIN + API_POMNG_INOUTMNG_WAREHOUSE_GRID_LIST,
            	pager: POMNG07010_GRID_PAGER,
            	rownumbers: false,
            	/*onCellSelect: function(rowId, cellIdx, cellValue) {
                    var cm = $(this).jqGrid('getGridParam', 'colModel');
                    var colNm = cm[cellIdx].name;
                    if (colNm === 'pchPodrUnqNo') {
                        const pchPodrUnqNoVal = $(this).jqGrid('getCell', rowId, 'pchPodrUnqNo');
                        const brandIdVal = $(this).jqGrid('getCell', rowId, 'brandId');
                        const spplyIdVal = LOGIN_USER_INFO.spplyId;
                        const key = {pchPodrUnqNo: pchPodrUnqNoVal, brandId: brandIdVal, spplyId: spplyIdVal};
                        var param = $.param(key);
                        viewObj.init(param);
                    }
				},*/
				loadComplete: function(data) {
					console.log(data);
                    itp_fn_grid_load_complete(data, POMNG07010_GRID_ID, true, 'number', 'POMNG07010', listObj.itp_POMNG07010_search, listObj.empty, true, data.gridRecords, true);
                    var ids = $(POMNG07010_GRID_ID).getDataIDs();
                    $.each(ids, function(idx, rowId) {
                        $(POMNG07010_GRID_ID).jqGrid('setCell', rowId, '', '', ITP_GRID_COL_STYLE.link);
                    });
				},
				onPaging: function(action) {
                    itp_fn_grid_paging(POMNG07010_GRID_ID, action, param);
                }
            };
            itp_fn_grid_make_remote(option);
		},
		clearData: function() {
			$(POMNG07010_GRID_ID).jqGrid('clearGridData', true);
            $(POMNG07010_GRID_LIST).find('.ui-jqgrid-bdiv').css('min-height', '100px');
            $(POMNG07010_GRID_EMPTY).html(ITP_MSG_LOCALE.message.grid.noData);
            $(POMNG07010_GRID_EMPTY).show();
		},
		unload: function() {
			$.jgrid.gridUnload(POMNG07010_GRID_ID);
		}
	},
	action: function() {
		var _this = this;
		// 공급업체 조회 버튼 클릭
		$('#ITP_BTN_POMNG07010_SEARCH_SPPLY_ID').on('click', function() {
			_this.popup('spply');
		});
		// 공급업체 텍스트 삭제 버튼 클릭
		$('#ITP_BTN_POMNG07010_DELETE_SPPLY_ID').on('click', function() {
			$('#ITP_FORM_POMNG07010_DETAIL_SPPLY_NM').val('');
			$('#ITP_FORM_POMNG07010_DETAIL_SPPLY_ID').val('');
		});
		// 매장/창고 조회 버튼 클릭
		$('#ITP_BTN_POMNG07010_SEARCH_WHS_ID').on('click', function() {
			_this.popup('whs');
		});
		// 매장/창고 텍스트 삭제 버튼 클릭
		$('#ITP_BTN_POMNG07010_DELETE_WHS_ID').on('click', function() {
			$('#ITP_FORM_POMNG07010_DETAIL_WHS_NM').val('');
			$('#ITP_FORM_POMNG07010_DETAIL_WHS_ID').val('');
		});
	},
	popup: function(keyword) {
		var popFn = this.callback.create;
		 
		if(keyword === 'spply'){
			const key = {brandId:fn_make_user_info.get('brandId'),storeId:fn_make_user_info.get('storeId')};
			fn_call_popup('biz', 'BIZPOP_STORE_SPPLY', '#ITP_ASIDE', popFn, key, 'S');
		} else if(keyword === 'whs'){
			var whsdvsn = "W01";
			if (fn_make_user_info.get('storeId') != '') {
				whsdvsn = "W02";
			}
			const key1 = {brandId:fn_make_user_info.get('brandId'),storeId:fn_make_user_info.get('storeId'), whsDvsn:whsdvsn};
			fn_call_popup('biz', 'BIZPOP_WHS_LOCATION', '#ITP_ASIDE', popFn, key1, 'S');
		}
	},
	callback: {
		create: function(rowDataPop) {
			console.log(rowDataPop);
			console.log(Array.isArray(rowDataPop));
			if(rowDataPop.hasOwnProperty('whsId') == false) {
				console.log(rowDataPop.spplyId);
				$('#ITP_FORM_POMNG07010_DETAIL_SPPLY_NM').val(rowDataPop.spplyNm);
				$('#ITP_FORM_POMNG07010_DETAIL_SPPLY_ID').val(rowDataPop.spplyId);
				//console.log(rowDataPop[0].storeId);
				//$('#ITP_FORM_POMNG07010_DETAIL_STORE_NM').val(rowDataPop[0].storeNm);
				//$('#ITP_FORM_POMNG07010_DETAIL_STORE_ID').val(rowDataPop[0].storeId);
			} else {
				console.log(rowDataPop);
				console.log(rowDataPop.whsId);
				$('#ITP_FORM_POMNG07010_DETAIL_WHS_NM').val(rowDataPop.whsNm);
				$('#ITP_FORM_POMNG07010_DETAIL_WHS_ID').val(rowDataPop.whsId);
			}
		}
	},
	excelDown: function() {
		var param = {
			'url': API_POMNG_INOUTMNG_WAREHOUSE_GRID_LIST,
			'param': $('#ITP_FORM_POMNG07010_SEARCH').serializeObject(),
			'gridColumns': $(POMNG07010_GRID_ID).jqGrid('getGridParam', 'colModel'),
			'fileName': '입고현황정보.xlsx',
			'sheetName': '입고현황리스트'
		};
		itp_fn_remote_to_excel(param);
	}
}
