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

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

/*화면 변수*/
const POMNG02010_GRID_ID = '#ITP_POMNG02010_jqGrid';
const POMNG02010_GRID_LIST = '#ITP_POMNG02010_jqGrid_list';
const POMNG02010_GRID_PAGER = '#ITP_POMNG02010_jqGridPager';
const POMNG02010_GRID_EMPTY = '#ITP_POMNG02010_jqGridEmpty';

const POMNG02010_VIEW_GRID_ID = '#ITP_POMNG02010_VIEW_jqGrid';
const POMNG02010_VIEW_GRID_LIST = '#ITP_POMNG02010_VIEW_jqGrid_list';
const POMNG02010_VIEW_GRID_PAGER = '#ITP_POMNG02010_VIEW_jqGridPager';
const POMNG02010_VIEW_GRID_EMPTY = '#ITP_POMNG02010_VIEW_jqGridEmpty';

const POMNG02010_DETAIL_GRID_ID = '#ITP_POMNG02010_DETAIL_jqGrid';
const POMNG02010_DETAIL_GRID_LIST = '#ITP_POMNG02010_DETAIL_jqGrid_list';
const POMNG02010_DETAIL_GRID_PAGER = '#ITP_POMNG02010_DETAIL_jqGridPager';
const POMNG02010_DETAIL_GRID_EMPTY = '#ITP_POMNG02010_DETAIL_jqGridEmpty';

//let ITP_FORM_POMNG02010_DETAIL_IS_DUPLICATE = false;
let ITP_FORM_POMNG02010_DETAIL_IS_WRITING = false;

let POMNG02010_GRID_LAST_ROW_ID;
let SCREEN_MODE;


//let ITP_COMMON_ASSGN_TASK = fn_make_common_cd_list(CODE_LIST, 'ASSGN_TASK', true, '담당업무');

/*API URL*/
let API_DETAIL_GRID_LIST 	= '/api/pomng/detail-grid-list';	// 목록
let API_DETAIL_INFO 		= '/api/pomng/info-pchReq';			// 상세
let API_DETAIL_SAVE 		= '/api/pomng/save-pchReq';			// 저장
//let API_INTI_PW				= '/api/spply/inti-spplyPw';		// 패스워드 초기화
//let API_POP_GRID_LIST 		= '/api/spply/pop-grid-list';		// 공급사 팝업 그리드 리스트

/*화면 Grid ColModel*/
const gridColModel = {
	list: [
		{
			index: 'BRAND_ID', name: 'brandId',
			label: ITP_MSG_LOCALE.label.brandId, //브랜드ID
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: true
		},
		{
			index: 'BRAND_NM', name: 'brandNm',
			label: ITP_MSG_LOCALE.label.brandNm, //브랜드명
			width: '13', fixed: false, align: 'left',
			minwidth: 120,
			sortable: false, hidden: false, classes: 'ui-ellipsis'
		},
		{
			index: 'STORE_ID', name: 'storeId',
			label: ITP_MSG_LOCALE.label.storeId, //매장아이디
			width: '13', fixed: false, align: 'center',
			sortable: false, hidden: true
		},
		{
			index: 'REQ_TYPE_NM', name: 'reqTypeNm',
			label: ITP_MSG_LOCALE.label.reqTypeNm, //요청구분
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'PCH_REQ_UNQ_NO', name: 'pchReqUnqNo',
			label: ITP_MSG_LOCALE.label.pchReqUnqNo, //구매요청번호
			width: '10', fixed: false, align: 'center',
			minwidth: 120,
			sortable: false, hidden: false
		},
		{
			index: 'PCH_REQ_NM', name: 'pchReqNm',
			label: ITP_MSG_LOCALE.label.pchReqNm, //구매요청명
			width: '13', fixed: false, align: 'left',
			minwidth: 200,
			sortable: false, hidden: false, classes: 'ui-ellipsis'
		},
		{
			index: 'PCH_REQ_ST_CD', name: 'pchReqStCd',
			label: ITP_MSG_LOCALE.label.pchReqStCd, //구매요청상태
			width: '15', fixed: false, align: 'center',
			sortable: false, hidden: true
		},
		{
			index: 'PCH_REQ_ST_NM', name: 'pchReqStNm',
			label: ITP_MSG_LOCALE.label.pchReqStNm, //구매요청상태명
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'PCH_REQ_DT', name: 'pchReqDt',
			label: ITP_MSG_LOCALE.label.pchReqDt, //구매요청일
			width: '10', fixed: false, align: 'center',
			minwidth: 100,
			sortable: false, hidden: false
		},
		{
			index: 'PCH_REQ_ITEM_QTY', name: 'pchReqItemQty',
			label: ITP_MSG_LOCALE.label.pchReqItemQty, //요청품목수
			width: '10', fixed: false, align: 'right',
			sortable: false, hidden: false,
			formatter: 'integer', formatoptions: { defaultValue: '', thousandsSeparator: ',' }
		},
		{
			index: 'PCH_REQ_TOTAL_AMT', name: 'pchReqTotalAmt',
			label: ITP_MSG_LOCALE.label.pchReqTotalAmt, //요청금액
			width: '10', fixed: false, align: 'right',
			sortable: false, hidden: false,
			formatter: 'integer', formatoptions: { defaultValue: '', thousandsSeparator: ',' }
		},
		{
			index: 'PCH_REQ_RJCT_DT', name: 'pchReqRjctDt',
			label: ITP_MSG_LOCALE.label.pchReqRjctDt, //반려일자
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'PCH_REQ_RJCT_NM', name: 'pchReqRjctNm',
			label: ITP_MSG_LOCALE.label.pchReqRjctNm, //반려자
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'PCH_REQ_MGR_NM', name: 'pchReqMgrNm',
			label: ITP_MSG_LOCALE.label.pchReqMgrNm, //구매요청자명
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'DLV_REQ_DT', name: 'dlvReqDt',
			label: ITP_MSG_LOCALE.label.dlvReqDt, //납품요청일
			width: '10', fixed: false, align: 'center',
			minwidth: 100,
			sortable: false, hidden: false
		},
		{
			index: 'WHS_LOCATION_NM', name: 'whsLocationNm',
			label: ITP_MSG_LOCALE.label.whsLocationNm, //납품창고
			width: '10', fixed: false, align: 'left',
			minwidth: 200,
			sortable: false, hidden: false, classes: 'ui-ellipsis'
		}
	],
	detail: [
		{
			index: 'VIEW_CD', name: 'viewCd',
			label: ITP_MSG_LOCALE.label.viewCd,
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: true
		},
		{
			index: 'PCH_REQ_UNQ_NO', name: 'pchReqUnqNo',
			label: ITP_MSG_LOCALE.label.pchReqUnqNo
			, //구매요청번호
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: true
		},
		{
			index: 'PCH_REQ_Dtl_NO', name: 'pchReqDtlNo',
			label: ITP_MSG_LOCALE.label.pchReqDtlNo
			, //구매요청상세번호
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: true
		},
		{
			index: 'ITEM_ID', name: 'itemId',
			label: ITP_MSG_LOCALE.label.itemId,
			width: '20', 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: '30', fixed: false, align: 'left',
			sortable: true, editable: false, edittype: 'text',
			editrules: { required: true }
		},
		{
			index: 'UNIT', name: 'unit',
			label: ITP_MSG_LOCALE.label.unit,
			width: '10', fixed: false, align: 'center',
			sortable: false, editable: false, edittype: 'text'
		},
		{
			index: 'UNIT_AMT', name: 'unitAmt',
			label: ITP_MSG_LOCALE.label.unitAmt,
			width: '10', fixed: false, align: 'right',
			sortable: false, editable: false, edittype: 'text', hidden: false,
			formatter:'integer', formatoptions: { defaultValue: '', thousandsSeparator: ',' },
			editoptions: {"onKeyup": "this.value=this.value.replace(/[^0-9]/g,'');"}
		},
		{
			index: 'PCH_REQ_QTY', name: 'pchReqQty',
			label: ITP_MSG_LOCALE.label.pchReqQty, //단가
			width: '10', fixed: false, align: 'right',
			classes: 'input_color',
			sortable: true, editable: true, edittype: 'text',
			editrules: {required: true, number:true},
			formatter:'integer',formatoptions: { defaultValue: '', thousandsSeparator: ',' },
			editoptions: {"onKeyup": "this.value=this.value.replace(/[^0-9]/g,'');"}
		},
		{
			index: 'PCH_REQ_AMT', name: 'pchReqAmt',
			label: ITP_MSG_LOCALE.label.pchReqAmt,
			width: '10', fixed: false, align: 'right',			
			sortable: false, editable: false, edittype: 'text', hidden: false,
			formatter:'integer',formatoptions: { defaultValue: '', thousandsSeparator: ',' }
		},
		{
			index: 'PCH_REQ_DTL_ST_NM', name: 'pchReqDtlStNm',
			label: ITP_MSG_LOCALE.label.pchReqDtlStNm,
			width: '10', fixed: false, align: 'center',
			sortable: false, editable: false, edittype: 'text', hidden: false
		},
		{
			index: 'PCH_REQ_DTL_ST_CD', name: 'pchReqDtlStCd',
			label: ITP_MSG_LOCALE.label.pchReqDtlStNm,
			width: '10', fixed: false, align: 'right',
			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();
	},
	itp_POMNG02010_param: {},
	itp_POMNG02010_search: false,
	ui: {
		init: function () {
			this.view();
			//this.form();
			this.grid();
			this.ready();
		},
		view: function() {
			// 버튼 권한설정
			fn_proc_btn_auth('POMNG02010');

			// 공통코드 표시
			$('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_POMNG02010 .input-group.date').datepicker(ITP_DATE_LANGUAGE);
			$('#ITP_FORM_POMNG02010_SEARCH_FROM_DT').datepicker('setDate', new Date(now.setDate(now.getDate()-30)));
			$('#ITP_FORM_POMNG02010_SEARCH_TO_DT').datepicker('setDate', new Date(now.setDate(now.getDate()+30)));
			
			
		},
		/*
		form: function() {
			itp_fn_form_event.onKeyup('#ITP_FORM_POMNG02010_DETAIL');
		},
		*/
		grid: function() {
			itp_fn_jqgrid_resize(POMNG02010_GRID_ID, POMNG02010_GRID_LIST, 'lg');
			
		},
		ready: function() {
			listObj.init();
		}
	},
	action: function () {
		var _this = this;
		// 납품장소 조회 버튼 클릭
		$('#ITP_FORM_POMNG02010_SSEARCH_SWHS_NM').on('click', function() {
			console.log("=================================");
			_this.popup('S');
		});
		// 납품장소 텍스트 삭제 버튼 클릭
		$('#ITP_FORM_POMNG02010_SDELETE_SWHS_NM').on('click', function() {
			console.log("=================================");
			$('#ITP_FORM_POMNG02010_SEARCH_SWHS_NM').val('');
			$('#ITP_FORM_POMNG02010_SEARCH_SWHS_ID').val('');
			
		});
		
		// 수정 화면에서의 납품장소 조회 버튼 클릭
		$('#ITP_FORM_POMNG02010_SEARCH_WHS_NM').on('click', function() {
			console.log("=================================");
			_this.popup('U');
		});
		// 납품장소 텍스트 삭제 버튼 클릭
		$('#ITP_FORM_POMNG02010_DELETE_WHS_NM').on('click', function() {
			console.log("=================================");
			$('#ITP_FORM_POMNG02010_DETAIL_WHS_NM').val('');
			$('#ITP_FORM_POMNG02010_DETAIL_WHS_ID').val('');
			$('#ITP_FORM_POMNG02010_DETAIL_LOCATION_NM').val('');
			$('#ITP_FORM_POMNG02010_DETAIL_LOCATION').val('');
			
		});
		
	},
	popup: function (arg) {
		var popFn ;
		// 팝업
		var whsDvsn = "";
		if (arg == "S") {
			popFn = this.callback.create;
			
			if (fn_make_user_info.get('storeId') == '' ) {
				whsDvsn = "";
			} else {
				whsDvsn = "W02";
			}
		} else {
			popFn = this.callback.modify;
			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) {
			console.log(rowDataPop);
			if(rowDataPop) {
				$('#ITP_FORM_POMNG02010_SEARCH_SWHS_NM').val(rowDataPop.whsNm);
				$('#ITP_FORM_POMNG02010_SEARCH_SWHS_ID').val(rowDataPop.whsId);
			}
			
		},
		modify: function(rowDataPop) {
			console.log(rowDataPop);
			if(rowDataPop) {
				$('#ITP_FORM_POMNG02010_DETAIL_WHS_NM').val(rowDataPop.whsNm);
				$('#ITP_FORM_POMNG02010_DETAIL_WHS_ID').val(rowDataPop.whsId);
				$('#ITP_FORM_POMNG02010_DETAIL_LOCATION_NM').val(rowDataPop.locationNm);
				$('#ITP_FORM_POMNG02010_DETAIL_LOCATION').val(rowDataPop.location);
			}
			
		}
	},
	event: {
		init: function () {
			this.button();
		},
		button: function () {
			// 버튼 클릭 이벤트
			$('button').each(function() {
				var id = $(this).attr('id');
				$(this).on('click', function() {
					switch (id) {
						case 'ITP_BTN_POMNG02010_SRH'					: listObj.button.search();		break;	// 조회 버튼 클릭
						//case 'ITP_BTN_POMNG02010_NEWREG'				: listObj.button.create(); 		break;	// 신규등록 버튼
						case 'ITP_BTN_POMNG02010_MODIFY'				: modifyObj.button.modify();	break;	// 수정 버튼
						case 'ITP_BTN_POMNG02010_CANCELLIST'			: modifyObj.button.cancel(); 	break;	// 취소/목록 버튼
						case 'ITP_BTN_POMNG02010_REQ'					: modifyObj.button.save("PR20"); break;	// 구매요청
						case 'ITP_BTN_POMNG02010_SAVE'					: modifyObj.button.save("PR00"); break;	// 임시저장
						case 'ITP_BTN_POMNG02010_DETAIL_ADDROW'			: pageObj.grid.button.addRow(); break;	// 품목추가
						case 'ITP_BTN_POMNG02010_DETAIL_DELROW'			: pageObj.grid.button.delRow(); break;	// 품목삭제
						case 'ITP_BTN_POMNG02010_EXCEL'					: listObj.excelDown(); 			break;	// 엑셀 다운로드 버튼
					}
				});
			});
			
			$('body').on('click', function(e) {
				var gridId = POMNG02010_DETAIL_GRID_ID.replace('#', '');
				var rids = $(POMNG02010_DETAIL_GRID_ID).jqGrid('getDataIDs');
				var last_row_id = rids[rids.length - 1];
				
				itp_fn_grid_reset_selection(e, last_row_id, gridId, 'POMNG02010_DETAIL');	
				
				pageObj.grid.recal();
			});

			
		}
	},
	switchScreen: function(mode) {
		$('.itp_det_head').find('button[id^="ITP_BTN_POMNG02010_"]').each(function(i) {
			$(this).hide();
		});
		$('#ITP_TAB_POMNG02010').find('div[id$="_CONTAINER"]').each(function(i) {
			$(this).hide();
		});
		if(mode == 'LIST') { // 목록
			itp_fn_fire_window_resize();
			fn_show_btn_auth_array(['#ITP_BTN_POMNG02010_SRH', '#ITP_BTN_POMNG02010_NEWREG']);
			$('#ITP_AJAX_POMNG02010_LIST_CONTAINER').show();
			$('#ITP_FORM_POMNG02010_DETAIL_SBRAND_ID').val(fn_make_user_info.get('brandId'));
			$('#ITP_FORM_POMNG02010_DETAIL_SSTORE_ID').val(fn_make_user_info.get('storeId'));
			$('#ITP_BTN_POMNG02010_EXCEL').show();
			SCREEN_MODE = 'LIST' ;
		} else if(mode == 'ADD') { // 등록
			fn_show_btn_auth_array(['#ITP_BTN_POMNG02010_CANCELLIST', '#ITP_BTN_POMNG02010_SAVE']);
			$('#ITP_AJAX_POMNG02010_DETAIL_CONTAINER').show();

			$('#ITP_FORM_POMNG02010_DETAIL').find('input, textarea, select, checkbox').each(function(i, elem) {
				$(this).attr('id') === 'ITP_FORM_POMNG02010_DETAIL_VIEW_CD' ? $(this).val('C') : $(this).val('');
				if(elem.type === 'select') {
					$(this).val('').prop('selected', true);
				}
			});
			SCREEN_MODE = 'DETAIL' ;
			
		} else if(mode == 'MODIFY') { // 수정
			fn_show_btn_auth_array(['#ITP_BTN_POMNG02010_CANCELLIST', '#ITP_BTN_POMNG02010_SAVE', '#ITP_BTN_POMNG02010_REQ']);
			
			$('#ITP_AJAX_POMNG02010_DETAIL_CONTAINER').show();
			$('#ITP_FORM_POMNG02010_DETAIL .itp_form_info').show();
			$('#ITP_FORM_POMNG02010_DETAIL .itp_form_change').hide();
			SCREEN_MODE = 'DETAIL' ;
		} else if(mode == 'VIEW') { // 보기
			fn_show_btn_auth_array(['#ITP_BTN_POMNG02010_MODIFY', '#ITP_BTN_POMNG02010_CANCELLIST']);
			$('#ITP_AJAX_POMNG02010_VIEW_CONTAINER').show();
			SCREEN_MODE = 'VIEW' ;
		}
	},
	grid: {
		init: function(mode, gridRows) {
			console.log(mode);
			this.gridId = (mode === 'VIEW') ? POMNG02010_VIEW_GRID_ID : POMNG02010_DETAIL_GRID_ID;
			this.gridList = (mode === 'VIEW') ? POMNG02010_VIEW_GRID_LIST : POMNG02010_DETAIL_GRID_LIST;
			this.gridEmpty = (mode === 'VIEW') ? POMNG02010_VIEW_GRID_EMPTY : POMNG02010_DETAIL_GRID_EMPTY;
			this.gridRows = gridRows;
			this.unload();
			this.load(mode, gridRows);
		},
		
		gridId: '',
		gridList: '',
		gridEmpty: '',
		gridRows: '',
		button: {
			addRow: function() {
				// 팝업
				var popFn = function(rowDataPop) {
					console.log(rowDataPop);
					// 기존등록 데이터
					var exists = '';
					const rowData = $(POMNG02010_DETAIL_GRID_ID).getRowData();
					$.each(rowData, function(key, value) {
						if (value.viewCd != "D") {
							exists = exists + value.brandUnitUnqNo + ';';	
						}
					});

					$.each(rowDataPop, function(key, value) {
						if (exists.indexOf(value.brandUnitUnqNo) < 0 && value.podrPssblDvsn == 'PO01') {
							value['viewCd'] = "C";
							$(POMNG02010_DETAIL_GRID_ID).jqGrid('addRowData', value.brandUnitUnqNo, value, 'last');
						}
					});
					$(POMNG02010_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(POMNG02010_DETAIL_GRID_ID);
				pageObj.grid.recal();
			}
		},
		load: function(mode, gridRows) {
			var _this = this;
			var option = {
				gridId: _this.gridId,
				colModel: gridColModel.detail,
				data: gridRows,
				multiselect: true,
				//cellEdit: (mode !== 'VIEW'),
				loadComplete: function(data) {
					//console.log(data);
					//$(_this.gridList).find('.ui-jqgrid .ui-jqgrid-bdiv').css('overflow-x', 'hidden');
					//(Array.isArray(data.rows) && data.rows.length === 0) ? $(_this.gridEmpty).show() : $(_this.gridEmpty).hide();
					$(_this.mode === 'VIEW' ? POMNG02010_VIEW_GRID_LIST : POMNG02010_DETAIL_GRID_LIST).find('.ui-jqgrid .ui-jqgrid-bdiv').css('overflow-x', 'hidden');
					data.records === 0 ? _this.clearData() : $(_this.mode === 'VIEW' ? POMNG02010_VIEW_GRID_EMPTY : POMNG02010_DETAIL_GRID_EMPTY).hide();
				},
				onCellSelect: function(rowid, cellIdx, cellValue) {
					if(mode !== 'VIEW') {
						POMNG02010_GRID_LAST_ROW_ID = itp_fn_set_data_editable(rowid, cellIdx, POMNG02010_GRID_LAST_ROW_ID, POMNG02010_DETAIL_GRID_ID, ['pchReqUnqNo']);
					}
				}
			};
			itp_fn_grid_make_local(option);
		},
		recal: function() {
			console.log("recal call");
			if (SCREEN_MODE === 'DETAIL') {
				var ids = $(POMNG02010_DETAIL_GRID_ID).getDataIDs();
				$.each(ids, function(idx, rowId) {
					console.log("recal start");
					var viewCd = jQuery(POMNG02010_DETAIL_GRID_ID).jqGrid('getCell', rowId, 'viewCd');
					var unitAmt = jQuery(POMNG02010_DETAIL_GRID_ID).jqGrid('getCell', rowId, 'unitAmt');
					var pchReqQty = jQuery(POMNG02010_DETAIL_GRID_ID).jqGrid('getCell', rowId, 'pchReqQty');
					
					if(viewCd != 'D' && unitAmt != null && unitAmt != '' && pchReqQty != null && pchReqQty != '') {		
						jQuery(POMNG02010_DETAIL_GRID_ID).jqGrid('setRowData',rowId,{pchReqAmt: parseInt(unitAmt)*parseInt(pchReqQty)});
					}
				});
				
				const rowData = $(POMNG02010_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_POMNG02010_DETAIL .fnPchReqTotalAmt').text(itp_fn_number_comma(pchReqAmt));
			}			
		},
		clearData : function() {
			$(this.gridId).jqGrid('clearGridData', true);
			$(this.mode === 'VIEW' ? POMNG02010_VIEW_GRID_LIST : POMNG02010_DETAIL_GRID_LIST).find('.ui-jqgrid-bdiv').css('min-height', '100px');
			$(this.mode === 'VIEW' ? POMNG02010_VIEW_GRID_EMPTY : POMNG02010_DETAIL_GRID_EMPTY).html(ITP_MSG_LOCALE.message.grid.noData);
			$(this.mode === 'VIEW' ? POMNG02010_VIEW_GRID_EMPTY : POMNG02010_DETAIL_GRID_EMPTY).show();
		},
		unload : function() {
			$.jgrid.gridUnload(this.gridId);
		}
		
	}
	
};

/*목록화면 Object*/
let listObj = {
	init: function () {
		this.grid.init();
	},
	itp_POMNG02010_search: false,
	button: {
		search: function() {
			listObj.itp_POMNG02010_search = true;
			let param = $('#ITP_FORM_POMNG02010_SEARCH').serializeObject();
			param.gridSize = $.jgrid.defaults.rowNum;
			param.gridPage = $.jgrid.defaults.page;
			console.log(param);
			$(POMNG02010_GRID_ID).data('grid-param',param);
			$(POMNG02010_GRID_ID).setGridParam({'postData': JSON.stringify(param)}).trigger('reloadGrid');
		},
		create: function() {
			if(!fn_make_user_info.isEmpty()) {
				//createObj.init();
			}
		}
	},
	empty: {
		init: function() {
			
		},
		itp_POMNG02010_param: {},
		push: function() {
			
		},
		back: function() {
			
		}
	},
	grid: {
		init: function () {
			// 데이터 없을때
			//itp_fn_jqgrid_resize(POMNG02010_GRID_ID, POMNG02010_GRID_LIST, 'lg');
			//itp_fn_fire_window_resize();
			//this.reload();
			this.search();
		},
		colModel: gridColModel.list,
		search: function() {
			pageObj.switchScreen('LIST');
			this.unload();
			this.load();
		},
		load: function() {
			let param = $('#ITP_FORM_POMNG02010_SEARCH').serializeObject();
			param.gridSize = $.jgrid.defaults.rowNum;
			param.sbrandId = fn_make_user_info.get('brandId');
			param.sstoreId = fn_make_user_info.get('storeId');
			var option = {
				gridId: POMNG02010_GRID_ID,
				colModel: gridColModel.list,
				//autowidth: true,
				//shrinkToFit:false, 
				param: param,
				url: DOMAIN + API_DETAIL_GRID_LIST,
				pager: POMNG02010_GRID_PAGER,
				multiselect: true,
				rownumbers: false,
				onCellSelect: function(rowId, cellIdx, cellValue) {
					var cm = $(this).jqGrid('getGridParam', 'colModel');
					var colNm = cm[cellIdx].name;
					if (colNm == 'pchReqUnqNo') {
						const selectVal = $(this).jqGrid('getCell', rowId, 'pchReqUnqNo');
						const key = {brandId:fn_make_user_info.get('brandId'), pchReqUnqNo: selectVal, viewCd: 'R'};
						var param = $.param(key);
						viewObj.init(param);
					}
				},
				loadComplete: function(data) {
					console.log(data);
					itp_fn_grid_load_complete(data, POMNG02010_GRID_ID, true, 'number', 'POMNG02010', listObj.itp_POMNG02010_search, listObj.empty, true, data.gridRecords, true);
					var ids = $(POMNG02010_GRID_ID).getDataIDs();
					$.each(ids, function(idx, rowId) {
						$(POMNG02010_GRID_ID).jqGrid('setCell', rowId, 'pchReqUnqNo', '', ITP_GRID_COL_STYLE.link);
					});
				},
				onPaging: function(action) {
					/*
					var pagingFn = {
						callBack: function(args) {
							$(args).trigger('reloadGrid');
						}
					};
					if (itp_fn_check_grid_is_writing(POMNG02010_DETAIL_GRID_ID)) {
						itp_fn_modal_confirm(ITP_MSG_LOCALE.message.ajax.cancelData, pagingFn, POMNG02010_DETAIL_GRID_ID);
						return 'stop';
					} else {
						itp_fn_grid_paging(POMNG02010_DETAIL_GRID_ID, action, param);
					}
					*/
					
					itp_fn_grid_paging(POMNG02010_GRID_ID, action, param);
				}
			};
			
			itp_fn_grid_make_remote(option);
		},
		/*
		reload : function() {
			var _this = this;
			$(POMNG02010_GRID_EMPTY).off('click').on('click', function() {
				pageObj.itp_OPER03010_param.gridSize = $.jgrid.defaults.rowNum;
				$(POMNG02010_GRID_ID).setGridParam({'postData': JSON.stringify(pageObj.itp_POMNG02010_param)}).trigger('reloadGrid');
			});
		},
		*/
		clearData : function() {
			$(POMNG02010_GRID_ID).jqGrid('clearGridData', true);
			$(POMNG02010_GRID_LIST).find('.ui-jqgrid-bdiv').css('min-height', '100px');
			$(POMNG02010_GRID_EMPTY).html(ITP_MSG_LOCALE.message.grid.noData);
			$(POMNG02010_GRID_EMPTY).show();
		},
		unload : function() {
			$.jgrid.gridUnload(POMNG02010_GRID_ID);
		}
	},
	excelDown: function() {
		
		var param = {
			'url': API_DETAIL_GRID_LIST,
			'param': $('#ITP_FORM_POMNG02010_SEARCH').serializeObject(),
			'gridColumns': $(POMNG02010_GRID_ID).jqGrid('getGridParam', 'colModel'),
			'fileName': '구매요청현황.xlsx',
			'sheetName': '구매요청리스트'
		};
		itp_fn_remote_to_excel(param);
	}
};

/*상세화면 Object*/
let viewObj = {
	init: function (param) {
		this.load(param);
	},
	load: function(param) {
		fn_ajax_call(API_DETAIL_INFO, param, this.callback, 'GET');
	},
	callback: function (result) {
		console.log(result);
		pageObj.switchScreen('VIEW');
		$('#ITP_FORM_POMNG02010_VIEW #ITP_FORM_POMNG02010_VIEW_PCH_REQ_UNQ_NO').val(result.pchReqUnqNo);
		$('#ITP_FORM_POMNG02010_VIEW #ITP_FORM_POMNG02010_VIEW_PCH_REQ_MGR_ID').val(result.pchReqMgrId);
		$('#ITP_FORM_POMNG02010_VIEW #ITP_FORM_POMNG02010_VIEW_PCH_REQ_ST_CD').val(result.pchReqStCd);
		
		$('#ITP_FORM_POMNG02010_VIEW .fnBrandNm').text(result.brandNm);
		$('#ITP_FORM_POMNG02010_VIEW .fnPchReqUnqNo').text(result.pchReqUnqNo);
		$('#ITP_FORM_POMNG02010_VIEW .fnPchReqNm').text(result.pchReqNm);
		$('#ITP_FORM_POMNG02010_VIEW .fnPchReqStNm').text(result.pchReqStNm);
		$('#ITP_FORM_POMNG02010_VIEW .pchReqMgrNm').text(result.pchReqMgrNm);
		
		
		$('#ITP_FORM_POMNG02010_VIEW .fnPchReqTotalAmt').text(itp_fn_number_comma(result.pchReqTotalAmt));
		$('#ITP_FORM_POMNG02010_VIEW .fnDlvReqDt').text(result.dlvReqDt);
		$('#ITP_FORM_POMNG02010_VIEW .fnWhsNm').text(result.whsNm + " - " + result.locationNm);
		$('#ITP_FORM_POMNG02010_VIEW .fnLoanDvsnNm').text(result.loanDvsnNm);
		$('#ITP_FORM_POMNG02010_VIEW .fnOrdUseAmt').text(itp_fn_number_comma(result.ordUseAmt));
		$('#ITP_FORM_POMNG02010_VIEW .fnNote').text(result.note);
		$('#ITP_FORM_POMNG02010_VIEW .fnPchReqRjctDt').text(result.pchReqRjctDt);
		$('#ITP_FORM_POMNG02010_VIEW .fnPchReqRjctNm').text(result.pchReqRjctNm);
		$('#ITP_FORM_POMNG02010_VIEW .fnPchReqRjctRsn').text(result.pchReqRjctRsn);
		
		
		
		// 품목  리스트 조회
		pageObj.grid.init('VIEW', result.pchReqDtlList);
	}
};

/*수정화면 Object*/
let modifyObj = {
	init: function (param) {
		pageObj.grid.init('DETAIL', []);
		//this.load(param);
	},
	button: {
		modify: function (param) {
			itp_fn_form_clear_validate(null, '#ITP_FORM_POMNG02010_DETAIL');
			
			const selectVal = $('#ITP_FORM_POMNG02010_VIEW_PCH_REQ_UNQ_NO').val();
			const writeVal = $('#ITP_FORM_POMNG02010_VIEW_PCH_REQ_MGR_ID').val();
			const stCd = $('#ITP_FORM_POMNG02010_VIEW_PCH_REQ_ST_CD').val();
			
			var userId = fn_make_user_info.get('userId');
			console.log(writeVal);
			console.log(userId);
			console.log(writeVal == userId);
			console.log(stCd);
			if (writeVal != userId) {
				alert(ITP_MSG_LOCALE.message.ajax.diffWrite);
				return;
			}
			
			if (stCd != "PR00") {
				alert(ITP_MSG_LOCALE.message.ajax.notWrite);
				return;
			}
			
			const key = {brandId:fn_make_user_info.get('brandId'), pchReqUnqNo: selectVal, viewCd: 'R'};
			var param = $.param(key);
			//modifyObj.init(param);
			modifyObj.load(param);
		},
		save: function(arg) {
			$('body').trigger('click');
			const formId = '#ITP_FORM_POMNG02010_DETAIL';
			itp_fn_form_clear_validate(null, formId);
			
			itp_fn_grid_save_rows(POMNG02010_DETAIL_GRID_ID);
			
			$('#ITP_FORM_POMNG02010_DETAIL_PCH_REQ_ST_CD').val(arg);
			
			//정산 타입이 무정산이면 스킵
			var loanDvsn = $('#ITP_FORM_POMNG02010_DETAIL_LOAN_DVSN').val();
			var dlvReqDt = $('#ITP_FORM_POMNG02010_DETAIL_DLV_REQ_DT').val();
			var itemcnt  = $(POMNG02010_DETAIL_GRID_ID).getGridParam('reccount');
			var dlvReqAmt = $('#ITP_FORM_POMNG02010_DETAIL .fnPchReqTotalAmt').text();
			var reqMsg = "";
			var apprArg = {};
			
			//정산 타입이 무정산이면 스킵
			var apprTypeCd = "Y" // Y 정상결재, NP 선불, NA 후불   
			
			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 dlvReqDt = $('#ITP_FORM_POMNG02010_DETAIL_DLV_REQ_DT').val();
			if (today > dlvReqDt) {
				alert("납품요청일은 오늘 이후이어야 합니다.");
				return;
			}	
			//console.log(loanDvsn);
			var pchActAtm = itp_fn_currency_unfmatter($('#ITP_FORM_POMNG02010_DETAIL .fnPchActAmt').text(),"","");
			var pchReqAtm = itp_fn_currency_unfmatter($('#ITP_FORM_POMNG02010_DETAIL .fnPchReqTotalAmt').text(),"","");
					
			if (loanDvsn != null && loanDvsn != "") {
				if (loanDvsn != 'LD03' && arg == 'PR20' ) {
					
					var mallId = $('#ITP_FORM_POMNG02010_DETAIL_MALL_ID').val();
					
					if (parseInt(pchActAtm) < parseInt(pchReqAtm)) {
						dlvReqAmt = itp_fn_number_comma(String(parseInt(pchReqAtm) - parseInt(pchActAtm)));
						
						if (mallId == '') {
							if (loanDvsn == 'LD01') {
								apprTypeCd = 'NPN';
							} else {
								apprTypeCd = 'NAN';
							}
						} else {
							if (loanDvsn == 'LD01') {
								apprTypeCd = 'NP';
							} else {
								apprTypeCd = 'NA';
							}
						} 
					} else {
						dlvReqAmt = 0 ;
					}
				} else if (loanDvsn == 'LD03' && arg == 'PR20' ) {
					dlvReqAmt = 0 ;
				}  
			}        

			if (itp_fn_form_event.isValid(formId)) {
				
				const rowData1 = $(POMNG02010_DETAIL_GRID_ID).getRowData();
				
				var dataCnt = 0;
				var chkQtyYn = "N";
				$.each(rowData1, function(key, value) {
					if (value.viewCd != 'D') {
						dataCnt = dataCnt + 1;
						
						if (value.pchReqQty == '' || value.pchReqQty < 1 ) {
							alert("요청수량을 입력해주세요!");
							chkQtyYn = "Y";
							return false;
						}
					} 
				});
				
				if (dataCnt == 0) {
					alert( "요청할 품목내역이 없습니다.");
					return ;
				}
				
				if (chkQtyYn == "Y") return;
				
				if (arg == 'PR20') {
					
					apprArg.dlvReqDt = dlvReqDt;
					apprArg.itemcnt = itemcnt;
					apprArg.pchReqAtm = itp_fn_number_comma(pchReqAtm);
					apprArg.pchPssblAtm = itp_fn_number_comma(pchActAtm);
					apprArg.dlvReqAmt = dlvReqAmt;
					
					
					if (apprTypeCd == "Y") {  // 여신 구분, 여신금액
						
						var prIngFn =  {
							callBack: function(args) {
									modifyObj.button.saveLastReq(arg);
								}
							};
						itp_fn_modal_confirm_req1(apprArg, prIngFn, arg);
							
					} else // 금액 부족시 
						modifyObj.button.saveApprReq(apprArg,apprTypeCd, arg);
					} else {
					modifyObj.button.saveReq(arg);
				}
			}
		},
		saveReq: function(arg) {
			const formId = '#ITP_FORM_POMNG02010_DETAIL';
			var saveFn = {
				callBack: function(args) {
						$(formId).val(arg);
						let gridInsertData = [];
						let gridUpdateData = [];
						let gridDeleteData = [];
						
						const rowData = $(POMNG02010_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;
						console.log(JSON.stringify(param));
						var searhFn = function() {
							ITP_FORM_POMNG02010_DETAIL_IS_WRITING = false;
							modifyObj.button.clear();
						};
						fn_ajax_call(API_DETAIL_SAVE, JSON.stringify(param), searhFn, 'POST');				
					}
				};
			itp_fn_modal_confirm(ITP_MSG_LOCALE.message.ajax.tmpSave, saveFn, null);
		},
		saveApprReq: function(param, apprTypeCd, arg) {
			var apprFn =  {
				callBack: function(args) {
						// 결재금액이 부족하여 결재란으로 이동처리
						var popFn = function(rowDataPop) {
							// 결재 성공시 승인처리함 
							console.log(rowDataPop);
							modifyObj.button.saveLastReq(arg);
						};			
						// 결제 팝업 : LD01(선불(충전)), LD02(후불(신용))
						// 결제타입코드 : 10(선불(충전)), 20(후불(결제)), 30(후불(선결제))		
						// 구매요청 번호 전달 - 
						//var loanDvsn = $('#ITP_FORM_LOANMNG02010_SEARCH_STORE_LOAN_DVSN').val();
						var pchActAtm = itp_fn_currency_unfmatter($('#ITP_FORM_POMNG02010_DETAIL .fnPchActAmt').text(),"","");
						var pchReqAtm = itp_fn_currency_unfmatter($('#ITP_FORM_POMNG02010_DETAIL .fnPchReqTotalAmt').text(),"","");
						
						
						var args = {'payTpCd': '40',
						'brandId':   fn_make_user_info.get('brandId'), 
						'storeId':   fn_make_user_info.get('storeId'),
						'prchReqUnqNo': $('ITP_FORM_POMNG02010_DETAIL_PCH_REQ_UNQ_NO').val(),
						'goodsAmt':  pchReqAtm-pchActAtm}; 
						
						fn_call_popup('biz', 'BIZPOP_PO_PAYMENT', '#ITP_ASIDE', popFn, args, 'S');
					}
				};
				
				var apprNFn =  {
				callBack: function(args) {
						// 임시저장 처리한다.
						arg = 'PR00';
						$('#ITP_FORM_POMNG02010_DETAIL_PCH_REQ_ST_CD').val(arg);
						
						modifyObj.button.saveLastReq(arg);
					}
				};
			
			if (apprTypeCd == 'NP') {  // 선불
				itp_fn_modal_confirm_req2(param, apprFn, arg);
			} else if  (apprTypeCd == 'NA')  { //후불
				itp_fn_modal_confirm_req3(param, apprFn, arg);
			} else if (apprTypeCd == 'NPN') { //선불 pg없음 임시저장으로
				itp_fn_modal_confirm_req4(param, apprNFn, arg);
			} else if (apprTypeCd == 'NAN') { //후불  pg없음 임시저장으로
				itp_fn_modal_confirm_req5(param, apprNFn, arg);
			}
		},
		saveLastReq: function(arg) {
			const formId = '#ITP_FORM_POMNG02010_DETAIL';
			
			$(formId).val(arg);
			let gridInsertData = [];
			let gridUpdateData = [];
			let gridDeleteData = [];
			
			const rowData = $(POMNG02010_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);
					}
				}
			});
			
			//if (chkQtyYn == "Y") return;
			
			let param = $(formId).serializeObject();
			param.gridInsertData = gridInsertData;
			param.gridUpdateData = gridUpdateData;
			param.gridDeleteData = gridDeleteData;
			console.log(JSON.stringify(param));
			var searhFn = function() {
				ITP_FORM_POMNG02010_DETAIL_IS_WRITING = false;
				modifyObj.button.clear();
			};
			fn_ajax_call(API_DETAIL_SAVE, JSON.stringify(param), searhFn, 'POST');				
				
		},	
		clear: function () {
			document.getElementById('ITP_FORM_POMNG02010_DETAIL').reset();
			listObj.grid.search();
        },
		cancel: function () {
            listObj.grid.search();
       }
	},
	load: function(param) {
		console.log("=================================");
		console.log(param);
		console.log("=================================");
		fn_ajax_call(API_DETAIL_INFO, param, this.callback, 'GET');
	},
	callback: function (result) {
		console.log(result);
		pageObj.switchScreen('MODIFY');
		
		$('#ITP_FORM_POMNG02010_DETAIL #ITP_FORM_POMNG02010_DETAIL_VIEW_CD').val('U');
		$('#ITP_FORM_POMNG02010_DETAIL #ITP_FORM_POMNG02010_DETAIL_PCH_REQ_UNQ_NO').val(result.pchReqUnqNo);
		$('#ITP_FORM_POMNG02010_DETAIL #ITP_FORM_POMNG02010_DETAIL_BRAND_ID').val(result.brandId);
		$('#ITP_FORM_POMNG02010_DETAIL .fnBrandNm').text(result.brandNm);
		$('#ITP_FORM_POMNG02010_DETAIL #ITP_FORM_POMNG02010_DETAIL_STORE_ID').val(result.storeId);
		$('#ITP_FORM_POMNG02010_DETAIL #ITP_FORM_POMNG02010_DETAIL_LOAN_DVSN').val(result.loanDvsn);
		$('#ITP_FORM_POMNG02010_DETAIL #ITP_FORM_POMNG02010_DETAIL_LOAN_MGNT_UNQ_NO').val(result.loanMgntUnqNo);
		$('#ITP_FORM_POMNG02010_DETAIL #ITP_FORM_POMNG02010_DETAIL_PCH_REQ_DVSN').val(result.pchReqDvsn);
		$('#ITP_FORM_POMNG02010_DETAIL #ITP_FORM_POMNG02010_DETAIL_PCH_REQ_ST_CD').val(result.pchReqStCd);
		$('#ITP_FORM_POMNG02010_DETAIL .fnPchReqUnqNo').text(result.pchReqUnqNo);
		$('#ITP_FORM_POMNG02010_DETAIL #ITP_FORM_POMNG02010_DETAIL_PCH_REQ_NM').val(result.pchReqNm);
		$('#ITP_FORM_POMNG02010_DETAIL .fnPchReqDept').text(result.pchReqDePt);
		$('#ITP_FORM_POMNG02010_DETAIL .fnPchReqMgrNm').text(result.pchReqMgrNm);
		$('#ITP_FORM_POMNG02010_DETAIL #ITP_FORM_POMNG02010_DETAIL_PCH_REQ_MGR_ID').val(result.pchReqMgrId);
		$('#ITP_FORM_POMNG02010_DETAIL .fnPchReqTotalAmt').text(itp_fn_number_comma(result.pchReqTotalAmt));
		$('#ITP_FORM_POMNG02010_DETAIL #ITP_FORM_POMNG02010_DETAIL_DLV_REQ_DT').val(result.dlvReqDt);
		$('#ITP_FORM_POMNG02010_DETAIL #ITP_FORM_POMNG02010_DETAIL_WHS_ID').val(result.whsId);
		$('#ITP_FORM_POMNG02010_DETAIL #ITP_FORM_POMNG02010_DETAIL_WHS_NM').val(result.whsNm);
		$('#ITP_FORM_POMNG02010_DETAIL #ITP_FORM_POMNG02010_DETAIL_LOCATION').val(result.location);
		$('#ITP_FORM_POMNG02010_DETAIL #ITP_FORM_POMNG02010_DETAIL_LOCATION_NM').val(result.locationNm);
		$('#ITP_FORM_POMNG02010_DETAIL .fnLoanDvsnNm').text(result.loanDvsnNm);
		$('#ITP_FORM_POMNG02010_DETAIL .fnPchActAmt').text(itp_fn_number_comma(result.ordUseAmt));
		$('#ITP_FORM_POMNG02010_DETAIL #ITP_FORM_POMNG02010_DETAIL_NOTE').val(result.note);
		$('#ITP_FORM_POMNG02010_DETAIL #ITP_FORM_POMNG02010_DETAIL_MALL_ID').val(result.mallId);
		
		
		

		// 품목  리스트 조회
		pageObj.grid.init('DETAIL', result.pchReqDtlList);
		// modifyObj.grid.load(result.spplyMgrList);
	},
	 
};


