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


//화면변수
const INOUTMNG02010_GRID_ID = '#ITP_INOUTMNG02010_jqGrid';
const INOUTMNG02010_GRID_LIST = '#ITP_INOUTMNG02010_jqGrid_list';
const INOUTMNG02010_GRID_PAGER = '#ITP_INOUTMNG02010_jqGridPager';
const INOUTMNG02010_GRID_EMPTY = '#ITP_INOUTMNG02010_jqGridEmpty';

let ITP_PODR_DTL_ST_CD = fn_make_common_cd_list(CODE_LIST, 'SHMT_REQ_ST_CD', true, '출하요청상태코드');

//API URL
let API_POMNG_INOUTMNG_OUTSEARCH_GRID_LIST = '/api/pomng/inoutmng/outsearch-grid-list';
let API_POMNG_INOUTMNG_INFO_INV = '/api/pomng/inoutmng/info-inv';


//화면 grid ColModel
const gridColModel = {
	list:[
		{
			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: ITP_MSG_LOCALE.label.brandNm,				// 브랜드명
			minwidth: 100,
			width: '10', fixed: false, align: 'left',
			sortable: false, hidden: false, classes: 'ui-ellipsis'
		},
		{
			index: 'SHMT_REQ_UNQ_NO', name: 'shmtReqUnqNo',
			label: ITP_MSG_LOCALE.label.shmtReqUnqNo,			// 출하지시번호
			minwidth: 140,
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'PCH_PODR_UNQ_NO', name: 'pchPodrUnqNo',
			label: ITP_MSG_LOCALE.label.pchPodrUnqNo,			// 발주번호
			minwidth: 140,
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'PCH_PODR_DTL_NO', name: 'pchPodrDtlNo',
			label: ITP_MSG_LOCALE.label.pchPodrDtlNo,			// 발주항번
			width: '8', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'SHMT_REQ_ST_CD', name: 'shmtReqStCd',
			label: ITP_MSG_LOCALE.label.shmtReqStCd,			// 출하상태코드
			minwidth: 120,
			width: '9', fixed: false, align: 'center',
			sortable: false, hidden: false, formatter: 'select', edittype: 'select',
			editoptions: {value: ITP_PODR_DTL_ST_CD}
		},
		{
			index: 'ITEM_ID', name: 'itemId',
			label: ITP_MSG_LOCALE.label.itemId,					// 품목번호
			minwidth: 140,
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'ITEM_NM', name: 'itemNm',
			label: ITP_MSG_LOCALE.label.itemNm,					// 품목명
			width: '10', fixed: false, align: 'left',
			minwidth: 100,
			sortable: false, hidden: false, classes: 'ui-ellipsis'
		},
		{
			index: 'WHS_NM', name: 'whsNm',
			label: ITP_MSG_LOCALE.label.whsNm,					// 납품장소
			width: '10', fixed: false, align: 'left',
			minwidth: 160,
			sortable: false, hidden: false, classes: 'ui-ellipsis'
		},
		{
			index: 'SHMT_QTY', name: 'shmtQty',
			label: ITP_MSG_LOCALE.label.shmtQty,				// 출하수량
			width: '12', fixed: false, align: 'right',
			sortable: false, hidden: false,
			formatter:'integer',formatoptions: { defaultValue: '', thousandsSeparator: ',' }
		},
		{
			index: 'SHMT_AMT', name: 'shmtAmt',
			label: ITP_MSG_LOCALE.label.shmtAmt,				// 출하금액
			width: '12', fixed: false, align: 'right',
			minwidth: 80,
			sortable: false, hidden: false,
			formatter:'integer',formatoptions: { defaultValue: '', thousandsSeparator: ',' }
		},
		{
			index: 'WHS_QTY', name: 'whsQty',
			label: ITP_MSG_LOCALE.label.whsQty,					// 입고수량
			width: '12', fixed: false, align: 'right',
			sortable: false, hidden: false,
			formatter:'integer',formatoptions: { defaultValue: '', thousandsSeparator: ',' }
		},
		{
			index: 'WHS_AMT', name: 'whsAmt',
			label: ITP_MSG_LOCALE.label.whsAmt,					// 입고금액
			width: '12', fixed: false, align: 'right',
			sortable: false, hidden: false,
			formatter:'integer',formatoptions: { defaultValue: '', thousandsSeparator: ',' }
		},
		{
			index: 'WHS_CNFM_NM', name: 'whsCnfmNm',
			label: ITP_MSG_LOCALE.label.whsCnfmNm,				// 입고확인자
			width: '13', fixed: false, align: 'center',
			minwidth: 100,
			sortable: false, hidden: false
		},
		{
			index: 'WHS_DT', name: 'whsDt',
			label: ITP_MSG_LOCALE.label.whsDt,					// 입고일
			width: '9', fixed: false, align: 'center',
			minwidth: 100,
			sortable: false, hidden: false
		},
		{
			index: 'DLV_STTMT_UNQ_NO', name: 'dlvSttmtUnqNo',
			label: ITP_MSG_LOCALE.label.dlvSttmtUnqNo,			// 납품번호
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: true
		}
	],
	view: [],
	detail: []
}


/*화면공통 Object*/
let pageObj = {
	init: function() {
		this.ui.init();
		this.event.init();
		this.action();
	},
	ui: {
		init: function() {
			this.view();
			this.grid();
			this.ready();
		},
		view: function() {
			// 버튼 권한설정
			fn_proc_btn_auth('INOUTMNG02010');
			// 공통코드 표시
			$('select').each(function() {
				if($(this).data('select-code')) {
					fn_make_select(CODE_LIST, $(this).data('select-code'), $(this).attr('id'));
				}
			});
			// 조회일자 지정	
			var now = new Date();
			var defaultToDate = new Date(now);
			defaultToDate.setDate(now.getDate() + 7);
			$('#ITP_TAB_INOUTMNG02010 .input-group.date').datepicker(ITP_DATE_LANGUAGE);
			$('#ITP_FORM_INOUTMNG02010_SEARCH_FROM_DT').datepicker('setDate', now);
			$('#ITP_FORM_INOUTMNG02010_SEARCH_TO_DT').datepicker('setDate', defaultToDate);
		},
		grid: function() {
			itp_fn_jqgrid_resize(INOUTMNG02010_GRID_ID, INOUTMNG02010_GRID_LIST, 'lg');
			//listObj.empty.init();
			
		},
		ready: function() {
			listObj.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_INOUTMNG02010_SRH'				: listObj.button.search();		break;	// 조회 버튼 클릭
						case 'ITP_BTN_INOUTMNG02010_NEWREG'				: listObj.button.create(); 		break;	// 신규등록 버튼
						case 'ITP_BTN_INOUTMNG02010_MODIFY'				: modifyObj.button.modify();	break;	// 수정 버튼
						case 'ITP_BTN_INOUTMNG02010_CANCELLIST'			: modifyObj.button.cancel(); 	break;	// 취소/목록 버튼
						case 'ITP_BTN_INOUTMNG02010_DELETE'				: modifyObj.button.del();		break;	// 발주 취소 버튼(예정)
						case 'ITP_BTN_INOUTMNG02010_EXCEL'				: listObj.excelDown();		break;	// 엑셀다운로드
					}
				});
			});
		}
	},
	switchScreen: function(mode) {
        $('.itp_det_head').find('button[id^="ITP_BTN_INOUTMNG02010_"]').each(function(i) {
            $(this).hide();
        });
        $('#ITP_TAB_INOUTMNG02010').find('div[id$="_CONTAINER"]').each(function(i) {
            $(this).hide();
        });
        if(mode == 'LIST') { // 목록
			itp_fn_fire_window_resize();
            fn_show_btn_auth_array(['#ITP_BTN_INOUTMNG02010_SRH', '#ITP_BTN_INOUTMNG02010_NEWREG']);
            $('#ITP_AJAX_INOUTMNG02010_LIST_CONTAINER').show();
            $('#ITP_FORM_INOUTMNG02010_SEARCH #ITP_FORM_INOUTMNG02010_SEARCH_BRAND_ID').val(fn_make_user_info.get('brandId'));
            $('#ITP_BTN_INOUTMNG02010_PRINT').show();
            $('#ITP_BTN_INOUTMNG02010_SRH').show();            
            $('#ITP_BTN_INOUTMNG02010_SEARCH_SHMT_WHS_ID').show();
            $('#ITP_BTN_INOUTMNG02010_DELETE_SHMT_WHS_NM').show();
            $('#ITP_BTN_INOUTMNG02010_SEARCH_WHS_ID').show();
            $('#ITP_BTN_INOUTMNG02010_DELETE_WHS_ID').show();
			$('#ITP_BTN_INOUTMNG02010_EXCEL').show();
            
        } /*else if(mode == 'ADD') { // 등록
            $('#ITP_AJAX_INOUTMNG02010_DETAIL_CONTAINER').show();
            fn_show_btn_auth_array(['#ITP_BTN_INOUTMNG02010_CANCELLIST', '#ITP_BTN_INOUTMNG02010_SAVE']);

            $('#ITP_FORM_INOUTMNG02010_DETAIL').find('input, textarea, select, checkbox').each(function(i, elem) {
                $(this).attr('id') === 'ITP_FORM_INOUTMNG02010_DETAIL_VIEW_CD' ? $(this).val('C') : $(this).val('');
                if(elem.type === 'select') {
                    $(this).val('').prop('selected', true);
                }
            });
            $('#ITP_FORM_INOUTMNG02010_DETAIL #ITP_FORM_INOUTMNG02010_DETAIL_FILE_NO').val('');
            $('#ITP_FORM_INOUTMNG02010_DETAIL_BRAND_ID').removeAttr('readonly');
            $('#ITP_FORM_INOUTMNG02010_DETAIL_BRAND_NM').removeAttr('readonly');
            $('#ITP_FORM_INOUTMNG02010_DETAIL_BSNS_REG_NO').removeAttr('readonly');
            $('#ITP_FORM_INOUTMNG02010_DETAIL_CORP_REG_NO').removeAttr('readonly');
            // $('#ITP_FORM_INOUTMNG02010_DETAIL_SEARCH_AFFL_SHOP').removeAttr('disabled');
            // $('#ITP_FORM_INOUTMNG02010_DETAIL_DELETE_AFFL_SHOP').removeAttr('disabled');
            $('#ITP_FORM_INOUTMNG02010_DETAIL_SEARCH_AFFL_SHOP').show();
            $('#ITP_FORM_INOUTMNG02010_DETAIL_DELETE_AFFL_SHOP').show();
			$('#ITP_FORM_INOUTMNG02010_DETAIL .itp_form_info').hide();
			$('#ITP_FORM_INOUTMNG02010_DETAIL .itp_form_change').show();

            $('#ITP_FORM_INOUTMNG02010_DETAIL #ITP_FORM_INOUTMNG02010_DETAIL_AFFL_SHOP_ID').val(fn_make_user_info.get('afflShopId'));
            $('#ITP_FORM_INOUTMNG02010_DETAIL #ITP_FORM_INOUTMNG02010_DETAIL_BRAND_ID').val(fn_make_user_info.get('brandId'));

            $('.fnBrandId').text('(자동부여)');
        } else if(mode == 'MODIFY') { // 수정
            $('#ITP_AJAX_INOUTMNG02010_DETAIL_CONTAINER').show();
            fn_show_btn_auth_array(['#ITP_BTN_INOUTMNG02010_CANCELLIST', '#ITP_BTN_INOUTMNG02010_SAVE']);

            $('#ITP_BTN_INOUTMNG02010_CANCELLIST').show();
            $('#ITP_BTN_INOUTMNG02010_DELETE').show();
            
            $('#ITP_FORM_INOUTMNG02010_DETAIL_BRAND_ID').attr('readonly', true);
            $('#ITP_FORM_INOUTMNG02010_DETAIL_BRAND_NM').attr('readonly', true);
            $('#ITP_FORM_INOUTMNG02010_DETAIL_BSNS_REG_NO').attr('readonly', true);
            $('#ITP_FORM_INOUTMNG02010_DETAIL_CORP_REG_NO').attr('readonly', true);
            // $('#ITP_FORM_INOUTMNG02010_DETAIL_SEARCH_AFFL_SHOP').attr('disabled', true);
            // $('#ITP_FORM_INOUTMNG02010_DETAIL_DELETE_AFFL_SHOP').attr('disabled', true);
            $('#ITP_FORM_INOUTMNG02010_DETAIL_SEARCH_AFFL_SHOP').hide();
            $('#ITP_FORM_INOUTMNG02010_DETAIL_DELETE_AFFL_SHOP').hide();
			$('#ITP_FORM_INOUTMNG02010_DETAIL .itp_form_info').show();
			$('#ITP_FORM_INOUTMNG02010_DETAIL .itp_form_change').hide();

            $('#ITP_FORM_INOUTMNG02010_DETAIL #ITP_FORM_INOUTMNG02010_DETAIL_BRAND_ID').val(fn_make_user_info.get('brandId'));
        } else if(mode == 'VIEW') { // 보기
            $('#ITP_AJAX_INOUTMNG02010_VIEW_CONTAINER').show();
            fn_show_btn_auth_array(['#ITP_BTN_INOUTMNG02010_MODIFY', '#ITP_BTN_INOUTMNG02010_CANCELLIST']);
        }*/
    },
    action: function() {
    	var _this = this;
    	// 출하창고 조회 버튼 클릭
		$('#ITP_BTN_INOUTMNG02010_PRINT').on('click', function() {
			_this.popup();
		});
	},
	popup: function() {		
		var selectedIds = $(INOUTMNG02010_GRID_ID).getGridParam('selarrrow');
		if(selectedIds.length > 1) { // 1이상 선택시
			alert("납품서 하나만 선택해주세요 (대표 납품서번호)") ;//출력
			return; //리턴
		}
		var selRowData ; //변수선언		
		for (var i=selectedIds.length-1; i>=0; i--) {		//1개만 선택시
			selRowData = $(INOUTMNG02010_GRID_ID).jqGrid('getRowData', selectedIds[i]);		//cell 선택
		}
		const key = {brandId: fn_make_user_info.get('brandId'), dlvSttmtUnqNo: selRowData.dlvSttmtUnqNo};		// popup key 값 설정
		fn_call_popup('biz', 'BIZPOP_DLV_STTMT_PRN', '#ITP_ASIDE', null, key, 'S');
	}
};


/*목록화면 Object*/
let listObj = {
	init: function() {
		this.grid.init();
		this.action();
	},
	itp_INOUTMNG02010_param: {},
	itp_INOUTMNG02010_search: false,
	button: {
		search: function() {
			listObj.itp_INOUTMNG02010_search = true;
			let param = $('#ITP_FORM_INOUTMNG02010_SEARCH').serializeObject();
			param.gridSize = $.jgrid.defaults.rowNum;
            param.gridPage = $.jgrid.defaults.page;
            param.sidx = '0';
            console.log(JSON.stringify(param));
			$(INOUTMNG02010_GRID_ID).data('grid-param',param);
            $(INOUTMNG02010_GRID_ID).setGridParam({'postData': JSON.stringify(param)}).trigger('reloadGrid');
        }
	},
	empty: {
		init: function() {
			/*
			var _this = this;
            this.push();
            $(INOUTMNG02010_GRID_EMPTY).on('click', function() {
                _this.back();
                listObj.itp_INOUTMNG02010_param.gridSize = $.jgrid.defaults.rowNum;
                $(INOUTMNG02010_GRID_ID).setGridParam({'postData': JSON.stringify(listObj.itp_INOUTMNG02010_param)}).trigger('reloadGrid');
            });
*/
		},
		push: function() {
			/*
            let param = $('#ITP_FORM_INOUTMNG02010_SEARCH').serializeObject();
            listObj.itp_INOUTMNG02010_param = param;
            param.sidx = '0';
*/
        },
        back: function() {
	/*
            $('#ITP_FORM_INOUTMNG02010_SERVICE_BRAND_TYPE').val(listObj.itp_INOUTMNG02010_param.brandType);
            $('#ITP_FORM_INOUTMNG02010_SERVICE_ST_CD').val(listObj.itp_INOUTMNG02010_param.stCd);
            $('#ITP_FORM_INOUTMNG02010_SEARCH_BRAND_NM').val(listObj.itp_INOUTMNG02010_param.brandNm);
*/
        }
	},
	grid: {
		init: function() {
			// 데이터 없을때
            listObj.empty.push();
            this.search();
		},
		colModel: gridColModel.list,
		search: function() {
			pageObj.switchScreen('LIST');
			this.unload();
			this.load();
		},
		load: function() {
            let param = $('#ITP_FORM_INOUTMNG02010_SEARCH').serializeObject();
            param.gridSize = $.jgrid.defaults.rowNum;
            param.sidx = '0';
            console.log(JSON.stringify(param));
            var option = {
            	gridId: INOUTMNG02010_GRID_ID,
            	colModel: gridColModel.list,
            	param: param,
            	url: DOMAIN + API_POMNG_INOUTMNG_OUTSEARCH_GRID_LIST,
            	pager: INOUTMNG02010_GRID_PAGER,
				multiselect: true,
				multiboxonly : false,
				rownumbers: false,/*
            	onCellSelect: function(rowId, cellIdx, cellValue) {
                    var cm = $(this).jqGrid('getGridParam', 'colModel');
                    var colNm = cm[cellIdx].name;
                    if (colNm === 'pchPodrUnqNo') {
                        const dlvSttmtUnqNoVal = $(this).jqGrid('getCell', rowId, 'dlvSttmtUnqNo');
                        const brandIdVal = $(this).jqGrid('getCell', rowId, 'brandId');
                        const key = {dlvSttmtUnqNo: dlvSttmtUnqNoVal, brandId: brandIdVal};
                        var param = $.param(key);
                        //modifyObj.init(param);
                    }
				},*/
				loadComplete: function(data) {
					console.log(data);
                    itp_fn_grid_load_complete(data, INOUTMNG02010_GRID_ID, true, 'number', 'INOUTMNG02010', listObj.itp_INOUTMNG02010_search, listObj.empty, true, data.gridRecords, true);
				},
				onPaging: function(action) {
                    itp_fn_grid_paging(INOUTMNG02010_GRID_ID, action, param);
                }
            };
            itp_fn_grid_make_remote(option);
		},
		clearData: function() {
			$(INOUTMNG02010_GRID_ID).jqGrid('clearGridData', true);
            $(INOUTMNG02010_GRID_LIST).find('.ui-jqgrid-bdiv').css('min-height', '100px');
            $(INOUTMNG02010_GRID_EMPTY).html(ITP_MSG_LOCALE.message.grid.noData);
            $(INOUTMNG02010_GRID_EMPTY).show();
		},
		unload: function() {
			$.jgrid.gridUnload(INOUTMNG02010_GRID_ID);
		}
	},
	action: function() {
		var _this = this;
		// 출하창고 조회 버튼 클릭
		$('#ITP_BTN_INOUTMNG02010_SEARCH_SHMT_WHS_ID').on('click', function() {
			_this.popup('shmtWhs');
		});
		// 출하창고 텍스트 삭제 버튼 클릭
		$('#ITP_BTN_INOUTMNG02010_DELETE_SHMT_WHS_NM').on('click', function() {
			$('#ITP_FORM_INOUTMNG02010_DETAIL_SHMT_WHS_ID').val('');
			$('#ITP_FORM_INOUTMNG02010_DETAIL_SHMT_WHS_NM').val('');
		});
		// 매장/창고 조회 버튼 클릭
		$('#ITP_BTN_INOUTMNG02010_SEARCH_WHS_ID').on('click', function() {
			_this.popup('whs');
		});
		// 매장/창고 텍스트 삭제 버튼 클릭
		$('#ITP_BTN_INOUTMNG02010_DELETE_WHS_ID').on('click', function() {
			$('#ITP_FORM_INOUTMNG02010_DETAIL_WHS_NM').val('');
			$('#ITP_FORM_INOUTMNG02010_DETAIL_WHS_ID').val('');
		});
	},
	popup: function(keyword) {
		var popFn ;
		
		if(keyword == 'shmtWhs') {
			popFn = this.callback.shmtWhs;
		} else if(keyword == 'whs'){
			popFn = this.callback.whs;
		}
		
		var whsDvsn = "";
		if(keyword == 'shmtWhs') {
			whsDvsn = "W01";
		} else if(keyword == 'whs'){
			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: {
		shmtWhs: function(rowDataPop) {
			console.log(rowDataPop);
			$('#ITP_FORM_INOUTMNG02010_DETAIL_SHMT_WHS_ID').val(rowDataPop.whsId);
			$('#ITP_FORM_INOUTMNG02010_DETAIL_SHMT_WHS_NM').val(rowDataPop.whsNm);
			
		},
		whs: function(rowDataPop) {
			console.log(rowDataPop);
			$('#ITP_FORM_INOUTMNG02010_DETAIL_WHS_ID').val(rowDataPop.whsId);
			$('#ITP_FORM_INOUTMNG02010_DETAIL_WHS_NM').val(rowDataPop.whsNm);
		}
	},
	excelDown: function() {
		var param = {
			'url': API_POMNG_INOUTMNG_OUTSEARCH_GRID_LIST,
			'param': $('#ITP_FORM_INOUTMNG02010_SEARCH').serializeObject(),
			'gridColumns': $(INOUTMNG02010_GRID_ID).jqGrid('getGridParam', 'colModel'),
			'fileName': '출하지시현황.xlsx',
			'sheetName': '출하지시현황리스트'
		};
		itp_fn_remote_to_excel(param);
	}
}

