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

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

/*화면 변수*/
const POMNG06010_GRID_ID = '#ITP_POMNG06010_jqGrid';
const POMNG06010_GRID_LIST = '#ITP_POMNG06010_jqGrid_list';
const POMNG06010_GRID_PAGER = '#ITP_POMNG06010_jqGridPager';
const POMNG06010_GRID_EMPTY = '#ITP_POMNG06010_jqGridEmpty';

let ITP_FORM_POMNG06010_DETAIL_IS_WRITING = false;
let POMNG06010_LAST_ROW_ID;


/*API URL*/
let API_DETAIL_GRID_LIST = '/api/pomng/inoutmng/warehouse-target-grid-list';	// 목록
let API_DETAIL_SAVE 	 = '/api/pomng/inoutmng/save-warehouse';			// 입고처리


/*화면 Grid ColModel*/
const gridColModel = {
	list: [
		{
			index: 'BRAND_ID', name: 'brandId',
			label: ITP_MSG_LOCALE.label.brandId, //브랜드아이디
			width: '13', 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
		},
		{
			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: '10', fixed: false, align: 'right',
			sortable: false, hidden: false
		},
		{
			index: 'ITEM_ID', name: 'itemId',
			label: ITP_MSG_LOCALE.label.itemId, //품목아이디
			width: '10', fixed: false, align: 'center',
			minwidth: 140,
			sortable: false, hidden: false
		},
		{
			index: 'ITEM_NM', name: 'itemNm',
			label: ITP_MSG_LOCALE.label.itemNm, //품목명
			width: '10', fixed: false, align: 'left',
			minwidth: 120,
			sortable: false, hidden: false
		},
		{
			index: 'PODR_QTY', name: 'podrQty',
			label: ITP_MSG_LOCALE.label.podrQty, //발주수량
			width: '10', fixed: false, align: 'right',
			sortable: false, hidden: false,
			formatter: 'integer', formatoptions: { defaultValue: '', thousandsSeparator: ',' }
		},
		{
			index: 'DLV_QTY', name: 'dlvQty',
			label: ITP_MSG_LOCALE.label.dlvQty, //납품/수주 수량
			width: '10', fixed: false, align: 'right',
			sortable: false, hidden: false,
			formatter: 'integer', formatoptions: { defaultValue: '', thousandsSeparator: ',' }
		},
		{
			index: 'WHS_QTY', name: 'whsQty',	
			label: ITP_MSG_LOCALE.label.whsQty, //입고수량
			width: '10', fixed: false, align: 'right',
			sortable: true, editable: true, edittype: 'text',
			editrules: { required: false, number: true },
			classes: 'input_color',
			formatter: 'integer', formatoptions: { defaultValue: '', thousandsSeparator: ',' },
			editoptions: {"onKeyup": "this.value=this.value.replace(/[^0-9]/g,'');"}
		},
		{
			index: 'WHS_AMT', name: 'whsAmt',
			label: ITP_MSG_LOCALE.label.whsAmt, //입고금액
			width: '13', fixed: false, align: 'right',
			sortable: false, hidden: true
		},
		{
			index: 'UNIT_AMT', name: 'unitAmt',
			label: ITP_MSG_LOCALE.label.unitAmt, //단가
			width: '6', fixed: false, align: 'right',
			minwidth: 70,
			sortable: false, hidden: false,
			formatter: 'integer', formatoptions: { defaultValue: '', thousandsSeparator: ',' }
		},
		{
			index: 'WHS_ID', name: 'whsId',
			label: ITP_MSG_LOCALE.label.whsId, //납품창고아이디
			width: '15', fixed: false, align: 'left',
			minwidth: 150,
			sortable: false, hidden: true
		},
		{
			index: 'LOCATION', name: 'location',
			label: ITP_MSG_LOCALE.label.location, //납품납품LOCATION
			width: '15', fixed: false, align: 'center',
			sortable: false, hidden: true
		},
		{
			index: 'WHS_NM', name: 'whsNm',
			label: ITP_MSG_LOCALE.label.whsNm, //납품창고명
			width: '15', fixed: false, align: 'left',
			minwidth: 200,
			sortable: false, hidden: false
		},
		{
			index: 'DLV_REQ_DT', name: 'dlvReqDt',
			label: ITP_MSG_LOCALE.label.dlvReqDt, //납품요청일
			width: '15', fixed: false, align: 'center',
			sortable: false, hidden: false
		},		
		{
			index: 'DLV_SCH_DT', name: 'dlvSchDt',
			label: ITP_MSG_LOCALE.label.dlvSchDt, //납품예정일
			width: '15', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'DLV_MGR_NM', name: 'dlvMgrNm',
			label: ITP_MSG_LOCALE.label.dlvMgrNm, //납품담당자명
			width: '15', fixed: false, align: 'left',
			sortable: false, hidden: false
		},		
		{
			index: 'DLV_MGR_TEL_NO', name: 'dlvMgrTelNo',
			label: ITP_MSG_LOCALE.label.dlvMgrTelNo, //납품담당자연락처
			width: '15', fixed: false, align: 'center',
			minwidth: 120,
			sortable: false, hidden: false
		},
		{
			index: 'PCH_PODR_UNQ_NO', name: 'pchPodrUnqNo',
			label: ITP_MSG_LOCALE.label.pchPodrUnqNo, //구매발주번호
			width: '15', fixed: false, align: 'center',
			sortable: false, hidden: true
		},		
		{
			index: 'PCH_REQ_UNQ_NO', name: 'pchReqUnqNo',
			label: ITP_MSG_LOCALE.label.pchReqUnqNo, //구매요청번호
			width: '15', fixed: false, align: 'center',
			sortable: false, hidden: true
		},
		{
			index: 'PCH_REQ_DTL_NO', name: 'pchReqDltNo',
			label: ITP_MSG_LOCALE.label.pchReqDltNo, //구매요청항번
			width: '15', fixed: false, align: 'center',
			sortable: false, hidden: true
		},
		{
			index: 'UNIT', name: 'unit',
			label: ITP_MSG_LOCALE.label.unit, //단위
			width: '15', fixed: false, align: 'center',
			sortable: false, hidden: true
		},
		{
			index: 'SPPLY_ID', name: 'spplyId',
			label: ITP_MSG_LOCALE.label.spplyId, //공급사아이디
			width: '15', fixed: false, align: 'center',
			sortable: false, hidden: true
		},
		{
			index: 'SPPLY_NM', name: 'spplyNm',
			label: ITP_MSG_LOCALE.label.spplyNm, //공급사명
			width: '15', fixed: false, align: 'center',
			sortable: false, hidden: true
		}
	]
};


/*목록화면 Object*/
let listObj = {
	init: function() {
		this.view();
		this.action();
		this.event.init();
		this.grid.init();
		this.screen();
	},
	view: function() {
		// 버튼 권한설정
		fn_proc_btn_auth('POMNG06010');

		// 공통코드 표시
		$('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_POMNG06010 .input-group.date').datepicker(ITP_DATE_LANGUAGE);
		$('#ITP_FORM_POMNG06010_SEARCH_FROM_DT').datepicker('setDate', new Date(now.setDate(now.getDate())));
		$('#ITP_FORM_POMNG06010_SEARCH_TO_DT').datepicker('setDate', new Date(now.setDate(now.getDate() + 30)));

		$('#ITP_BTN_POMNG06010_EXCEL').show();
	},
	itp_POMNG06010_search: false,
	button: {
		search: function() {
			console.log("search event");
			listObj.itp_POMNG06010_search = true;
			let param = $('#ITP_FORM_POMNG06010_SEARCH').serializeObject();
			param.gridSize = $.jgrid.defaults.rowNum;
			param.gridPage = $.jgrid.defaults.page;
			param.sbrandId = fn_make_user_info.get('brandId');
			param.sstoreId = fn_make_user_info.get('storeId');
			
			if (param.swhsId == "") {
				alert("입고창고를 지정해주세요!");
				return;
			}
			
			if (param.fromDt == '' || param.toDt == '') {
				alert("납품예정일 기간을 지정해주세요!");
				return;
			}
			
			$(POMNG06010_GRID_ID).setGridParam({ 'postData': JSON.stringify(param) }).trigger('reloadGrid');
		},
		save: function() {
			
			$('body').trigger('click');
			
				var modalFn = {
					callBack: () => {
						//itp_fn_form_event.removeChar('#ITP_FORM_OPER03010_DETAIL');
						var chkQtyYn = "N";
						let gridInsertData = [];
						const rowData = $(POMNG06010_GRID_ID).getRowData();
						var cwhsId = "";
						
						$.each(rowData, function(key, value) {
							
							if (value.whsQty != '') {
								if (parseInt(value.whsQty) > parseInt(value.dlvQty)) {
									alert("납품수량보다 입고수량이 더 많습니다.");
									chkQtyYn = "Y";
									return false;
								}
								
								if (cwhsId != "" && cwhsId != value.whsId) {
									alert("서로 다른 입고창고 품목은 처리할 수 없습니다.");
									chkQtyYn = "Y";
									return false;
								}
								cwhsId = value.whsId;
								gridInsertData.push(value);
							}
							
						});
						
						if (chkQtyYn == "Y") return;
						
						if (gridInsertData.length == 0) {
							alert("입고처리할 품목에 입고수량을 입력해주세요!");
							return ;
						}
						
						
						
						let param = {};
						param.viewCd = "C";
						param.whsId = cwhsId;
						param.brandId = fn_make_user_info.get('brandId');
						param.storeId = fn_make_user_info.get('storeId');
						param.dlvCnfmDocFileNo = "";
						param.gridInsertData = gridInsertData;
						console.log(JSON.stringify(param));
						
						var searhFn = function () {
							//ITP_FORM_INOUTMNG01010_DETAIL_IS_WRITING = false;
							listObj.button.search();
						}
						fn_ajax_call(API_DETAIL_SAVE, JSON.stringify(param), searhFn, 'POST');
					}
				};
			
				itp_fn_modal_confirm('입고처리 하시겠습니까?', modalFn);
			
		}
	},
	action: function() {
		var _this = this;
		// 공급업체 조회 버튼 클릭
		$('#ITP_BTN_POMNG06010_SEARCH_SPPLY_ID').on('click', function() {
			_this.popup('spply');
		});
		// 공급업체 텍스트 삭제 버튼 클릭
		$('#ITP_BTN_POMNG06010_DELETE_SPPLY_ID').on('click', function() {
			$('#ITP_FORM_POMNG06010_SEARCH_SPPLY_NM').val('');
			$('#ITP_FORM_POMNG06010_SEARCH_SPPLY_ID').val('');
		});
		
		// 매장/창고 조회 버튼 클릭
		$('#ITP_BTN_POMNG06010_SEARCH_WHS_ID').on('click', function() {
			_this.popup('whs');
		});
		// 매장/창고 텍스트 삭제 버튼 클릭
		$('#ITP_BTN_POMNG06010_DELETE_WHS_ID').on('click', function() {
			$('#ITP_FORM_POMNG06010_SEARCH_WHS_NM').val('');
			$('#ITP_FORM_POMNG06010_SEARCH_WHS_ID').val('');
		});

	},
	popup: function(arg) {
		var popFn = this.callback.create;

		var whsDvsn = "";
		
		if (fn_make_user_info.get('storeId') == "") {
			whsDvsn = "W01";
		} else { 
			whsDvsn = "W02";
		}
		
		//param.sstoreId = fn_make_user_info.get('storeId');
		
		if(arg === '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(arg === 'whs'){
			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);
			if(rowDataPop.hasOwnProperty('whsId') == false) {
				$('#ITP_FORM_POMNG06010_SEARCH_SPPLY_NM').val(rowDataPop.spplyNm);
				$('#ITP_FORM_POMNG06010_SEARCH_SPPLY_ID').val(rowDataPop.spplyId);
			} else {
				$('#ITP_FORM_POMNG06010_SEARCH_WHS_NM').val(rowDataPop.whsNm);
				$('#ITP_FORM_POMNG06010_SEARCH_WHS_ID').val(rowDataPop.whsId);
			}
		}
	},
	event: {
		init: function() {
			this.button();
		},
		button: function() {
			// 버튼 클릭 이벤트
			$('button').each(function() {
				var id = $(this).attr('id');
				$(this).on('click', function() {
					switch (id) {
						case 'ITP_BTN_POMNG06010_SRH': listObj.button.search(); break;	// 조회 버튼 클릭
						case 'ITP_BTN_POMNG06010_MODIFY': listObj.button.save(); break;	// 입고처리 버튼
						case 'ITP_BTN_POMNG06010_EXCEL': listObj.excelDown(); break;	// excel 버튼

					}
				});
			});

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

				itp_fn_grid_reset_selection(e, last_row_id, gridId, 'POMNG06010');
			});


		}
	},
	empty: {
		init: function() {
			/*
			var _this = this;
			this.push();
			$(POMNG06010_GRID_EMPTY).on('click', function() {
				_this.back();
				_this.itp_POMNG06010_param.gridSize = $.jgrid.defaults.rowNum;
				$(POMNG06010_GRID_ID).setGridParam({ 'postData': JSON.stringify(_this.itp_POMNG06010_param) }).trigger('reloadGrid');
			});
			*/
		},
		itp_POMNG06010_param: {},
		push: function() {
			/*
			let param = $('#ITP_FORM_POMNG06010_SEARCH').serializeObject();
			listObj.itp_POMNG06010_param = param;
			*/
		},
		back: function() {
			/*
			$('#ITP_FORM_POMNG06010_SEARCH_FROM_DT').val(this.itp_POMNG06010_param.fromDt);
			$('#ITP_FORM_POMNG06010_SEARCH_TO_DT').val(this.itp_POMNG06010_param.toDt);
			$('#ITP_FORM_POMNG06010_SEARCH_DLV_STTMT_UNQ_NO').val(this.itp_POMNG06010_param.sDlvSttmtUnqNo);
			$('#ITP_FORM_POMNG06010_SEARCH_SPPLY_ID').val(this.itp_POMNG06010_param.sSpplyId);
			$('#ITP_FORM_POMNG06010_SEARCH_WHS_ID').val(this.itp_POMNG06010_param.sWhsId);
			$('#ITP_FORM_POMNG06010_SEARCH_ITEM_NM').val(this.itp_POMNG06010_param.sItemNm);
			*/
		}
	},
	grid: {
		init: function() {
			// 데이터 없을때
			listObj.empty.push();
			itp_fn_jqgrid_resize(POMNG06010_GRID_ID, POMNG06010_GRID_LIST, 'lg');
			this.search();

		},
		colModel: gridColModel.list,
		search: function() {
			this.unload();
			this.load();
		},
		load: function() {
			let param = $('#ITP_FORM_POMNG06010_SEARCH').serializeObject();
			param.gridSize = $.jgrid.defaults.rowNum;
			param.sbrandId = fn_make_user_info.get('brandId');
			param.sstoreId = fn_make_user_info.get('storeId');
			param.swhsId = "Order";
			$(POMNG06010_GRID_ID).data('grid-param',param);
			var option = {
				//multiselect: true,
				autowidth: true,
				gridId: POMNG06010_GRID_ID,
				colModel: gridColModel.list,
				param: param,
				url: DOMAIN + API_DETAIL_GRID_LIST,
				pager: POMNG06010_GRID_PAGER,

				onCellSelect: function(rowid, cellIdx, cellValue) {
					POMNG06010_LAST_ROW_ID = itp_fn_set_data_editable(rowid, cellIdx, POMNG06010_LAST_ROW_ID, POMNG06010_GRID_ID, ['pchPodrUnqNo']);
				},
				loadComplete: function(data) {
					itp_fn_grid_load_complete(data, POMNG06010_GRID_ID, true, 'number', 'POMNG06010', listObj.itp_POMNG06010_search, listObj.empty, true, data.gridRecords, true);
				},
				onPaging: function(action) {
					itp_fn_grid_paging(POMNG06010_GRID_ID, action, param);
				}
			};
			itp_fn_grid_make_remote(option);
		},
		button: {
		},
		unload: function() {
			$.jgrid.gridUnload(POMNG06010_GRID_ID);
		},
		clearData: function() {
			$(POMNG06010_GRID_ID).jqGrid('clearGridData', true);
			$(POMNG06010_GRID_LIST).find('.ui-jqgrid-bdiv').css('min-height', '100px');
			$(POMNG06010_GRID_EMPTY).html(ITP_MSG_LOCALE.message.grid.noData);
			$(POMNG06010_GRID_EMPTY).show();
		}
		
	},
	screen: function() {
		$('#ITP_BTN_POMNG06010_DELETE_WHS_ID').show();
		$('#ITP_BTN_POMNG06010_DELETE_SPPLY_ID').show();
	},
	excelDown: function() {
		var excelParam = $('#ITP_FORM_POMNG06010_SEARCH').serializeObject();
		excelParam.sbrandId = fn_make_user_info.get('brandId');
		excelParam.sstoreId = fn_make_user_info.get('storeId');
		var param = {
			'url': API_DETAIL_GRID_LIST,
			'param': excelParam,
			'gridColumns': $(POMNG06010_GRID_ID).jqGrid('getGridParam', 'colModel'),
			'fileName': '입고처리대상정보.xlsx',
			'sheetName': '입고처리대상리스트'
		};
		itp_fn_remote_to_excel(param);
	}
};


