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

/********************************************************
 --------------------------------------------------------
 - Object 목록								            -
 --------------------------------------------------------
 * const gridColModel = {}	: 화면 Grid Object			*
 * let pageObj = {}			: 화면공통 Object			*
 * let listObj = {}			: 목록화면 Object			*
 * let viewObj = {}			: 상세화면 Object			*
 * let modifyObj = {}		: 수정화면 Object			*
 * let createObj = {}		: 신규화면 Object			*
 *******************************************************/

/*화면 변수*/
const OPER03011_GRID_ID = '#ITP_OPER03011_jqGrid';
const OPER03011_GRID_LIST = '#ITP_OPER03011_jqGrid_list';
const OPER03011_GRID_PAGER = '#ITP_OPER03011_jqGridPager';
const OPER03011_GRID_EMPTY = '#ITP_OPER03011_jqGridEmpty';

const OPER03011_VIEW_GRID_ID = '#ITP_OPER03011_VIEW_jqGrid';
const OPER03011_VIEW_GRID_LIST = '#ITP_OPER03011_VIEW_jqGrid_list';
const OPER03011_VIEW_GRID_PAGER = '#ITP_OPER03011_VIEW_jqGridPager';
const OPER03011_VIEW_GRID_EMPTY = '#ITP_OPER03011_VIEW_jqGridEmpty';

const OPER03011_DETAIL_GRID_ID = '#ITP_OPER03011_DETAIL_jqGrid';
const OPER03011_DETAIL_GRID_LIST = '#ITP_OPER03011_DETAIL_jqGrid_list';
const OPER03011_DETAIL_GRID_PAGER = '#ITP_OPER03011_DETAIL_jqGridPager';
const OPER03011_DETAIL_GRID_EMPTY = '#ITP_OPER03011_DETAIL_jqGridEmpty';

let ITP_FORM_OPER03011_DETAIL_IS_DUPLICATE = false;
let ITP_FORM_OPER03011_DETAIL_IS_WRITING = false;

/*API URL*/
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/affl/save-affi';
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: 'SALE_MGR_ID', name: 'saleMgrId',
			label: '영업담당자ID',
			width: '20', fixed: false, align: 'center',
			sortable: false, editable: false, edittype: 'text',
			editrules: {required: true}
		},
		{
			index: 'SALE_MGR_NM', name: 'saleMgrNm',
			label: '영업담당자명',
			width: '30', fixed: false, align: 'center',
			sortable: true, editable: false, edittype: 'text',
			editrules: {required: true}
		},
		{
			index: 'RPRST_TEL_NO', name: 'rprstTelNo',
			label: ITP_MSG_LOCALE.label.rprstTelNo,
			width: '10', fixed: false, align: 'center',
			sortable: false, editable: false, edittype: 'text'
		},
		{
			index: 'RPRST_EMAIL', name: 'rprstEmai',
			label: ITP_MSG_LOCALE.label.rprstEmal,
			width: '10', fixed: false, align: 'center',
			sortable: false, editable: false, edittype: 'text'
		},
		{
			index: 'ST_CD', name: 'stCd',
			label: ITP_MSG_LOCALE.label.status,
			width: '10', fixed: false, align: 'center',
			sortable: false, editable: false, edittype: 'text', hidden: true
		},
		{
			index: 'ST_NM', name: 'stNm',
			label: ITP_MSG_LOCALE.label.status,
			width: '10', fixed: false, align: 'center',
			sortable: false, editable: false, edittype: 'text'
		},
		{
			index: 'AFFL_SHOP_ID', name: 'afflShopId',
			label: '브랜드그룹코드',
			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();
	},
	itp_OPER03011_param: {},
	itp_OPER03011_search: false,
	ui: {
		init: function () {
			this.view();
			this.form();
			this.grid();
			this.ready();
		},
		view: function() {
			// 버튼 권한설정
			fn_proc_btn_auth('OPER03011');

			// 공통코드 표시
			$('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_OPER03011 .input-group.date').datepicker(ITP_DATE_LANGUAGE);
			$('#ITP_FORM_OPER03011_SEARCH_FROM_DT').datepicker('setDate', new Date(now.setMonth(now.getMonth() - 1)));
			$('#ITP_FORM_OPER03011_SEARCH_TO_DT').datepicker('setDate', new Date());

			// form alert message 주입
			$('input[data-alert-required="ONLYCHK"]').each(function() {
				if($(this).data('alert-msg') === 'address') {
					$(this).data('alert-msg', ITP_MSG_LOCALE.message.form.emptyAddr);
				}
			});
		},
		form: function() {
			itp_fn_form_event.onKeyup('#ITP_FORM_OPER03011_DETAIL');
		},
		grid: function() {
		},
		ready: function() {
			viewObj.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_OPER03011_MODIFY'					: modifyObj.button.modify();	break;	// 수정 버튼
						case 'ITP_BTN_OPER03011_CANCELLIST'				: modifyObj.button.cancel(); 	break;	// 취소/목록 버튼
						case 'ITP_BTN_OPER03011_SAVE'					: modifyObj.button.save(); 		break;	// 저장 버튼
						case 'ITP_BTN_OPER03011_DETAIL_AFFL_SHOP_KEY'	: modifyObj.button.duplicate();	break;	// 중복체크
						case 'ITP_BTN_OPER03011_RESET_PW'				: modifyObj.button.resetPass();	break;	// 상세:비밀번호 초기화
						case 'ITP_FORM_OPER03011_DETAIL_ADRES_SCH'		: modifyObj.button.address();	break;	// 신규등록 주소 찾기
						case 'ITP_BTN_OPER03011_DETAIL_ADDROW'			: pageObj.grid.button.addRow();	break;	// 신규등록 영업담당자 행 추가
						case 'ITP_BTN_OPER03011_DETAIL_DELROW'			: pageObj.grid.button.delRow();	break;	// 상세:삭제버튼
					}
				});
			});

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

		}
	},
	fileUpload: function() {
		//파일업로드(수정화면)
		var id = 'OPER03011';
		$('#ITP_' + id + '_DETAIL_UPLOAD').empty();
		$('#ITP_' + id + '_DETAIL_LOGO_FILE').empty();
		var removeFn = (param) => {
			$('#ITP_' + id + '_DETAIL_LOGO_FILE').empty();
		};
		const fileArgs = {
			'fileNo': $('#ITP_FORM_' + id + '_DETAIL_FILE_NO').val(),
			'viewCd': $('#ITP_FORM_' + id + '_DETAIL_VIEW_CD').val(),
			'showYn': $('#ITP_' + id + '_DETAIL_UPLOAD').attr('data-show-yn'),
			'fileId': '#ITP_FORM_' + id + '_DETAIL_FILE_NO' //파일번호를 서버에서 받아서 넣을 파일번호 인풋박스 아이디
		};
		itp_fn_set_file_upload('ITP_' + id + '_DETAIL_UPLOAD', 'notice', true, false, id, fileArgs, removeFn);
	},
	switchScreen: function(mode) {
		$('.itp_det_head').find('button[id^="ITP_BTN_OPER03011_"]').each(function(i) {
			$(this).hide();
		});
		$('#ITP_TAB_OPER03011').find('div[id$="_CONTAINER"]').each(function(i) {
			$(this).hide();
		});
		if(mode === 'MODIFY') { // 수정
			$('#ITP_AJAX_OPER03011_DETAIL_CONTAINER').show();
			fn_show_btn_auth_array(['#ITP_BTN_OPER03011_CANCELLIST', '#ITP_BTN_OPER03011_SAVE', '#ITP_BTN_OPER03011_RESET_PW']);

			// $('#ITP_FORM_OPER03011_DETAIL_AFFL_SHOP_NM').prop('readonly', true);
			$('#ITP_FORM_OPER03011_DETAIL_AFFL_SHOP_KEY').prop('readonly', true);
			$('#ITP_BTN_OPER03011_DETAIL_AFFL_SHOP_KEY').prop('disabled', true);

		} else if(mode === 'VIEW') { // 보기
			$('#ITP_AJAX_OPER03011_VIEW_CONTAINER').show();
			fn_show_btn_auth_array(['#ITP_BTN_OPER03011_MODIFY']);
		}
	},
	grid: {
		init: function(mode, gridData) {
			this.mode = mode;
			this.gridId = (mode === 'VIEW') ? OPER03011_VIEW_GRID_ID : OPER03011_DETAIL_GRID_ID;
			this.unload();
			this.load(gridData);
		},
		mode: 'DETAIL',
		gridId: '',
		button: {
			addRow: function () {
				// 팝업
				var popFn = function(rowDataPop) {
					console.log(rowDataPop);
					// 기존등록 데이터
					var exists = '';
					const rowData = $(OPER03011_DETAIL_GRID_ID).getRowData();
					$.each(rowData, function(key, value) {
						exists = exists + value.saleMgrId + ';';
					});

					$.each(rowDataPop, function(key, value) {
						if(exists.indexOf(value.saleMgrId) < 0) {
							value['viewCd'] =  "C";
							$(OPER03011_DETAIL_GRID_ID).jqGrid('addRowData', value.saleMgrId, value, 'last');
						}
					});
					$(OPER03011_DETAIL_GRID_EMPTY).hide();
				};
				fn_call_popup('biz', 'BIZPOP_APPL_SALES_USER_SCH', '#ITP_ASIDE', popFn, null, 'S');
			},
			delRow: function () {
				itp_fn_grid_del_row(OPER03011_DETAIL_GRID_ID);
			}
		},
		load: function(gridData) {
			var _this = this;
			var option = {
				gridId: this.gridId,
				colModel: gridColModel.detail,
				data: gridData,
				multiselect: (this.mode !== 'VIEW'),
				loadComplete: function(data) {
					$(_this.mode === 'VIEW' ? OPER03011_VIEW_GRID_LIST : OPER03011_DETAIL_GRID_LIST).find('.ui-jqgrid .ui-jqgrid-bdiv').css('overflow-x', 'hidden');
					if(data.records === 0) {
						_this.clearData();
						var gridEmpty = (this.mode === 'VIEW') ? OPER03011_VIEW_GRID_EMPTY : OPER03011_DETAIL_GRID_EMPTY;
						$(gridEmpty).html(ITP_MSG_LOCALE.message.grid.noData);
						$(gridEmpty).show();
					}
				}
			};
			itp_fn_grid_make_local(option);
		},
		clearData : function() {
			$(this.gridId).jqGrid('clearGridData', true);
			$(this.mode === 'VIEW' ? OPER03011_VIEW_GRID_LIST : OPER03011_DETAIL_GRID_LIST).find('.ui-jqgrid-bdiv').css('min-height', '100px');
			$(this.mode === 'VIEW' ? OPER03011_VIEW_GRID_EMPTY : OPER03011_DETAIL_GRID_EMPTY).html(ITP_MSG_LOCALE.message.grid.noData);
			$(this.mode === 'VIEW' ? OPER03011_VIEW_GRID_EMPTY : OPER03011_DETAIL_GRID_EMPTY).show();
		},
		unload : function() {
			$.jgrid.gridUnload(this.gridId);
		}
	}
};

/*상세화면 Object*/
let viewObj = {
	init: function () {
		this.load();
	},
	load: function() {
		const key = {afflShopId: fn_make_user_info.get('afflShopId'), viewCd: 'R'};
		fn_ajax_call(API_DETAIL_INFO,  $.param(key), this.callback, 'GET');
	},
	callback: function (result) {
		console.log(result);
		pageObj.switchScreen('VIEW');
		$('#ITP_FORM_OPER03011_VIEW #ITP_FORM_OPER03011_VIEW_AFFL_SHOP_ID').val(result.afflShopId);

		$('#ITP_FORM_OPER03011_VIEW .fnAfflShopId').text(result.afflShopId);
		$('#ITP_FORM_OPER03011_VIEW .fnAfflShopNm').text(result.afflShopNm);
		$('#ITP_FORM_OPER03011_VIEW .fnAfflAbbr').text(result.afflAbbr);
		$('#ITP_FORM_OPER03011_VIEW .fnStCd').text(result.stNm);
		$('#ITP_FORM_OPER03011_VIEW .fnCorpTypeNm').text(result.authTypeNm);
		$('#ITP_FORM_OPER03011_VIEW .fnBsnsRegNo').text(result.bsnsRegNo);
		$('#ITP_FORM_OPER03011_VIEW .fnCorpRegNo').text(result.corpRegNo);
		$('#ITP_FORM_OPER03011_VIEW .fnTelNo').text(result.ownerTelNo);
		$('#ITP_FORM_OPER03011_VIEW .fnFaxNo').text(result.rprstFaxNo);
		$('#ITP_FORM_OPER03011_VIEW .fnEmalAddr').text(result.rprstEmai);
		$('#ITP_FORM_OPER03011_VIEW .fnBsnsCndt').text(result.bsnsCndt);
		$('#ITP_FORM_OPER03011_VIEW .fnOwnerNm').text(result.ownerNm);
		$('#ITP_FORM_OPER03011_VIEW .fnCtgrBsns').text(result.ctgrBsns);
		$('#ITP_FORM_OPER03011_VIEW .fnOwnerTelNo').text(result.ownerTelNo);
		$('#ITP_FORM_OPER03011_VIEW .fnJoinSttDt').text(result.joinSttDt);
		$('#ITP_FORM_OPER03011_VIEW .fnJoinEndDt').text(result.joinEndDt);
		$('#ITP_FORM_OPER03011_VIEW .fnZipNo').text(result.zipNo);
		$('#ITP_FORM_OPER03011_VIEW .fnLoadAddr').text(result.addr1);
		$('#ITP_FORM_OPER03011_VIEW .fnDtlAddr').text(result.addr2);

		$('#ITP_FORM_OPER03010_DETAIL #ITP_FORM_OPER03010_DETAIL_FILE_NO').val(result.cmpnyLogoFileNo);
		pageObj.fileUpload();
		itp_fn_attach_file.view('ITP_OPER03011_VIEW_LOGO_FILE', result.fileLogNoList
			, 'form-control itp_input', 'border:none; top:12px; left:12px; height:100px; width:125px; position:absolute;');

		let locate = result.addr1 + ' ' + result.addr2;
		kakaoMap.init('ITP_FORM_OPER03011_VIEW', locate, result.latX, result.longY);

		// 영업담당자정보  리스트 조회
		pageObj.grid.init('VIEW', result.saleList);
	}
};

/*수정화면 Object*/
let modifyObj = {
	button: {
		modify: function (param) {
			itp_fn_form_clear_validate(null, '#ITP_FORM_OPER03011_DETAIL');
			const key = {afflShopId: fn_make_user_info.get('afflShopId'), viewCd: 'R'};
			modifyObj.load($.param(key));
		},
		duplicate: function() {
			const formId = '#ITP_FORM_OPER03011_DETAIL';
			itp_fn_form_clear_validate(null, formId);
			if (itp_fn_form_validate(formId, formId + '_AFFL_SHOP_KEY', ['empty'], undefined)) {
				var dupFn = function(result) {
					if (result.code === 'N') {
						ITP_FORM_OPER03011_DETAIL_IS_DUPLICATE = false;
					} else {
						ITP_FORM_OPER03011_DETAIL_IS_DUPLICATE = true;
					}
				};
				const key = {'afflAbbr':  $(formId + '_AFFL_SHOP_KEY').val()};
				const param = $.param(key);
				fn_ajax_call(API_CHECK_DUPLICATE, param, dupFn, 'GET');
			}
		},
		resetPass: function() {
			var resetPwFn = {
				callBack: function(args) {
					const key = {'userId':  $('#ITP_FORM_OPER03011_DETAIL_CMPY_CD').val()};
					const param = $.param(key);
					fn_ajax_call(API_INTI_USERPW, param, undefined, 'GET');
				}
			};
			itp_fn_modal_confirm(ITP_MSG_LOCALE.message.ajax.askResetUserPw, resetPwFn, null);
		},
		address: function() {
			kakaoMap.address('ITP_FORM_OPER03011_DETAIL');
		},
		cancel: function() {
			viewObj.init();
		},
		save: function() {
			const formId = '#ITP_FORM_OPER03011_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_OPER03011_DETAIL_CMPY_ZIPNO').val() === '' || $('#ITP_FORM_OPER03011_DETAIL_CMPY_ADRES').val() === '') {
				// 	itp_fn_modal_alert('주소 검색을 통해 회사 주소를 입력하세요.');
				// 	return;
				// }

				if (ITP_FORM_OPER03011_DETAIL_IS_DUPLICATE) {
					itp_fn_modal_duplicate('회사코드 중복체크를 해주세요.', formId + '_AFFL_SHOP_ID');
				} else {
					let gridInsertData = [];
					let gridUpdateData = [];
					let gridDeleteData = [];
					const rowData = $(OPER03011_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_OPER03011_DETAIL_IS_WRITING = false;
						viewObj.init();
					};
					fn_ajax_call(API_DETAIL_SAVE, JSON.stringify(param), searhFn, 'POST');
				}
			}
		}
	},
	load: function(param) {
		fn_ajax_call(API_DETAIL_INFO, param, this.callback, 'GET');
	},
	callback: function (result) {
		console.log(result);
		pageObj.switchScreen('MODIFY');
		$('#ITP_FORM_OPER03011_DETAIL #ITP_FORM_OPER03011_DETAIL_VIEW_CD').val('U');

		$('#ITP_FORM_OPER03011_DETAIL #ITP_FORM_OPER03011_DETAIL_AFFL_SHOP_ID').val(result.afflShopId);
		$('#ITP_FORM_OPER03011_DETAIL .fnAfflShopId').text(result.afflShopId);
		$('#ITP_FORM_OPER03011_DETAIL #ITP_FORM_OPER03011_DETAIL_AFFL_SHOP_NM').val(result.afflShopNm);
		$('#ITP_FORM_OPER03011_DETAIL #ITP_FORM_OPER03011_DETAIL_AFFL_SHOP_KEY').val(result.afflAbbr);
		$('#ITP_FORM_OPER03011_DETAIL #ITP_FORM_OPER03011_DETAIL_ST_CD').val(result.stCd);
		$('#ITP_FORM_OPER03011_DETAIL #ITP_FORM_OPER03011_DETAIL_AUTH_TYPE').val(result.authType);
		$('#ITP_FORM_OPER03011_DETAIL #ITP_FORM_OPER03011_DETAIL_CORP_TYPE').val(result.corpType);
		$('#ITP_FORM_OPER03011_DETAIL #ITP_FORM_OPER03011_DETAIL_BSNS_REG_NO').val(result.bsnsRegNo);
		$('#ITP_FORM_OPER03011_DETAIL #ITP_FORM_OPER03011_DETAIL_CORP_REG_NO').val(result.corpRegNo);
		$('#ITP_FORM_OPER03011_DETAIL #ITP_FORM_OPER03011_DETAIL_TEL_NO').val(result.ownerTelNo);
		$('#ITP_FORM_OPER03011_DETAIL #ITP_FORM_OPER03011_DETAIL_FAX_NO').val(result.rprstFaxNo);
		$('#ITP_FORM_OPER03011_DETAIL #ITP_FORM_OPER03011_DETAIL_EMAL_ADDR').val(result.rprstEmai);
		$('#ITP_FORM_OPER03011_DETAIL #ITP_FORM_OPER03011_DETAIL_BSNS_CNDT').val(result.bsnsCndt);
		$('#ITP_FORM_OPER03011_DETAIL #ITP_FORM_OPER03011_DETAIL_OWNER_NM').val(result.ownerNm);
		$('#ITP_FORM_OPER03011_DETAIL #ITP_FORM_OPER03011_DETAIL_CTGR_BSNS').val(result.ctgrBsns);
		$('#ITP_FORM_OPER03011_DETAIL #ITP_FORM_OPER03011_DETAIL_OWNER_TEL_NO').val(result.ownerTelNo);
		$('#ITP_FORM_OPER03011_DETAIL #ITP_FORM_OPER03011_SEARCH_JOIN_STT_DT').val(result.joinSttDt === '' ? today : result.joinSttDt);
		$('#ITP_FORM_OPER03011_DETAIL #ITP_FORM_OPER03011_SEARCH_JOIN_END_DT').val(result.joinEndDt === '' ? today : result.joinEndDt);
		$('#ITP_FORM_OPER03011_DETAIL #ITP_FORM_OPER03011_DETAIL_ZIPNO').val(result.zipNo);
		$('#ITP_FORM_OPER03011_DETAIL #ITP_FORM_OPER03011_DETAIL_ADRES').val(result.addr1);
		$('#ITP_FORM_OPER03011_DETAIL #ITP_FORM_OPER03011_DETAIL_ADRES_DTL').val(result.addr2);

		$('#ITP_FORM_OPER03011_DETAIL .fnAddDt').text(result.regDt);
		$('#ITP_FORM_OPER03011_DETAIL .fnChgDt').text(result.chgDt);

		itp_fn_attach_file.view('ITP_FORM_OPER03011_DETAIL_LOGO_FILE', result.fileLogNoList
			, 'form-control itp_input', 'border:none; top:12px; left:12px; height:70px; width:85px; position:absolute;');

		kakaoMap.init('ITP_FORM_OPER03011_DETAIL', $('#ITP_FORM_OPER03011_DETAIL_ADRES').val(), result.latX, result.longY);

		// 권한정보 리스트 조회
		pageObj.grid.init('MODIFY', result.saleList);
	}
};

