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

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

/*화면 변수*/
const RTNMNG01010_DETAIL_GRID_ID = '#ITP_RTNMNG01010_DETAIL_jqGrid';
const RTNMNG01010_DETAIL_GRID_LIST = '#ITP_RTNMNG01010_DETAIL_jqGrid_list';
const RTNMNG01010_DETAIL_GRID_PAGER = '#ITP_RTNMNG01010_DETAIL_jqGridPager';
const RTNMNG01010_DETAIL_GRID_EMPTY = '#ITP_RTNMNG01010_DETAIL_jqGridEmpty';  // ==>dwkim html확인필요

let RTNMNG01010_DETAIL_GRID_LAST_ROW_ID;

/* 공통코드 리스트 */
let ITP_COMMON_CD_RTN_DVSN = fn_make_common_cd_list(CODE_LIST, 'RTN_DVSN', false);
let ITP_COMMON_CD_RTN_RSN_DVSN = fn_make_common_cd_list(CODE_LIST, 'RTN_RSN_DVSN', false);

/*API URL*/
let API_DETAIL_INIT_INFO = '/api/rtnmng/init-rtnReq'
let API_DETAIL_SAVE = '/api/rtnmng/save-rtnReq';

/*화면 Grid ColModel   ==>선택박스 항목 추가 부분  */
const gridColModel = {
	detail: [
		{
			index: 'VIEW_CD', name: 'viewCd',
			label: ITP_MSG_LOCALE.label.viewCd,
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: true
		},
		{
			index: 'RTN_REQ_UNQ_NO', name: 'rtnReqUnqNo',
			label: '반품요청번호',
			width: '10', fixed: false, align: 'center',
			sortable: false, editable: false, edittype: 'text', hidden: true
		},
		{
			index: 'RTN_REQ_DTL_NO', name: 'rtnReqDtlNo',
			label: '반품요청상세번호',
			width: '10', fixed: false, align: 'center',
			sortable: false, editable: false, edittype: 'text', hidden: true
		},
		{
			index: 'ITEM_ID', name: 'itemId',
			label: ITP_MSG_LOCALE.label.itemId,
			width: '10', fixed: false, align: 'center',
			sortable: false, editable: false, edittype: 'text',
			editrules: { required: true }
		},
		{
			index: 'ITEM_NM', name: 'itemNm',
			label: ITP_MSG_LOCALE.label.itemNm,
			width: '8', fixed: false, align: 'left',
			sortable: false, editable: false, edittype: 'text',
			editrules: { required: true }, classes: 'ui-ellipsis'
		},
		{
			index: 'UNIT', name: 'unit',
			label: ITP_MSG_LOCALE.label.unit,
			width: '8', fixed: false, align: 'center',
			sortable: false, editable: false, edittype: 'text'
		},
		{
			index: 'UNIT_AMT', name: 'unitAmt',
			label: ITP_MSG_LOCALE.label.unitAmt,
			width: '6', fixed: false, align: 'right',
			sortable: false, editable: false, edittype: 'text', hidden: false, 
			formatter:'integer',formatoptions: { defaultValue: '', thousandsSeparator: ',' }
		},
		{
			index: 'RTN_QTY', name: 'rtnQty',
			label: '반품수량', classes: 'input_color',
			width: '8', fixed: false, align: 'right',
			sortable: false, editable: true, edittype: 'text',
			editoptions: {"onKeyup": "this.value=this.value.replace(/[^0-9]/g,'');", maxlength: 10}, 
			formatter:'integer', formatoptions: { defaultValue: '', thousandsSeparator: ',' },
		},
		{
			index: 'RTN_AMT', name: 'rtnAmt',
			label: '반품예상금액',
			width: '8', fixed: false, align: 'right',
			sortable: false, editable: false, edittype: 'text', hidden: false, 
			formatter:'integer',formatoptions: { defaultValue: '', thousandsSeparator: ',' }
		},		
		{
			index: 'RTN_DVSN', name: 'rtnDvsn',
			label: '반품구분', classes: 'input_color',
			width: '9', fixed: false, align: 'left',
			sortable: false, editable: true, formatter: 'select', edittype: 'select',
			editoptions: {value: ITP_COMMON_CD_RTN_DVSN},
			editrules: {required: true}
		},
		{
			index: 'RTN_RSN_DVSN', name: 'rtnRsnDvsn',
			label: '사유구분', classes: 'input_color',
			width: '9', fixed: false, align: 'left',
			sortable: false, editable: true, formatter: 'select', edittype: 'select',
			editoptions: {value: ITP_COMMON_CD_RTN_RSN_DVSN},
			editrules: {required: true}
		},
		{
			index: 'RTN_RSN', name: 'rtnRsn',
			label: '반품사유', classes: 'input_color',
			width: '12', fixed: false, align: 'left',
			sortable: false, editable: true, edittype: 'text',
			editoptions: {maxlength: 200}
		},
		{
			index: 'SPPLY_ID', name: 'spplyId',
			label: '공급사아이디',
			width: '10', fixed: false, align: 'center',
			sortable: false, editable: false, edittype: 'text', hidden: true
		},
		{
			index: 'BRAND_UNIT_UNQ_NO', name: 'brandUnitUnqNo',
			label: ITP_MSG_LOCALE.label.brandUnitUnqNo,
			width: '10', fixed: false, align: 'center',
			sortable: false, editable: false, edittype: 'text', hidden: true
		},
		{
			index: 'STORE_UNIT_UNQ_NO', name: 'storeUnitUnqNo',
			label: ITP_MSG_LOCALE.label.storeUnitUnqNo,
			width: '10', fixed: false, align: 'center',
			sortable: false, editable: false, edittype: 'text', hidden: true
		},
		{
			index: 'UNIT_GUBUN', name: 'unitGubun',
			label: ITP_MSG_LOCALE.label.unitGubun,
			width: '10', fixed: false, align: 'center',
			sortable: false, editable: false, edittype: 'text', hidden: true
		}
	]
};

/*화면공통 Object*/
let pageObj = {
	init: function() {
		this.ui.init();
		this.event.init();
		this.action();
	},
	action: function () {
		var _this = this;
		// 납품장소 조회 버튼 클릭
		$('#ITP_FORM_RTNMNG01010_SEARCH_WHS_NM').on('click', function() {
			_this.popup();
		});
		// 납품장소 텍스트 삭제 버튼 클릭
		$('#ITP_FORM_RTNMNG01010_DELETE_WHS_NM').on('click', function() {
			$('#ITP_FORM_RTNMNG01010_DETAIL_RTN_WHS_NM').val('');
			$('#ITP_FORM_RTNMNG01010_DETAIL_RTN_WHS_ID').val('');
			$('#ITP_FORM_RTNMNG01010_DETAIL_RTN_LOCATION_NM').val('');
			$('#ITP_FORM_RTNMNG01010_DETAIL_RTN_LOCATION').val('');
			
		});
	},
	popup: function () {
		// 팝업
		var popFn = this.callback.create;
		
		var whsDvsn = "";
		if (fn_make_user_info.get('storeId') == '' ) {
			whsDvsn = "W01";
		} else {
			whsDvsn = "W02";
		}
		
		const key = {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, key, 'S');
		
	},
	callback: {
		create: function(rowDataPop) {
			if(rowDataPop) {
				$('#ITP_FORM_RTNMNG01010_DETAIL_RTN_WHS_NM').val(rowDataPop.whsNm);
				$('#ITP_FORM_RTNMNG01010_DETAIL_RTN_WHS_ID').val(rowDataPop.whsId);
				$('#ITP_FORM_RTNMNG01010_DETAIL_RTN_LOCATION_NM').val(rowDataPop.locationNm);
				$('#ITP_FORM_RTNMNG01010_DETAIL_RTN_LOCATION').val(rowDataPop.location);
			}			
		}
	},
	itp_RTNMNG01010_param: {},  // ==>dwkim 
	itp_RTNMNG01010_search: false,  // ==>dwkim 
	ui: {
		init: function() {
			this.view();
			this.grid();
			this.ready();
		},
		view: function() {
			// 버튼 권한설정
			fn_proc_btn_auth('RTNMNG01010');
			
			// 공통코드 표시
			$('select').each(function() {
				if ($(this).data('select-code')) {
					fn_make_select(CODE_LIST, $(this).data('select-code'), $(this).attr('id'));
				}
			});

			// 조회일자 지정
			//var now = new Date(date.getDate() + 5);
			var now = new Date();
			$('#ITP_TAB_RTNMNG01010 .input-group.date').datepicker(ITP_DATE_LANGUAGE);
			$('#ITP_FORM_RTNMNG01010_DETAIL_COL_REQ_DT').datepicker('setDate', new Date(now.setDate(now.getDate() + 5)));
			
			//납품장소 필드 readonly
			$('#ITP_FORM_RTNMNG01010_DETAIL_WHS_NM').attr('readonly', true);
			$('#ITP_FORM_RTNMNG01010_DETAIL_LOCATION_NM').attr('readonly', true);
					
		},
		grid: function() {
			itp_fn_jqgrid_resize(RTNMNG01010_DETAIL_GRID_ID, RTNMNG01010_DETAIL_GRID_LIST, 'lg');
			
		},
		ready: function() {
			createObj.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_RTNMNG01010_REQ'			: createObj.button.save("RR20"); break;		// 요청
						case 'ITP_BTN_RTNMNG01010_TEMP_SAVE'	: createObj.button.save("RR00"); break;	// 임시저장
						case 'ITP_BTN_RTNMNG01010_DETAIL_ADDROW': pageObj.grid.button.addRow(); break;	// 품목추가
						case 'ITP_BTN_RTNMNG01010_DETAIL_DELROW': pageObj.grid.button.delRow(); break;	// 품목삭제
					}
				});
			});
			
			$('body').on('click', function(e) {
				var gridId = RTNMNG01010_DETAIL_GRID_ID.replace('#', '');
				var rids = $(RTNMNG01010_DETAIL_GRID_ID).jqGrid('getDataIDs');
				var last_row_id = rids[rids.length - 1];
				
				itp_fn_grid_reset_selection(e, last_row_id, gridId, 'RTNMNG01010_DETAIL');	
				
				pageObj.grid.recal();			
			});

		}
	},
	grid: {
		init: function(mode, gridData) {
			this.mode = mode;
			this.gridId = RTNMNG01010_DETAIL_GRID_ID;
			this.unload();  // ==>dwkim 
			this.load(gridData);
		},
		mode: 'DETAIL',
		gridId: '',
		button: {
			addRow: function() {
				// 팝업
				var popFn = function(rowDataPop) {
					// 기존등록 데이터
					var exists = '';
					const rowData = $(RTNMNG01010_DETAIL_GRID_ID).getRowData();
					$.each(rowData, function(key, value) {
						exists = exists + value.brandUnitUnqNo + ';';
					});

					$.each(rowDataPop, function(key, value) {
						if (exists.indexOf(value.brandUnitUnqNo) < 0) {
							value['viewCd'] = "C";
							$(RTNMNG01010_DETAIL_GRID_ID).jqGrid('addRowData', value.brandUnitUnqNo, value, 'last');
						}
					});
					$(RTNMNG01010_DETAIL_GRID_EMPTY).hide();
				};
				const key = {brandId:fn_make_user_info.get('brandId'),storeId:fn_make_user_info.get('storeId')};
				fn_call_popup('biz', 'BIZPOP_ITEM', '#ITP_ASIDE', popFn, key, 'S');  // ==>dwkim 추후 작업 진행  파라메타 설명필요
			},
			delRow: function() {
				itp_fn_grid_del_row(RTNMNG01010_DETAIL_GRID_ID);
				// 그리드 포문으로 금액 재계산후 구매요청금액에 넣어줌
				pageObj.grid.recal();  //==>dwkim 왜 호출이 안될까요
			}
		},
		load: function(gridData) {  // ==>dwkim  오픈시 데이타 가져오는 부분 넣으면 되는건지 여부 gird가 아님
			var _this = this;
			var option = {
				gridId: this.gridId,
				colModel: gridColModel.detail,
				data: gridData,
				multiselect: true,
				// cellEdit: true,
				onCellSelect: function(rowId, cellIdx, cellValue) {
					RTNMNG01010_DETAIL_GRID_LAST_ROW_ID = itp_fn_set_data_editable(rowId, cellIdx, RTNMNG01010_DETAIL_GRID_LAST_ROW_ID, RTNMNG01010_DETAIL_GRID_ID, ['pchReqQty']);
		   		},
				loadComplete: function(data) {
					_this.clearData();
				}
			};
			itp_fn_grid_make_local(option);
		},
		clearData: function() {
			$(RTNMNG01010_DETAIL_GRID_ID).jqGrid('clearGridData', true);
			$(RTNMNG01010_DETAIL_GRID_LIST).find('.ui-jqgrid .ui-jqgrid-bdiv').css('overflow-x', 'hidden');
			$(RTNMNG01010_DETAIL_GRID_LIST).find('.ui-jqgrid-bdiv').css('min-height', '100px');
			$(RTNMNG01010_DETAIL_GRID_EMPTY).html(ITP_MSG_LOCALE.message.grid.noData);
			$(RTNMNG01010_DETAIL_GRID_EMPTY).show();
		},
		recal: function() {
			
			var ids = $(RTNMNG01010_DETAIL_GRID_ID).getDataIDs();
			$.each(ids, function(idx, rowId) {
				
				var viewCd = jQuery(RTNMNG01010_DETAIL_GRID_ID).jqGrid('getCell', rowId, 'viewCd');
				var unitAmt = jQuery(RTNMNG01010_DETAIL_GRID_ID).jqGrid('getCell', rowId, 'unitAmt');
				var rtnQty = jQuery(RTNMNG01010_DETAIL_GRID_ID).jqGrid('getCell', rowId, 'rtnQty');
				
				if(viewCd != 'D' && unitAmt != null && unitAmt != '' && rtnQty != null && rtnQty != '') {		
					jQuery(RTNMNG01010_DETAIL_GRID_ID).jqGrid('setRowData',rowId,{rtnAmt: parseInt(unitAmt)*parseInt(rtnQty)});
				}
			});
			
			const rowData = $(RTNMNG01010_DETAIL_GRID_ID).getRowData();
			var pchReqAmt = 0 ;
			$.each(rowData, function(key, value) {
				// console.log(JSON.stringify(rowData));
				if (value.pchReqAmt != null && value.pchReqAmt != "" && value.viewCd != "D") {
					pchReqAmt = pchReqAmt + parseInt(value.pchReqAmt) ;
				}				
			});
			$('#ITP_FORM_RTNMNG01010_DETAIL .fnPchReqAmt').text(itp_fn_number_comma(pchReqAmt));
		},
		unload: function() {
			$.jgrid.gridUnload(this.gridId);
		}
	}
};

/*신규화면 Object*/
let createObj = {
	init: function() {
		$('#ITP_FORM_RTNMNG01010_DETAIL_BRAND_ID').val(fn_make_user_info.get('brandId'));
		$('#ITP_FORM_RTNMNG01010_DETAIL_STORE_ID').val(fn_make_user_info.get('storeId'));
		// 매장에서 로그인하는 경우
		if(fn_make_user_info.get('storeId') != '') {
			$('#ITP_FORM_RTNMNG01010_SEARCH_WHS_NM').hide();
			$('#ITP_FORM_RTNMNG01010_DELETE_WHS_NM').hide();
		} else {
			$('#ITP_FORM_RTNMNG01010_SEARCH_WHS_NM').show();
			$('#ITP_FORM_RTNMNG01010_DELETE_WHS_NM').show();
		}
		//let param = 'brandId=' + LOGIN_USER_INFO.brandId + "&spplyId=" + LOGIN_USER_INFO.spplyId;
		this.load();
	},
	newinit: function() {
		$('#ITP_FORM_RTNMNG01010_DETAIL_BRAND_ID').val(fn_make_user_info.get('brandId'));
		$('#ITP_FORM_RTNMNG01010_DETAIL_STORE_ID').val(fn_make_user_info.get('storeId'));
		$('#ITP_FORM_RTNMNG01010_DETAIL_NOTE').val('');
		
		var now = new Date();
		$('#ITP_TAB_RTNMNG01010 .input-group.date').datepicker(ITP_DATE_LANGUAGE);
		$('#ITP_FORM_RTNMNG01010_DETAIL_COL_REQ_DT').datepicker('setDate', new Date(now.setDate(now.getDate() + 5)));
		
		this.load();  //==>dwkim 초기화 하여 다시 초기 데이타 가져와 뿌려줌
		const key = {brandId:fn_make_user_info.get('brandId'),storeId:fn_make_user_info.get('storeId')};
		fn_ajax_call(API_DETAIL_INIT_INFO, key, this.callback, 'GET');
	},
	button: {
		save: function(arg) {
			$('body').trigger('click');
			
			const formId = '#ITP_FORM_RTNMNG01010_DETAIL';
			itp_fn_form_clear_validate(null, formId);
			$('#ITP_FORM_RTNMNG01010_DETAIL_RTN_REQ_ST_CD').val(arg);
			
			if (itp_fn_form_event.isValid(formId)) {
				// 품목대상 정보 확인 필요
				var records = $(RTNMNG01010_DETAIL_GRID_ID).getGridParam('reccount');
				if (records == 0) {
					itp_fn_modal_alert( "요청할 품목내역이 없습니다.");
					return ;
				}		
				
				
				//반품창고 입력 여부 체크
				/*
				var whsId = $('#ITP_FORM_RTNMNG01010_DETAIL_RTN_WHS_ID').val();
				var location = $('#ITP_FORM_RTNMNG01010_DETAIL_RTN_LOCATION').val();
				
				if (whsId == '' || location == '') {
					alert("반품장소를 선택해주세요!");
					return;
				}
				*/
				
				
				var now = new Date();
				var today = now.getFullYear() +
							"." + (now.getMonth()+1 > 9 ? (now.getMonth()+1).toString() : "0" + (now.getMonth()+1).toString()) +
							"." + (now.getDate() > 9 ? now.getDate().toString() : "0" + now.getDate().toString());
				
				var colReqDt = $('#ITP_FORM_RTNMNG01010_DETAIL_COL_REQ_DT').val();
				if (today > colReqDt) {
					alert("수거요청일은 오늘 이후이어야 합니다.");
					return;
				}	
				
				
				
				const rowData = $(RTNMNG01010_DETAIL_GRID_ID).getRowData();
				
				var rtnQtyCheck = true;
				var rtnDvsnCheck = true;
				var rtnRsnDvsnCheck = true;
				var rtnRsnCheck = true;
				
				$.each(rowData, function(key, value) {					
					if(value.rtnQty == '') {
						rtnQtyCheck = false;
					}
					if(value.rtnDvsn == '') {
						rtnDvsnCheck = false;
					}
					if(value.rtnRsnDvsn == '') {
						rtnRsnDvsnCheck = false;
					}
					if(value.rtnRsn == '') {
						rtnRsnCheck = false;
					}
				});
				
				if(rtnQtyCheck == false) {
					itp_fn_modal_alert( "반품수량을 입력하세요.");
					return;
				}		
				if(rtnDvsnCheck == false) {
					itp_fn_modal_alert( "반품구분을 입력하세요.");
					return;
				}
				if(rtnRsnDvsnCheck == false) {
					itp_fn_modal_alert( "사유구분을 입력하세요.");
					return;
				}
				if(rtnRsnCheck == false) {
					itp_fn_modal_alert( "반품사유를 입력하세요.");
					return;
				}
				
				var saveReq = {
				callBack: function(args) {
						$(formId).val(arg);
						let gridInsertData = [];
						let gridUpdateData = [];
						let gridDeleteData = [];
						
						const rowData = $(RTNMNG01010_DETAIL_GRID_ID).getRowData();
						
						$.each(rowData, function(key, value) {
							if (value.viewCd !== 'R') {
								if (value.viewCd === 'C') {
									gridInsertData.push(value);
								} else if (value.viewCd === 'U') {
									gridUpdateData.push(value);
								} else if (value.viewCd === 'D') {
									gridDeleteData.push(value);
								}
							}
						});						
						
						let param = $(formId).serializeObject();
						param.gridInsertData = gridInsertData;
						param.gridUpdateData = gridUpdateData;
						param.gridDeleteData = gridDeleteData;
						
						var searhFn = function() {
							createObj.newinit();
						};
						fn_ajax_call(API_DETAIL_SAVE, JSON.stringify(param), searhFn, 'POST');				
					}
				};
				if (arg == 'RR20') {
					itp_fn_modal_confirm('반품 요청하시겠습니까?', saveReq, null);
				} else {
					itp_fn_modal_confirm(ITP_MSG_LOCALE.message.ajax.tmpSave, saveReq, null);
				}
			}
		}
	},
	load: function() {
		const key = {brandId:fn_make_user_info.get('brandId'), storeId:fn_make_user_info.get('storeId')};
		fn_ajax_call(API_DETAIL_INIT_INFO, key, this.callback, 'GET');
	},
	callback: function(result) {
		$('#ITP_FORM_RTNMNG01010_DETAIL #ITP_FORM_RTNMNG01010_DETAIL_VIEW_CD').val('C');

		$('#ITP_FORM_RTNMNG01010_DETAIL #ITP_FORM_RTNMNG01010_DETAIL_BRAND_ID').val(result.brandId);
		$('#ITP_FORM_RTNMNG01010_DETAIL #ITP_FORM_RTNMNG01010_DETAIL_STORE_ID').val(result.storeId);		
		$('#ITP_FORM_RTNMNG01010_DETAIL #ITP_FORM_RTNMNG01010_DETAIL_REQ_DEPT').val(result.reqDept);
		$('#ITP_FORM_RTNMNG01010_DETAIL #ITP_FORM_RTNMNG01010_DETAIL_AUTH_TP_CD').val(result.authTpCd);
		$('#ITP_FORM_RTNMNG01010_DETAIL #ITP_FORM_RTNMNG01010_DETAIL_WHS_DVSN').val(result.whsDvsn);
		$('#ITP_FORM_RTNMNG01010_DETAIL #ITP_FORM_RTNMNG01010_DETAIL_RTN_WHS_ID').val(result.rtnWhsId);
		$('#ITP_FORM_RTNMNG01010_DETAIL #ITP_FORM_RTNMNG01010_DETAIL_RTN_WHS_NM').val(result.rtnWhsNm);
		$('#ITP_FORM_RTNMNG01010_DETAIL #ITP_FORM_RTNMNG01010_DETAIL_RTN_LOCATION').val(result.rtnLocation);
		$('#ITP_FORM_RTNMNG01010_DETAIL #ITP_FORM_RTNMNG01010_DETAIL_RTN_LOCATION_NM').val(result.rtnLocationNm);
		
		$('#ITP_FORM_RTNMNG01010_DETAIL .fnBrandNm').text(result.brandNm);

		pageObj.grid.init();
	}
};
