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 RTNMNG05010_GRID_ID = '#ITP_RTNMNG05010_jqGrid';
const RTNMNG05010_GRID_LIST = '#ITP_RTNMNG05010_jqGrid_list';
const RTNMNG05010_GRID_PAGER = '#ITP_RTNMNG05010_jqGridPager';
const RTNMNG05010_GRID_EMPTY = '#ITP_RTNMNG05010_jqGridEmpty';

let ITP_FORM_RTNMNG05010_DETAIL_IS_WRITING = false;
let RTNMNG05010_LAST_ROW_ID;


/*API URL*/
let API_DETAIL_GRID_LIST = '/api/rtnmng/inoutmng/retstock-target-grid-list';	// 목록
let API_DETAIL_SAVE 	 = '/api/rtnmng/inoutmng/save-retstock';				// 반품처리


/*화면 Grid ColModel*/
const gridColModel = {
	list: [
		{
			index: 'BRAND_ID', name: 'brandId',
			label: ITP_MSG_LOCALE.label.brandId, //브랜드아이디
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: true
		},
		{
			index: 'STORE_ID', name: 'storeId',
			label: '매장아이디', 
			width: '10', 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: 100,
			sortable: false, hidden: false, classes: 'ui-ellipsis'
		},
		{
			index: 'COL_PICK_UNQ_NO', name: 'colPickUnqNo',
			label: '수거서번호', 
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: true
		},
		{
			index: 'COL_PICK_DTL_NO', name: 'colPickDtlNo',
			label: '수거서항번', 
			width: '5', fixed: false, align: 'center',
			sortable: false, hidden: true
		},		
		{
			index: 'RTN_PODR_UNQ_NO', name: 'rtnPodrUnqNo',
			label: '반품발주번호', 
			width: '12', fixed: false, align: 'center',
			minwidth: 140,
			sortable: false, hidden: false
		},
		{
			index: 'RTN_PODR_DTL_NO', name: 'rtnPodrDtlNo',
			label: '항번', 
			width: '5', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'ITEM_ID', name: 'itemId',
			label: ITP_MSG_LOCALE.label.itemId, //품목아이디
			width: '13', fixed: false, align: 'center',
			minwidth: 140,
			sortable: false, hidden: false
		},
		{
			index: 'ITEM_NM', name: 'itemNm',
			label: ITP_MSG_LOCALE.label.itemNm, //품목명
			width: '7', fixed: false, align: 'left',
			minwidth: 100,
			sortable: false, hidden: false, classes: 'ui-ellipsis'
		},
		{
			index: 'COL_QTY', name: 'colQty',
			label: '수거수량', classes: 'input_color',
			width: '8', fixed: false, align: 'right',
			sortable: true, editable: true, edittype: 'text',
			editrules: { required: false, number: true },
			formatter: 'integer', formatoptions: { defaultValue: '', thousandsSeparator: ',' },
			editoptions: {"onKeyup": "this.value=this.value.replace(/[^0-9]/g,'');", maxlength: 10}
		},
		{
			index: 'COL_REQ_QTY', name: 'colReqQty',
			label: '수거요청수량', 
			minwidth: 100,
			width: '9', fixed: false, align: 'right',
			sortable: false, hidden: false,
			formatter: 'integer', formatoptions: { defaultValue: '', thousandsSeparator: ',' }
		},
		{
			index: 'COL_REQ_AMT', name: 'colReqAmt',
			label: '수거요청금액', 
			width: '9', fixed: false, align: 'right',
			sortable: false, hidden: false, 
			formatter: 'integer', formatoptions: { defaultValue: '', thousandsSeparator: ',' }
		},
		{
			index: 'RODR_QTY', name: 'rodrQty',
			label: '반품발주수량', 
			width: '8', fixed: false, align: 'right',
			sortable: false, hidden: true,
			formatter: 'integer', formatoptions: { defaultValue: '', thousandsSeparator: ',' }
		},
		{
			index: 'WHS_ID', name: 'whsId',
			label: '반품입고창고', 
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: true
		},
		{
			index: 'LOCATION', name: 'location',
			label: '반품입고창고location', 
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: true
		},
		{
			index: 'WHS_NM', name: 'whsNm',
			label: '반품입고창고', 
			minwidth: 120,
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'RTN_WHS_ID', name: 'rtnWhsId',
			label: '수거창고', 
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: true
		},
		{
			index: 'RTN_LOCATION', name: 'rtnLocation',
			label: '수거LOCATION', 
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: true
		},
		{
			index: 'RTN_WHS_NM', name: 'rtnWhsNm',
			label: '수거창고명', 
			minwidth: 140,
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: false, classes: 'ui-ellipsis'
		},
		{
			index: 'COL_REQ_DT', name: 'colReqDt',
			label: '수거요청일', 
			minwidth: 140,
			width: '8', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'COL_SCH_DT', name: 'colSchDt',
			label: '수거예정일', 
			minwidth: 140,
			width: '8', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'PICK_MGR_NM', name: 'pickMgrNm',
			label: '수거담당자명', 
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'PICK_MGR_TEL_NO', name: 'pickMgrTelNo',
			label: '수거담당자연락처', 
			minwidth: 140,
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'SPPLY_ID', name: 'spplyId',
			label: '공급사아이디', 
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: true
		},
		{
			index: 'SPPLY_NM', name: 'spplyNm',
			label: '공급사명', 
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: true
		}
	]
};


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

		// 공통코드 표시
		$('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_RTNMNG05010 .input-group.date').datepicker(ITP_DATE_LANGUAGE);
		$('#ITP_FORM_RTNMNG05010_SEARCH_FROM_DT').datepicker('setDate', new Date(now.setDate(now.getDate())));
		$('#ITP_FORM_RTNMNG05010_SEARCH_TO_DT').datepicker('setDate', new Date(now.setDate(now.getDate() + 30)));
		
		$('#ITP_FORM_RTNMNG05010_SEARCH_SRTN_WHS_ID').val('xxx'); // 임시
		
		$('#ITP_BTN_RTNMNG05010_SEARCH_DEL_SRTN_WHS_NM').show();
		$('#ITP_BTN_RTNMNG05010_SEARCH_DEL_SSPPLY_NM').show();
		$('#ITP_BTN_RTNMNG05010_SEARCH_DEL_SWHS_NM').show();
		
		$('#ITP_BTN_RTNMNG05010_EXCEL').show();
	},
	itp_RTNMNG05010_search: false,
	button: {
		search: function() {
			listObj.itp_RTNMNG05010_search = true;
			let param = $('#ITP_FORM_RTNMNG05010_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 == "") {
			if ($('#ITP_FORM_RTNMNG05010_SEARCH_SRTN_WHS_NM').val() == "") {
				itp_fn_modal_alert("수거창고를 지정해주세요!");
				return;
			}
			
			if (param.fromDt == '' || param.toDt == '') {
				itp_fn_modal_alert("수거요청일 기간을 지정해주세요!");
				return;
			}
			$(RTNMNG05010_GRID_ID).data('grid-param',param);
			$(RTNMNG05010_GRID_ID).setGridParam({ 'postData': JSON.stringify(param) }).trigger('reloadGrid');
		},
		save: function() {
			
			$('body').trigger('click');
			
			var chkQtyYn1 = true;
			var chkQtyYn2 = true;
			var chkQtyYn3 = true;
			let gridInsertData = [];
			const rowData = $(RTNMNG05010_GRID_ID).getRowData();
			var swhsId = "";
			var srtnWhsId = "";
			var storeId = "";
			
			$.each(rowData, function(key, value) {		
				
				if (value.colQty !== '') {
									
					if (parseInt(value.colQty) > parseInt(value.colReqQty)) {									
						chkQtyYn1 = false;
					}								
					if (swhsId !== "" && swhsId !== value.whsId) {
						chkQtyYn2 = false;
					}
					if (srtnWhsId !== "" && srtnWhsId !== value.rtnWhsId) {
						chkQtyYn3 = false;
					}
					swhsId = value.whsId;
					srtnWhsId = value.rtnWhsId;
					storeId = value.storeId;
					gridInsertData.push(value);	
				}						
			});
			
			if (chkQtyYn1 === false) {
				itp_fn_modal_alert("수거요청수량보다 수거수량이 더 많습니다.");
				return;	
			}
			if (chkQtyYn2 === false) {
				itp_fn_modal_alert("서로 다른 반품입고창고 품목은 처리할 수 없습니다.");
				return;	
			}
			if (chkQtyYn3 === false) {
				itp_fn_modal_alert("서로 다른 수거창고 품목은 처리할 수 없습니다.");
				return;	
			}						
			
			if (gridInsertData.length == 0) {
				itp_fn_modal_alert("반품처리할 품목을 없습니다.");
				return ;
			}
			
			var modalFn = {
				callBack: () => {
					let param = {};
					param.viewCd = "C";
					param.whsId = swhsId;
					param.rtnWhsId = srtnWhsId;
					param.brandId = fn_make_user_info.get('brandId');
					param.storeId = storeId; 
					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_RTNMNG05010_SEARCH_POP_SSPPLY_NM').on('click', function() {
			_this.popup('spply');
		});
		// 공급업체 텍스트 삭제 버튼 클릭
		$('#ITP_BTN_RTNMNG05010_SEARCH_DEL_SSPPLY_NM').on('click', function() {
			$('#ITP_FORM_RTNMNG05010_SEARCH_SSPPLY_NM').val('');
			$('#ITP_FORM_RTNMNG05010_SEARCH_SSPPLY_ID').val('');
		});
		
		// 매장/창고 조회 버튼 클릭
		/*
		$('#ITP_BTN_RTNMNG05010_SEARCH_POP_SWHS_NM').on('click', function() {
			_this.popup('whs');
		});
		// 매장/창고 텍스트 삭제 버튼 클릭
		$('#ITP_BTN_RTNMNG05010_SEARCH_DEL_SWHS_NM').on('click', function() {
			$('#ITP_FORM_RTNMNG05010_SEARCH_SWHS_NM').val('');
			$('#ITP_FORM_RTNMNG05010_SEARCH_SWHS_ID').val('');
		});
		*/
		
		// 수거창고 조회 버튼 클릭
		$('#ITP_BTN_RTNMNG05010_SEARCH_POP_SRTN_WHS_NM').on('click', function() {
			_this.popup('rwhs');
		});
		// 수거창고 텍스트 삭제 버튼 클릭
		$('#ITP_BTN_RTNMNG05010_SEARCH_DEL_SRTN_WHS_NM').on('click', function() {
			$('#ITP_FORM_RTNMNG05010_SEARCH_SRTN_WHS_NM').val('');
			$('#ITP_FORM_RTNMNG05010_SEARCH_SRTN_WHS_ID').val('');
		});

	},
	popup: function(arg) {
		var whsDvsn = "";		
		if (fn_make_user_info.get('storeId') == "") {  // 브랜드
			whsDvsn = "W01";
		} else { 
			whsDvsn = "W02";
		}
		
		if(arg === 'spply'){
			var popFn = this.callback.supply;			
			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 === 'rwhs'){  //수거창고
			var popFn = this.callback.rwhs;
			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: {
		supply: function(rowDataPop) {
			$('#ITP_FORM_RTNMNG05010_SEARCH_SSPPLY_NM').val(rowDataPop.spplyNm);
			$('#ITP_FORM_RTNMNG05010_SEARCH_SSPPLY_ID').val(rowDataPop.spplyId);
		},
		rwhs: function(rowDataPop) {
			$('#ITP_FORM_RTNMNG05010_SEARCH_SRTN_WHS_NM').val(rowDataPop.whsNm);
			$('#ITP_FORM_RTNMNG05010_SEARCH_SRTN_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_RTNMNG05010_SRH'		: listObj.button.search(); 	break;	// 조회 버튼 클릭
						case 'ITP_BTN_RTNMNG05010_RTN_PROC'	: listObj.button.save(); 	break;	// 입고처리 버튼
						case 'ITP_BTN_RTNMNG05010_EXCEL'	: listObj.excelDown(); 	break;	// 엑셀다운로드

					}
				});
			});

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

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


		}
	},
	empty: {
		init: function() {
			
		},
		itp_RTNMNG05010_param: {},
		push: function() {
			
		},
		back: function() {
			
		}
	},
	grid: {
		init: function() {
			// 데이터 없을때
			itp_fn_jqgrid_resize(RTNMNG05010_GRID_ID, RTNMNG05010_GRID_LIST, 'lg');
			this.search();

		},
		colModel: gridColModel.list,
		search: function() {
			this.unload();
			this.load();
		},
		load: function() {
			let param = $('#ITP_FORM_RTNMNG05010_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";
			var option = {
				autowidth: true,
				gridId: RTNMNG05010_GRID_ID,
				colModel: gridColModel.list,
				param: param,
				url: DOMAIN + API_DETAIL_GRID_LIST,
				pager: RTNMNG05010_GRID_PAGER,
				onCellSelect: function(rowid, cellIdx, cellValue) {
					RTNMNG05010_LAST_ROW_ID = itp_fn_set_data_editable(rowid, cellIdx, RTNMNG05010_LAST_ROW_ID, RTNMNG05010_GRID_ID, ['pchPodrUnqNo']);
				},
				loadComplete: function(data) {
					itp_fn_grid_load_complete(data, RTNMNG05010_GRID_ID, true, 'number', 'RTNMNG05010', listObj.itp_RTNMNG05010_search, listObj.empty, true, data.gridRecords, true);
				},
				onPaging: function(action) {
					itp_fn_grid_paging(RTNMNG05010_GRID_ID, action, param);
				}
			};
			itp_fn_grid_make_remote(option);
		},
		button: {
		},
		unload: function() {
			$.jgrid.gridUnload(RTNMNG05010_GRID_ID);
		},
		clearData: function() {
			$(RTNMNG05010_GRID_ID).jqGrid('clearGridData', true);
			$(RTNMNG05010_GRID_LIST).find('.ui-jqgrid-bdiv').css('min-height', '100px');
			$(RTNMNG05010_GRID_EMPTY).html(ITP_MSG_LOCALE.message.grid.noData);
			$(RTNMNG05010_GRID_EMPTY).show();
		}
		
	},
	excelDown: function() {
		
		var excelParam =  $('#ITP_FORM_RTNMNG05010_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': $(RTNMNG05010_GRID_ID).jqGrid('getGridParam', 'colModel'),
			'fileName': '반품처리정보.xlsx',
			'sheetName': '반품처리대상리스트'
		};
		itp_fn_remote_to_excel(param);
	}
};


