/********************************************************
 --------------------------------------------------------
 - Object 목록								            -
 --------------------------------------------------------
 * const gridColModel = {}	: 화면 Grid Object			*
 * let pageObj = {}			: 화면공통 Object			*
 * let listObj = {}			: 목록화면 Object			*
 * let viewObj = {}			: 상세화면 Object			*
 * let stockCddObj = {}		: 재고실사 Object			*
 *******************************************************/

/*화면 변수*/
const STOCKMNG02010_GRID_ID = '#ITP_STOCKMNG02010_jqGrid';
const STOCKMNG02010_GRID_LIST = '#ITP_STOCKMNG02010_jqGrid_list';
const STOCKMNG02010_GRID_PAGER = '#ITP_STOCKMNG02010_jqGridPager';
const STOCKMNG02010_GRID_EMPTY = '#ITP_STOCKMNG02010_jqGridEmpty';

const STOCKMNG02010_VIEW_GRID_ID = '#ITP_STOCKMNG02010_VIEW_jqGrid';
const STOCKMNG02010_VIEW_GRID_LIST = '#ITP_STOCKMNG02010_VIEW_jqGrid_list';
const STOCKMNG02010_VIEW_GRID_PAGER = '#ITP_STOCKMNG02010_VIEW_jqGridPager';
const STOCKMNG02010_VIEW_GRID_EMPTY = '#ITP_STOCKMNG02010_VIEW_jqGridEmpty';

const STOCKMNG02010_DETAIL_GRID_ID = '#ITP_STOCKMNG02010_DETAIL_jqGrid';
const STOCKMNG02010_DETAIL_GRID_LIST = '#ITP_STOCKMNG02010_DETAIL_jqGrid_list';
const STOCKMNG02010_DETAIL_GRID_PAGER = '#ITP_STOCKMNG02010_DETAIL_jqGridPager';
const STOCKMNG02010_DETAIL_GRID_EMPTY = '#ITP_STOCKMNG02010_DETAIL_jqGridEmpty';

let ITP_FORM_STOCKMNG02010_DETAIL_IS_DUPLICATE = false;
let ITP_FORM_STOCKMNG02010_DETAIL_IS_WRITING = false;
let STOCKMNG02010_DETAIL_GRID_LAST_ROW_ID;

let LOGIN_AUTH_TYPE_CD;

/* 공통코드 리스트 */
// let ITP_COMMON_CD_STCK_DVSN = fn_make_common_cd_list(CODE_LIST, 'STCK_DVSN', true);
// let ITP_COMMON_CD_LOC_ST_CD = fn_make_common_cd_list(CODE_LIST, 'LOC_ST_CD', true);

/*API URL*/
let STOCK_CDD_INFO_CDD = '/api/stock/cdd/info-cdd';
let STOCK_CDD_SAVE_STOCK_CDD = '/api/stock/cdd/save-stock-cdd'; // 재고실사 저장

let STOCK_CDD_DETAIL_GRID_LIST = '/api/stock/cdd/detail-grid-list';
let STOCK_CDD_CDD_DETAIL_GRID_LIST = '/api/stock/cdd/cdd-detail-grid-list';
let WHS_MNG_DETAIL_GRID_LIST = '/api/whs/mng/detail-grid-list';
let WHS_MNG_LOCATION_GRID_LIST = '/api/whs/mng/location-grid-list';
let STOCK_MNG_CDD_GRID_LIST = '/api/stock/mng/cdd-grid-list'; // 재고실사 - 엑셀업로드

let STOCK_MNG_INFO_WHS_ITEM_EXCEL = '/api/stock/mng/info-whs-item-excel';

/*화면 Grid ColModel*/
const gridColModel = {
	list: [
		{
			index: 'CDD_ID', name: 'cddId',
			label: "실사번호", 
			width: '6', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'BRAND_ID', name: 'brandId',
			label: "브랜드ID", 
			width: '0', fixed: false, align: 'center',
			sortable: false, hidden: true
		},
		{
			index: 'STORE_ID', name: 'storeId',
			label: "매장ID", 
			width: '0', 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',
			sortable: false, hidden: false, classes: 'ui-ellipsis'
		},
		{
			index: 'STORE_NM', name: 'storeNm',
			label: "매장명", 
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'WHS_ID', name: 'whsId',
			label: "창고번호", 
			width: '8', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'WHS_NM', name: 'whsNm',
			label: "창고명", 
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: false, classes: 'ui-ellipsis'
		},
		{
			index: 'LOCATION_NM', name: 'locationNm',
			label: "로케이션명", 
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: false, classes: 'ui-ellipsis'
		},		
		{
			index: 'CDD_MGR_NM', name: 'cddMgrNm',
			label: "실사담당자", 
			width: '8', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'CDD_DT', name: 'cddDt',
			label: "실사일자", 
			width: '8', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'CDD_TM', name: 'cddTm',
			label: "실사시각", 
			width: '8', fixed: false, align: 'center',
			sortable: false, hidden: false
		},		
		{
			index: 'CDD_DVSN_NM', name: 'cddDvsnNm',
			label: "실사구분", 
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: false
		}
	],
	view: [
		{
			index: 'VIEW_CD', name: 'viewCd',
			label: ITP_MSG_LOCALE.label.viewCd,
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: true
		},
		{
			index: 'BRAND_NM', name: 'brandNm',
			label: "브랜드",
			width: '10', fixed: false, align: 'center',
			sortable: false, editable: false, edittype: 'text',
			editrules: {required: false}, classes: 'ui-ellipsis'
		},
		{
			index: 'WHS_ID', name: 'whsId',
			label: "창고번호",
			width: '10', fixed: false, align: 'center',
			sortable: false, editable: false, edittype: 'text',
			editrules: {required: false}
		},
		{
			index: 'WHS_NM', name: 'whsNm',
			label: "창고명",
			width: '10', fixed: false, align: 'center',
			sortable: false, editable: false, edittype: 'text',
			editrules: {required: false}, classes: 'ui-ellipsis'
		},
		{
			index: 'LOCATION_NM', name: 'locationNm',
			label: "로케이션명",
			width: '10', fixed: false, align: 'center',
			sortable: false, editable: false, edittype: 'text',
			editrules: {required: false}, classes: 'ui-ellipsis'
		},
		{
			index: 'ITEM_ID', name: 'itemId',
			label: "품목번호",
			width: '12', fixed: false, align: 'center',
			sortable: false, editable: false, edittype: 'text',
			editrules: {required: false}
		},
		{
			index: 'ITEM_NM', name: 'itemNm',
			label: "품목명",
			width: '10', fixed: false, align: 'center',
			sortable: false, editable: false, edittype: 'text',
			editrules: {required: false}, classes: 'ui-ellipsis'
		},
		{
			index: 'UNIT', name: 'unit',
			label: "단위",
			width: '5', fixed: false, align: 'center',
			sortable: false, editable: false, edittype: 'text',
			editrules: {required: false}
		},
		{
			index: 'COM_EXST_QTY', name: 'comExstQty',
			label: "현재고수량",
			width: '8', fixed: false, align: 'right',
			sortable: false, editable: false, edittype: 'text',
			editrules: {required: false},
			formatter: 'integer', formatoptions: {thousandsSeparator: ','}
		},
		{
			index: 'CDD_QTY', name: 'cddQty',
			label: "실사수량",
			width: '10', fixed: false, align: 'right',
			sortable: false, editable: false, edittype: 'text',
			editrules: {required: false},
			formatter: 'integer', formatoptions: {thousandsSeparator: ','}
		}
	],
	detail: [
		{
			index: 'VIEW_CD', name: 'viewCd',
			label: ITP_MSG_LOCALE.label.viewCd,
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: true
		},
		{
			index: 'NORMAL_YN', name: 'normalYn',
			label: "정상여부",
			width: '6', fixed: false, align: 'center',
			sortable: false, editable: false, edittype: 'text',
			minwidth: 100,
			editrules: {required: false}
		},
		{
			index: 'ERROR_MSG', name: 'errorMsg',
			label: "에러메시지",
			width: '10', fixed: false, align: 'center',
			sortable: false, editable: false, edittype: 'text',
			editrules: {required: false}, classes: 'ui-ellipsis'
		},
		{
			index: 'BRAND_NM', name: 'brandNm',
			label: "브랜드",
			width: '10', fixed: false, align: 'left',
			sortable: false, editable: false, edittype: 'text',
			editrules: {required: false}, classes: 'ui-ellipsis'
		},
		{
			index: 'WHS_ID', name: 'whsId',
			label: "창고번호",
			width: '8', fixed: false, align: 'center',
			sortable: false, editable: false, edittype: 'text',
			editrules: {required: false}
		},
		{
			index: 'WHS_NM', name: 'whsNm',
			label: "창고명",
			width: '11', fixed: false, align: 'left',
			sortable: false, editable: false, edittype: 'text',
			editrules: {required: false}, classes: 'ui-ellipsis'
		},
		{
			index: 'LOCATION_NM', name: 'locationNm',
			label: "로케이션명",
			width: '10', fixed: false, align: 'left',
			sortable: false, editable: false, edittype: 'text',
			minwidth: 100,
			editrules: {required: false}, classes: 'ui-ellipsis'
		},
		{
			index: 'ITEM_ID', name: 'itemId',
			label: "품목번호",
			width: '12', fixed: false, align: 'center',
			sortable: false, editable: false, edittype: 'text',
			editrules: {required: false}
		},
		{
			index: 'ITEM_NM', name: 'itemNm',
			label: "품목명",
			width: '10', fixed: false, align: 'center',
			sortable: false, editable: false, edittype: 'text',
			editrules: {required: false}, classes: 'ui-ellipsis'
		},
		{
			index: 'UNIT', name: 'unit',
			label: "단위",
			width: '5', fixed: false, align: 'center',
			sortable: false, editable: false, edittype: 'text',
			editrules: {required: false}
		},
		{
			index: 'STCK_QTY', name: 'stckQty',
			label: "현재고수량",
			width: '9', fixed: false, align: 'right',
			sortable: false, editable: false, edittype: 'text',
			editrules: {required: false},
			formatter: 'integer', formatoptions: {thousandsSeparator: ','}
		},
		{
			index: 'CDD_QTY', name: 'cddQty',
			label: "실사수량",
			width: '10', fixed: false, align: 'right',
			classes: 'input_color',
			sortable: false, editable: true, edittype: 'text',
			editrules: {required: false},
			editoptions: {"onKeyup": "this.value=this.value.replace(/[^0-9]/g,'');", maxlength: 10},
			formatter:'integer', formatoptions: { defaultValue: '', thousandsSeparator: ',' },
		}
	]
};

require(['config'], function() {
	require([
		'jquery.bootstrap.fileUpload',	//파일 업로드가 있는 페이지에서 로딩
		'xlsx' 		// 엑셀 다운로드
	], function($) {
		pageObj.init();
	});
});

/*화면공통 Object*/
let pageObj = {
	init: function () {
		this.ui.init();
		this.event.init();
	},
	ui: {
		init: function () {
			this.view();
			this.grid();
			this.ready();
		},
		view: function() {
			// 버튼 권한설정
			fn_proc_btn_auth('STOCKMNG02010');
			
			// 브랜드ID 지정
			$('#ITP_FORM_STOCKMNG02010_SEARCH_BRAND_ID').val(fn_make_user_info.get('brandId'));
			$('#ITP_FORM_STOCKMNG02010_SEARCH_BRAND_NM').val(fn_make_user_info.get('brandNm'));
			$('#ITP_FORM_STOCKMNG02010_SEARCH_STORE_ID').val(fn_make_user_info.get('storeId'));
			LOGIN_AUTH_TYPE_CD = fn_make_user_info.get('authTpCd'); // 권한타입
			
			pageObj.fnWhsList(function() {
				pageObj.fnLocationList();
			}); // 창고리스트
			
			// 공통코드 표시
			$('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_STOCKMNG02010 .input-group.date').datepicker(ITP_DATE_LANGUAGE);
			$('#ITP_FORM_STOCKMNG02010_SEARCH_FROM_DT').datepicker('setDate', new Date(now.setMonth(now.getMonth() - 1)));
			$('#ITP_FORM_STOCKMNG02010_SEARCH_TO_DT').datepicker('setDate', new Date());
			$('#ITP_FORM_STOCKMNG02010_DETAIL_CDD_DT').val(itp_fn_date_format(new Date(), 2));
								
		},
		grid: function() {
			itp_fn_jqgrid_resize(STOCKMNG02010_GRID_ID, STOCKMNG02010_GRID_LIST, 'lg');
			listObj.empty.init();
			
		},
		ready: function() {
			listObj.init();
			stockCddObj.change();
		}
	},
	event: {
		init: function () {
			this.button();
			this.change();
		},
		button: function () {
			// 버튼 클릭 이벤트
			$('button').each(function() {
				var id = $(this).attr('id');
				$(this).on('click', function() {
					switch (id) {
						case 'ITP_BTN_STOCKMNG02010_SRH'				: listObj.button.search();		break;	// 조회 버튼 클릭
						case 'ITP_BTN_STOCKMNG02010_STOCK_CDD'			: listObj.button.fnStockCdd(); 	break;	// 재고실사 버튼
						case 'ITP_BTN_STOCKMNG02010_CANCELLIST'			: stockCddObj.button.cancel(); 	break;	// 취소/목록 버튼
						case 'ITP_BTN_STOCKMNG02010_SAVE'				: stockCddObj.button.save(); 		break;	// 저장 버튼
						case 'ITP_BTN_STOCKMNG02010_DETAIL_ADDROW'		: stockCddObj.button.addRow();	break;	// 품목추가 버튼
						// case 'ITP_BTN_STOCKMNG02010_DETAIL_DELROW'		: locInfoObj.button.delRow();	break;	// 상세:삭제버튼
						case 'ITP_BTN_STOCKMNG02010_DETAIL_EXCEL_UPLOAD'	: stockCddObj.button.uploadExcel();	break;	// 엑셀업로드
						case 'ITP_BTN_STOCKMNG02010_DETAIL_TEMPLATE_DOWNLOAD'	: stockCddObj.button.downTemplate();	break;	// 템플릿다운로드
					}
				});
			});

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

		}, 
		change: function () {
			// 창고 변경
			$('#ITP_FORM_STOCKMNG02010_SEARCH_WHS_ID').on('change', function() {
				pageObj.fnLocationList(function() {
					listObj.button.search(); // 조회	
				}); // 로케이션 리스트
			});
			$('#ITP_FORM_STOCKMNG02010_SEARCH_LOCATION').on('change', function() {
				listObj.button.search(); // 조회
			});
			
		}
	},
	switchScreen: function(mode) {
		if(mode == 'LIST') { // 목록
			itp_fn_fire_window_resize();
			$('#ITP_BTN_STOCKMNG02010_MODIFY').hide();
			$('#ITP_BTN_STOCKMNG02010_CANCELLIST').hide();
			$('#ITP_BTN_STOCKMNG02010_DELETE').hide();
			$('#ITP_BTN_STOCKMNG02010_SAVE').hide();
			$('#ITP_BTN_STOCKMNG02010_DETAIL_ADDROW').hide();
			
			fn_show_btn_auth('#ITP_BTN_STOCKMNG02010_SRH');
			fn_show_btn_auth('#ITP_BTN_STOCKMNG02010_STOCK_CDD');

			$('#ITP_AJAX_STOCKMNG02010_LIST_CONTAINER').show();
			$('#ITP_AJAX_STOCKMNG02010_DETAIL_CONTAINER').hide();
			$('#ITP_AJAX_STOCKMNG02010_VIEW_CONTAINER').hide();
		} else if(mode == 'ADD') { // 재고실사
			ITP_FORM_STOCKMNG02010_DETAIL_IS_DUPLICATE = true;

			$('#ITP_BTN_STOCKMNG02010_SRH').hide();
			$('#ITP_BTN_STOCKMNG02010_MODIFY').hide();
			$('#ITP_BTN_STOCKMNG02010_STOCK_CDD').hide();
			$('#ITP_BTN_STOCKMNG02010_DELETE').hide();		
			$('#ITP_BTN_STOCKMNG02010_DETAIL_ADDROW').show();
			
			fn_show_btn_auth('#ITP_BTN_STOCKMNG02010_CANCELLIST');
			fn_show_btn_auth('#ITP_BTN_STOCKMNG02010_SAVE');

			$('#ITP_AJAX_STOCKMNG02010_LIST_CONTAINER').hide();
			$('#ITP_AJAX_STOCKMNG02010_DETAIL_CONTAINER').show();
			$('#ITP_AJAX_STOCKMNG02010_VIEW_CONTAINER').hide();
						
			$('#ITP_FORM_STOCKMNG02010_DETAIL_BRAND_ID').val($('#ITP_FORM_STOCKMNG02010_SEARCH_BRAND_ID').val());
			$('#ITP_FORM_STOCKMNG02010_DETAIL_STORE_ID').val($('#ITP_FORM_STOCKMNG02010_SEARCH_STORE_ID').val());
			$('#ITP_FORM_STOCKMNG02010_DETAIL_WHS_ID').val($('#ITP_FORM_STOCKMNG02010_SEARCH_WHS_ID').val());
			$('#ITP_FORM_STOCKMNG02010_DETAIL_LOCATION').val($('#ITP_FORM_STOCKMNG02010_SEARCH_LOCATION').val());
			
		} else if(mode == 'VIEW') { // 보기
			$('#ITP_BTN_STOCKMNG02010_SRH').hide();
			$('#ITP_BTN_STOCKMNG02010_STOCK_CDD').hide();
			$('#ITP_BTN_STOCKMNG02010_DELETE').hide();
			$('#ITP_BTN_STOCKMNG02010_SAVE').hide();
			
			fn_show_btn_auth('#ITP_BTN_STOCKMNG02010_MODIFY');
			fn_show_btn_auth('#ITP_BTN_STOCKMNG02010_CANCELLIST');

			$('#ITP_AJAX_STOCKMNG02010_LIST_CONTAINER').hide();
			$('#ITP_AJAX_STOCKMNG02010_DETAIL_CONTAINER').hide();
			$('#ITP_AJAX_STOCKMNG02010_VIEW_CONTAINER').show();
		}
	}, 
	fnWhsList: function(fnCall) {
		const brandIdVal = $('#ITP_FORM_STOCKMNG02010_SEARCH_BRAND_ID').val();	
		const storeIdVal = $('#ITP_FORM_STOCKMNG02010_SEARCH_STORE_ID').val();	
		const whsDvsnVal = LOGIN_AUTH_TYPE_CD == '50' ? 'W02' : 'W01'; // 본사/매장 구분
		
		const param = {swhsDvsn: whsDvsnVal, sbrandId: brandIdVal, sstoreId: storeIdVal, pagingYn: false};
		
		fn_ajax_call(WHS_MNG_DETAIL_GRID_LIST, JSON.stringify(param), function(result) {
			
			fn_make_select_whs(result.gridRows, 'ITP_FORM_STOCKMNG02010_SEARCH_WHS_ID');
			fn_make_select_whs(result.gridRows, 'ITP_FORM_STOCKMNG02010_DETAIL_WHS_ID');
			
			if (fnCall !== undefined || typeof fnCall !== 'undefined') fnCall();
					
		}, 'POST');
	}, 
	fnLocationList: function(fnCall) {
		const brandIdVal = $('#ITP_FORM_STOCKMNG02010_SEARCH_BRAND_ID').val();
		const storeIdVal = $('#ITP_FORM_STOCKMNG02010_SEARCH_STORE_ID').val();	
		const whsIdVal = $('#ITP_FORM_STOCKMNG02010_SEARCH_WHS_ID').val();	
		const param = {brandId: brandIdVal, storeId: storeIdVal, whsId: whsIdVal, pagingYn: false};
		
		fn_ajax_call(WHS_MNG_LOCATION_GRID_LIST, JSON.stringify(param), function(result) {
			
			fn_make_select_location(result.gridRows, 'ITP_FORM_STOCKMNG02010_SEARCH_LOCATION');
			fn_make_select_location(result.gridRows, 'ITP_FORM_STOCKMNG02010_DETAIL_LOCATION');
			
			if (fnCall !== undefined || typeof fnCall !== 'undefined') fnCall();
					
		}, 'POST');
	}
};

/*목록화면 Object*/
let listObj = {
	init: function () {
		this.grid.init();
	},
	itp_STOCKMNG02010_search: false,
	button: {
		search: function() {
			listObj.itp_STOCKMNG02010_search = true;
			let param = $('#ITP_FORM_STOCKMNG02010_SEARCH').serializeObject();
			param.gridSize = $.jgrid.defaults.rowNum;
			param.gridPage = $.jgrid.defaults.page;
			$(STOCKMNG02010_GRID_ID).data('grid-param',param);
			$(STOCKMNG02010_GRID_ID).setGridParam({'postData': JSON.stringify(param)}).trigger('reloadGrid');
		},
		fnStockCdd: function() {
			pageObj.switchScreen('ADD');			
			itp_fn_form_clear_validate(null, '#ITP_FORM_STOCKMNG02010_DETAIL');						
			stockCddObj.init();
		}
	},
	empty: {
		init: function() {
			var _this = this;
			this.push();
			$(STOCKMNG02010_GRID_EMPTY).on('click', function() {
				_this.back();
				_this.itp_STOCKMNG02010_param.gridSize = $.jgrid.defaults.rowNum;
				$(STOCKMNG02010_GRID_ID).setGridParam({'postData': JSON.stringify(_this.itp_STOCKMNG02010_param)}).trigger('reloadGrid');
			});
		},
		itp_STOCKMNG02010_param: {},
		push: function() {
			let param = $('#ITP_FORM_STOCKMNG02010_SEARCH').serializeObject();
			listObj.itp_STOCKMNG02010_param = param;
		},
		back: function() {
			$('#ITP_FORM_STOCKMNG02010_DEVI_TP_CD').val(this.itp_STOCKMNG02010_param.deviTpCd);
			$('#ITP_FORM_STOCKMNG02010_ORDER_YN').val(this.itp_STOCKMNG02010_param.orderYn);
			$('#ITP_FORM_STOCKMNG02010_ADT_AUTH_CD').val(this.itp_STOCKMNG02010_param.adtAuthCd);
			$('#ITP_FORM_STOCKMNG02010_EMAIL_RCV_YN').val(this.itp_STOCKMNG02010_param.emailRcvYn);
			$('#ITP_FORM_STOCKMNG02010_MEMB_EXIT_DT').val(this.itp_STOCKMNG02010_param.membExitDt);
			$('#ITP_FORM_STOCKMNG02010_FROM_DT').val(this.itp_STOCKMNG02010_param.fromDt);
			$('#ITP_FORM_STOCKMNG02010_TO_DT').val(this.itp_STOCKMNG02010_param.toDt);
			$('#ITP_FORM_STOCKMNG02010_KEYWORD').val(this.itp_STOCKMNG02010_param.keyword);
		}
	},
	grid: {
		init: function () {
			// 데이터 없을때
			listObj.empty.push();
			this.search();
		},
		colModel: gridColModel.list,
		search: function() {
			pageObj.switchScreen('LIST');
			this.unload();
			this.load();
		},
		load: function() {
			$('#ITP_FORM_STOCKMNG02010_SEARCH_BRAND_ID').val(fn_make_user_info.get('brandId'));
			
			let param = $('#ITP_FORM_STOCKMNG02010_SEARCH').serializeObject();
			param.gridSize = $.jgrid.defaults.rowNum;

			var option = {
				gridId: STOCKMNG02010_GRID_ID,
				colModel: gridColModel.list,
				param: param,
				url: DOMAIN + STOCK_CDD_DETAIL_GRID_LIST,
				pager: STOCKMNG02010_GRID_PAGER,
				onCellSelect: function(rowId, cellIdx, cellValue) {
					var cm = $(this).jqGrid('getGridParam', 'colModel');
					var colNm = cm[cellIdx].name;
					if (colNm == 'cddDt') {
						const cddIdVal = $(this).jqGrid('getCell', rowId, 'cddId');
						
						const key = {cddId: cddIdVal, viewCd: 'R'};
						var param = $.param(key);
						viewObj.init(param);
					}
				},
				loadComplete: function(data) {
					console.log(data);
					itp_fn_grid_load_complete(data, STOCKMNG02010_GRID_ID, true, 'number', 'STOCKMNG02010', listObj.itp_STOCKMNG02010_search, listObj.empty, true, data.gridRecords, true);
					var ids = $(STOCKMNG02010_GRID_ID).getDataIDs();
					$.each(ids, function(idx, rowId) {
						$(STOCKMNG02010_GRID_ID).jqGrid('setCell', rowId, 'cddDt', '', ITP_GRID_COL_STYLE.link);
					});
				},
				onPaging: function(action) {
					itp_fn_grid_paging(STOCKMNG02010_GRID_ID, action, param);
				}
			};
			itp_fn_grid_make_remote(option);
		},
		clearData : function() {
			$(STOCKMNG02010_GRID_ID).jqGrid('clearGridData', true);
			$(STOCKMNG02010_GRID_LIST).find('.ui-jqgrid-bdiv').css('min-height', '100px');
			$(STOCKMNG02010_GRID_EMPTY).html(ITP_MSG_LOCALE.message.grid.noData);
			$(STOCKMNG02010_GRID_EMPTY).show();
		},
		unload : function() {
			$.jgrid.gridUnload(STOCKMNG02010_GRID_ID);
		}
	}
};

/*상세화면 Object*/
let viewObj = {
	init: function (param) {
		this.load(param);
	},
	load: function(param) {
		fn_ajax_call(STOCK_CDD_INFO_CDD, param, this.callback, 'GET');
	},
	callback: function (result) {
		// console.log(result);
		pageObj.switchScreen('VIEW');
		$('#ITP_FORM_STOCKMNG02010_VIEW #ITP_FORM_STOCKMNG02010_VIEW_CDD_ID').val(result.cddId);
		
		$('#ITP_FORM_STOCKMNG02010_VIEW .fnBrandNm').text(result.brandNm);
		$('#ITP_FORM_STOCKMNG02010_VIEW .fnCddMgrNm').text(result.cddMgrNm);
		$('#ITP_FORM_STOCKMNG02010_VIEW .fnWhsId').text(result.whsId);
		$('#ITP_FORM_STOCKMNG02010_VIEW .fnWhsNm').text(result.whsNm);
		$('#ITP_FORM_STOCKMNG02010_VIEW .fnLocation').text(result.locationNm);
		$('#ITP_FORM_STOCKMNG02010_VIEW .fnStoreNm').text(result.storeNm == null ? '' : result.storeNm);
		$('#ITP_FORM_STOCKMNG02010_VIEW .fnCddDtm').text(result.cddDt + ' ' + (result.cddTm == null ? '' : result.cddTm));

		// 권한정보 리스트 조회
		viewObj.grid.init();
	},
	grid: {
		init: function() {
			this.unload();
			this.load();
		},
		load : function() {
			let param = $('#ITP_FORM_STOCKMNG02010_VIEW').serializeObject();
			param.gridSize = $.jgrid.defaults.rowNum;
			param.pagingYn = true; 

			var option = {
				gridId: STOCKMNG02010_VIEW_GRID_ID,
				colModel: gridColModel.view,
				param: param,
				url: DOMAIN + STOCK_CDD_CDD_DETAIL_GRID_LIST,
				pager: STOCKMNG02010_VIEW_GRID_PAGER,
				loadComplete: function(data) {
					itp_fn_grid_load_complete(data, STOCKMNG02010_VIEW_GRID_ID, true, undefined, 'STOCKMNG02010_VIEW');
				},
				onPaging: function(action) {
					var pagingFn = {
						callBack: function(args) {
							$(args).trigger('reloadGrid');
						}
					};
					if (itp_fn_check_grid_is_writing(STOCKMNG02010_VIEW_GRID_ID)) {
						itp_fn_modal_confirm(ITP_MSG_LOCALE.message.ajax.cancelData, pagingFn, STOCKMNG02010_VIEW_GRID_ID);
						return 'stop';
					} else {
						itp_fn_grid_paging(STOCKMNG02010_VIEW_GRID_ID, action, param);
					}
				},
				onSortCol: function(index, columnIndex, sortOrder) {
					var sortingFn = {
						callBack: function(args) {
							$(args).trigger('reloadGrid');
						}
					};
					if (itp_fn_check_grid_is_writing(STOCKMNG02010_VIEW_GRID_ID)) {
						itp_fn_modal_confirm(ITP_MSG_LOCALE.message.ajax.cancelData, sortingFn, STOCKMNG02010_VIEW_GRID_ID);
						return 'stop';
					} else {
						itp_fn_grid_sorting(STOCKMNG02010_VIEW_GRID_ID, index, sortOrder);
					}
				}
			};
			itp_fn_grid_make_remote(option);
		},
		clearData : function() {
			$(STOCKMNG02010_VIEW_GRID_ID).jqGrid('clearGridData', true);
			$(STOCKMNG02010_VIEW_GRID_LIST).find('.ui-jqgrid-bdiv').css('min-height', '100px');
			$(STOCKMNG02010_VIEW_GRID_EMPTY).html(ITP_MSG_LOCALE.message.grid.noData);
			$(STOCKMNG02010_VIEW_GRID_EMPTY).show();
		},
		unload : function() {
			$.jgrid.gridUnload(STOCKMNG02010_VIEW_GRID_ID);
		}
	}
};

/*재고실사 Object*/
let stockCddObj = {
	init: function () {
		this.unload();
		this.load();
	},
	change: function() {
		// 파일선택
		$(document).on('change', '#ITP_FORM_STOCKMNG02010_DETAIL_EXCEL_UPLOAD_SELECT_FILE', function(obj) {						
			var input = obj.target;
		    var reader = new FileReader();
			var rABS = !!reader.readAsBinaryString;
		    reader.onload = function(){
		        var fileData = reader.result;
		        var wb = XLSX.read(fileData, {type : rABS ? 'binary' : 'array'});
		        var sheetNameList = wb.SheetNames; // 시트 이름 목록 가져오기 
		        var firstSheetName = sheetNameList[0]; // 첫번째 시트명
		        var firstSheet = wb.Sheets[firstSheetName]; // 첫번째 시트 
		        var rowObj =XLSX.utils.sheet_to_json(firstSheet, {header:"A", defval: ""});

				// console.log(JSON.stringify(rowObj));
				// console.log(rowObj.length);
				
				$('#ITP_FORM_STOCKMNG02010_DETAIL_EXCEL_UPLOAD_SELECT_FILE').val('');
				if(rowObj.length < 2) {
					itp_fn_modal_alert_ajax('엑셀파일에 실사 품목 데이터를 기술하세요.');
					return;
				} else if(rowObj.length > 1001) {
					itp_fn_modal_alert_ajax('엑셀 일괄처리는 최대 1000건까지 가능합니다.');
					return;
				}				
				
				stockCddObj.button.makeExcelDataList(rowObj);				
		    };
		    if(rABS) reader.readAsBinaryString(input.files[0]); 
			else reader.readAsArrayBuffer(input.files[0]);			
		});
	}, 
	button: {
		cancel: function() {
			listObj.grid.search();
		},
		uploadExcel: function() {			
			stockCddObj.clearData(); 
			// 파일선택
			$('#ITP_FORM_STOCKMNG02010_DETAIL_EXCEL_UPLOAD_SELECT_FILE').click();
		}, 
		downTemplate: function() {
			// var lidx = window.location.href.lastIndexOf('/');
			// window.location.assign(window.location.href.substring(0, lidx) + '/excel_template/stock_cdd_v1.xlsx');
			
			let param = $('#ITP_FORM_STOCKMNG02010_DETAIL').serializeObject();
			param.gridSize = $.jgrid.defaults.rowNum;
			param.pagingYn = false;
			param.whsId = $('#ITP_FORM_STOCKMNG02010_DETAIL_WHS_ID').val();
			param.location = $('#ITP_FORM_STOCKMNG02010_DETAIL_LOCATION').val();
			
			var searhFn = function(result) {
				// 엑셀 다운로드 구현
				// console.log(JSON.stringify(result));
				var today = new Date();
				const version = itp_fn_date_format(today);
				itp_fn_export_excel(result.gridRows, '재고실사_템플릿_'+version+'.xlsx', '재고실사');
			};
			fn_ajax_call(STOCK_MNG_INFO_WHS_ITEM_EXCEL, JSON.stringify(param), searhFn, 'POST');
			
			
		}, 
		makeExcelDataList: function(excelData) {
			var processArray = [];
			
			excelData.shift();
			excelData.some(function(data) {
				var processData = {};				
				processData.itemId 	= data.A.toString().trim(); // 품목아이디		
				// processData.itemNm 	= data.B.toString();
				processData.cddQty 	= data.C.toString(); // 실사수량
				
				processArray.push(processData);
			});
			
			// 엑셀 목록을 서버에서 조회한다.
			const itemMap = new Map();
			const formId = '#ITP_FORM_STOCKMNG02010_DETAIL';
			let param = $(formId).serializeObject();
			param.whsId = $('#ITP_FORM_STOCKMNG02010_DETAIL_WHS_ID').val();
			param.location = $('#ITP_FORM_STOCKMNG02010_DETAIL_LOCATION').val();
			param.gridItemData = processArray;
			//console.log(JSON.stringify(param));
			var callbackFn = function(result) {
				// 엑셀 데이터를 현재고수량 참고하여 ROW를 추가한다.
				// console.log('RESULT : ' + JSON.stringify(result));
				$.each(result.gridRows, function(key, value) {
					itemMap.set(value.itemId.toString(), value);	
				});
				
				var brandId = $('#ITP_FORM_STOCKMNG02010_DETAIL_BRAND_ID').val();
				var brandNm = $('#ITP_FORM_STOCKMNG02010_SEARCH_BRAND_NM').val();
				var whsId = $('#ITP_FORM_STOCKMNG02010_DETAIL_WHS_ID').val();
				var whsNm = $('#ITP_FORM_STOCKMNG02010_DETAIL_WHS_ID option:selected').text();
				var location = $('#ITP_FORM_STOCKMNG02010_DETAIL_LOCATION').val();
				var locationNm = $('#ITP_FORM_STOCKMNG02010_DETAIL_LOCATION option:selected').text();
				
				$.each(processArray, function(key, value) {
					// console.log(JSON.stringify(value));
					// 품목번호 체크
					var normalYn = 'Y';
					var errorMsg = '';
					var itemObject;
					if (!itemMap.has(value.itemId)) {
						normalYn = "N";
						errorMsg = "품목번호 미존재";
					} else {
						itemObject = itemMap.get(value.itemId)
					}
					
					// 행추가
					$(STOCKMNG02010_DETAIL_GRID_ID).jqGrid('addRow', {position: 'last'});
					var rids = $(STOCKMNG02010_DETAIL_GRID_ID).jqGrid('getDataIDs');
					var last_row_id = rids[rids.length - 1];
					$(STOCKMNG02010_DETAIL_GRID_ID).jqGrid('setCell', last_row_id, 'viewCd', 'C');					
					$(STOCKMNG02010_DETAIL_GRID_ID).jqGrid('setCell', last_row_id, 'normalYn', normalYn); // 정상여부
					$(STOCKMNG02010_DETAIL_GRID_ID).jqGrid('setCell', last_row_id, 'errorMsg', errorMsg); 
					$(STOCKMNG02010_DETAIL_GRID_ID).jqGrid('setCell', last_row_id, 'brandId', brandId);
					$(STOCKMNG02010_DETAIL_GRID_ID).jqGrid('setCell', last_row_id, 'brandNm', brandNm);
					$(STOCKMNG02010_DETAIL_GRID_ID).jqGrid('setCell', last_row_id, 'whsId', whsId);
					$(STOCKMNG02010_DETAIL_GRID_ID).jqGrid('setCell', last_row_id, 'whsNm', whsNm);
					$(STOCKMNG02010_DETAIL_GRID_ID).jqGrid('setCell', last_row_id, 'location', location);
					$(STOCKMNG02010_DETAIL_GRID_ID).jqGrid('setCell', last_row_id, 'locationNm', locationNm);
					$(STOCKMNG02010_DETAIL_GRID_ID).jqGrid('setCell', last_row_id, 'itemId', value.itemId);
					$(STOCKMNG02010_DETAIL_GRID_ID).jqGrid('setCell', last_row_id, 'itemNm', itemObject ? itemObject.itemNm : '');
					$(STOCKMNG02010_DETAIL_GRID_ID).jqGrid('setCell', last_row_id, 'unit', itemObject ? itemObject.unit : '');
					$(STOCKMNG02010_DETAIL_GRID_ID).jqGrid('setCell', last_row_id, 'stckQty', itemObject ? itemObject.stckQty : '');
					$(STOCKMNG02010_DETAIL_GRID_ID).jqGrid('setCell', last_row_id, 'cddQty', value.cddQty);										
			 	});
				$(STOCKMNG02010_DETAIL_GRID_EMPTY).hide();
				
			};
			fn_ajax_call(STOCK_MNG_CDD_GRID_LIST, JSON.stringify(param), callbackFn, 'POST');
						
		}, 
		addRow: function() {
			var brandId = $('#ITP_FORM_STOCKMNG02010_DETAIL_BRAND_ID').val();
			var whsId = $('#ITP_FORM_STOCKMNG02010_DETAIL_WHS_ID').val();
			var location = $('#ITP_FORM_STOCKMNG02010_DETAIL_LOCATION').val();
			
			var args = {'brandId': brandId, 'whsId': whsId, 'location': location};
			fn_call_popup('biz', 'BIZPOP_PO_STOCK_ITEM_ADD', '#ITP_ASIDE', stockCddObj.button.addRowCallback, args, 'S');
		}, 
		addRowCallback: function(rowDataPop) {
			var brandId = $('#ITP_FORM_STOCKMNG02010_DETAIL_BRAND_ID').val();
			var brandNm = $('#ITP_FORM_STOCKMNG02010_SEARCH_BRAND_NM').val();
			var whsId = $('#ITP_FORM_STOCKMNG02010_DETAIL_WHS_ID').val();
			var whsNm = $('#ITP_FORM_STOCKMNG02010_DETAIL_WHS_ID option:selected').text();
			var location = $('#ITP_FORM_STOCKMNG02010_DETAIL_LOCATION').val();
			var locationNm = $('#ITP_FORM_STOCKMNG02010_DETAIL_LOCATION option:selected').text();
			
			
			// 기존등록 데이터 체크
			var exists = '';
			const rowData = $(STOCKMNG02010_DETAIL_GRID_ID).getRowData();
			$.each(rowData, function(key, value) {
				exists = exists + value.itemId + ';';
			});

			$.each(rowDataPop, function(key, value) {
				if(exists.indexOf(value.itemId) < 0) {
					// 행추가
					$(STOCKMNG02010_DETAIL_GRID_ID).jqGrid('addRow', {position: 'last'});
					var rids = $(STOCKMNG02010_DETAIL_GRID_ID).jqGrid('getDataIDs');
					var last_row_id = rids[rids.length - 1];
					$(STOCKMNG02010_DETAIL_GRID_ID).jqGrid('setCell', last_row_id, 'viewCd', 'C');					
					$(STOCKMNG02010_DETAIL_GRID_ID).jqGrid('setCell', last_row_id, 'normalYn', 'Y'); // 정상여부
					$(STOCKMNG02010_DETAIL_GRID_ID).jqGrid('setCell', last_row_id, 'brandId', brandId);
					$(STOCKMNG02010_DETAIL_GRID_ID).jqGrid('setCell', last_row_id, 'brandNm', brandNm);
					$(STOCKMNG02010_DETAIL_GRID_ID).jqGrid('setCell', last_row_id, 'whsId', whsId);
					$(STOCKMNG02010_DETAIL_GRID_ID).jqGrid('setCell', last_row_id, 'whsNm', whsNm);
					$(STOCKMNG02010_DETAIL_GRID_ID).jqGrid('setCell', last_row_id, 'location', location);
					$(STOCKMNG02010_DETAIL_GRID_ID).jqGrid('setCell', last_row_id, 'locationNm', locationNm);
					$(STOCKMNG02010_DETAIL_GRID_ID).jqGrid('setCell', last_row_id, 'itemId', value.itemId);
					$(STOCKMNG02010_DETAIL_GRID_ID).jqGrid('setCell', last_row_id, 'itemNm', value.itemNm);
					$(STOCKMNG02010_DETAIL_GRID_ID).jqGrid('setCell', last_row_id, 'unit', value.unit);
					$(STOCKMNG02010_DETAIL_GRID_ID).jqGrid('setCell', last_row_id, 'stckQty', value.stckQty);
				}
			});
			$(STOCKMNG02010_DETAIL_GRID_EMPTY).hide();
		}, 
		save: function() {
			const formId = '#ITP_FORM_STOCKMNG02010_DETAIL';
			itp_fn_form_clear_validate(null, formId);
			
			var vali_cddDt = itp_fn_form_validate(formId, formId + '_CDD_DT', ['empty'], undefined); 
			var vali_cddDvsn = itp_fn_form_validate(formId, formId + '_CDD_DVSN', ['empty'], undefined);
			
			if (vali_cddDt && vali_cddDvsn) {
				let gridInsertData = [];
				const rowData = $(STOCKMNG02010_DETAIL_GRID_ID).getRowData();
				
				if(rowData.length < 1) {
					itp_fn_modal_alert_ajax(ITP_MSG_LOCALE.message.grid.noData);
					return;
				}	
				var cddQtyCheck = true;			
				var normalYnCheck = true;			
				$.each(rowData, function(key, value) {
					if (value.cddQty == '' || isNaN(value.cddQty)) {
						cddQtyCheck = false;
					}		
					if (value.normalYn == 'N') {
						normalYnCheck = false;
					}			
					gridInsertData.push(value);
				});
				// 데이터 체크
				if(!cddQtyCheck) {
					itp_fn_modal_alert_ajax('실사수량을 입력하세요.');
					return;
				}			
				if(!normalYnCheck) {
					itp_fn_modal_alert_ajax('정상여부 값이 N인 데이터가 있습니다.\n품목번호를 확인하세요.');
					return;
				}	
				let param = $(formId).serializeObject();
				param.whsId = $('#ITP_FORM_STOCKMNG02010_DETAIL_WHS_ID').val();
				param.location = $('#ITP_FORM_STOCKMNG02010_DETAIL_LOCATION').val();
				param.gridInsertData = gridInsertData;
				// console.log(JSON.stringify(param));
				var searhFn = function() {
					ITP_FORM_STOCKMNG02010_DETAIL_IS_WRITING = false;
					listObj.grid.search();
				};
				fn_ajax_call(STOCK_CDD_SAVE_STOCK_CDD, JSON.stringify(param), searhFn, 'POST');
			}
		}
	},
	load: function () {
		let param = $('#ITP_FORM_STOCKMNG02010_DETAIL').serializeObject();
		param.gridSize = $.jgrid.defaults.rowNum;
		param.pagingYn = false; // 페이지안함

		var option = {
			gridId: STOCKMNG02010_DETAIL_GRID_ID,
			colModel: gridColModel.detail,
			param: param,
			url: DOMAIN + WHS_MNG_LOCATION_GRID_LIST,
			pager: STOCKMNG02010_DETAIL_GRID_PAGER,
			// multiselect: true,
			onCellSelect: function(rowId, cellIdx, cellValue) {
				STOCKMNG02010_DETAIL_GRID_LAST_ROW_ID = itp_fn_set_data_editable(rowId, cellIdx, STOCKMNG02010_DETAIL_GRID_LAST_ROW_ID, STOCKMNG02010_DETAIL_GRID_ID);
	   		},
			loadComplete: function(data) {
				itp_fn_grid_load_complete(data, STOCKMNG02010_DETAIL_GRID_ID, true, undefined, 'STOCKMNG02010_DETAIL');
			},
			onPaging: function(action) {
				var pagingFn = {
					callBack: function(args) {
						$(args).trigger('reloadGrid');
					}
				};
				if (itp_fn_check_grid_is_writing(STOCKMNG02010_DETAIL_GRID_ID)) {
					itp_fn_modal_confirm(ITP_MSG_LOCALE.message.ajax.cancelData, pagingFn, STOCKMNG02010_DETAIL_GRID_ID);
					return 'stop';
				} else {
					itp_fn_grid_paging(STOCKMNG02010_DETAIL_GRID_ID, action, param);
				}
			},
			onSortCol: function(index, columnIndex, sortOrder) {
				var sortingFn = {
					callBack: function(args) {
						$(args).trigger('reloadGrid');
					}
				};
				if (itp_fn_check_grid_is_writing(STOCKMNG02010_DETAIL_GRID_ID)) {
					itp_fn_modal_confirm(ITP_MSG_LOCALE.message.ajax.cancelData, sortingFn, STOCKMNG02010_DETAIL_GRID_ID);
					return 'stop';
				} else {
					itp_fn_grid_sorting(STOCKMNG02010_DETAIL_GRID_ID, index, sortOrder);
				}
			}
		};
		itp_fn_grid_make_remote(option);
	},
	clearData : function() {
		$(STOCKMNG02010_DETAIL_GRID_ID).jqGrid('clearGridData', true);
		$(STOCKMNG02010_DETAIL_GRID_LIST).find('.ui-jqgrid-bdiv').css('min-height', '100px');
		$(STOCKMNG02010_DETAIL_GRID_EMPTY).html(ITP_MSG_LOCALE.message.grid.noData);
		$(STOCKMNG02010_DETAIL_GRID_EMPTY).show();
	},
	unload : function() {
		$.jgrid.gridUnload(STOCKMNG02010_DETAIL_GRID_ID);
	}
};
