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			*
 *******************************************************/

/*화면 변수*/
/*
const POMNG01010_GRID_ID = '#ITP_POMNG01010_jqGrid';
const POMNG01010_GRID_LIST = '#ITP_POMNG01010_jqGrid_list';
const POMNG01010_GRID_PAGER = '#ITP_POMNG01010_jqGridPager';
const POMNG01010_GRID_EMPTY = '#ITP_POMNG01010_jqGridEmpty';

const POMNG01010_VIEW_GRID_ID = '#ITP_POMNG01010_VIEW_jqGrid';
const POMNG01010_VIEW_GRID_LIST = '#ITP_POMNG01010_VIEW_jqGrid_list';
const POMNG01010_VIEW_GRID_PAGER = '#ITP_POMNG01010_VIEW_jqGridPager';
const POMNG01010_VIEW_GRID_EMPTY = '#ITP_POMNG01010_VIEW_jqGridEmpty';
*/
const POMNG01010_DETAIL_GRID_ID = '#ITP_POMNG01010_DETAIL_jqGrid';
const POMNG01010_DETAIL_GRID_LIST = '#ITP_POMNG01010_DETAIL_jqGrid_list';
const POMNG01010_DETAIL_GRID_PAGER = '#ITP_POMNG01010_DETAIL_jqGridPager';
const POMNG01010_DETAIL_GRID_EMPTY = '#ITP_POMNG01010_DETAIL_jqGridEmpty';  // ==>dwkim html확인필요

/*
let ITP_FORM_POMNG01010_DETAIL_IS_DUPLICATE = false;
let ITP_FORM_POMNG01010_DETAIL_IS_WRITING = false;
*/

/*API URL*/
let API_DETAIL_INIT_INFO = '/api/pomng/init-pchReq'
//let API_DETAIL_GRID_LIST = '/api/affl/detail-grid-list';
//let API_DETAIL_INFO = '/api/affl/info-affl';
//let COMPANY_INFO_COMPANY = '/api/affl/info-affl';
let API_DETAIL_SAVE = '/api/pomng/save-pchReq';
//let API_CHECK_DUPLICATE = '/api/affl/check-duplicate';
//let API_INTI_USERPW = '/api/user/inti-userpw';

/*화면 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: '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: 'center',
			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: 'center',
			sortable: false, editable: false, edittype: 'text', hidden: false
		},
		{
			index: 'PCH_REQ_QTY', name: 'pchReqQty',
			label: ITP_MSG_LOCALE.label.pchReqQty, //단가
			width: '10', fixed: false, align: 'right',
			sortable: true, editable: true, edittype: 'text',
			editrules: { number:true}
		},
		{
			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
		},

		{
			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_POMNG01010_SEARCH_WHS_NM').on('click', function() {
			_this.popup();
		});
		// 납품장소 텍스트 삭제 버튼 클릭
		$('#ITP_FORM_POMNG01010_DELETE_WHS_NM').on('click', function() {
			$('#ITP_FORM_POMNG01010_DETAIL_WHS_NM').val('');
			$('#ITP_FORM_POMNG01010_DETAIL_WHS_ID').val('');
			$('#ITP_FORM_POMNG01010_DETAIL_LOCATION_NM').val('');
			$('#ITP_FORM_POMNG01010_DETAIL_LOCATION').val('');
			
		});
	},
	popup: function () {
		// 팝업
		var popFn = this.callback.create;
		const key = {brandId:fn_make_user_info.get('brandId'),storeId:fn_make_user_info.get('storeId')};
		fn_call_popup('biz', 'BIZPOP_WHS_LOCATION', '#ITP_ASIDE', popFn, key, 'S');
		
	},
	callback: {
		create: function(rowDataPop) {
			console.log(rowDataPop);
			if(rowDataPop) {
				$('#ITP_FORM_POMNG01010_DETAIL_WHS_NM').val(rowDataPop.whsNm);
				$('#ITP_FORM_POMNG01010_DETAIL_WHS_ID').val(rowDataPop.whsId);
				$('#ITP_FORM_POMNG01010_DETAIL_LOCATION_NM').val(rowDataPop.locationNm);
				$('#ITP_FORM_POMNG01010_DETAIL_LOCATION').val(rowDataPop.location);
			}
		}
	},
	itp_POMNG01010_param: {},  // ==>dwkim 
	itp_POMNG01010_search: false,  // ==>dwkim 
	ui: {
		init: function() {
			this.view();
			this.grid();
			this.ready();
		},
		view: function() {
			// 버튼 권한설정
			fn_proc_btn_auth('POMNG01010');
			
			// 공통코드 표시
			$('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_POMNG01010 .input-group.date').datepicker(ITP_DATE_LANGUAGE);
			$('#ITP_FORM_POMNG01010_DETAIL_DLV_REQ_DT').datepicker('setDate', new Date(now.setDate(now.getDate() + 5)));
			
			
			
			//납품장소 필드 readonly
			$('#ITP_FORM_POMNG01010_DETAIL_WHS_NM').attr('readonly', true);
			$('#ITP_FORM_POMNG01010_DETAIL_LOCATION_NM').attr('readonly', true);
			
		},
		grid: function() {
			itp_fn_jqgrid_resize(POMNG01010_DETAIL_GRID_ID, POMNG01010_DETAIL_GRID_LIST, 'lg');
			//listObj.empty.init();
			itp_fn_fire_window_resize();
		},
		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_POMNG01010_SRH': modifyObj.button.save(); break;	// 구매요청
						case 'ITP_BTN_POMNG01010_NEWREG': modifyObj.button.newReg(); break;	// 임시저장
						case 'ITP_BTN_POMNG01010_DETAIL_ADDROW': pageObj.grid.button.addRow(); break;	// 품목추가
						case 'ITP_BTN_POMNG01010_DETAIL_DELROW': pageObj.grid.button.delRow(); break;	// 품목삭제
					}
				});
			});

			$('body').on('click', function(e) {
				// afflUserObj.grid.resetGrid(e);
			});

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

					$.each(rowDataPop, function(key, value) {
						if (exists.indexOf(value.itemId) < 0 && value.podrPssblDvsn == 'PO01') {
							value['viewCd'] = "C";
							$(POMNG01010_DETAIL_GRID_ID).jqGrid('addRowData', value.itemId, value, 'last');
						}
					});
					$(POMNG01010_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(POMNG01010_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,
				loadComplete: function(data) {
					_this.clearData();
				},
				afterSaveCell: function(rowid,name,val,iRow,iCol) {
					// 구매요청금액 계산 (기존금액과 )
					var unitAmt = jQuery(POMNG01010_DETAIL_GRID_ID).jqGrid('getCell',rowid,iCol-1);
					jQuery(POMNG01010_DETAIL_GRID_ID).jqGrid('setRowData',rowid,{pchReqAmt: parseInt(val)*parseInt(unitAmt)});
					// 그리드 포문으로 금액 재계산후 구매요청금액에 넣어줌
					_this.recal();
				}
			};
			itp_fn_grid_make_local(option);
		},
		clearData: function() {
			console.log(this.gridId);
			$(POMNG01010_DETAIL_GRID_ID).jqGrid('clearGridData', true);
			$(POMNG01010_DETAIL_GRID_LIST).find('.ui-jqgrid .ui-jqgrid-bdiv').css('overflow-x', 'hidden');
			$(POMNG01010_DETAIL_GRID_LIST).find('.ui-jqgrid-bdiv').css('min-height', '100px');
			$(POMNG01010_DETAIL_GRID_EMPTY).html(ITP_MSG_LOCALE.message.grid.noData);
			$(POMNG01010_DETAIL_GRID_EMPTY).show();
		},
		recal: function() {
			//PCH_REQ_AMT
			const rowData = $(POMNG01010_DETAIL_GRID_ID).getRowData();
			var pchReqAmt = 0 ;
			$.each(rowData, function(key, value) {
				if (value.pchReqAmt != null && value.pchReqAmt != "") {
					pchReqAmt = pchReqAmt + parseInt(value.pchReqAmt) ;
				}
				
			});
			$('#ITP_FORM_POMNG01010_DETAIL .fnPchReqAmt').text(pchReqAmt);
		},
		unload: function() {
			$.jgrid.gridUnload(this.gridId);
		}
	}
};

/*신규화면 Object*/
let createObj = {
	init: function() {
		$('#ITP_FORM_POMNG01010_DETAIL_BRAND_ID').val(fn_make_user_info.get('brandId'));
		$('#ITP_FORM_POMNG01010_DETAIL_STORE_ID').val(fn_make_user_info.get('storeId'));
		//let param = 'brandId=' + LOGIN_USER_INFO.brandId + "&spplyId=" + LOGIN_USER_INFO.spplyId;
		this.load();
	},
	button: {
		save: function() {
			const formId = '#ITP_FORM_POMNG01010_DETAIL';
			itp_fn_form_clear_validate(null, formId);

			// if (vali_cmpyCd && vali_cmpyStatCd && vali_cmpyTypeCd && vali_cmpyNm && vali_bossNm && vali_mainTel && vali_mainEmail) {
			if (itp_fn_form_event.isValid(formId)) {

				// if($('#ITP_FORM_POMNG01010_DETAIL_CMPY_ZIPNO').val() === '' || $('#ITP_FORM_POMNG01010_DETAIL_CMPY_ADRES').val() === '') {
				// 	itp_fn_modal_alert('주소 검색을 통해 회사 주소를 입력하세요.');
				// 	return;
				// }

				if (ITP_FORM_POMNG01010_DETAIL_IS_DUPLICATE) {
					itp_fn_modal_duplicate('회사코드 중복체크를 해주세요.', formId + '_AFFL_SHOP_ID');
				} else {
					let gridInsertData = [];
					let gridUpdateData = [];
					let gridDeleteData = [];
					const rowData = $(POMNG01010_DETAIL_GRID_ID).getRowData();
					const keyValue = $(formId + '_AFFL_SHOP_ID').val();
					$.each(rowData, function(key, value) {
						if (value.viewCd !== 'R') {
							value.afflShopId = keyValue;
							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_POMNG01010_DETAIL_IS_WRITING = false;
						viewObj.init();
					};
					fn_ajax_call(API_DETAIL_SAVE, JSON.stringify(param), searhFn, 'POST');
				}
			}
		}
	},
	load: function() {
		fn_ajax_call(API_DETAIL_INIT_INFO, '', this.callback, 'GET');
	},
	callback: function(result) {
		console.log(result);

		$('#ITP_FORM_POMNG01010_DETAIL #ITP_FORM_POMNG01010_DETAIL_VIEW_CD').val('C');

		$('#ITP_FORM_POMNG01010_DETAIL #ITP_FORM_POMNG01010_DETAIL_BRAND_ID').val(result.brandId);
		$('#ITP_FORM_POMNG01010_DETAIL #ITP_FORM_POMNG01010_DETAIL_STORE_ID').val(result.storeId);
		$('#ITP_FORM_POMNG01010_DETAIL #ITP_FORM_POMNG01010_DETAIL_LOAN_DVSN').val(result.loanDvsn);
		$('#ITP_FORM_POMNG01010_DETAIL #ITP_FORM_POMNG01010_DETAIL_LOAN_MGNT_UNQ_NO').val(result.loanMgntUnqNo);
		$('#ITP_FORM_POMNG01010_DETAIL #ITP_FORM_POMNG01010_DETAIL_PCH_REQ_DVSN').val(result.pchReqDvsn);
		$('#ITP_FORM_POMNG01010_DETAIL .fnBrandNm').text(result.brandNm);
		$('#ITP_FORM_POMNG01010_DETAIL .fnPchReqDept').text(result.reqDept);
		$('#ITP_FORM_POMNG01010_DETAIL .fnPchReqMgrNm').text(result.userNm);
		$('#ITP_FORM_POMNG01010_DETAIL .fnPchReqAmt').text("0");
		$('#ITP_FORM_POMNG01010_DETAIL .fnLoanDvsnNm').text(result.loanDvsnNm);
		$('#ITP_FORM_POMNG01010_DETAIL .fnPchActAmt').text(result.ordUseAmt);

		pageObj.grid.init();
	}
};
