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


// 화면변수
const ORDMNG01010_GRID_ID = '#ITP_ORDMNG01010_jqGrid';
const ORDMNG01010_GRID_LIST = '#ITP_ORDMNG01010_jqGrid_list';
const ORDMNG01010_GRID_PAGER = '#ITP_ORDMNG01010_jqGridPager';
const ORDMNG01010_GRID_EMPTY = '#ITP_ORDMNG01010_jqGridEmpty';

const ORDMNG01010_VIEW_GRID_ID = '#ITP_ORDMNG01010_VIEW_jqGrid';
const ORDMNG01010_VIEW_GRID_LIST = '#ITP_ORDMNG01010_VIEW_jqGrid_list';
const ORDMNG01010_VIEW_GRID_PAGER = '#ITP_ORDMNG01010_VIEW_jqGridPager';
const ORDMNG01010_VIEW_GRID_EMPTY = '#ITP_ORDMNG01010_VIEW_jqGridEmpty';

let ITP_COMMON_PCH_ODR_ST_CD = fn_make_common_cd_list(CODE_LIST, 'PCH_ODR_ST_CD', true, '발주상태코드');


//API URL
let API_POMNG_PO_SPPLY_PO_GRID_LIST = '/api/pomng/po/spply-po-grid-list';
let API_POMNG_PO_INFO_SPPLY_PCHORD = '/api/pomng/po/info-spply-pchOdr';


//화면 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, classes: 'ui-ellipsis'
		},
		{
			index: 'BRAND_ID', name: 'brandId',
			label: ITP_MSG_LOCALE.label.brandId,
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: true
		},
		{
			index: 'PODR_MGR_NM', name: 'podrMgrNm',
			label: ITP_MSG_LOCALE.label.podrMgrNm,
			width: '10', fixed: false, align: 'center',
			sortable: false, hidden: true
		},
		{
			index: 'BRAND_NM', name: 'brandNm',
			label: ITP_MSG_LOCALE.label.brandNm, 		// 브랜드명
			width: '8', fixed: false, align: 'left',
			sortable: false, hidden: false, classes: 'ui-ellipsis'
		},
		{
			index: 'PCH_PODR_UNQ_NO', name: 'pchPodrUnqNo',
			label: ITP_MSG_LOCALE.label.pchPodrUnqNo, 	// 발주번호
			width: '6', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'PCH_ORD_ST_CD', name: 'pchOdrStCd',
			label: ITP_MSG_LOCALE.label.pchOdrStNm, 	// 발주상태
			width: '5', fixed: false, align: 'center',
			sortable: false, formatter: 'select',
			editoptions: {value: ITP_COMMON_PCH_ODR_ST_CD}
		},
		{
			index: 'PODR_DT', name: 'podrDt',
			label: ITP_MSG_LOCALE.label.podrDt, 		// 발주일자
			width: '5', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'DIV_REQ_DT', name: 'dlvReqDt',
			label: ITP_MSG_LOCALE.label.dlvReqDt, 		// 납품요청일
			width: '5', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'WHS_NM', name: 'whsNm',
			label: ITP_MSG_LOCALE.label.whsNm, 			// 납품장소
			width: '10', fixed: false, align: 'left',
			minwidth: 240,
			sortable: false, hidden: false, classes: 'ui-ellipsis'
		},
		{
			index: 'PODR_TOTAL_AMT', name: 'podrTotalAmt',
			label: ITP_MSG_LOCALE.label.podrTotalAmt, 	// 총 발주금액
			width: '5', fixed: false, align: 'right',
			sortable: false, hidden: false,
			formatter: 'integer', formatoptions: {thousandsSeparator: ','}
		},
		{
			index: 'SPPLY_ITME_ID', name: 'podrItemQty',
			label: ITP_MSG_LOCALE.label.podrItemQty, 	// 발주품목수
			width: '4', fixed: false, align: 'right',
			sortable: false, hidden: false
		},
		{
			index: 'PODR_MGR_NM', name: 'podrMgrNm',
			label: ITP_MSG_LOCALE.label.podrMgrNm, 		// 발주 담당자
			width: '5', fixed: false, align: 'center',
			sortable: false, hidden: false
		}
	],
	view: [
		{
			index: 'PCH_PODR_DTL_NO', name: 'pchPodrDtlNo',
			label: ITP_MSG_LOCALE.label.pchPodrDtlNo, 	// 항번
			width: '5', 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: '12', fixed: false, align: 'left',
			sortable: false, hidden: false, classes: 'ui-ellipsis'
		},
		{
			index: 'UNIT_AMT', name: 'unitAmt',
			label: ITP_MSG_LOCALE.label.unitAmt, 		// 단가
			width: '6', fixed: false, align: 'right',
			sortable: false, hidden: false,
			formatter: 'integer', formatoptions: {thousandsSeparator: ','}
		},
		{
			index: 'UNIT', name: 'unit',
			label: ITP_MSG_LOCALE.label.unit, 			// 기본단위
			width: '6', fixed: false, align: 'center',
			sortable: false, hidden: false
		},
		{
			index: 'PODR_QTY', name: 'podrQty',
			label: ITP_MSG_LOCALE.label.podrQty, 		// 발주수량
			width: '6', fixed: false, align: 'right',
			sortable: false, hidden: false
		},
		{
			index: 'PODR_AMT', name: 'podrAmt',
			label: ITP_MSG_LOCALE.label.podrAmt, 		// 발주금액
			width: '8', fixed: false, align: 'right',
			sortable: false, hidden: false,
			formatter: 'integer', formatoptions: {thousandsSeparator: ','}
		}
	],
	detail: []
};


/*화면공통 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('ORDMNG01010');
			// 공통코드 표시
			$('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_ORDMNG01010 .input-group.date').datepicker(ITP_DATE_LANGUAGE);
			$('#ITP_FORM_ORDMNG01010_SEARCH_FROM_DT').datepicker('setDate', now);
			$('#ITP_FORM_ORDMNG01010_SEARCH_TO_DT').datepicker('setDate', defaultToDate);
		},
		grid: function() {
			itp_fn_jqgrid_resize(ORDMNG01010_GRID_ID, ORDMNG01010_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_ORDMNG01010_SRH'				: listObj.button.search();		break;	// 조회 버튼 클릭
						case 'ITP_BTN_ORDMNG01010_NEWREG'			: listObj.button.create(); 		break;	// 신규등록 버튼
						case 'ITP_BTN_ORDMNG01010_MODIFY'			: modifyObj.button.modify();	break;	// 수정 버튼
						case 'ITP_BTN_ORDMNG01010_CANCELLIST'		: viewObj.button.cancel(); 		break;	// 취소/목록 버튼
						case 'ITP_BTN_ORDMNG01010_DELETE'			: 								break;	// 삭제 버튼
						case 'ITP_BTN_ORDMNG01010_SAVE'				: createObj.button.save(); 		break;	// 저장 버튼
						case 'ITP_FORM_ORDMNG01010_VIEW_DUP'		: createObj.button.duplicate();	break;	// 중복체크
						case 'ITP_BTN_ORDMNG01010_RESET_PW'			: createObj.button.resetPass();	break;	// 상세:비밀번호 초기화
						case 'ITP_BTN_ORDMNG01010_VIEW_ADDROW'		: pageObj.grid.button.addRow();	break;	// 상세:추가버튼
						case 'ITP_BTN_ORDMNG01010_VIEW_DELROW'		: pageObj.grid.button.delRow();	break;	// 상세:삭제버튼
						case 'ITP_BTN_ORDMNG01010_EXCEL'		    : listObj.excelDown();	break;	// 엑셀 다운로드
					}
				});
			});
		}
	},
	switchScreen: function(mode) {
        $('.itp_det_head').find('button[id^="ITP_BTN_ORDMNG01010_"]').each(function(i) {
            $(this).hide();
        });
        $('#ITP_TAB_ORDMNG01010').find('div[id$="_CONTAINER"]').each(function(i) {
            $(this).hide();
        });
        if(mode == 'LIST') { // 목록
			itp_fn_fire_window_resize();
            fn_show_btn_auth_array(['#ITP_BTN_ORDMNG01010_SRH', '#ITP_BTN_ORDMNG01010_NEWREG']);
            $('#ITP_AJAX_ORDMNG01010_LIST_CONTAINER').show();
            $('#ITP_FORM_ORDMNG01010_SEARCH #ITP_FORM_ORDMNG01010_SEARCH_BRAND_ID').val(fn_make_user_info.get('brandId'));
            $('#ITP_FORM_ORDMNG01010_SEARCH #ITP_FORM_ORDMNG01010_SEARCH_SPPLY_ID').val(fn_make_user_info.get('spplyId'));
            $('#ITP_BTN_ORDMNG01010_SEARCH_WHS_NM').show();
            $('#ITP_BTN_ORDMNG01010_DELETE_WHS_NM').show();

			$('#ITP_BTN_ORDMNG01010_EXCEL').show();

        } else if(mode == 'ADD') { // 등록
            $('#ITP_AJAX_ORDMNG01010_DETAIL_CONTAINER').show();
            fn_show_btn_auth_array(['#ITP_BTN_ORDMNG01010_CANCELLIST', '#ITP_BTN_ORDMNG01010_SAVE']);

            $('#ITP_FORM_ORDMNG01010_DETAIL').find('input, textarea, select, checkbox').each(function(i, elem) {
                $(this).attr('id') === 'ITP_FORM_ORDMNG01010_DETAIL_VIEW_CD' ? $(this).val('C') : $(this).val('');
                if(elem.type === 'select') {
                    $(this).val('').prop('selected', true);
                }
            });
            $('#ITP_FORM_ORDMNG01010_DETAIL #ITP_FORM_ORDMNG01010_DETAIL_FILE_NO').val('');
            $('#ITP_FORM_ORDMNG01010_DETAIL_BRAND_ID').removeAttr('readonly');
            $('#ITP_FORM_ORDMNG01010_DETAIL_BRAND_NM').removeAttr('readonly');
            $('#ITP_FORM_ORDMNG01010_DETAIL_BSNS_REG_NO').removeAttr('readonly');
            $('#ITP_FORM_ORDMNG01010_DETAIL_CORP_REG_NO').removeAttr('readonly');
            // $('#ITP_FORM_ORDMNG01010_DETAIL_SEARCH_AFFL_SHOP').removeAttr('disabled');
            // $('#ITP_FORM_ORDMNG01010_DETAIL_DELETE_AFFL_SHOP').removeAttr('disabled');
            $('#ITP_FORM_ORDMNG01010_DETAIL_SEARCH_AFFL_SHOP').show();
            $('#ITP_FORM_ORDMNG01010_DETAIL_DELETE_AFFL_SHOP').show();
			$('#ITP_FORM_ORDMNG01010_DETAIL .itp_form_info').hide();
			$('#ITP_FORM_ORDMNG01010_DETAIL .itp_form_change').show();

            $('#ITP_FORM_ORDMNG01010_DETAIL #ITP_FORM_ORDMNG01010_DETAIL_AFFL_SHOP_ID').val(fn_make_user_info.get('afflShopId'));
            $('#ITP_FORM_ORDMNG01010_DETAIL #ITP_FORM_ORDMNG01010_DETAIL_BRAND_ID').val(fn_make_user_info.get('brandId'));

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

            $('#ITP_FORM_ORDMNG01010_DETAIL_BRAND_ID').attr('readonly', true);
            $('#ITP_FORM_ORDMNG01010_DETAIL_BRAND_NM').attr('readonly', true);
            $('#ITP_FORM_ORDMNG01010_DETAIL_BSNS_REG_NO').attr('readonly', true);
            $('#ITP_FORM_ORDMNG01010_DETAIL_CORP_REG_NO').attr('readonly', true);
            // $('#ITP_FORM_ORDMNG01010_DETAIL_SEARCH_AFFL_SHOP').attr('disabled', true);
            // $('#ITP_FORM_ORDMNG01010_DETAIL_DELETE_AFFL_SHOP').attr('disabled', true);
            $('#ITP_FORM_ORDMNG01010_DETAIL_SEARCH_AFFL_SHOP').hide();
            $('#ITP_FORM_ORDMNG01010_DETAIL_DELETE_AFFL_SHOP').hide();
			$('#ITP_FORM_ORDMNG01010_DETAIL .itp_form_info').show();
			$('#ITP_FORM_ORDMNG01010_DETAIL .itp_form_change').hide();

            $('#ITP_FORM_ORDMNG01010_DETAIL #ITP_FORM_ORDMNG01010_DETAIL_BRAND_ID').val(fn_make_user_info.get('brandId'));
        } else if(mode == 'VIEW') { // 보기
            $('#ITP_AJAX_ORDMNG01010_VIEW_CONTAINER').show();
            fn_show_btn_auth_array(['#ITP_BTN_ORDMNG01010_MODIFY', '#ITP_BTN_ORDMNG01010_CANCELLIST']);
        }
    }
};


/*목록화면 Object*/
let listObj = {
	init: function() {
		this.grid.init();
		this.action();
	},
	itp_ORDMNG01010_param: {},
	itp_ORDMNG01010_search: false,
	button: {
		search: function() {
			listObj.itp_ORDMNG01010_search = true;
			let param = $('#ITP_FORM_ORDMNG01010_SEARCH').serializeObject();
			param.gridSize = $.jgrid.defaults.rowNum;
            param.gridPage = $.jgrid.defaults.page;
            param.sidx = '0';
			$(ORDMNG01010_GRID_ID).data('grid-param',param);
            $(ORDMNG01010_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_ORDMNG01010_SEARCH').serializeObject();
            param.gridSize = $.jgrid.defaults.rowNum;
            param.sidx = '0';
            var option = {
            	gridId: ORDMNG01010_GRID_ID,
            	colModel: gridColModel.list,
            	param: param,
            	url: DOMAIN + API_POMNG_PO_SPPLY_PO_GRID_LIST,
            	pager: ORDMNG01010_GRID_PAGER,
            	onCellSelect: function(rowId, cellIdx, cellValue) {
                    var cm = $(this).jqGrid('getGridParam', 'colModel');
                    var colNm = cm[cellIdx].name;
                    if (colNm === 'pchPodrUnqNo') {
                        const pchPodrUnqNoVal = $(this).jqGrid('getCell', rowId, 'pchPodrUnqNo');
                        const brandIdVal = $(this).jqGrid('getCell', rowId, 'brandId');
                        const spplyIdVal = fn_make_user_info.get('spplyId'); 
                        const key = {pchPodrUnqNo: pchPodrUnqNoVal, brandId: brandIdVal, spplyId: spplyIdVal};
                        var param = $.param(key);
                        viewObj.init(param);
                    }
				},
				loadComplete: function(data) {
                    itp_fn_grid_load_complete(data, ORDMNG01010_GRID_ID, true, 'number', 'ORDMNG01010', listObj.itp_ORDMNG01010_search, listObj.empty, true, data.gridRecords, true);
                    var ids = $(ORDMNG01010_GRID_ID).getDataIDs();
                    $.each(ids, function(idx, rowId) {
                        $(ORDMNG01010_GRID_ID).jqGrid('setCell', rowId, 'pchPodrUnqNo', '', ITP_GRID_COL_STYLE.link);
                    });
				},
				onPaging: function(action) {
                    itp_fn_grid_paging(ORDMNG01010_GRID_ID, action, param);
                }
            };
            itp_fn_grid_make_remote(option);
		},
		clearData: function() {
			$(ORDMNG01010_GRID_ID).jqGrid('clearGridData', true);
            $(ORDMNG01010_GRID_LIST).find('.ui-jqgrid-bdiv').css('min-height', '100px');
            $(ORDMNG01010_GRID_EMPTY).html(ITP_MSG_LOCALE.message.grid.noData);
            $(ORDMNG01010_GRID_EMPTY).show();
		},
		unload: function() {
			$.jgrid.gridUnload(ORDMNG01010_GRID_ID);
		}
	},
    action: function() {
		var _this = this;
		// 납품장소 조회 버튼 클릭
		$('#ITP_BTN_ORDMNG01010_SEARCH_WHS_NM').on('click', function() {
			_this.popup();
		});
		// 납품장소 텍스트 삭제 버튼 클릭
		$('#ITP_BTN_ORDMNG01010_DELETE_WHS_NM').on('click', function() {
			$('#ITP_FORM_ORDMNG01010_DETAIL_WHS_NM').val('');
			$('#ITP_FORM_ORDMNG01010_DETAIL_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_ORDMNG01010_DETAIL_WHS_NM').val(rowDataPop.whsNm);
				$('#ITP_FORM_ORDMNG01010_DETAIL_WHS_ID').val(rowDataPop.whsId);
			}
		}
	},
	excelDown: function() {
		var param = {
			'url': API_POMNG_PO_SPPLY_PO_GRID_LIST,
			'param': $('#ITP_FORM_ORDMNG01010_SEARCH').serializeObject(),
			'gridColumns': $(ORDMNG01010_GRID_ID).jqGrid('getGridParam', 'colModel'),
			'fileName': '공급사 수주현황.xlsx',
			'sheetName': '공급사 수주리스트'
		};
		itp_fn_remote_to_excel(param);
	}
};

/*상세화면 Object*/
let viewObj = {
	init: function(param) {
		this.load(param);
	},
	itp_ORDMNG01010_param: {},
	itp_ORDMNG01010_search: false,
	button: {
		cancel: function() {
			listObj.grid.search();
		}
	},
	empty: {
		init: function() {
            var _this = this;
            this.push();
            $(ORDMNG01010_VIEW_GRID_EMPTY).on('click', function() {
                _this.back();
                viewObj.itp_ORDMNG01010_param.gridSize = $.jgrid.defaults.rowNum;
                $(ORDMNG01010_GRID_ID).setGridParam({'postData': JSON.stringify(viewObj.itp_ORDMNG01010_param)}).trigger('reloadGrid');
            });
        },
        push: function() {
            let param = $('#ITP_FORM_ORDMNG01010_VIEW').serializeObject();
            viewObj.itp_ORDMNG01010_param = param;
        },
        back: function() {
            $('#ITP_FORM_ORDMNG01010_SERVICE_BRAND_TYPE').val(viewObj.itp_ORDMNG01010_param.brandType);
            $('#ITP_FORM_ORDMNG01010_SERVICE_ST_CD').val(viewObj.itp_ORDMNG01010_param.stCd);
            $('#ITP_FORM_ORDMNG01010_SEARCH_BRAND_NM').val(viewObj.itp_ORDMNG01010_param.brandNm);
        }
	},
	load: function(param) {
		fn_ajax_call(API_POMNG_PO_INFO_SPPLY_PCHORD, param, this.callback, 'GET');
	},
	callback: function(result) {
		// 그리드 전화번호 '-' 함수
		function convertTel(value){
			answer = (value.startsWith('0')) ? value.replace(/[^0-9]/g, "")
					.replace(/(^02|^0505|^1[0-9]{3}|^0[0-9]{2})([0-9]+)?([0-9]{4})$/,"$1-$2-$3")
					.replace("--", "-") : '';
			return answer;
		}
		
		let telNo = convertTel(result.podrMgrTelNo);
		
		
		pageObj.switchScreen('VIEW');
		$('#ITP_FORM_ORDMNG01010_VIEW #ITP_FORM_ORDMNG01010_VIEW_AFFL_SHOP_ID').val(result.afflShopId);
		$('#ITP_FORM_ORDMNG01010_VIEW .fnBrandNm').text(result.brandNm);				// 브랜드명
		$('#ITP_FORM_ORDMNG01010_VIEW .fnPchPodrUnqNo').text(result.pchPodrUnqNo);
		$('#ITP_FORM_ORDMNG01010_VIEW .fnPodrDt').text(result.podrDt);
		$('#ITP_FORM_ORDMNG01010_VIEW .fnPchOdrStCd').text(result.pchOdrStNm);
		$('#ITP_FORM_ORDMNG01010_VIEW .fnPodrTotalAmt').text(result.podrTotalAmt.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','));
		$('#ITP_FORM_ORDMNG01010_VIEW .fnPodrMgrNm').text(result.podrMgrNm + ' (' + telNo + ')');
		$('#ITP_FORM_ORDMNG01010_VIEW .fnDlvReqDt').text(result.dlvReqDt);
		
		viewObj.grid.init('VIEW', result.pchOdrDtlList)
	},
	grid: {
		init: function(mode, gridData) {
			this.mode = mode;
			this.gridId = (mode === 'VIEW') ? ORDMNG01010_VIEW_GRID_ID : ORDMNG01010_DETAIL_GRID_ID;
			this.gridList = (mode === 'VIEW') ? ORDMNG01010_VIEW_GRID_LIST : ORDMNG01010_DETAIL_GRID_LIST;
			this.gridEmpty = (mode === 'VIEW') ? ORDMNG01010_VIEW_GRID_EMPTY : ORDMNG01010_DETAIL_GRID_EMPTY;
			this.unload();
			this.load(mode, gridData);
		},
		mode: '',
		colModel: gridColModel.view,
		load: function(mode, gridData) {
			var _this = this;
			var option = {
				gridId: _this.gridId,
				colModel: gridColModel.view,
				data: gridData,
				multiselect: true,
				loadComplete: function(data) {
					itp_fn_grid_load_complete(data, ORDMNG01010_VIEW_GRID_ID, true, 'number', 'ORDMNG01010', viewObj.itp_ORDMNG01010_search, viewObj.empty, true, data.gridRecords, true);
				}
			};
			itp_fn_grid_make_local(option);
		},
		unload: function() {
			$.jgrid.gridUnload(this.gridId);
		}
	}
	
};
