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


//화면변수
const COLLMNG01010_GRID_ID = '#ITP_COLLMNG01010_jqGrid';
const COLLMNG01010_GRID_LIST = '#ITP_COLLMNG01010_jqGrid_list';
const COLLMNG01010_GRID_PAGER = '#ITP_COLLMNG01010_jqGridPager';
const COLLMNG01010_GRID_EMPTY = '#ITP_COLLMNG01010_jqGridEmpty';

const COLLMNG01010_DETAIL_GRID_ID = '#ITP_COLLMNG01010_DETAIL_jqGrid';
const COLLMNG01010_DETAIL_GRID_LIST = '#ITP_COLLMNG01010_DETAIL_jqGrid_list';
const COLLMNG01010_DETAIL_GRID_PAGER = '#ITP_COLLMNG01010_DETAIL_jqGridPager';
const COLLMNG01010_DETAIL_GRID_EMPTY = '#ITP_COLLMNG01010_DETAIL_jqGridEmpty';


//API URL
let API_RTNMNG_RTN_SPPLY_RTN_GRID_LIST = '/api/rtnmng/rtn/spply-rtn-grid-list';
let API_RTNMNG_RTN_INFO_INFO_RTNODR = '/api/rtnmng/rtn/info-rtnOdr';


//화면 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, 			// 브랜드명
			width: '10', fixed: false, align: 'left',
			sortable: false, hidden: false, classes: 'ui-ellipsis'
		},
		{
			index: 'RTN_PODR_UNQ_NO', name: 'rtnPodrUnqNo',
			label: ITP_MSG_LOCALE.label.rtnPodrUnqNo, 		// 반품발주번호
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'RTN_ODR_STNM', name: 'rtnOdrStNm',
			label: ITP_MSG_LOCALE.label.rtnOdrStNm, 		// 번품발주상태명
			width: '8', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'RTN_ODR_REG_DT', name: 'rtnOdrRegDt',
			label: ITP_MSG_LOCALE.label.rtnOdrRegDt, 		// 반품발주일자
			width: '7', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'COL_REQ_DT', name: 'colReqDt',
			label: ITP_MSG_LOCALE.label.colReqDt, 			// 수거요청일
			width: '7', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'RTN_WHS_NM', name: 'rtnWhsNm',
			label: ITP_MSG_LOCALE.label.rtnWhsNm, 			// 수거장소
			width: '10', fixed: false, align: 'left',
			sortable: false, hidden: false, classes: 'ui-ellipsis'
		},
		{
			index: 'RTN_DODR_TOTAL_AMT', name: 'rtnDodrTotalAmt',
			label: ITP_MSG_LOCALE.label.rtnDodrTotalAmt, 	// 총 수거금액
			width: '7', fixed: false, align: 'right',
			sortable: false, hidden: false,
			formatter: 'integer', formatoptions: {thousandsSeparator: ','}
		},
		{
			index: 'RTN_DODR_ITEM_QTY', name: 'rtnDodrItemQty',
			label: ITP_MSG_LOCALE.label.rtnDodrItemQty, 	// 수거품목수
			width: '6', fixed: false, align: 'right',
			sortable: false, hidden: false
		},
		{
			index: 'RTN_MGR_NM', name: 'rtnMgrNm',
			label: ITP_MSG_LOCALE.label.rtnMgrNm, 			// 수거 담당자
			width: '7', fixed: false, align: 'center',
			sortable: false, hidden: false, classes: 'ui-ellipsis'
		}
	],
	view: [],
	detail: [
		{
			index: 'RTN_PODR_DTL_NO', name: 'rtnPodrDtlNo',
			label: ITP_MSG_LOCALE.label.rtnPodrDtlNo, 		// 반품발주항번
			width: '6', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'ITEM_ID', name: 'itemId',
			label: ITP_MSG_LOCALE.label.itemId, 			// 품목번호
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'ITEM_NM', name: 'itemNm',
			label: ITP_MSG_LOCALE.label.itemNm, 			// 품목명
			width: '16', fixed: false, align: 'left',
			sortable: false, hidden: false, classes: 'ui-ellipsis'
		},
		{
			index: 'UNIT_AMT', name: 'unitAmt',
			label: ITP_MSG_LOCALE.label.unitAmt, 			// 단가
			width: '7', fixed: false, align: 'right',
			sortable: false, hidden: false,
			formatter: 'integer', formatoptions: {thousandsSeparator: ','}
		},
		{
			index: 'UNIT', name: 'unit',
			label: ITP_MSG_LOCALE.label.unit, 				// 기본단위
			width: '5', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'RTN_ODR_QTY', name: 'rtnOdrQty',
			label: ITP_MSG_LOCALE.label.rtnOdrQty, 			// 수거수량
			width: '7', fixed: false, align: 'right',
			sortable: false, hidden: false
		},
		{
			index: 'RTN_ODR_AMT', name: 'rtnOdrAmt',
			label: ITP_MSG_LOCALE.label.rtnAmt, 			// 수거금액
			width: '7', fixed: false, align: 'right',
			sortable: false, hidden: false,
			formatter: 'integer', formatoptions: {thousandsSeparator: ','}
		},
		{
			index: 'COL_REQ_DT', name: 'colReqDt',
			label: ITP_MSG_LOCALE.label.colReqDt, 			// 수거요청일
			width: '6', fixed: false, align: 'center',
			sortable: false, hidden: false
		}
	]
};


/*화면공통 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('COLLMNG01010');
			// 공통코드 표시
			$('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_COLLMNG01010 .input-group.date').datepicker(ITP_DATE_LANGUAGE);
			$('#ITP_FORM_COLLMNG01010_SEARCH_FROM_DT').datepicker('setDate', now);
			$('#ITP_FORM_COLLMNG01010_SEARCH_TO_DT').datepicker('setDate', defaultToDate);
		},
		grid: function() {
			//itp_fn_jqgrid_resize(COLLMNG01010_GRID_ID, COLLMNG01010_GRID_LIST, 'lg');
			itp_fn_fire_window_resize();
		},
		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_COLLMNG01010_SRH'				: listObj.button.search();		break;	// 조회 버튼 클릭
						case 'ITP_BTN_COLLMNG01010_NEWREG'			: listObj.button.create(); 		break;	// 신규등록 버튼
						case 'ITP_BTN_COLLMNG01010_MODIFY'			: modifyObj.button.modify();	break;	// 수정 버튼
						case 'ITP_BTN_COLLMNG01010_CANCELLIST'		: viewObj.button.cancel(); 		break;	// 취소/목록 버튼
						case 'ITP_BTN_COLLMNG01010_DELETE'			: 								break;	// 삭제 버튼
						case 'ITP_BTN_COLLMNG01010_EXCEL'			: listObj.excelDown();			break;	// 엑셀 다운로드
					}
				});
			});
		}
	},
	switchScreen: function(mode) {
        $('.itp_det_head').find('button[id^="ITP_BTN_COLLMNG01010_"]').each(function(i) {
            $(this).hide();
        });
        $('#ITP_TAB_COLLMNG01010').find('div[id$="_CONTAINER"]').each(function(i) {
            $(this).hide();
        });
        if(mode == 'LIST') { // 목록
            fn_show_btn_auth_array(['#ITP_BTN_COLLMNG01010_SRH', '#ITP_BTN_COLLMNG01010_NEWREG']);
            $('#ITP_AJAX_COLLMNG01010_LIST_CONTAINER').show();
            $('#ITP_FORM_COLLMNG01010_SEARCH #ITP_FORM_COLLMNG01010_SEARCH_BRAND_ID').val(fn_make_user_info.get('brandId'));
            $('#ITP_FORM_COLLMNG01010_SEARCH #ITP_FORM_COLLMNG01010_SEARCH_SPPLY_ID').val(fn_make_user_info.get('spplyId'));
            $('#ITP_BTN_COLLMNG01010_SEARCH_WHS_NM').show();
            $('#ITP_BTN_COLLMNG01010_DELETE_WHS_NM').show();
            $('#ITP_BTN_COLLMNG01010_EXCEL').show();
        } /*else if(mode == 'ADD') { // 등록
            $('#ITP_AJAX_COLLMNG01010_DETAIL_CONTAINER').show();
            fn_show_btn_auth_array(['#ITP_BTN_COLLMNG01010_CANCELLIST', '#ITP_BTN_COLLMNG01010_SAVE']);

            $('#ITP_FORM_COLLMNG01010_DETAIL').find('input, textarea, select, checkbox').each(function(i, elem) {
                $(this).attr('id') === 'ITP_FORM_COLLMNG01010_DETAIL_VIEW_CD' ? $(this).val('C') : $(this).val('');
                if(elem.type === 'select') {
                    $(this).val('').prop('selected', true);
                }
            });
            $('#ITP_FORM_COLLMNG01010_DETAIL #ITP_FORM_COLLMNG01010_DETAIL_FILE_NO').val('');
            $('#ITP_FORM_COLLMNG01010_DETAIL_BRAND_ID').removeAttr('readonly');
            $('#ITP_FORM_COLLMNG01010_DETAIL_BRAND_NM').removeAttr('readonly');
            $('#ITP_FORM_COLLMNG01010_DETAIL_BSNS_REG_NO').removeAttr('readonly');
            $('#ITP_FORM_COLLMNG01010_DETAIL_CORP_REG_NO').removeAttr('readonly');
            // $('#ITP_FORM_COLLMNG01010_DETAIL_SEARCH_AFFL_SHOP').removeAttr('disabled');
            // $('#ITP_FORM_COLLMNG01010_DETAIL_DELETE_AFFL_SHOP').removeAttr('disabled');
            $('#ITP_FORM_COLLMNG01010_DETAIL_SEARCH_AFFL_SHOP').show();
            $('#ITP_FORM_COLLMNG01010_DETAIL_DELETE_AFFL_SHOP').show();
			$('#ITP_FORM_COLLMNG01010_DETAIL .itp_form_info').hide();
			$('#ITP_FORM_COLLMNG01010_DETAIL .itp_form_change').show();

            $('#ITP_FORM_COLLMNG01010_DETAIL #ITP_FORM_COLLMNG01010_DETAIL_AFFL_SHOP_ID').val(fn_make_user_info.get('afflShopId'));
            $('#ITP_FORM_COLLMNG01010_DETAIL #ITP_FORM_COLLMNG01010_DETAIL_BRAND_ID').val(fn_make_user_info.get('brandId'));

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

            $('#ITP_FORM_COLLMNG01010_DETAIL_BRAND_ID').attr('readonly', true);
            $('#ITP_FORM_COLLMNG01010_DETAIL_BRAND_NM').attr('readonly', true);
            $('#ITP_FORM_COLLMNG01010_DETAIL_BSNS_REG_NO').attr('readonly', true);
            $('#ITP_FORM_COLLMNG01010_DETAIL_CORP_REG_NO').attr('readonly', true);
            // $('#ITP_FORM_COLLMNG01010_DETAIL_SEARCH_AFFL_SHOP').attr('disabled', true);
            // $('#ITP_FORM_COLLMNG01010_DETAIL_DELETE_AFFL_SHOP').attr('disabled', true);
            $('#ITP_FORM_COLLMNG01010_DETAIL_SEARCH_AFFL_SHOP').hide();
            $('#ITP_FORM_COLLMNG01010_DETAIL_DELETE_AFFL_SHOP').hide();
			$('#ITP_FORM_COLLMNG01010_DETAIL .itp_form_info').show();
			$('#ITP_FORM_COLLMNG01010_DETAIL .itp_form_change').hide();

            $('#ITP_FORM_COLLMNG01010_DETAIL #ITP_FORM_COLLMNG01010_DETAIL_BRAND_ID').val(fn_make_user_info.get('brandId'));
        } else if(mode == 'VIEW') { // 보기
            $('#ITP_AJAX_COLLMNG01010_VIEW_CONTAINER').show();
            fn_show_btn_auth_array(['#ITP_BTN_COLLMNG01010_MODIFY', '#ITP_BTN_COLLMNG01010_CANCELLIST']);
        }
    }
};


/*목록화면 Object*/
let listObj = {
	init: function() {
		this.grid.init();
		this.action();
	},
	itp_COLLMNG01010_param: {},
	itp_COLLMNG01010_search: false,
	button: {
		search: function() {
			listObj.itp_COLLMNG01010_search = true;
			let param = $('#ITP_FORM_COLLMNG01010_SEARCH').serializeObject();
			console.log(JSON.stringify(param));
			param.gridSize = $.jgrid.defaults.rowNum;
            param.gridPage = $.jgrid.defaults.page;
            $(COLLMNG01010_GRID_ID).setGridParam({'postData': JSON.stringify(param)}).trigger('reloadGrid');
        }
	},
	empty: {
		init: function() {
           
        },
        push: function() {
          
        },
        back: function() {
          
        }
	},
	grid: {
		init: function() {
			// 데이터 없을때
            this.search();
		},
		colModel: gridColModel.list,
		search: function() {
			pageObj.switchScreen('LIST');
			this.unload();
			this.load();
		},
		load: function() {
            let param = $('#ITP_FORM_COLLMNG01010_SEARCH').serializeObject();
            param.gridSize = $.jgrid.defaults.rowNum;
            var option = {
            	gridId: COLLMNG01010_GRID_ID,
            	colModel: gridColModel.list,
            	param: param,
            	url: DOMAIN + API_RTNMNG_RTN_SPPLY_RTN_GRID_LIST,
            	pager: COLLMNG01010_GRID_PAGER,
            	onCellSelect: function(rowId, cellIdx, cellValue) {
                    var cm = $(this).jqGrid('getGridParam', 'colModel');
                    var colNm = cm[cellIdx].name;
                    if (colNm === 'rtnPodrUnqNo') {
                        const rtnPodrUnqNoVal = $(this).jqGrid('getCell', rowId, 'rtnPodrUnqNo');
                        const brandIdVal = $(this).jqGrid('getCell', rowId, 'brandId');
                        const spplyIdVal = fn_make_user_info.get('spplyId'); 
                        const key = {rtnPodrUnqNo: rtnPodrUnqNoVal, brandId: brandIdVal, spplyId: spplyIdVal};
                        var param = $.param(key);
                        viewObj.init(param);
                    }
				},
				loadComplete: function(data) {
                    itp_fn_grid_load_complete(data, COLLMNG01010_GRID_ID, true, 'number', 'COLLMNG01010', listObj.itp_COLLMNG01010_search, listObj.empty, true, data.gridRecords, true);
                    var ids = $(COLLMNG01010_GRID_ID).getDataIDs();
                    $.each(ids, function(idx, rowId) {
                        $(COLLMNG01010_GRID_ID).jqGrid('setCell', rowId, 'rtnPodrUnqNo', '', ITP_GRID_COL_STYLE.link);
                    });
				},
				onPaging: function(action) {
                    itp_fn_grid_paging(COLLMNG01010_GRID_ID, action, param);
                }
            };
            itp_fn_grid_make_remote(option);
		},
		clearData: function() {
			$(COLLMNG01010_GRID_ID).jqGrid('clearGridData', true);
            $(COLLMNG01010_GRID_LIST).find('.ui-jqgrid-bdiv').css('min-height', '100px');
            $(COLLMNG01010_GRID_EMPTY).html(ITP_MSG_LOCALE.message.grid.noData);
            $(COLLMNG01010_GRID_EMPTY).show();
		},
		unload: function() {
			$.jgrid.gridUnload(COLLMNG01010_GRID_ID);
		}
	},
	action: function() {
		var _this = this;
		// 납품장소 조회 버튼 클릭
		$('#ITP_BTN_COLLMNG01010_SEARCH_WHS_NM').on('click', function() {
			_this.popup();
		});
		// 납품장소 텍스트 삭제 버튼 클릭
		$('#ITP_BTN_COLLMNG01010_DELETE_WHS_NM').on('click', function() {
			$('#ITP_FORM_COLLMNG01010_DETAIL_RTN_WHS_NM').val('');
			$('#ITP_FORM_COLLMNG01010_DETAIL_RTN_WHS_ID').val('');
		});
	},
	popup: function() {
		// 팝업
		var popFn = this.callback.create;
		const key = {brandId:fn_make_user_info.get('brandId'),storeId:fn_make_user_info.get('storeId'), whsDvsn:""};
		fn_call_popup('biz', 'BIZPOP_WHS_LOCATION', '#ITP_ASIDE', popFn, key, 'S');
	},
	callback: {
		create: function(rowDataPop) {
			if(rowDataPop) {
				$('#ITP_FORM_COLLMNG01010_DETAIL_RTN_WHS_NM').val(rowDataPop.whsNm);
				$('#ITP_FORM_COLLMNG01010_DETAIL_RTN_WHS_ID').val(rowDataPop.whsId);
			}
		}
	},
	excelDown: function() {
		var param = {
			'url': API_RTNMNG_RTN_SPPLY_RTN_GRID_LIST,
			'param': $('#ITP_FORM_COLLMNG01010_SEARCH').serializeObject(),
			'gridColumns': $(COLLMNG01010_GRID_ID).jqGrid('getGridParam', 'colModel'),
			'fileName': '공급사 수거현황.xlsx',
			'sheetName': '공급사 수거리스트'
		};
		itp_fn_remote_to_excel(param);
	}
}


/*상세화면 Object*/
let viewObj = {
	init: function(param) {
		this.load(param);
	},
	itp_COLLMNG01010_param: {},
	itp_COLLMNG01010_search: false,
	button: {
		cancel: function() {
			listObj.grid.search();
		}
	},
	empty: {
		init: function() {
            var _this = this;
            this.push();
            $(COLLMNG01010_VIEW_GRID_EMPTY).on('click', function() {
                _this.back();
                viewObj.itp_COLLMNG01010_param.gridSize = $.jgrid.defaults.rowNum;
                $(COLLMNG01010_DETAIL_GRID_ID).setGridParam({'postData': JSON.stringify(viewObj.itp_COLLMNG01010_param)}).trigger('reloadGrid');
            });
        },
        push: function() {
            let param = $('#ITP_FORM_COLLMNG01010_DETAIL').serializeObject();
            viewObj.itp_COLLMNG01010_param = param;
        },
        back: function() {
            $('#ITP_FORM_COLLMNG01010_SERVICE_BRAND_TYPE').val(viewObj.itp_COLLMNG01010_param.brandType);
            $('#ITP_FORM_COLLMNG01010_SERVICE_ST_CD').val(viewObj.itp_COLLMNG01010_param.stCd);
            $('#ITP_FORM_COLLMNG01010_SEARCH_BRAND_NM').val(viewObj.itp_COLLMNG01010_param.brandNm);
        }
	},
	load: function(param) {
		fn_ajax_call(API_RTNMNG_RTN_INFO_INFO_RTNODR, param, this.callback, 'GET');
	},
	callback: function(result) {		
		pageObj.switchScreen('MODIFY');
		$('#ITP_FORM_COLLMNG01010_DETAIL .fnBrandNm').text(result.brandNm);							// 브랜드명
		$('#ITP_FORM_COLLMNG01010_DETAIL .fnRtnPodrUnqNo').text(result.rtnPodrUnqNo);				// 발주번호
		$('#ITP_FORM_COLLMNG01010_DETAIL .fnRtnOdrRegDt').text(result.rtnOdrRegDt);					// 수거일자
		$('#ITP_FORM_COLLMNG01010_DETAIL .fnRtnOdrStNm').text(result.rtnOdrStNm);					// 수거상태
		$('#ITP_FORM_COLLMNG01010_DETAIL .fnRtnWhsNm').text(result.rtnWhsNm);						// 수거장소
		$('#ITP_FORM_COLLMNG01010_DETAIL .fnRtnDodrTotalAmt').text(result.rtnDodrTotalAmt);			// 수거 총 금액
		$('#ITP_FORM_COLLMNG01010_DETAIL .fnRtnMgrNm').text(result.rtnMgrNm);						// 발주담당자
		$('#ITP_FORM_COLLMNG01010_DETAIL .fnRtnMgrTelNo').text(result.rtnMgrTelNo);					// 발주담당자연락처
		
		for(var i = 0; i < result.rtnOdrDtlList.length; i++){
			result.rtnOdrDtlList[i].colReqDt = result.colReqDt;
		}
		
		viewObj.grid.init(result.rtnOdrDtlList);
	},
	grid: {
		init: function(gridData) {
			this.mode = 'MODIFY';
			this.gridId = COLLMNG01010_DETAIL_GRID_ID;
			this.gridList = COLLMNG01010_DETAIL_GRID_LIST;
			this.gridEmpty = COLLMNG01010_DETAIL_GRID_EMPTY;
			this.unload();
			this.load(gridData);
		},
		mode: '',
		colModel: gridColModel.detail,
		load: function(gridData) {
			var _this = this;
			var option = {
				gridId: _this.gridId,
				colModel: gridColModel.detail,
				data: gridData,
				multiselect: true,
				loadComplete: function(data) {
					itp_fn_grid_load_complete(data, COLLMNG01010_DETAIL_GRID_ID, true, 'number', 'COLLMNG01010', viewObj.itp_COLLMNG01010_search, viewObj.empty, true, data.gridRecords, true);
				}
			};
			itp_fn_grid_make_local(option);
		},
		unload: function() {
			$.jgrid.gridUnload(this.gridId);
		}
	}
};
