
const KOPER01010_GRID_ID = '#ITP_KOPER01010_jqGrid';
const KOPER01010_GRID_LIST = '#ITP_KOPER01010_jqGrid_list';
const KOPER01010_GRID_PAGER = '#ITP_KOPER01010_jqGridPager';
const KOPER01010_GRID_EMPTY = '#ITP_KOPER01010_jqGridEmpty';

const KOPER01010_VIEW_GRID_ID = '#ITP_KOPER01010_VIEW_jqGrid';
const KOPER01010_VIEW_GRID_LIST = '#ITP_KOPER01010_VIEW_jqGrid_list';
const KOPER01010_VIEW_GRID_PAGER = '#ITP_KOPER01010_VIEW_jqGridPager';
const KOPER01010_VIEW_GRID_EMPTY = '#ITP_KOPER01010_VIEW_jqGridEmpty';

const KOPER01010_DETAIL_GRID_ID = '#ITP_KOPER01010_DETAIL_jqGrid';
const KOPER01010_DETAIL_GRID_LIST = '#ITP_KOPER01010_DETAIL_jqGrid_list';
const KOPER01010_DETAIL_GRID_PAGER = '#ITP_KOPER01010_DETAIL_jqGridPager';
const KOPER01010_DETAIL_GRID_EMPTY = '#ITP_KOPER01010_DETAIL_jqGridEmpty';


let ITP_FORM_KOPER01010_DETAIL_IS_DUPLICATE = false;
let ITP_FORM_KOPER01010_DETAIL_IS_WRITING = false;

let COMPANY_GRID_LIST = '/api/frcomp/grid-list';
let USER_SALESUSER_GRID_LIST = '/api/frcomp/cmpy-saleusers-list'; 
let COMPANY_INFO_COMPANY = '/api/frcomp/info-frcomp';
let COMPANY_SAVE_COMPANY = '/api/frcomp/save-frcomp';
let COMPANY_CHECK_DUPLICATE = '/api/frcomp/check-duplicate';
let USER_INTI_USERPW = '/api/user/inti-userpw';

require(['config'], function() {
	require([
		'jquery', 
		'kakao.postcode', 
		'kakao.maps'
	], function($) {
		// 버튼 권한설정
		fn_proc_btn_auth('KOPER01010');
		// 공통코드 표시
		fn_make_select(CODE_LIST, 'CMPY_STAT_CD', 'ITP_FORM_KOPER01010_SEARCH_CMPY_STAT_CD');
		fn_make_select(CODE_LIST, 'CMPY_STAT_CD', 'ITP_FORM_KOPER01010_DETAIL_CMPY_STAT_CD', true, '선택');
		fn_make_select(CODE_LIST, 'CMPY_TYPE_CD', 'ITP_FORM_KOPER01010_DETAIL_CMPY_TYPE_CD', true, '선택');
		fn_make_select(CODE_LIST, 'FRCOMP_AUTH_CD', 'ITP_FORM_KOPER01010_DETAIL_FRCOMP_AUTH_CD', true, '선택');
		
		// 조회일자 지정
		// var now = new Date();
		$('#ITP_TAB_KOPER01010 .input-group.date').datepicker(ITP_DATE_LANGUAGE);
		// $('#ITP_FORM_KOPER01010_SEARCH_FROM_DT').datepicker('setDate', new Date(now.setMonth(now.getMonth() - 1)));
		// $('#ITP_FORM_KOPER01010_SEARCH_TO_DT').datepicker('setDate', new Date());
				
		// 그리드				
		itp_fn_jqgrid_resize(KOPER01010_GRID_ID, KOPER01010_GRID_LIST, 'lg');
		itp_fn_KOPER01010_grid.init();
    	itp_fn_fire_window_resize();

		// 조회    	
    	itp_fn_KOPER01010_search();
    	
		// 조회 버튼 클릭
		$('#ITP_BTN_KOPER01010_SRH').on('click', function() {
			itp_KOPER01010_search = true;
			let param = $('#ITP_FORM_KOPER01010_SEARCH').serializeObject();
			param.gridSize = $.jgrid.defaults.rowNum;
			param.gridPage = $.jgrid.defaults.page;
			$(KOPER01010_GRID_ID).setGridParam({'postData': JSON.stringify(param)}).trigger('reloadGrid');
		});
		
		// 수정 버튼
		$('#ITP_BTN_KOPER01010_MODIFY').on('click', function() {
			itp_fn_form_clear_validate(null, '#ITP_FORM_KOPER01010_DETAIL');			
			const cmpyCdVal = $('#ITP_FORM_KOPER01010_VIEW_CMPY_CD').val();
			const key = {cmpyCd: cmpyCdVal, viewCd: 'R'};
			var param = $.param(key);
			itp_fn_KOPER01010_detail(param);	
		});
		
		// 신규등록 버튼
		$('#ITP_BTN_KOPER01010_NEWREG').on('click', function() {
			itp_fn_KOPER01010_switch_screen('ADD');			
			itp_fn_form_clear_validate(null, '#ITP_FORM_KOPER01010_DETAIL');
			itp_fn_KOPER01010_detail_map($('#ITP_FORM_KOPER01010_DETAIL_STREET_ADDRESS').val());	
			
			// 영업담당자 리스트 조회		
			itp_fn_KOPER01010_detail_grid.unload();
			itp_fn_KOPER01010_detail_grid.callBack();	
		});
		
		// 취소/목록 버튼
		$('#ITP_BTN_KOPER01010_CANCELLIST').on('click', function() {
			itp_fn_KOPER01010_search();
    	});
		
		// 삭제 버튼
		$('#ITP_BTN_KOPER01010_DELETE').on('click', function() {
			
		});
		
		// 저장 버튼
		$('#ITP_BTN_KOPER01010_SAVE').on('click', function() {			
			const formId = '#ITP_FORM_KOPER01010_DETAIL';
			itp_fn_form_clear_validate(null, formId);			
			var vali_cmpyCd = itp_fn_form_validate(formId, formId + '_CMPY_CD', ['empty'], undefined);
			var vali_cmpyStatCd = itp_fn_form_validate(formId, formId + '_CMPY_STAT_CD', ['empty'], undefined);
			var vali_cmpyTypeCd = itp_fn_form_validate(formId, formId + '_CMPY_TYPE_CD', ['empty'], undefined);
			var vali_cmpyNm = itp_fn_form_validate(formId, formId + '_CMPY_NM', ['empty'], undefined);			
			var vali_bossNm = itp_fn_form_validate(formId, formId + '_BOSS_NM', ['empty'], undefined);
			var vali_mainTel = itp_fn_form_validate(formId, formId + '_MAIN_TEL', ['empty'], undefined);
			var vali_mainEmail = itp_fn_form_validate(formId, formId + 'MAIN_EMAIL', ['empty'], undefined);
			
			if (vali_cmpyCd && vali_cmpyStatCd && vali_cmpyTypeCd && vali_cmpyNm && vali_bossNm && vali_mainTel && vali_mainEmail) {
				
				if($('#ITP_FORM_KOPER01010_DETAIL_CMPY_ZIPNO').val() == '' || $('#ITP_FORM_KOPER01010_DETAIL_CMPY_ADRES').val() == '') {
					itp_fn_modal_alert('주소 검색을 통해 회사 주소를 입력하세요.');
					return;
				}
				
				if (ITP_FORM_KOPER01010_DETAIL_IS_DUPLICATE) {
					itp_fn_modal_duplicate('회사코드 중복체크를 해주세요.', formId + '_CMPY_CD');
				} else {
					let gridInsertData = [];
					let gridUpdateData = [];
					let gridDeleteData = [];
					const rowData = $(KOPER01010_DETAIL_GRID_ID).getRowData();
					const keyValue = $(formId + '_CMPY_CD').val();
					$.each(rowData, function(key, value) {
						if (value.viewCd != 'R') {
							value.userId = 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;
					var searhFn = function() {
						ITP_FORM_KOPER01010_DETAIL_IS_WRITING = false;
						itp_fn_KOPER01010_search();
					};
					console.log(JSON.stringify(param));
					fn_ajax_call(COMPANY_SAVE_COMPANY, JSON.stringify(param), searhFn, 'POST');	
				}
			}
		});		
		
		// 중복체크
		$('#ITP_FORM_KOPER01010_DETAIL_DUP').on('click', function() {
			const formId = '#ITP_FORM_KOPER01010_DETAIL';
			itp_fn_form_clear_validate(null, formId + '_DETAIL');
			var vali_cmpyCd = itp_fn_form_validate(formId + '_DETAIL', formId + '_CMPY_CD', ['empty'], undefined);
			if (vali_cmpyCd) {
				var dupFn = function(result) {
					if (result.code == 'N') {
						ITP_FORM_KOPER01010_DETAIL_IS_DUPLICATE = false;
					} else {
						ITP_FORM_KOPER01010_DETAIL_IS_DUPLICATE = true;
					}
				};
				const key = {'cmpyCd':  $(formId + '_CMPY_CD').val()};
				const param = $.param(key);
				fn_ajax_call(COMPANY_CHECK_DUPLICATE, param, dupFn, 'GET');
			}
		});
		
		// 상세:비밀번호 초기화
		$('#ITP_BTN_KOPER01010_RESET_PW').on('click', function() {
			var resetPwFn = {
				callBack: function(args) {
					const key = {'userId':  $('#ITP_FORM_KOPER01010_DETAIL_CMPY_CD').val()};
					const param = $.param(key);
					fn_ajax_call(USER_INTI_USERPW, param, undefined, 'GET');					
				}
			};
			itp_fn_modal_confirm(ITP_MSG_LOCALE.message.ajax.askResetUserPw, resetPwFn, null);		
		});
		
		$('#ITP_FORM_KOPER01010_DETAIL_ADRES_SCH').on('click', function() {
			new daum.Postcode({
		    	oncomplete: function(data) {
					// 전체주소 리턴
					document.getElementById('ITP_FORM_KOPER01010_DETAIL_CMPY_ZIPNO').value = data.zonecode;
					document.getElementById('ITP_FORM_KOPER01010_DETAIL_CMPY_ADRES').value = data.roadAddress;
					document.getElementById('ITP_FORM_KOPER01010_DETAIL_LOTS_ADDRESS').value = !!data.autoJibunAddress ? data.autoJibunAddress : data.jibunAddress;
					document.getElementById('ITP_FORM_KOPER01010_DETAIL_STREET_ADDRESS').value = data.roadAddress;
					document.getElementById('ITP_FORM_KOPER01010_DETAIL_HJ_DONG').value = !!data.hname ? data.hname : data.bname;
					document.getElementById('ITP_FORM_KOPER01010_DETAIL_BJ_DONG').value = data.bname;
					
					itp_fn_KOPER01010_detail_map(data.roadAddress);
					document.getElementById('ITP_FORM_KOPER01010_DETAIL_CMPY_ADRES_DTL').focus();		  
		        }
			}).open();
		});
		
		
		$('#ITP_BTN_KOPER01010_DETAIL_ADDROW').on('click', function() {
			// 팝업
			var popFn = function(rowDataPop) {
				// 기존등록 데이터 
				var exists = '';				
				const rowData = $(KOPER01010_DETAIL_GRID_ID).getRowData();
				$.each(rowData, function(key, value) {
					exists = exists + value.salesUserId + ';';
				});
				
				$.each(rowDataPop, function(key, value) {
					if(exists.indexOf(value.salesUserId) < 0) {
						// 행추가
						$(KOPER01010_DETAIL_GRID_ID).jqGrid('addRow', {position: 'last'});
						var rids = $(KOPER01010_DETAIL_GRID_ID).jqGrid('getDataIDs');
						var last_row_id = rids[rids.length - 1];
						$(KOPER01010_DETAIL_GRID_ID).jqGrid('setCell', last_row_id, 'viewCd', 'C');
						$(KOPER01010_DETAIL_GRID_ID).jqGrid('setCell', last_row_id, 'salesUserId', value.salesUserId);
						$(KOPER01010_DETAIL_GRID_ID).jqGrid('setCell', last_row_id, 'salesUserNm', value.salesUserNm);
						$(KOPER01010_DETAIL_GRID_ID).jqGrid('setCell', last_row_id, 'useStatCd', value.useStatCd);
						$(KOPER01010_DETAIL_GRID_ID).jqGrid('setCell', last_row_id, 'useStatNm', value.useStatNm);
						$(KOPER01010_DETAIL_GRID_ID).jqGrid('setCell', last_row_id, 'cmpyCd', '');	
					}
				});
				$(KOPER01010_DETAIL_GRID_EMPTY).hide();
			};
			fn_call_popup('biz', 'BIZPOP_NK_SALES_USER_SCH', '#ITP_ASIDE', popFn, null, 'S');  //=====================================================================================
		});
		// 상세:삭제버튼
		$('#ITP_BTN_KOPER01010_DETAIL_DELROW').on('click', function() {
			itp_fn_grid_del_row(KOPER01010_DETAIL_GRID_ID);
		});
		
		$('body').on('click', function(e) {
			var gridId = KOPER01010_DETAIL_GRID_ID.replace('#', '');
			var rids = $(KOPER01010_DETAIL_GRID_ID).jqGrid('getDataIDs');
			var last_row_id = rids[rids.length - 1];			
			itp_fn_grid_reset_selection(e, last_row_id, gridId, 'KOPER01010_DETAIL');
		});
		
	});
});

var itp_fn_KOPER01010_detail_map = function(locate) {
	
	kakao.maps.load(function() {
				
		var mapContainer = document.getElementById('ITP_FORM_KOPER01010_DETAIL_MAP'), // 지도를 표시할 div 
		    mapOption = {
		        center: new kakao.maps.LatLng(37.56684, 126.97865), // 지도의 중심좌표
		        level: 3, // 지도의 확대 레벨
		        mapTypeId : kakao.maps.MapTypeId.ROADMAP // 지도종류
		    }; 
	
		// 지도를 생성한다 
		var map = new kakao.maps.Map(mapContainer, mapOption); 
		
		// 마우스 휠과 모바일 터치를 이용한 지도 확대, 축소를 막는다
		map.setZoomable(false);   
	
		// 지도에 확대 축소 컨트롤을 생성한다
		//var zoomControl = new kakao.maps.ZoomControl();
	
		// 지도의 우측에 확대 축소 컨트롤을 추가한다
		//map.addControl(zoomControl, kakao.maps.ControlPosition.RIGHT);
	
		function searchDetailAddrFromCoords(coords, callback) {
		    // 좌표로 법정동 상세 주소 정보를 요청합니다
		    geocoder.coord2Address(coords.getLng(), coords.getLat(), callback);
		}
		
		// 주소-좌표 변환 객체를 생성합니다
		var geocoder = new kakao.maps.services.Geocoder();	
		var map;
		
		if( !locate || locate.length == 0 ) {
			// 지도에 마커를 생성하고 표시한다
		    	marker = new kakao.maps.Marker({
		  	    position: new kakao.maps.LatLng(37.56684, 126.97865), // 마커의 좌표
		   	    map: map // 마커를 표시할 지도 객체
	    	});
		} else {
			// 주소로 좌표를 검색합니다
			geocoder.addressSearch(locate, function(result, status) {
			    // 정상적으로 검색이 완료됐으면 
			     if (status === kakao.maps.services.Status.OK) {
		
			        var coords = new kakao.maps.LatLng(result[0].y, result[0].x);
			        document.getElementById('ITP_FORM_KOPER01010_DETAIL_LAT').value = result[0].y;
			        document.getElementById('ITP_FORM_KOPER01010_DETAIL_LNG').value = result[0].x;
			        
			        // 결과값으로 받은 위치를 마커로 표시합니다
			        	marker = new kakao.maps.Marker({
			            map: map,
			            position: coords
			        });
		
			        // 지도의 중심을 결과값으로 받은 위치로 이동시킵니다
			        map.setCenter(coords);
			    }
			});    
		}
		
		// 지도 드래깅 이벤트를 등록한다 (드래그 시작 : dragstart, 드래그 종료 : dragend)
		kakao.maps.event.addListener(map, 'drag', function () {
		    searchDetailAddrFromCoords(map.getCenter(), function(result, status) {
		        if (status === kakao.maps.services.Status.OK) {
	
	   		        document.getElementById('ITP_FORM_KOPER01010_DETAIL_LOTS_ADDRESS').value = result[0].address.address_name ;
	   		        document.getElementById('ITP_FORM_KOPER01010_DETAIL_CMPY_ADRES').value = !!result[0].road_address ? result[0].road_address.address_name : result[0].address.address_name ;
	   		        document.getElementById('ITP_FORM_KOPER01010_DETAIL_STREET_ADDRESS').value = !!result[0].road_address ? result[0].road_address.address_name : $('#ITP_FORM_KOPER01010_DETAIL_STREET_ADDRESS').val();
	   		        document.getElementById('ITP_FORM_KOPER01010_DETAIL_CMPY_ZIPNO').value = !!result[0].road_address ? result[0].road_address.zone_no : $('#ITP_FORM_KOPER01010_DETAIL_CMPY_ZIPNO').val() ;
			        document.getElementById('ITP_FORM_KOPER01010_DETAIL_LAT').value = map.getCenter().getLat();
			        document.getElementById('ITP_FORM_KOPER01010_DETAIL_LNG').value = map.getCenter().getLng();
		                        
		            // 마커를 클릭한 위치에 표시합니다
		            marker.setPosition(map.getCenter());
		            marker.setMap(map);
		        }   
		    });
			/* 	var message = '지도를 드래그 하고 있습니다. 지도의 중심 좌표는 ' + map.getCenter().toString() +' 입니다.';
			console.log(message); */
		});
	});
};

var itp_fn_KOPER01010_view_map = function(locate) {
	
	kakao.maps.load(function() {
				
		var mapContainer = document.getElementById('ITP_FORM_KOPER01010_VIEW_MAP'), // 지도를 표시할 div 
		    mapOption = {
		        center: new kakao.maps.LatLng(37.56684, 126.97865), // 지도의 중심좌표
		        level: 3, // 지도의 확대 레벨
		        mapTypeId : kakao.maps.MapTypeId.ROADMAP // 지도종류
		    }; 
	
		// 지도를 생성한다 
		var map = new kakao.maps.Map(mapContainer, mapOption); 
		
		// 마우스 휠과 모바일 터치를 이용한 지도 확대, 축소를 막는다
		map.setZoomable(false);   
	
		// 지도에 확대 축소 컨트롤을 생성한다
		//var zoomControl = new kakao.maps.ZoomControl();
	
		// 지도의 우측에 확대 축소 컨트롤을 추가한다
		//map.addControl(zoomControl, kakao.maps.ControlPosition.RIGHT);
		
		// 주소-좌표 변환 객체를 생성합니다
		var geocoder = new kakao.maps.services.Geocoder();	
		var map;
		
		if( !locate || locate.length == 0 ) {
			// 지도에 마커를 생성하고 표시한다
		    	marker = new kakao.maps.Marker({
		  	    position: new kakao.maps.LatLng(37.56684, 126.97865), // 마커의 좌표
		   	    map: map // 마커를 표시할 지도 객체
	    	});
		} else {
			// 주소로 좌표를 검색합니다
			geocoder.addressSearch(locate, function(result, status) {
			    // 정상적으로 검색이 완료됐으면 
			     if (status === kakao.maps.services.Status.OK) {
		
			        var coords = new kakao.maps.LatLng(result[0].y, result[0].x);
			        
			        // 결과값으로 받은 위치를 마커로 표시합니다
			        marker = new kakao.maps.Marker({
			            map: map,
			            position: coords
			        });
		
			        // 지도의 중심을 결과값으로 받은 위치로 이동시킵니다
			        map.setCenter(coords);
			    }
			});    
		}
	});
};
	
var itp_fn_KOPER01010_switch_screen = function(mode) {
	if(mode == 'LIST') { // 목록
		$('#ITP_BTN_KOPER01010_MODIFY').hide();
		$('#ITP_BTN_KOPER01010_CANCELLIST').hide();
		$('#ITP_BTN_KOPER01010_DELETE').hide();
		$('#ITP_BTN_KOPER01010_SAVE').hide();
		fn_show_btn_auth('#ITP_BTN_KOPER01010_SRH');
		fn_show_btn_auth('#ITP_BTN_KOPER01010_NEWREG');
		
		$('#ITP_AJAX_KOPER01010_LIST_CONTAINER').show();
		$('#ITP_AJAX_KOPER01010_DETAIL_CONTAINER').hide();		
		$('#ITP_AJAX_KOPER01010_VIEW_CONTAINER').hide();
	} else if(mode == 'ADD') { // 등록
		ITP_FORM_KOPER01010_DETAIL_IS_DUPLICATE = true;
	
		$('#ITP_BTN_KOPER01010_SRH').hide();
		$('#ITP_BTN_KOPER01010_MODIFY').hide();
		$('#ITP_BTN_KOPER01010_NEWREG').hide();
		$('#ITP_BTN_KOPER01010_DELETE').hide();
		$('#ITP_BTN_KOPER01010_RESET_PW').hide();
		fn_show_btn_auth('#ITP_BTN_KOPER01010_CANCELLIST');
		fn_show_btn_auth('#ITP_BTN_KOPER01010_SAVE');
		
		$('#ITP_AJAX_KOPER01010_LIST_CONTAINER').hide();
		$('#ITP_AJAX_KOPER01010_DETAIL_CONTAINER').show();
		$('#ITP_AJAX_KOPER01010_VIEW_CONTAINER').hide();		
		$('#ITP_FORM_KOPER01010_DETAIL_CMPY_CD').removeAttr('readonly');
		$('#ITP_FORM_KOPER01010_DETAIL_DUP').removeAttr('disabled');
		
		$('#ITP_FORM_KOPER01010_DETAIL_VIEW_CD').val('C');
		$('#ITP_FORM_KOPER01010_DETAIL_CMPY_NM').val('');
		$('#ITP_FORM_KOPER01010_DETAIL_CMPY_STAT_CD').val('');
		$('#ITP_FORM_KOPER01010_DETAIL_FRCOMP_AUTH_CD').val('');
		$('#ITP_FORM_KOPER01010_DETAIL_CMPY_CD').val('');
		$('#ITP_FORM_KOPER01010_DETAIL_CMPY_TYPE_CD').val('');
		$('#ITP_FORM_KOPER01010_DETAIL_CMPY_REG_NUM').val('');
		$('#ITP_FORM_KOPER01010_DETAIL_COPT_NUM').val('');
		$('#ITP_FORM_KOPER01010_DETAIL_BIZ_CATE').val('');
		$('#ITP_FORM_KOPER01010_DETAIL_BIZ_TYPE').val('');
		$('#ITP_FORM_KOPER01010_DETAIL_BOSS_NM').val('');
		$('#ITP_FORM_KOPER01010_DETAIL_MAIN_TEL').val('');
		$('#ITP_FORM_KOPER01010_DETAIL_MAIN_FAX').val('');
		$('#ITP_FORM_KOPER01010_DETAIL_MAIN_EMAIL').val('');
		$('#ITP_FORM_KOPER01010_DETAIL_CMPY_ZIPNO').val('');
		$('#ITP_FORM_KOPER01010_DETAIL_CMPY_ADRES').val('');
		$('#ITP_FORM_KOPER01010_DETAIL_CMPY_ADRES_DTL').val('');
		$('#ITP_FORM_KOPER01010_DETAIL_LOTS_ADDRESS').val('');
		$('#ITP_FORM_KOPER01010_DETAIL_STREET_ADDRESS').val('');
		$('#ITP_FORM_KOPER01010_DETAIL_LAT').val('');
		$('#ITP_FORM_KOPER01010_DETAIL_LNG').val('');
		$('#ITP_FORM_KOPER01010_DETAIL_HJ_DONG').val('');
		$('#ITP_FORM_KOPER01010_DETAIL_BJ_DONG').val('');
		
	} else if(mode == 'MODIFY') { // 수정
		$('#ITP_BTN_KOPER01010_SRH').hide();
		$('#ITP_BTN_KOPER01010_MODIFY').hide();
		$('#ITP_BTN_KOPER01010_NEWREG').hide();		
		$('#ITP_BTN_KOPER01010_DELETE').hide();
		fn_show_btn_auth('#ITP_BTN_KOPER01010_RESET_PW');
		fn_show_btn_auth('#ITP_BTN_KOPER01010_CANCELLIST');
		fn_show_btn_auth('#ITP_BTN_KOPER01010_SAVE');
		
		$('#ITP_AJAX_KOPER01010_LIST_CONTAINER').hide();
		$('#ITP_AJAX_KOPER01010_DETAIL_CONTAINER').show();
		$('#ITP_AJAX_KOPER01010_VIEW_CONTAINER').hide();
		$('#ITP_FORM_KOPER01010_DETAIL_CMPY_CD').attr('readonly', true);
		$('#ITP_FORM_KOPER01010_DETAIL_DUP').attr('disabled', true);
	} else if(mode == 'VIEW') { // 보기
		$('#ITP_BTN_KOPER01010_SRH').hide();
		$('#ITP_BTN_KOPER01010_NEWREG').hide();		
		$('#ITP_BTN_KOPER01010_DELETE').hide();
		$('#ITP_BTN_KOPER01010_SAVE').hide();
		fn_show_btn_auth('#ITP_BTN_KOPER01010_MODIFY');
		fn_show_btn_auth('#ITP_BTN_KOPER01010_CANCELLIST');
		
		$('#ITP_AJAX_KOPER01010_LIST_CONTAINER').hide();
		$('#ITP_AJAX_KOPER01010_DETAIL_CONTAINER').hide();
		$('#ITP_AJAX_KOPER01010_VIEW_CONTAINER').show();
	}	
};

var itp_fn_KOPER01010_grid = {
	init: function() {
		// 데이터 없을때
		itp_fn_KOPER01010_empty.push();
		$(KOPER01010_GRID_EMPTY).on('click', function() {
			itp_fn_KOPER01010_empty.back();
			itp_KOPER01010_param.gridSize = $.jgrid.defaults.rowNum;
			$(KOPER01010_GRID_ID).setGridParam({'postData': JSON.stringify(itp_KOPER01010_param)}).trigger('reloadGrid');
		});	
	},
	callBack: function() {
		let param = $('#ITP_FORM_KOPER01010_SEARCH').serializeObject();
		param.gridSize = $.jgrid.defaults.rowNum;	
		$(KOPER01010_GRID_ID).jqGrid({
			colModel: [
				{
					index: 'CMPY_CD', name: 'cmpyCd',
					label: '가입자코드', 
					width: '6', fixed: false, align: 'center',
					sortable: false, hidden: false
				},
				{
					index: 'CMPY_NM', name: 'cmpyNm',
					label: '가입자명', 
					width: '10', fixed: false, align: 'center',
					sortable: false, hidden: false
				},
				{
					index: 'CMPY_TYPE_NM', name: 'cmpyTypeNm',
					label: '기업형태', 
					width: '6', fixed: false, align: 'center',
					sortable: false, hidden: false
				},
				{
					index: 'CMPY_STAT_NM', name: 'cmpyStatNm',
					label: '기업상태', 
					width: '6', fixed: false, align: 'center',
					sortable: false, hidden: false
				},
				{
					index: 'BOSS_NM', name: 'bossNm',
					label: '대표자명', 
					width: '6', fixed: false, align: 'center',
					sortable: false, hidden: false
				},
				{
					index: 'MAIN_TEL', name: 'mainTel',
					label: '대표연락처', 
					width: '6', fixed: false, align: 'center',
					sortable: false, hidden: false
				},
				{
					index: 'ADD_DT', name: 'addDt',
					label: '가입일자', 
					width: '8', fixed: false, align: 'center',
					sortable: false, hidden: false
				}
			],
			loadBeforeSend: function(jqXHR) {
			    jqXHR.setRequestHeader('X-AUTH-TOKEN', CONN_KEY);
			},
			postData: JSON.stringify(param),
			url: DOMAIN + COMPANY_GRID_LIST,
			pager: KOPER01010_GRID_PAGER,
			multiselect: false,
			rownumbers: true, 
			onCellSelect: function(rowId, cellIdx, cellValue) {
				var cm = $(this).jqGrid('getGridParam', 'colModel');
				var colNm = cm[cellIdx].name;
				if (colNm == 'cmpyNm') {
					const cmpyCdVal = $(this).jqGrid('getCell', rowId, 'cmpyCd');
					const key = {cmpyCd: cmpyCdVal, viewCd: 'R'};
					var param = $.param(key);
					itp_fn_KOPER01010_view(param);
				}
		   	},
			loadComplete: function(data) {
				console.log(JSON.stringify(data));
				itp_fn_grid_load_complete(data, KOPER01010_GRID_ID, true, 'number', 'KOPER01010', itp_KOPER01010_search, itp_fn_KOPER01010_empty, true, data.gridRecords, true);
				var ids = $(KOPER01010_GRID_ID).getDataIDs();
				$.each(ids, function(idx, rowId) {
					$(KOPER01010_GRID_ID).jqGrid('setCell', rowId, 'cmpyNm', '', ITP_GRID_COL_STYLE.link);
				});	
		    },
		    loadError: function(jqXHR, textStatus, errorThrown) {
		    	itp_fn_grid_load_error(jqXHR, textStatus, errorThrown);
		    },
		    onPaging: function(action) {
		    	itp_fn_grid_paging(KOPER01010_GRID_ID, action, param);
		    }
		}).navGrid(KOPER01010_GRID_PAGER, ITP_GRID_NAV_DEFAULTS.navGrid);
	},
	clearData : function() {
		$(KOPER01010_GRID_ID).jqGrid('clearGridData', true);
		$(KOPER01010_GRID_LIST).find('.ui-jqgrid-bdiv').css('min-height', '100px');
		$(KOPER01010_GRID_EMPTY).html(ITP_MSG_LOCALE.message.grid.noData);
		$(KOPER01010_GRID_EMPTY).show();
	}, 
	unload : function() {
		$.jgrid.gridUnload(KOPER01010_GRID_ID); 
	}
};

var itp_fn_KOPER01010_search = function() {
	itp_fn_KOPER01010_switch_screen('LIST');	
	itp_fn_KOPER01010_grid.unload();
	itp_fn_KOPER01010_grid.callBack();
};

let itp_KOPER01010_param = {};
let itp_KOPER01010_search = false;
var itp_fn_KOPER01010_empty = {
	push: function() {
		let param = $('#ITP_FORM_KOPER01010_SEARCH').serializeObject();
		itp_KOPER01010_param = param;
	},
	back: function() {
		$('#ITP_FORM_KOPER01010_DEVI_TP_CD').val(itp_KOPER01010_param.deviTpCd);
		$('#ITP_FORM_KOPER01010_ORDER_YN').val(itp_KOPER01010_param.orderYn);
		$('#ITP_FORM_KOPER01010_ADT_AUTH_CD').val(itp_KOPER01010_param.adtAuthCd);
		$('#ITP_FORM_KOPER01010_EMAIL_RCV_YN').val(itp_KOPER01010_param.emailRcvYn);
		$('#ITP_FORM_KOPER01010_SMS_RCV_YN').val(itp_KOPER01010_param.smsRcvYn);
		$('#ITP_FORM_KOPER01010_MEMB_EXIT_DT').val(itp_KOPER01010_param.membExitDt);
		$('#ITP_FORM_KOPER01010_FROM_DT').val(itp_KOPER01010_param.fromDt);
		$('#ITP_FORM_KOPER01010_TO_DT').val(itp_KOPER01010_param.toDt);
		$('#ITP_FORM_KOPER01010_KEYWORD').val(itp_KOPER01010_param.keyword);
	}
};

var itp_fn_KOPER01010_view = function(param) {
	fn_ajax_call(COMPANY_INFO_COMPANY, param, itp_fn_KOPER01010_view_callback, 'GET');
};

var itp_fn_KOPER01010_view_callback = function(result) {
	// console.log(result);
	itp_fn_KOPER01010_switch_screen('VIEW');
	$('#ITP_FORM_KOPER01010_VIEW #ITP_FORM_KOPER01010_VIEW_CMPY_CD').val(result.cmpyCd);
	
	$('#ITP_FORM_KOPER01010_VIEW .fnCmpyNm').text(result.cmpyNm);
	$('#ITP_FORM_KOPER01010_VIEW .fnCmpyStatCd').text(result.cmpyStatNm);
	$('#ITP_FORM_KOPER01010_VIEW .fnCmpyCd').text(result.cmpyCd);
	$('#ITP_FORM_KOPER01010_VIEW .fnCmpyTypeCd').text(result.cmpyTypeNm);
	$('#ITP_FORM_KOPER01010_VIEW .fnCmpyRegNum').text(result.cmpyRegNum);
	$('#ITP_FORM_KOPER01010_VIEW .fnFrcompAuthCd').text(result.frcompAuthNm);
	$('#ITP_FORM_KOPER01010_VIEW .fnCoptNum').text(result.coptNum);
	$('#ITP_FORM_KOPER01010_VIEW .fnBizCate').text(result.bizCate);
	$('#ITP_FORM_KOPER01010_VIEW .fnBizType').text(result.bizType);
	$('#ITP_FORM_KOPER01010_VIEW .fnBossNm').text(result.bossNm);
	$('#ITP_FORM_KOPER01010_VIEW .fnMainTel').text(result.mainTel);
	$('#ITP_FORM_KOPER01010_VIEW .fnMainFax').text(result.mainFax);
	$('#ITP_FORM_KOPER01010_VIEW .fnMainEmail').text(result.mainEmail);
	$('#ITP_FORM_KOPER01010_VIEW .fnCmpyAddress').text('('+ result.cmpyZipno + ') ' + result.cmpyAdres + ' ' + result.cmpyAdresDtl);
	
	$('#ITP_FORM_KOPER01010_VIEW .fnAddDt').text(result.addDt);
	$('#ITP_FORM_KOPER01010_VIEW .fnChgDt').text(result.chgDt);
	
	itp_fn_KOPER01010_view_map(result.cmpyAdres);	
	
	// 영업담당자정보  리스트 조회
	itp_fn_KOPER01010_view_grid.unload();
	itp_fn_KOPER01010_view_grid.callBack();
};

var itp_fn_KOPER01010_view_grid = {
	init: function() {
	},
	callBack: function() {
		let param = $('#ITP_FORM_KOPER01010_VIEW').serializeObject();
		param.gridSize = $.jgrid.defaults.rowNum; 
		param.pagingYn = false; // 페이징안함
		
		$(KOPER01010_VIEW_GRID_ID).jqGrid({
			colModel: [
				{
					index: 'VIEW_CD', name: 'viewCd',
					label: ITP_MSG_LOCALE.label.viewCd,
					width: '10', fixed: false, align: 'center',
					sortable: false, hidden: true
				},
				{
					index: 'SALES_USER_ID', name: 'salesUserId',
					label: '영업담당자ID',
					width: '20', fixed: false, align: 'center',
					sortable: false, editable: false, edittype: 'text',
					editrules: {required: true}
				},
				{
					index: 'SALES_USER_NM', name: 'salesUserNm',
					label: '영업담당자명',
					width: '30', fixed: false, align: 'center',
					sortable: true, editable: false, edittype: 'text',
					editrules: {required: true}
				},
				{
					index: 'USE_STAT_CD', name: 'useStatCd',
					label: ITP_MSG_LOCALE.label.status,
					width: '10', fixed: false, align: 'center',
					sortable: false, editable: false, edittype: 'text', hidden: true
				},
				{
					index: 'USE_STAT_NM', name: 'useStatNm',
					label: ITP_MSG_LOCALE.label.status,
					width: '10', fixed: false, align: 'center',
					sortable: false, editable: false, edittype: 'text'
				},
				{
					index: 'CMPY_CD', name: 'cmpyCd',
					label: '브랜드그룹코드',
					width: '10', fixed: false, align: 'center',
					sortable: false, editable: false, edittype: 'text', hidden: true
				}
			],
			loadBeforeSend: function(jqXHR) {
			    jqXHR.setRequestHeader('X-AUTH-TOKEN', CONN_KEY);
			},
			postData: JSON.stringify(param),
			url: DOMAIN + USER_SALESUSER_GRID_LIST,
			pager: KOPER01010_VIEW_GRID_PAGER,
			multiselect: false,
			loadComplete: function(data) {				
				itp_fn_grid_load_complete(data, KOPER01010_VIEW_GRID_ID, true, undefined, 'KOPER01010_VIEW');
		    },
		    loadError: function(jqXHR, textStatus, errorThrown) {
		    	itp_fn_grid_load_error(jqXHR, textStatus, errorThrown);
		    },
		    onPaging: function(action) {
		    	var pagingFn = {
	    			callBack: function(args) {
	    				$(args).trigger('reloadGrid');
	    			}
	    		};
		    	if (itp_fn_check_grid_is_writing(KOPER01010_VIEW_GRID_ID)) {
		    		itp_fn_modal_confirm(ITP_MSG_LOCALE.message.ajax.cancelData, pagingFn, KOPER01010_VIEW_GRID_ID);
		    		return 'stop';
		    	} else {
		    		itp_fn_grid_paging(KOPER01010_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(KOPER01010_VIEW_GRID_ID)) {
		    		itp_fn_modal_confirm(ITP_MSG_LOCALE.message.ajax.cancelData, sortingFn, KOPER01010_VIEW_GRID_ID);
		    		return 'stop';
		    	} else {
		    		itp_fn_grid_sorting(KOPER01010_VIEW_GRID_ID, index, sortOrder);
		    	}
		    }
		}).navGrid(KOPER01010_VIEW_GRID_PAGER, ITP_GRID_NAV_DEFAULTS.navGrid);
	},
	clearData : function() {
		$(KOPER01010_VIEW_GRID_ID).jqGrid('clearGridData', true);
		$(KOPER01010_VIEW_GRID_LIST).find('.ui-jqgrid-bdiv').css('min-height', '100px');
		$(KOPER01010_VIEW_GRID_EMPTY).html(ITP_MSG_LOCALE.message.grid.noData);
		$(KOPER01010_VIEW_GRID_EMPTY).show();
	}, 
	unload : function() {
		$.jgrid.gridUnload(KOPER01010_VIEW_GRID_ID); 
	}
};

var itp_fn_KOPER01010_detail = function(param) {
	fn_ajax_call(COMPANY_INFO_COMPANY, param, itp_fn_KOPER01010_detail_callback, 'GET');
};

var itp_fn_KOPER01010_detail_callback = function(result) {
	// console.log(result);
	itp_fn_KOPER01010_switch_screen('MODIFY');
	$('#ITP_FORM_KOPER01010_DETAIL #ITP_FORM_KOPER01010_DETAIL_VIEW_CD').val('U');
	
	$('#ITP_FORM_KOPER01010_DETAIL #ITP_FORM_KOPER01010_DETAIL_CMPY_NM').val(result.cmpyNm);
	$('#ITP_FORM_KOPER01010_DETAIL #ITP_FORM_KOPER01010_DETAIL_CMPY_STAT_CD').val(result.cmpyStatCd);
	$('#ITP_FORM_KOPER01010_DETAIL #ITP_FORM_KOPER01010_DETAIL_FRCOMP_AUTH_CD').val(result.frcompAuthCd);
	$('#ITP_FORM_KOPER01010_DETAIL #ITP_FORM_KOPER01010_DETAIL_CMPY_CD').val(result.cmpyCd);	
	$('#ITP_FORM_KOPER01010_DETAIL #ITP_FORM_KOPER01010_DETAIL_CMPY_TYPE_CD').val(result.cmpyTypeCd);
	$('#ITP_FORM_KOPER01010_DETAIL #ITP_FORM_KOPER01010_DETAIL_CMPY_REG_NUM').val(result.cmpyRegNum);
	$('#ITP_FORM_KOPER01010_DETAIL #ITP_FORM_KOPER01010_DETAIL_COPT_NUM').val(result.coptNum);
	$('#ITP_FORM_KOPER01010_DETAIL #ITP_FORM_KOPER01010_DETAIL_BIZ_CATE').val(result.bizCate);
	$('#ITP_FORM_KOPER01010_DETAIL #ITP_FORM_KOPER01010_DETAIL_BIZ_TYPE').val(result.bizType);
	$('#ITP_FORM_KOPER01010_DETAIL #ITP_FORM_KOPER01010_DETAIL_BOSS_NM').val(result.bossNm);
	$('#ITP_FORM_KOPER01010_DETAIL #ITP_FORM_KOPER01010_DETAIL_MAIN_TEL').val(result.mainTel);
	$('#ITP_FORM_KOPER01010_DETAIL #ITP_FORM_KOPER01010_DETAIL_MAIN_FAX').val(result.mainFax);
	$('#ITP_FORM_KOPER01010_DETAIL #ITP_FORM_KOPER01010_DETAIL_MAIN_EMAIL').val(result.mainEmail);
		
	$('#ITP_FORM_KOPER01010_DETAIL #ITP_FORM_KOPER01010_DETAIL_CMPY_ZIPNO').val(result.cmpyZipno);	
	$('#ITP_FORM_KOPER01010_DETAIL #ITP_FORM_KOPER01010_DETAIL_CMPY_ADRES').val(result.cmpyAdres);	
	$('#ITP_FORM_KOPER01010_DETAIL #ITP_FORM_KOPER01010_DETAIL_CMPY_ADRES_DTL').val(result.cmpyAdresDtl);		
	
	$('#ITP_FORM_KOPER01010_DETAIL .fnAddDt').text(result.addDt);
	$('#ITP_FORM_KOPER01010_DETAIL .fnChgDt').text(result.chgDt);
	
	itp_fn_KOPER01010_detail_map($('#ITP_FORM_KOPER01010_DETAIL_CMPY_ADRES').val());
	
	// 영업담당자 리스트 조회
	itp_fn_KOPER01010_detail_grid.unload();
	itp_fn_KOPER01010_detail_grid.callBack();
};


var itp_fn_KOPER01010_detail_grid = {
	init: function() {
	},
	callBack: function() {
		let param = $('#ITP_FORM_KOPER01010_DETAIL').serializeObject();
		param.gridSize = $.jgrid.defaults.rowNum; 
		param.pagingYn = false; // 페이지안함 
		
		$(KOPER01010_DETAIL_GRID_ID).jqGrid({
			colModel: [
				{
					index: 'VIEW_CD', name: 'viewCd',
					label: ITP_MSG_LOCALE.label.viewCd,
					width: '10', fixed: false, align: 'center',
					sortable: false, hidden: true
				},
				{
					index: 'SALES_USER_ID', name: 'salesUserId',
					label: '영업담당자ID',
					width: '20', fixed: false, align: 'center',
					sortable: false, editable: false, edittype: 'text',
					editrules: {required: true}
				},
				{
					index: 'SALES_USER_NM', name: 'salesUserNm',
					label: '영업담당자명',
					width: '30', fixed: false, align: 'center',
					sortable: true, editable: false, edittype: 'text',
					editrules: {required: true}
				},
				{
					index: 'USE_STAT_CD', name: 'useStatCd',
					label: ITP_MSG_LOCALE.label.status,
					width: '10', fixed: false, align: 'center',
					sortable: false, editable: false, edittype: 'text', hidden: true
				},
				{
					index: 'USE_STAT_NM', name: 'useStatNm',
					label: ITP_MSG_LOCALE.label.status,
					width: '10', fixed: false, align: 'center',
					sortable: false, editable: false, edittype: 'text'
				},
				{
					index: 'CMPY_CD', name: 'cmpyCd',
					label: '브랜드그룹코드',
					width: '10', fixed: false, align: 'center',
					sortable: false, editable: false, edittype: 'text', hidden: true
				}
			],
			loadBeforeSend: function(jqXHR) {
			    jqXHR.setRequestHeader('X-AUTH-TOKEN', CONN_KEY);
			},
			postData: JSON.stringify(param),
			url: DOMAIN + USER_SALESUSER_GRID_LIST,
			pager: KOPER01010_DETAIL_GRID_PAGER,
			loadComplete: function(data) {				
				itp_fn_grid_load_complete(data, KOPER01010_DETAIL_GRID_ID, true, undefined, 'KOPER01010_DETAIL');
		    },
		    loadError: function(jqXHR, textStatus, errorThrown) {
		    	itp_fn_grid_load_error(jqXHR, textStatus, errorThrown);
		    },
		    onPaging: function(action) {
		    	var pagingFn = {
	    			callBack: function(args) {
	    				$(args).trigger('reloadGrid');
	    			}
	    		};
		    	if (itp_fn_check_grid_is_writing(KOPER01010_DETAIL_GRID_ID)) {
		    		itp_fn_modal_confirm(ITP_MSG_LOCALE.message.ajax.cancelData, pagingFn, KOPER01010_DETAIL_GRID_ID);
		    		return 'stop';
		    	} else {
		    		itp_fn_grid_paging(KOPER01010_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(KOPER01010_DETAIL_GRID_ID)) {
		    		itp_fn_modal_confirm(ITP_MSG_LOCALE.message.ajax.cancelData, sortingFn, KOPER01010_DETAIL_GRID_ID);
		    		return 'stop';
		    	} else {
		    		itp_fn_grid_sorting(KOPER01010_DETAIL_GRID_ID, index, sortOrder);
		    	}
		    }
		}).navGrid(KOPER01010_DETAIL_GRID_PAGER, ITP_GRID_NAV_DEFAULTS.navGrid);
	},
	clearData : function() {
		$(KOPER01010_DETAIL_GRID_ID).jqGrid('clearGridData', true);
		$(KOPER01010_DETAIL_GRID_LIST).find('.ui-jqgrid-bdiv').css('min-height', '100px');
		$(KOPER01010_DETAIL_GRID_EMPTY).html(ITP_MSG_LOCALE.message.grid.noData);
		$(KOPER01010_DETAIL_GRID_EMPTY).show();
	}, 
	unload : function() {
		$.jgrid.gridUnload(KOPER01010_DETAIL_GRID_ID); 
	}
};