$(function() {
	const node = $(".node");
	const alarm = $(".alarm");
	const cancleButton=$(".cancle-button");
	const consumerCancleButton=$(".consumer-cancle-button");
	const consummer = $(".consummer");
	const searchButton = $(".search-button");
	const consumerSearchButton = $(".consumer-search-button");
	const alarmUpdateBtn= $(".alarm-update-button");
	const alarmSaveBtn = $(".alarm-save-button");
	const alarmCancelBtn= $(".alarm-cancel-button");
	const consumerSearchInput=$('.consumer-search > div:nth-child(1) > input');
	const citySelect = $(".city-select");
	const guSelect = $(".gu-select");
	const nodeSearch = $(".node-search");
	const alarmSearch = $(".alarm-search");
	const consumerSearch = $(".consumer-search");
	const intersectionSelect = $(".intersection-select");
	const addButton = $(".add-button");
	const consumerAddButton = $(".consumer-add-button");
	const updateButton = $(".update-button");
	const consumerUpdateButton = $(".consumer-update-button");
	const saveButton = $(".save-button");
	const consumerSaveButton = $(".consumer-save-button");
	const deleteButton = $(".delete-button");
	const consumerDeleteButton = $(".consumer-delete-button");
	const enroller = $(".consumer-search > div:nth-child(1) > input");
	const cityOptionUri = "/setCityOption.do";
	const guOptionUri = "/setGuOption.do";
	const isOptionUri = "/setIntersectionOption.do";
	const nodeAllDataUri = "/getSearchNodeAllData.do"
	const searchWithCityNodeDataUri = "/getSearchWithCityNodeData.do"
	const searchWithCityGuNodeDataUri = "/getSearchWithCityGuNodeData.do"
	const searchWithCityGuIsNodeDataUri = "/getSearchWithCityGuIsNodeData.do"
	const consumerAllDataUri="/getSearchConsumerAllData.do"
	const consumerDataUri="/getSearchCompanyData.do"
	const updateUri = "/updateNode.do";
	const guOptionHead = $("<option value=''>군/구를 선택해주세요</option>");
	const isOpitonHead = $("<option value=''>교차로를 선택해주세요</option>");
	const latitudePattern = /^([0-9]{1,2})([.]{1})([0-9]{1,14})$/
	const longitudePattern = /^([0-9]{1,3})([.]{1})([0-9]{1,14})$/
	const nodeIdPattern = /^[0-9]{1,10}$/;
	const phonePattern = /^[0-9]{2,3}-[0-9]{3,4}-[0-9]{4}$/;
	const emailPattern = /^[0-9a-zA-Z]([-_.]?[0-9a-zA-Z])*@[0-9a-zA-Z]([-_.]?[0-9a-zA-Z])*.[a-zA-Z]{2,3}$/i;
	const cancleAdd = "노드 추가 작업을 그만하시겠습니까? 작성하신 내용은 모두 지워집니다.";
	const cancleConsumerAdd = "Consumer 추가 작업을 그만하시겠습니까? 작성하신 내용은 모두 지워집니다.";
	const cancleUpdate = "노드 수정 작업을 그만하시겠습니까? 작성하신 내용은 모두 지워집니다.";
	const cancleConsumerUpdate = "Consumer 수정 작업을 그만하시겠습니까? 작성하신 내용은 모두 지워집니다.";
	const cancleDelete = "노드 삭제 작업을 그만하시겠습니까?";
	const cancleConsumerDelete = "Consumer 삭제 작업을 그만하시겠습니까?";
	const ntPattern=/^[0-9]*$/;
	
	//메인 실행 함수
	function init() {
			//지역(시) option 세팅
			setOption(cityOptionUri, citySelect);
			
			//지역(시)에 따른 군/구 option 세팅
			citySelect.on("change", () => {
				var citySelectVal = citySelect.val();
				guSelect.children('option').remove();
				guSelect.append(guOptionHead);
				intersectionSelect.children('option').remove();
				intersectionSelect.append(isOpitonHead);
				if (!nullChecker(citySelectVal)) setOption(guOptionUri, guSelect, citySelectVal);
			})

			// 군/구에 따른 교차로 option 세팅 
			guSelect.on("change", () => {
				var citySelectVal = citySelect.val();
				var guSelectVal = guSelect.val();
				intersectionSelect.children('option').remove();
				intersectionSelect.append(isOpitonHead);
				if (!nullChecker(citySelectVal) && !nullChecker(guSelectVal)) setOption(isOptionUri, intersectionSelect, citySelectVal, guSelectVal)
			})
			
		nodeOnOff();
		
		//노드 관리 클릭 시 발생 이벤트
		node.on("click", () => {
			//css 작업
			classToggle(node, consummer, alarm);
			searchToggle(nodeSearch, consumerSearch,alarmSearch);
			nodeOnOff();
		})


		//consummer 클릭 발생 이벤트
		consummer.on("click", () => {
			classToggle(consummer, node, alarm);
			searchToggle(consumerSearch, nodeSearch,alarmSearch);
			//초기화 및 클릭 이벤트 기본 세팅
			consumerOnOff();
		})
		
		//알람 정책 관리 발생 이벤트
		alarm.on("click", () =>{
			classToggle(alarm,node,consummer);
			searchToggle(alarmSearch,consumerSearch, nodeSearch);
			alarmOnOff();
		})
		
		
	}

	init()


	//---------------------------------[조회 관련 함수]----------------------------------------------------------------------
	function nodeTitle(){
		var table = $(".data-table");
		table.empty();
		table.append($("<tr><th colspan='15' class='table-title'>노드 정보</th></tr>"));
		table.append($("<tr class='table-column'>"
					+ "<th style='width:100px'>NODE ID</th>"
					+ "<th style='width:105px'>교차로</th>"
					+ "<th style='width:120px'>위도</th>"
					+ "<th style='width:120px'>경도</th>"
					+ "<th style='width:80px'>지역(시)</th>"
					+ "<th style='width:80px'>군/구</th>"
					+ "<th style='width:263.5px'>주소</th>"
					+ "<th style='width:100px'>ADD NODE</th>"
					+ "<th style='width:150px'>IP 주소</th>"
					+ "<th style='width:80px'>사용 여부</th>"
					+ "<th style='width:78px'>CVIM TOPIC</th>"
					+ "<th style='width:78px'>NODE TOPIC</th>"
					+ "<th style='width:78px'>TEST TOPIC</th>"
					+ "<th style='width:78px'>NODE TYPE</th>"
					+ "<th style='width:80px'>권역 ID</th>"
					+ "</tr>"))
	}
	
	//테이블 그리기
	function drawTable(data) {
		var table = $(".data-table");
		var trArr = [];
		nodeTitle()
		data.forEach((d) => {
			var tr = $("<tr>");

			if (d.ipaddr == null) d.ipaddr = '';

			tr.html(
				"<td>" + d.nodeid + "</td>"
				+ "<td>" + d.name + "</td>"
				+ "<td>" + Number(d.latitude) + "</td>"
				+ "<td>" + Number(d.longitude) + "</td>"
				+ "<td>" + d.addr1 + "</td>"
				+ "<td>" + d.addr2 + "</td>"
				+ "<td>" + d.addr3 + "</td>"
				+ "<td>" + d.addnode + "</td>"
				+ "<td>" + d.ipaddr + "</td>"
				+ "<td>" + d.useyn + "</td>"
				+ "<td>" + d.cvimyn + "</td>"
				+ "<td>" + d.nodeyn + "</td>"
				+ "<td>" + d.testyn + "</td>"
				+ "<td>" + d.nodetype + "</td>"
				+ "<td>" + d.regionName + "</td>"
			)
			trArr.push(tr);
		})
		table.append(trArr);
	}
	function nodeOnOff(){
			//버튼 초기화
			addButton.off('click');
			updateButton.off('click');
			deleteButton.off('click');
			searchButton.off('click');
			saveButton.off('click');
			$(".excel-button").off('click');
			//테이블 초기화
			var table = $(".consumer-box2 > div > table:nth-child(1)");
			table.removeClass("update-table");
			table.addClass("consumer-info");
			table.empty();
			//css 초기화 
			nomalCss();
			noneClickCss("node");
			
			//수정 체크 박스 초기화
			$("input[name='useyn']").prop("checked",false);
			$("input[name='cvimyn']").prop("checked",false);
			$("input[name='nodeyn']").prop("checked",false);
			$("input[name='testyn']").prop("checked",false);
			$("input[name='addnode']").prop("checked",false);
			
			//엑셀 버튼 이벤트
			$(".excel-button").on('click',()=>{
				if(confirm("엑셀로 내려받으시겠습니까?"))fnExcelReport('data-table','node-table')
			})
			searchNode(citySelect.val(), guSelect.val(), intersectionSelect.val());
			//조회 버튼 클릭 발생 이벤트
			searchButton.on('click', () => {
				searchNode(citySelect.val(), guSelect.val(), intersectionSelect.val());
			})
			//추가 버튼 이벤트
			addButton.on("click", () => {
				addEvent();
			})
			//수정 버튼 이벤트
			updateButton.on("click", () => {
				updateEvent();
			})

			//삭제 버튼 이벤트
			deleteButton.on("click", () => {
				deleteEvent();
			})
	}
	//-------------------------------------[노드 관리]----------------------------------------------------------------------------	
	//---------------------------------[노드 삭제 관련 함수]------------------------------------------------------------------------	
	//node 삭제 기능
	function deleteNode() {
		var inputArr = $('input[type="checkbox"]');
		var str = ""
		for (let i = 0; i < inputArr.length; i++) {
			if (inputArr[i].checked) str += $("#check" + i).parent().next().text() + ",";
		}
		if (str !== "") {
			if (confirm("선택하신 노드 정보를 삭제하시겠습니까?")) {
				$.ajax({
					url:"/deleteNode.do",
					async:false,
					type: "get",
					dataType: "json",
					data:{
						nodeid:str
					},
					success:function(result){
						if(result==0){
							alert("노드 삭제가 정상적으로 처리되지 않았습니다.");	
							nodeOnOff();
							return 
						}
						alert("노드 정보 "+result+"건이 삭제 되었습니다.");
						nodeOnOff();
					}, error: function(error) {
						console.log(error)
					}
				})
			}
		}
		if (str == "") alert("선택된 노드 정보가 없습니다.")
	}

	//node 삭제 이벤트 
	function deleteEvent() {
		if ($(".data-table > tr:nth-child(3)").length == 0) return;
		searchNode(citySelect.val(), guSelect.val(), intersectionSelect.val(), false, true);
		clickCss("node");
		var inp = $('input[type="checkbox"]');
		$(".delete-all").on("click", () => {

			for (let i = 0; i < inp.length; i++) {
				inp[i].checked = true;
			}
		})
		$(".delete-cancle").on("click", () => {
			for (let i = 0; i < inp.length; i++) {
				inp[i].checked = false;
			}
		})
		cancleButton.off("click");
		cancleButton.on("click", () => {
			cancleAlarm(cancleDelete);
		})
		searchButton.off("click");
		searchButton.on("click", () => {
			cancleAlarm(cancleDelete);
		})
		saveButton.off("click");
		saveButton.on("click", () => {
			deleteNode()
		})
	}

	//삭제 테이블 그리기
	function drawDeletTable(data) {
		var table = $(".data-table");
		table.empty();
		var trArr = [];
		var cnt = 0;
		table.append($("<tr>"
			+ "<th colspan='16' class='table-title'><span style='position:relative;left:115px'>노드 정보</span> "
			+ " <input type='button' class='delete-all' value='전체 선택'>"
			+ "<input class='delete-cancle' type='button' value='선택 해제'>"
			+ "</th>"
			+ "</tr>"));
		table.append($("<tr class='table-column'>"
			+ "<th>선택</th>"
			+ "<th>NODE ID</th>"
			+ "<th>교차로</th>"
			+ "<th>위도</th>"
			+ "<th>경도</th>"
			+ "<th>지역(시)</th>"
			+ "<th>군/구</th>"
			+ "<th>주소</th>"
			+ "<th>ADD NODE</th>"
			+ "<th>IP 주소</th>"
			+ "<th>사용 여부</th>"
			+ "<th>CVIM TOPIC</th>"
			+ "<th>NODE TOPIC</th>"
			+ "<th>TEST TOPIC</th>"
			+ "<th>NODE TYPE</th>"
			+ "<th>권역 ID</th>"
			+ "</tr>"))
		data.forEach((d) => {
			var tr = $("<tr>");

			if (d.ipaddr == null) d.ipaddr = '';

			tr.html(
				"<td><input type='checkbox' id='check" + cnt + "'></td>"
				+ "<td>" + d.nodeid + "</td>"
				+ "<td>" + d.name + "</td>"
				+ "<td>" + Number(d.latitude) + "</td>"
				+ "<td>" + Number(d.longitude) + "</td>"
				+ "<td>" + d.addr1 + "</td>"
				+ "<td>" + d.addr2 + "</td>"
				+ "<td>" + d.addr3 + "</td>"
				+ "<td>" + d.addnode + "</td>"
				+ "<td>" + d.ipaddr + "</td>"
				+ "<td>" + d.useyn + "</td>"
				+ "<td>" + d.cvimyn + "</td>"
				+ "<td>" + d.nodeyn + "</td>"
				+ "<td>" + d.testyn + "</td>"
				+ "<td>" + d.nodetype + "</td>"
				+ "<td>" + d.regionName + "</td>"
			)
			trArr.push(tr);
			cnt++;
		})
		table.append(trArr);
	}
	//---------------------------------[노드 추가 관련 함수]------------------------------------------------------------------------	


	//node추가 이벤트
	function addEvent() {
		addCss("node");
		addColumn();
		$(".add-column-button").off("click");
		$(".add-column-button").on("click",()=>{
			addColumn();
		})
		var cancle=$(".add-cancle-button");
		cancle.on('click',()=>{
			cancleAlarm(cancleAdd);
		})
		cancleButton.off("click");
		cancleButton.on("click", () => {
			cancleAlarm(cancleAdd);
		})
		saveButton.off("click");
		saveButton.on("click", () => {
			addNode();
		})
	}
	
	//-버튼 클릭시 row 삭제 함수
	function deleteColumn(parent){
		if(confirm("선택 하신 행을 삭제하시겠습니까?"))parent.remove();
	};

	//추가 버튼 클릭 시 한줄 추가 함수
	function addColumn() {
		var table=$(".consumer-info");
		var region=[];
		var str="";	
			table.css('width','100%');
			regionArr(region);
			region[0].forEach((r)=>{
				str+="<option value='"+r.region_id+"'>"+r.region_name+"</option>"
			})
			if(!$(".consumer-info > tr > th").text().includes("노드 정보 추가")){
				table.append($("<tr>"
					+ "<th colspan='17' class='table-title'>노드 정보 추가 <span class='add-cancle-button' style='position: relative;left: 800px'>X</sapn>"
					+ "</th>"
					+ "</tr>"));
				table.append($("<tr class='table-column'>"
					+ "<th class='add-column-button' style='width:50px'>+</th>"
					+ "<th style='width:100px'>NODE ID</th>"
					+ "<th style='width:105px'>교차로</th>"
					+ "<th style='width:120px'>위도</th>"
					+ "<th style='width:120px'>경도</th>"
					+ "<th style='width:80px'>지역(시)</th>"
					+ "<th style='width:80px'>군/구</th>"
					+ "<th style='width:263.5px'>주소</th>"
					+ "<th style='width:100px'>ADD NODE</th>"
					+ "<th style='width:150px'>IP 주소</th>"
					+ "<th style='width:80px'>사용 여부</th>"
					+ "<th style='width:80px'>CVIM TOPIC</th>"
					+ "<th style='width:80px'>NODE TOPIC</th>"
					+ "<th style='width:80px'>TEST TOPIC</th>"
					+ "<th style='width:80px'>NODE TYPE</th>"
					+ "<th style='width:80px'>권역 ID</th>"
					+ "</tr>"))
			}
		table.append($("<tr>"
			+ "<td class='delete-column-button'>-</td>"
			+ "<td><input type='text' name='nodeid' placeholder='NODE ID'></td>"
			+ "<td><input type='text' name='name' placeholder='교차로'></td>"
			+ "<td><input type='text' name='latitude' placeholder='위도'></td>"
			+ "<td><input type='text' name='longitude' placeholder='경도'></td>"
			+ "<td><input type='text' name='addr1' placeholder='지역(시)'></td>"
			+ "<td><input type='text' name='addr2' placeholder='군/구'></td>"
			+ "<td><input type='text' name='addr3' placeholder='주소'></td>"
			+ "<td><select name='addnode'>"
			+ "<option value='T'>연등지</option>"
			+ "<option value='F' selected>비연등지</option>"
			+ "</select>"
			+ "</td>"
			+ "<td><input type='text' name='ipaddr' placeholder='IP 주소'></td>"
			+ "<td>"
			+ "<select style='width:78px' name='useyn'>"
			+ "<option value='Y'>사용</option>"
			+ "<option value='N'>미사용</option>"
			+ "</select>"
			+ "</td>"
			+ "<td>"
			+ "<select name='cvimyn'>"
			+ "<option value='Y' selected>사용</option>"
			+ "<option value='N'>미사용</option>"
			+ "</select>"
			+ "</td>"
			+ "<td>"
			+ "<select name='nodeyn'>"
			+ "<option value='Y' selected>사용</option>"
			+ "<option value='N'>미사용</option>"
			+ "</select>"
			+ "</td>"
			+ "<td>"
			+ "<select name='testyn'>"
			+ "<option value='Y' selected>사용</option>"
			+ "<option value='N'>미사용</option>"
			+ "</select>"
			+ "</td>"
			+ "<td><input type='text' name='nodetype' placeholder='NODE TYPE'></td>"
			+ "<td><select style='width:80px' name='regionId'>"
			+ str	
			+"</select></td>"
			+ "</tr>"))
		var rowDelete=$(".consumer-info >tr")[$(".consumer-info >tr").length-1].firstChild;
		rowDelete.onclick=(()=>{
			deleteColumn(rowDelete.parentNode);
		})
	}
	
	//추가 버튼 클릭 시 저장 버튼 이벤트
	function addNode() {
		for (let i = 0; i < $("input[name='nodeid']").length; i++) {
			var checker = [];
			allNodeId($("input[name='nodeid']")[i].value, checker)
			if (nullChecker($("input[name='nodeid']")[i].value)) {
				alert("NODE ID를 입력하세요");
				$("input[name='nodeid']")[i].focus();
				return
			}
			if (checker[0]) {
				alert("중복된 NODE ID 입니다.")
				$("input[name='nodeid']")[i].focus();
				return
			}

			if (!nodeIdPattern.test($("input[name='nodeid']")[i].value)) {
				alert("NODE ID는 10자리 이하 숫자만 입력이 가능합니다.");
				$("input[name='nodeid']")[i].focus();
				return
			}

			if (nullChecker($("input[name='name']")[i].value)) {
				alert("교차로를 입력하세요");
				$("input[name='name']")[i].focus();
				return
			}
			if (nullChecker($("input[name='latitude']")[i].value)) {
				alert("위도를 입력하세요");
				$("input[name='latitude']")[i].focus();
				return
			}
			if (!latitudePattern.test($("input[name='latitude']")[i].value)) {
				alert("소수점 포함 앞자리 0~2자리, 뒷자리 0~14자리로 입력해주세요")
				$("input[name='latitude']")[i].focus();
				return
			}
			if (nullChecker($("input[name='longitude']")[i].value)) {
				alert("경도를 입력하세요");
				$("input[name='longitude']")[i].focus();
				return
			}
			if (!longitudePattern.test($("input[name='longitude']")[i].value)) {
				alert("소수점 포함 앞자리 0~3자리, 뒷자리 0~14자리로 입력해주세요")
				$("input[name='longitude']")[i].focus();
				return
			}
			if (nullChecker($("input[name='addr1']")[i].value)) {
				alert("지역(시)를 입력하세요");
				$("input[name='addr1']")[i].focus();
				return
			}
			if (nullChecker($("input[name='addr2']")[i].value)) {
				alert("군/구를 입력하세요");
				$("input[name='addr2']")[i].focus();
				return
			}
			if (nullChecker($("input[name='addr3']")[i].value)) {
				alert("주소를 입력하세요");
				$("input[name='addr3']")[i].focus();
				return
			}
			if (nullChecker($("select[name='addnode']")[i].value)) {
				alert("연등지 여부를 체크하세요");
				$("select[name='addnode']")[i].focus();
				return
			}
			if (nullChecker($("input[name='nodetype']")[i].value)) {
				alert("NODE TYPE을 입력하세요");
				$("input[name='nodetype']")[i].focus();
				return
			}
			if(!ntPattern.test($("input[name='nodetype']")[i].value)){
				alert("NODE TYPE 형식에 맞게 입력하세요(숫자만 입력 가능)")
				$("input[name='nodetype']")[i].focus();
				return
			}
		}
		var addData=[];
		var tableLength=$(".consumer-info > tr").length;
		var trArr=$(".consumer-info > tr");
		for(let i=2;i<tableLength;i++){
			var valArr=[];
			for(let j=1;j<trArr[i].children.length;j++){
				trArr[i].children[j].children[0].value==null?
					valArr.push(null):valArr.push(trArr[i].children[j].children[0].value);
			}
			addData.push(new NodeVO(valArr[0],valArr[1],valArr[2],valArr[3],valArr[4],
									valArr[5],valArr[6],valArr[7],valArr[8],valArr[9]
									,valArr[10],valArr[11],valArr[12],valArr[13],valArr[14]));
		}
		
		var jsonData = JSON.stringify(addData);
		jQuery.ajaxSettings.traditional = true;

		if (confirm("노드 정보를 추가 하시겠습니까?")) {
			$.ajax({
				url:"/addNode.do",
				async:false,
				type: "get",
				dataType: "json",
				data:{
					jsonData:jsonData
				},
				success:function(result){
					if(result==0){
						alert("노드 추가가 정상적으로 처리되지 않았습니다.");	
						nodeOnOff();
						return 
					}
					alert("노드 정보 "+result+"건이 추가 되었습니다.");
					nodeOnOff();
				}, error: function(error) {
					console.log(error)
				}
			
			})
		}
		
	}
	//전체 nodeId 조회
	function allNodeId(value, checker) {
		$.ajax({
			url: "/getAllNodeId.do",
			async: false,
			cache: false,
			type: "get",
			dataType: "json",
			success: function(result) {
				var include = result.includes(value.toString());
				checker.push(include);
			}, error: function(error) {
				console.log(error)
			}

		})
	}

	//---------------------------------[노드 수정 관련 함수]------------------------------------------------------------------------	
	//node 수정 이벤트
	function updateEvent() {
		var trArr=$(".data-table > tr")
		addCss("node");
		drawUpdateTable();
		for(let i=2; i < trArr.length; i++){
			trArr[i].onclick=function(){
				drawUpdateTable($(this));
			}
			trArr[i].onmouseover=function(){
				$(this).css("cursor","pointer");
			}
		}
		searchButton.off("click");
		searchButton.on("click", () => {
			cancleAlarm(cancleUpdate);
		})
		cancleButton.off("click");
		cancleButton.on("click", () => {
			cancleAlarm(cancleUpdate);
		})
		saveButton.off("click");
		saveButton.on("click", () => {
			updateNode();
		})
	}
	function regionArr(arr){
		$.ajax({
				url:"/api/getAllRegion.do",
				async:false,
				type: "get",
				dataType: "json",
				success:function(result){
					arr.push(result);
				}, error: function(error) {
				console.log(error)
				}
			
		})
	}

	//수정 버튼 클릭 시 저장 버튼 이벤트
	function updateNode() {
			var addnode=$("input[name='addnode']").is(":checked")?'T':'F'
			var useyn=$("input[name='useyn']").is(":checked")?'Y':'N'
			var cvimyn=$("input[name='cvimyn']").is(":checked")?'Y':'N'
			var nodeyn=$("input[name='nodeyn']").is(":checked")?'Y':'N'
			var testyn=$("input[name='testyn']").is(":checked")?'Y':'N'
			
		
			var nodeVO=new NodeVO($("input[name='nodeid']").val(),
									$("input[name='name']").val(),
									$("input[name='latitude']").val(),
									$("input[name='longitude']").val(),
									$("input[name='addr1']").val(),
									$("input[name='addr2']").val(),
									$("input[name='addr3']").val(),
									addnode,
									$("input[name='ipaddr']").val(),
									useyn,cvimyn,nodeyn,testyn,
									$("input[name='nodetype']").val(),
									$("select[name='regionId']").val()
									);
		var jsonData = JSON.stringify(nodeVO);
		jQuery.ajaxSettings.traditional = true;
		if(nullChecker($("input[name='nodeid']").val()))return alert("수정 하실 내용을 선택해주세요");
		if (confirm("노드 정보를 수정 하시겠습니까?")) {
			$.ajax({
				url:updateUri,
				async:false,
				type: "get",
				dataType: "json",
				data:{
					jsonData:jsonData
				},
				success:function(result){
					if(result==0){
						alert("수정 사항이 없습니다.");	
						nodeOnOff();
						return 
					}
					alert("노드 정보 "+result+"건 수정되었습니다.");
					nodeOnOff();
				}, error: function(error) {
				console.log(error)
				}
			
			})
		}
		
	}

	function NodeVO(nodeid,  name,  latitude,  longitude,  addr1,  addr2,
			 addr3,  addnode,  ipaddr,  useyn,  cvimyn,  nodeyn,  testyn,
			 nodetype,  regionId){
		this.nodeid = nodeid;
		this.name = name;
		this.latitude = latitude;
		this.longitude = longitude;
		this.addr1 = addr1;
		this.addr2 = addr2;
		this.addr3 = addr3;
		this.addnode = addnode;
		this.ipaddr = ipaddr;
		this.useyn = useyn;
		this.cvimyn = cvimyn;
		this.nodeyn = nodeyn;
		this.testyn = testyn;
		this.nodetype = nodetype;
		this.regionId = regionId;
	}

	//수정 테이블
	function drawUpdateTable(data) {
		var table = $(".consumer-box2 > div > table:nth-child(1)");
		table.removeClass("consumer-info");
		table.addClass("update-table");
		
		$(".config-table").css("display","block");
		$(".config-table").css("width","570px");
		$(".update-table").css("width","1230px");
		
		table.empty();
		$(".config-table").empty();
		var str='';
		str+='<tr>'
          +'<th colspan="4" style="color: #7b7c7d; background: rgb(52 55 58);height: 50px;">노드 정보 수정</th>'
        +'</tr>'
        +'<tr>'
          +'<td style="background: #22252b; color: rgb(123 124 125); font-weight: bold; width: 200px;">분류</td>'
          +'<td style="background: #22252b; color: rgb(123 124 125); font-weight: bold;">내용</td>'
          +'<td style="background: #22252b; color: rgb(123 124 125); font-weight: bold; width: 200px;">분류</td>'
          +'<td style="background: #22252b; color: rgb(123 124 125); font-weight: bold;">내용</td>'
        +'</tr>'
        +'<tr>'
          +'<td>NODE ID</td>'
          +'<td><input type="text" name="nodeid" value="" disabled></td>'
          +'<td>IP 주소</td>'
          +'<td><input type="text" name="ipaddr" value="" disabled></td>'
        +'</tr>'
        +'<tr>'
          +'<td>교차로</td>'
          +'<td><input type="text" name="name" value="" disabled></td>'
            +'<td>지역(시)</td>'
            +'<td><input type="text" name="addr1" value="" disabled></td>'
        +'</tr>'
        +'<tr>'
            +'<td>위도</td>'
            +'<td><input type="text" name="latitude" value="" disabled></td>'
            +'<td>군/구</td>'
            +'<td><input type="text" name="addr2" value="" disabled></td>'
          +'</tr>'
          +'<tr>'
            +'<td>경도</td>'
            +'<td><input type="text" name="longitude" value="" disabled></td>'
            +'<td>NODE TYPE</td>'
            +'<td><input type="text" name="nodetype" value="" disabled></td>'
         +'</tr>'
         +'<tr>'
         	+' <td>권역 ID</td>'
          +'<td><select name="regionId" disabled>'
		  +'</select></td>'
          +'<td>주소</td>'
          +'<td><input type="text" name="addr3" value="" disabled></td>'
      '</tr>';
		var tbody=$("<tbody>").html(str);
			table.append(tbody);
		var config='<tr>'
						+'<th colspan="2" style="color: #7b7c7d; background: rgb(52 55 58); width:732px; height: 50px;">'
								+'설정 정보 선택</th>'
						+'</tr>'
						+'<tr>'
							+'<td style="background: #22252b; color: rgb(123 124 125); font-weight: bold;">'
							+	'분류'
							+'</td>'
							+'<td style="background: #22252b; color: rgb(123 124 125); font-weight: bold;">Off/On'
							+'</td>'
					+'</tr>'
					+'<tr style="height:37.55px">'
						+'<td>사용여부</td>'
						+'<td><label class="switch">'
							+'<input type="checkbox" name="useyn" value="Y" disabled>' 
									+'<span class="slider round"></span>'
							+'</label></td>'
						+'</tr>'
						+'<tr style="height:37.55px">'
							+'<td>CVIM TOPIC</td>'
							+'<td>'
								+'<label class="switch">' 
									+'<input type="checkbox" name="cvimyn" value="Y" disabled>' 
									+'<span class="slider round"></span>'
								+'</label>'
							+'</td>'
						+'</tr>'
						+'<tr style="height:37.55px">'
							+'<td>NODE TOPIC</td>'
							+'<td>'
								+'<label class="switch">' 
									+'<input type="checkbox" name="nodeyn" value="Y" disabled>' 
									+'<span class="slider round"></span>'
								+'</label>'
							+'</td>'
						+'</tr>'
						+'<tr style="height:37.55px">'
							+'<td>TEST TOPIC</td>'
							+'<td>'
								+'<label class="switch">'
									+'<input type="checkbox" name="testyn" value="Y" disabled>' 
									+'<span class="slider round"></span>'
								+'</label>'
							+'</td>'
						+'</tr>'
						+'<tr style="height:37.55px">'
							+'<td>연등지</td>'
							+'<td>'
								+'<label class="switch">' 
									+'<input type="checkbox" name="addnode" value="T" disabled>' 
									+'<span class="slider round"></span>'
								+'</label>'
							+'</td>'
						+'</tr>';
			$(".config-table").append($("<tbody>").html(config));
			$(".config-table > tbody > tr > td").css("height","36px");
		if(data !== undefined){
			var	region=[];
				dataArr=[];
			var regionOption ="";
				for(let i =0; i<data.children().length;i++){
					dataArr.push(data.children().eq(i).text());
				}
				regionArr(region);
				region[0].forEach((r)=>{
					if(dataArr[14] == r.region_name)regionOption+="<option value='"+r.region_id+"' selected>"+r.region_name+"</option>"
					if(dataArr[14] !== r.region_name)regionOption+="<option value='"+r.region_id+"'>"+r.region_name+"</option>"
				})
				$("input").removeAttr("disabled");
				$("select").removeAttr("disabled");
				$("checkbox").removeAttr("disabled");
				$("input[name='nodeid']").attr("readonly",true);				
				$(".update-table > tbody > tr > td > input").removeData('disabled');
				$("input[name='nodeid']").prop('value',dataArr[0]);				
				$("input[name='name']").prop('value',dataArr[1]);
				$("input[name='latitude']").prop('value',dataArr[2]);
				$("input[name='longitude']").prop('value',dataArr[3]);
				$("input[name='addr1']").prop('value',dataArr[4]);
				$("input[name='addr2']").prop('value',dataArr[5]);
				$("input[name='addr3']").prop('value',dataArr[6]);
				$("input[name='ipaddr']").prop('value',dataArr[8]);
				$("input[name='nodetype']").prop('value',dataArr[13]);
				$("select[name='regionId']").empty();
				$("select[name='regionId']").append(regionOption);
			var useYn=$("input[name='useyn']");
			var cvimYn=$("input[name='cvimyn']");
			var nodeYn=$("input[name='nodeyn']");
			var testYn=$("input[name='testyn']");
			var addNode=$("input[name='addnode']");
				dataArr[7]=="연등지"?addNode.prop("checked",true):addNode.prop("checked",false);
				dataArr[9]=="사용"?useYn.prop("checked",true):useYn.prop("checked",false);
				dataArr[10]=="사용"?cvimYn.prop("checked",true):cvimYn.prop("checked",false);
				dataArr[11]=="사용"?nodeYn.prop("checked",true):nodeYn.prop("checked",false);
				dataArr[12]=="사용"?testYn.prop("checked",true):testYn.prop("checked",false);
		}
	}
	//--------------------------[메뉴 관련]--------------------------------------------------
	//메뉴 클래스 변환 함수
	function classToggle(on, off1,off2) {
		on.addClass("manager-on");
		on.removeClass("manager-off");
		off1.addClass("manager-off");
		off1.removeClass("manager-on");
		off2.addClass("manager-off");
		off2.removeClass("manager-on");
		$(".consumer-search > div:nth-child(1) >input").val("");
		citySelect.children().first().prop("selected","selected");
	}
	
	function searchToggle(flex, none1, none2) {
		flex.css("display", "flex");
		none1.css("display", "none");
		none2.css("display", "none");
	}


	//--------------------------[노드 데이터 관련 함수]----------------------------------------------	
	//데이터 가져오는 함수
	function setOption(url, select, city, gu) {
		$.ajax({
			url: url,
			type: "get",
			dataType: "json",
			data: {
				city: city,
				gu: gu
			},
			success: function(result) {
				result.forEach((d) => {
					var option = $("<option value='" + d + "'>" + d + "</option>")
					select.append(option);
				})
			},
			error: function(error) {
				console.log(error)
			}
		})
	}

	//검색한 데이터 가져오기
	function searchNode(city, gu, intersection, updateSearch, deleteSearch) {
		var url = "";
		if (nullChecker(city) && nullChecker(gu) && nullChecker(intersection)) url = nodeAllDataUri;
		if (!nullChecker(city) && nullChecker(gu) && nullChecker(intersection)) url = searchWithCityNodeDataUri;
		if (!nullChecker(city) && !nullChecker(gu) && nullChecker(intersection)) url = searchWithCityGuNodeDataUri;
		if (!nullChecker(city) && !nullChecker(gu) && !nullChecker(intersection)) url = searchWithCityGuIsNodeDataUri;
		$.ajax({
			url: url,
			async: false,
			cache: false,
			type: "get",
			dataType: "json",
			data: {
				city: city,
				gu: gu,
				intersection: intersection
			},
			success: function(result) {
				if(nullChecker(result))return alert("검색 결과가 없습니다.");
				if (deleteSearch)return drawDeletTable(result);
				drawTable(result);
			}, error: function(error) {
				console.log(error)
			}

		})
	}

	//-----------------------[노드 버튼 관련 함수]---------------------------------------------------------	
	//작업 중 다른 작업 실행 할때 발생 함수 
	function cancleAlarm(text) {
		if (confirm(text))nodeOnOff();
	}
	function noneClickCss(type){
		var table = $(".consumer-box2 > div > table:nth-child(1)");
			table.removeClass("update-table");
			table.addClass("consumer-info");
			table.empty();
		if(type === "node"){
			addButton.css("display","block");
			updateButton.css("display","block");
			deleteButton.css("display","block");
			$(".excel-button").css("display","block");
			saveButton.css("display","none");
			cancleButton.css("display","none");
		}
		if(type === "consumer"){
			consumerAddButton.css("display","block");
			consumerUpdateButton.css("display","block");
			consumerDeleteButton.css("display","block");
			$(".excel-button").css("display","block");
			consumerSaveButton.css("display","none");
			consumerCancleButton.css("display","none");
		}
		if(type === "alarm"){
			block(alarmUpdateBtn);
			none(alarmCancelBtn);
			none(alarmSaveBtn);
		}
	}
	function clickCss(type){
			
		if(type === "node"){
			addButton.css("display","none");
			updateButton.css("display","none");
			deleteButton.css("display","none");
			$(".excel-button").css("display","none");
			saveButton.css("display","block");
			cancleButton.css("display","block");
		}
		if(type === "consumer"){
			consumerAddButton.css("display","none");
			consumerUpdateButton.css("display","none");
			consumerDeleteButton.css("display","none");
			$(".excel-button").css("display","none");
			consumerSaveButton.css("display","block");
			consumerCancleButton.css("display","block");
		}
		if(type === "alarm"){
			none(alarmUpdateBtn);
			block(alarmCancelBtn);
			block(alarmSaveBtn);
		}
	}
	//-------------------------------------------------[노드 관리]------------------------------------------------------------------
	//------------------------------------------------[컨슈머 관리]-----------------------------------------------------------------
	//---------------------------------------------[컨슈머 버튼 관련 함수]---------------------------------------------------------	
	//작업 중 다른 작업 실행 할때 발생 함수 
	function cancleConsumerAlarm(text) {
		if (confirm(text))consumerOnOff();
	}
	function consumerOnOff(){
			searchConsumer(enroller.val());
			consumerDeleteButton.off("click");
			consumerUpdateButton.off("click");
			consumerAddButton.off("click");
			consumerSearchButton.off("click");
			consumerSaveButton.off("click");
			consumerSearchInput.off('keydown');
			consumerCancleButton.off("click");
			$(".excel-button").off("click");
			noneClickCss("consumer");
			//테이블 초기화
			nomalCss()
			$(".token-td").on("click",function(){
				var popupX = (window.screen.width / 2) - (400 / 2);
				var popupY= (window.screen.height / 2) - (400 / 2);
				var input=$(this).next().children().attr('id');
				var inputCnt=input.substr(input.indexOf("y")+1, input.length);
				var config = 'width=400,height=342,left='+popupX+',top='+popupY+',resizable=no'
				window.open('/checkToken?row='+inputCnt,'tokenBox',config);
			})
			
			$(".excel-button").on('click',()=>{
				if(confirm("엑셀로 내려받으시겠습니까?"))fnExcelReport('data-table','consumer-table')
			})
			consumerDeleteButton.on("click", () => {
				deleteConsumerEvent();
			})
			consumerUpdateButton.on("click", () => {
				updateConsumerEvent();
			})
			consumerAddButton.on("click", () => {
				addConsumerEvent();
			})
			consumerSearchInput.on('keydown',(e)=>{
				if(e.key === 'Enter'){
					searchConsumer(enroller.val());
				}
			})
			consumerSearchButton.on("click", () => {
				searchConsumer(enroller.val());
			})
	}
	//-----------------------------------------------[컨슈머 추가 관련]-------------------------------------------------------------
	function addCss(type){
		$(".result-box > div:nth-child(4)").addClass('consumer-box1');
		$(".result-box > div:nth-child(4)").removeClass('table-box');
		$(".consumer-box2").css("display","block");
		clickCss(type);
	}
	function nomalCss(){
		$(".result-box > div:nth-child(4)").addClass('table-box');
		$(".result-box > div:nth-child(4)").removeClass('consumer-box1');
		$(".consumer-box2").css("display","none");
		none($(".config-table"));
		none($(".api-acl-table"));
	}
	//Consumer추가 이벤트
	function addConsumerEvent() {
		addCss("consumer")
		addConsumerColumn()
		$(".add-column-button").off("click")
		
		$(".add-column-button").on("click",()=>{
			addConsumerColumn()
			var tokenButton=$(".consumer-info >tr").eq($(".consumer-info >tr").length-1).children().first().next();
				tokenButton.on("click",function(){
				var popupX = (window.screen.width / 2) - (400 / 2);
				var popupY= (window.screen.height / 2) - (400 / 2);
				var input=$(this).next().children().attr('id');
				var inputCnt=input.substr(input.indexOf("y")+1, input.length);
					window.open('/setToken?row='+inputCnt,'tokenBox','width=400,height=400,left='+popupX+',top='+popupY+',scrollbars=yes,resizable=no');
			})
		})
		
		var tokenButton=$(".consumer-info >tr").eq($(".consumer-info >tr").length-1).children().first().next();
		tokenButton.on("click",function(){
			var popupX = (window.screen.width / 2) - (400 / 2);
			var popupY= (window.screen.height / 2) - (400 / 2);
			var input=$(this).next().children().attr('id');
			var inputCnt=input.substr(input.length-1, input.length);
			window.open('/setToken?row='+inputCnt,'tokenBox','width=400,height=400,left='+popupX+',top='+popupY+',scrollbars=yes,resizable=no');
		})
		
		var cancle=$(".add-cancle-button");
		cancle.on('click',()=>{
			cancleConsumerAlarm(cancleConsumerAdd);
		})
		
		consumerCancleButton.off("click");
		consumerCancleButton.on("click", () => {
			cancleConsumerAlarm(cancleConsumerAdd);
		})
		
		consumerSaveButton.off("click");
		consumerSaveButton.on("click", () => {
			addConsumer();
		})
	}
	function addConsumerColumn() {
		var now = new Date().toISOString();
		var cnt =$(".consumer-info > tr").length-2;
		now=now.substr(0,now.lastIndexOf(':'));
		var table=$(".consumer-info");
		table.css('width','100%');
		if(!$(".consumer-info > tr > th").text().includes("Consumer 정보 추가")){
				table.append($("<tr><th colspan=15 class='table-title'>Consumer 정보 추가<span class='add-cancle-button' style='position: relative;left: 780px'>X</sapn></th></tr>"))
				table.append($("<tr class='table-column'>"
							+ "<th class='add-column-button' style='width:50px'>+</th>"
							+ "<th>API Token</th>"
							+ "<th>업체명</th>"
							+ "<th>담당자</th>"
							+ "<th>E-mail</th>"
							+ "<th>담당자 연락처</th>"
							+ "<th>API 사용 만료일</th>"
							+ "<th>등록자</th>"
							+ "<th>IP주소</th>"
							+ "<th style='width:100px'>Client<br>유형</th>"
							+ "<th>Broker ID</th>"
							+ "<th>Broker Password</th>"
							+ "<th style='width:100px'>Client<br>상태</th>"
							+ "<th style='width:80px'>사용 여부</th>"
							+ "</tr>"))
			cnt =0;
		}
		table.append(
			$("<tr>"
				+"<td class='delete-column-button'>-</td>"
				+ "<td class='token-set-button'>클릭</td>"
				+ "<td style='display:none;'>"
				+ "<input id='add-company"+cnt+"' type='checkbox' value='company'>"
				+ "<input id='add-manager"+cnt+"' type='checkbox' value='manager'>"
				+ "<input id='add-phone"+cnt+"' type='checkbox' value='phone'>"
				+ "<input id='add-email"+cnt+"' type='checkbox' value='email'>"
				+ "</td>"
				+ "<td>" 
					+"<input type='text' name='company' placeholder='API 사용업체'>" 
				+ "</td>"
				+ "<td>" 
					+"<input type='text' name='manager' placeholder='담당자'>"
				+ "</td>"
				+ "<td>" 
					+"<input type='email' name='email' placeholder='E-mail'>" 
				+ "</td>"
				+ "<td>" 
					+"<input type='tel' name='phone' placeholder='담당자 연락처'>" 
				+ "</td>"
				+ "<td>" 
					+"<input type='datetime-local' min='"+now+"' name='expiredt'>" 
				+ "</td>"
				+ "<td>" 
					+"<input type='text' name='enroller' placeholder='등록자'>"
				+ "</td>"
				+ "<td>" 
					+"<input type='text' name='ipaddr' placeholder='IP주소' value='*'>" 
				+ "</td>"
				+ "<td>" 
					+"<select name='clientType'>"
							+"<option value='SYS' selected='selected'>SYS</option>"
							+"<option value='DEV'>DEV</option>"
							+"<option value='APP'>APP</option>"	
					+"</select>"
				+"</td>"		
				+ "<td>" 
					+"<input type='text' name='brokerId' placeholder='Broker ID'>" 
				+ "</td>"
				+ "<td>" 
					+"<input type='text' name='brokerPwd' placeholder='Broker Password'>" 
				+ "</td>"
				+ "<td>" 
					+"<select name='state'>"
						+"<option value='C' selected='selected'>등록완료</option>"
						+"<option value='R' >등록요청</option>"
					+"</select>"
				+ "</td>"
				+ "<td>" 
					+"<select name='useyn'>"
						+"<option value='Y' selected='selected'>사용</option>"
						+"<option value='N'>사용안함</option>"
					+"</select>"
				+ "</td>"
			+"</tr>"))
			var rowDelete=$(".consumer-info >tr")[$(".consumer-info >tr").length-1].firstChild
				rowDelete.onclick=()=>{
					deleteColumn(rowDelete.parentNode);
				}
	}
	
	//추가 버튼 클릭 시 저장 버튼 이벤트
	function addConsumer() {
		var checkArr=[];
		for (let i = 0; i < $(".consumer-info > tr").length-2; i++) {
			
				if(nullChecker($("input[name='company']")[i].value)) {
					alert("API 사용 업체를 입력하세요");
					$("input[name='company']")[i].focus();
					return
				}
				if(nullChecker($("input[name='manager']")[i].value)) {
					alert("담당자를 입력하세요");
					$("input[name='manager']")[i].focus();
					return
				}
				if(nullChecker($("input[name='email']")[i].value)) {
					alert("담당자 이메일을 입력하세요");
					$("input[name='email']")[i].focus();
					return
				}
				if(!emailPattern.test($("input[name='email']")[i].value)){
					alert("이메일 형식에 맞게 입력해주세요")
					$("input[name='email']")[i].focus();
					return 
				}
			
				if(nullChecker($("input[name='phone']")[i].value)) {
					alert("담당자 연락처를 입력하세요");
					$("input[name='phone']")[i].focus();
					return
				}
				if(!phonePattern.test($("input[name='phone']")[i].value)){
					alert("연락처 형식에 맞게 입력해주세요");
					$("input[name='phone']")[i].focus();
					return
				}
				if(nullChecker($("input[name='expiredt']")[i].value)) {
					alert("API 사용 만료일을 입력하세요");
					$("input[name='expiredt']")[i].focus();
					return
				}
				if(nullChecker($("input[name='enroller']")[i].value)) {
					alert("등록인을 입력하세요");
					$("input[name='enroller']")[i].focus();
					return
				}
				if(nullChecker($("input[name='ipaddr']")[i].value)) {
					alert("IP 주소를 입력하세요");
					$("input[name='ipaddr']")[i].focus();
					return
				}
				if(nullChecker($("select[name='clientType']")[i].value)) {
					alert("클라이언트 유형을 선택해주세요");
					$("select[name='clientType']")[i].focus();
					return
				}
				if(nullChecker($("input[name='brokerId']")[i].value)) {
					alert("BROKER ID를 입력하세요");
					$("input[name='brokerId']")[i].focus();
					return
				}
				if(nullChecker($("input[name='brokerPwd']")[i].value)) {
					alert("BROKER Password를 입력하세요");
					$("input[name='brokerPwd']")[i].focus();
					return
				}
				if(nullChecker($("select[name='useyn']")[i].value)) {
					alert("사용 여부를 선택해주세요");
					$("select[name='useyn']")[i].focus();
					return
				}
				var company=$("#add-company"+i).prop("checked")==true?$("input[name='company']")[i].value:'';
				var manager=$("#add-manager"+i).prop("checked")==true?$("input[name='manager']")[i].value:'';
				var phone=$("#add-phone"+i).prop("checked")==true?$("input[name='phone']")[i].value:'';
				var email=$("#add-email"+i).prop("checked")==true?$("input[name='email']")[i].value:'';
				
				if(company=='' && manager=='' && phone=='' && email==''){
					alert('API Token 버튼을 클릭 후 설정 해주세요');
					return 
				}
				
				checkArr.push({
					company:company,
					manager:manager,
					phone:phone,
					email:email
				});
		}
		var addData=[];
		var tableLength=$(".consumer-info > tr").length;
		var trArr=$(".consumer-info > tr");
		for(let i=2;i<tableLength;i++){
			var valArr=[];
			for(let j=2;j<trArr[i].children.length;j++){
				if(j==2)valArr.push(checkArr[j-2]);
				if(j !==2 ){
					trArr[i].children[j].children[0].value=="null"?
							valArr.push(null):valArr.push(trArr[i].children[j].children[0].value)
				}
			}
			
			var eventdt=new Date();
			var str=eventdt.toISOString().substr(0,eventdt.toISOString().indexOf('T')+1)
						+eventdt.toTimeString().substr(0,eventdt.toTimeString().indexOf(" "))
			eventdt=str
			addData.push(new TscApiClientVO(valArr[0],valArr[1],valArr[2],valArr[3],valArr[4],
									valArr[5],eventdt,valArr[6],valArr[7],valArr[8],valArr[9]
									,valArr[10],valArr[11],valArr[12]));
		}
			var jsonData = JSON.stringify(addData);
			jQuery.ajaxSettings.traditional = true;

		if (confirm("컨슈머 정보를 추가 하시겠습니까?")) {
			$.ajax({
				url:"/addConsumer.do",
				async:false,
				type: "get",
				dataType: "json",
				data:{
					jsonData:jsonData
				},
				success:function(result){
					if(result==0){
						alert("컨슈머 정보 추가가 정상적으로 처리되지 않았습니다.");	
						consumerOnOff();
						return 
					}
					alert("컨슈머 정보 "+result+"건이 추가 되었습니다.");
					consumerOnOff();
				}, error: function(error) {
				console.log(error)
				}
			
			})
		}
	}


	//-----------------------------------------------[컨슈머 수정 관련]-------------------------------------------------------------
	function updateConsumerEvent(){
		addCss("consumer");
		drawUpdateConsumerTable();
		$(".token-td").off("click");
		var trArr = $(".data-table > tr")
		for(let i=2; i < trArr.length; i++){
			trArr[i].onclick=function(){
				drawUpdateConsumerTable($(this));
			}
			trArr[i].onmouseover=function(){
				$(this).css("cursor","pointer");
			}
		}
		consumerCancleButton.off("click");
		consumerCancleButton.on("click", () => {
			cancleConsumerAlarm(cancleConsumerUpdate);
		});
		consumerSearchButton.off("click");
		consumerSearchButton.on("click", () => {
			cancleConsumerAlarm(cancleConsumerUpdate);
		})
		
		consumerSearchInput.off('keydown');
		consumerSearchInput.on('keydown',(e) =>{
			if(e.key==='Enter')cancleConsumerAlarm(cancleConsumerUpdate);
		});
		consumerSaveButton.off("click");
		consumerSaveButton.on("click", () => {
			updateConsumer();
		})	
	}


	//수정 버튼 클릭 시 저장 버튼 이벤트
	function updateConsumer() {
	 	var tokenArr=[];
		var trArr=$(".data-table > tr")
		var currentToken;
		
		for(let ii=2; ii<trArr.length; ii++){
			if(trArr.eq(ii).children().first().text()===$(".apitoken-value").text()){
				 currentToken=trArr.eq(ii).children().first().next().children();
			}
		}
		
		var cnt =0;		
		currentToken.eq(0).is(":checked") === $("input[name='token-company']").is(":checked")? null : cnt++;
		currentToken.eq(1).is(":checked") === $("input[name='token-manager']").is(":checked")? null : cnt++;
		currentToken.eq(2).is(":checked") === $("input[name='token-phone']").is(":checked")? null : cnt++;
		currentToken.eq(3).is(":checked") === $("input[name='token-email']").is(":checked")? null : cnt++;
		
		if(cnt>0){
			var company=$("input[name='token-company']").is(":checked")?$("input[name='company']").val():'';
			var manager=$("input[name='token-manager']").is(":checked")?$("input[name='manager']").val():'';
			var phone=$("input[name='token-phone']").is(":checked")?$("input[name='phone']").val():'';
			var email=$("input[name='token-email']").is(":checked")?$("input[name='email']").val():'';
			tokenArr.push({
					  apiToken:$(".apitoken-value").text(),
			          company:company,
					  manager:manager,
					  phone:phone,
					  email:email})
		}
		
		if(cnt===0){
			tokenArr.push({apiToken:$(".apitoken-value").text()});
		} 
		
		var brokerInfo="/api/brokerInfo/{apiToken}"
		var nodeInfo="/api/nodeInfo/{apiToken}"
		var uuid="/api/uuid"
		var acl=[];
		$("input[name='brokerInfo']")
						.is(":checked")
						?acl.push({apiid:brokerInfo,acl:"A"})
						:acl.push({apiid:brokerInfo,acl:"D"});
		
		$("input[name='nodeInfo']")
						.is(":checked")
						?acl.push({apiid:nodeInfo,acl:"A"})
						:acl.push({apiid:nodeInfo,acl:"D"});
		$("input[name='uuid']")
						.is(":checked")
						?acl.push({apiid:uuid,acl:"A"})
						:acl.push({apiid:uuid,acl:"D"});
		
		var expiredt=$("input[name='expiredt']").val()
		
		if($("input[name='expiredt']").val().length===16){
			expiredt+=":00";
		}

		var updateData;
			updateData=
				new TscApiClientVO(
									tokenArr,
									$("input[name='company']").val(),
									$("input[name='manager']").val(),
									$("input[name='email']").val(),
									$("input[name='phone']").val(),
									expiredt,
									null,$("input[name='enroller']").val(),
									$("input[name='ipaddr']").val(),
									$("select[name='clientType']").val(),
									$("input[name='brokerId']").val(),
									$("input[name='brokerPwd']").val(),
									$("select[name='state']").val(),
									$("select[name='useyn']").val(),
									acl);
		
		var jsonData = JSON.stringify(updateData);
		jQuery.ajaxSettings.traditional = true;
		if(nullChecker($(".apitoken-value").text()))return alert("수정할 내용을 선택해주세요")
		if (confirm("컨슈머 정보를 수정 하시겠습니까?")) {
			$.ajax({
				url:"/updateConsumer.do",
				async:false,
				type: "get",
				dataType: "json",
				data:{
					jsonData:jsonData,
				},
				success:function(result){
					if(result==0){
						alert("수정 사항이 없습니다.");	
						consumerOnOff();
						return 
					}
					alert("컨슈머 정보 "+result+"건 수정되었습니다.");
					consumerOnOff();
				}, error: function(error) {
				console.log(error)
				}
			
			})
		}
	}

	function TscApiClientVO(apitoken,company,manager,email,phone,expiredt
							,eventdt,enroller,ipaddr,clientType,brokerId
							,brokerPwd,state,useyn,acl){
		this.apitoken = apitoken;
		this.company = company;
		this.manager = manager;
		this.phone = phone;
		this.email = email;
		this.expiredt = expiredt;
		this.eventdt = eventdt;
		this.enroller = enroller;
		this.ipaddr = ipaddr;
		this.clientType = clientType;
		this.brokerId = brokerId;
		this.brokerPwd = brokerPwd;
		this.state = state;
		this.useyn = useyn;
		this.acl = acl;
	}
	
	//수정 테이블
	function drawUpdateConsumerTable(data) {
		var table = $(".consumer-box2 > div > table:nth-child(1)");
		table.removeClass("consumer-info");
		table.addClass("update-table");
		$(".config-table").css("display","block");
		$(".api-acl-table").css("display","block");
		$(".config-table").css("width","280px");
		$(".update-table").css("width","835px");
		table.empty();
		$(".api-acl-table").empty();
		$(".config-table").empty();
		var str='';
		str+='<tr>'
          +'<th colspan="4" style="color: #7b7c7d; background: rgb(52 55 58);height: 50px;">Consumer 정보 수정</th>'
        +'</tr>'
        +'<tr>'
          +'<td style="background: #22252b; color: rgb(123 124 125); font-weight: bold;">분류</td>'
          +'<td style="background: #22252b; color: rgb(123 124 125); font-weight: bold;">내용</td>'
          +'<td style="background: #22252b; color: rgb(123 124 125); font-weight: bold;">분류</td>'
          +'<td style="background: #22252b; color: rgb(123 124 125); font-weight: bold;">내용</td>'
        +'</tr>'
        +'<tr>'
          +'<td>업체명</td>'
          +'<td><input type="text" name="company" value="" disabled></td>'
          +'<td>Broker ID</td>'
          +'<td><input type="text" name="brokerId" value="" disabled></td>'
        +'</tr>'
        +'<tr>'
          +'<td>담당자</td>'
          +'<td><input type="text" name="manager" value="" disabled></td>'
            +'<td>Broker Password</td>'
            +'<td><input type="text" name="brokerPwd" value="" disabled></td>'
        +'</tr>'
        +'<tr>'
            +'<td>연락처</td>'
            +'<td><input type="text" name="phone" value="" disabled></td>'
            +'<td>IP 주소</td>'
            +'<td><input type="text" name="ipaddr" value="" disabled></td>'
          +'</tr>'
          +'<tr>'
            +'<td>등록자</td>'
            +'<td><input type="text" name="enroller" value="" disabled></td>'
            +'<td>Client 유형</td>'
            +'<td><select name="clientType"disabled></select></td>'
         +'</tr>'
         +'<tr>'
         	+' <td>E-mail</td>'
          	+'<td><input type="text" name="email" value="" disabled></td>'
          	+'<td>API 사용 만료일</td>'
          	+'<td><input type="datetime-local" name="expiredt" value="" disabled></td>'
		 +'</tr>'
		+'<tr>'
			+'<td>사용 여부</td>'
      		+'<td><select name="useyn" disabled></select></td>'
          	+'<td>Client 상태</td>'
          	+'<td><select name="state" disabled></select></td>'
		'</tr>';
		var tbody=$("<tbody>").html(str);
			table.append(tbody);
		var config='<tr>'
						+'<th colspan="2" style="color: #7b7c7d; background: rgb(52 55 58); width:732px; height: 50px;">'
								+'API TOKEN 설정</th>'
						+'</tr>'
						+'<tr>'
							+'<td style="background: #22252b; color: rgb(123 124 125);height:30.5px; font-weight: bold;">'
							+	'분류'
							+'</td>'
							+'<td style="background: #22252b; color: rgb(123 124 125); height:30.5px; font-weight: bold;">Off/On'
							+'</td>'
					+'</tr>'
					+'<tr style="height: 48.5px;">'
						+'<td>Company</td>'
						+'<td><label class="switch">'
							+'<input type="checkbox" name="token-company" value="C" disabled>' 
									+'<span class="slider round"></span>'
							+'</label></td>'
						+'</tr>'
						+'<tr style="height: 48.5px;">'
							+'<td>Manager</td>'
							+'<td>'
								+'<label class="switch">' 
									+'<input type="checkbox" name="token-manager" value="M" disabled>' 
									+'<span class="slider round"></span>'
								+'</label>'
							+'</td>'
						+'</tr>'
						+'<tr style="height: 48.5px;">'
							+'<td>Phone</td>'
							+'<td>'
								+'<label class="switch">' 
									+'<input type="checkbox" name="token-phone" value="P" disabled>' 
									+'<span class="slider round"></span>'
								+'</label>'
							+'</td>'
						+'</tr>'
						+'<tr style="height: 48.5px;">'
							+'<td>E-mail</td>'
							+'<td>'
								+'<label class="switch">'
									+'<input type="checkbox" name="token-email" value="E" disabled>' 
									+'<span class="slider round"></span>'
								+'</label>'
							+'</td>'
						+'</tr>'
			$(".config-table").append($("<tbody>").html(config));
			let aclTbody=$("<tbody>")
				aclTbody.html('<tr>'
					 		 +'<th colspan="3" style="color: #7b7c7d; background: rgb(52 55 58); width: 680px; height: 50px;">'
					 		 +'API Token ACL 설정</th>'
					 		 +'</tr>'
							 +'<tr>'
							 +'<td style="background: #22252b; color: rgb(123 124 125); width:100px">분류</td>'
							 +'<td style="background: #22252b; color: rgb(123 124 125);" colspan="2">내용</td>'
							 +'</tr>'
							 +'<tr>'
							 +'<td style="height:47px;">API TOKEN</td>'
							 +'<td style="height:47px;" colspan="2" class="apitoken-value"></td>'
							 +'</tr>'
							 +'<tr>'
							 +'<td rowspan="3">API ID</td>'
							 +'<td style="height:47px;">/api/brokerInfo/{apiToken}</td>'
							 +'<td style="height:47px;">'
							 +'<label class="switch">' 
									+'<input type="checkbox" name="brokerInfo" value="A" disabled>' 
									+'<span class="slider round"></span>'
							 +'</label>'
							 +'</td>'
							 +'</tr>'
							 +'<tr>'
							 +'<td style="height:47px">'
							 +'/api/nodeInfo/{apiToken}'
							 +'</td>'
							 +'<td style="height:47px;">'
						     	+'<label class="switch">' 
									+'<input type="checkbox" name="nodeInfo" value="A" disabled>' 
									+'<span class="slider round"></span>'
							 	+'</label>'
	                         +'</td>'
							 +'</tr>'
							 +'<tr>'
							 +'<td style="height:47px;">'
							 +'/api/uuid'
							 +'</td>'
							 +'<td style="height:47px;">'
							 +'<label class="switch">' 
									+'<input type="checkbox" name="uuid" value="A" disabled>' 
									+'<span class="slider round"></span>'
							 +'</label>'
						     +'</td>'
							 +'</tr>'
							
							 +'</tr>');
					
			$(".api-acl-table").append(aclTbody);
		if(data !== undefined){
				dataArr=[];
				for(let i =0; i<data.children().length;i++){
					dataArr.push(data.children().eq(i).text());
				}
				$.ajax({
					url:"/getApiAcl.do",
					async:false,
					type: "get",
					dataType: "json",
					data:{
						apiToken:dataArr[0]
					},
					success:function(result){
						let aclArr=result.map((item)=>{
							return item.acl
						})
						aclArr[0]==="A"?$("input[name='brokerInfo']").prop("checked",true):null
						aclArr[1]==="A"?$("input[name='nodeInfo']").prop("checked",true):null
						aclArr[2]==="A"?$("input[name='uuid']").prop("checked",true):null
					}, 
					error: function(error) {
							console.log(error)
					}
			
				})
				var tokenCheckArr=data.children().first().next().children();
				$("input, select, checkbox").removeAttr("disabled");
				$("input[name='company']").prop('value',dataArr[2]);				
				$("input[name='manager']").prop('value',dataArr[3]);
				$("input[name='email']").prop('value',dataArr[4]);
				$("input[name='phone']").prop('value',dataArr[5]);
				var expiredt=dataArr[6].split(" ");
				$("input[name='expiredt']").prop('value',expiredt[0]+"T"+expiredt[1]);
				$("input[name='enroller']").prop('value',dataArr[8]);
				$("input[name='ipaddr']").prop('value',dataArr[9]);
				$("input[name='clientType']").prop('value',dataArr[10]);
				$("input[name='brokerId']").prop('value',dataArr[11]);
				$("input[name='brokerPwd']").prop('value',dataArr[12]);
				
				$("select[name='useyn'], select[name='state'], select[name='clientType']").empty();
				$(".apitoken-value").text(dataArr[0]);
				
				var uyOption="<option value='Y'>사용</option>"
				 +"<option value='N' selected>미사용</option>"
				if(dataArr[14]=='사용')uyOption="<option value='Y' selected>사용</option><option value='N'>미사용</option>"
				
				var statOption="<option value='C'>등록완료</option>"
				 +"<option value='R' selected>등록요청</option>"
				if(dataArr[13]=='등록완료')statOption="<option value='C' selected>등록완료</option><option value='R'>등록요청</option>"	
				
				var ctOption="";
				dataArr[10]=='SYS'?
					ctOption="<option value='SYS' selected>SYS</option><option value='DEV'>DEV</option><option value='APP'>APP</option>":ctOption				
				dataArr[10]=='DEV'?
					ctOption="<option value='SYS'>SYS</option><option value='DEV' selected>DEV</option><option value='APP'>APP</option>":ctOption				
				if(dataArr[10]=='APP'){
					ctOption="<option value='SYS'>SYS</option>"
							+"<option value='DEV'>DEV</option>"
							+"<option value='APP' selected>APP</option>"				
					$("input[name='token-company'], input[name='token-phone'],"
					+" input[name='token-manager'],input[name='token-email'],"
					+"select[name='clientType']").attr("disabled",true);
				}
				$("select[name='clientType']").append(ctOption);
				$("select[name='state']").append(statOption)
				$("select[name='useyn']").append(uyOption);
				tokenCheckArr[0].checked === true?$("input[name='token-company']").prop("checked",true):null;
				tokenCheckArr[1].checked === true?$("input[name='token-manager']").prop("checked",true):null;
				tokenCheckArr[2].checked === true?$("input[name='token-phone']").prop("checked",true):null;
				tokenCheckArr[3].checked === true?$("input[name='token-email']").prop("checked",true):null;
		}
	}
		
	//-----------------------------------------------[컨슈머 삭제 관련]-------------------------------------------------------------
	//consumer 삭제 기능
	function deleteConsumer() {
		var inputArr = $('input[type="checkbox"]');
		var str = ""
		for (let i = 0; i < inputArr.length; i++) {
			if (inputArr[i].checked) str += $("#check" + i).parent().next().text() + ",";
		}
	if (str !== "") {
			if (confirm("선택하신 Consumer 정보를 삭제하시겠습니까?")) {
				$.ajax({
					url:"/deleteConsumer.do",
					async:false,
					type: "get",
					dataType: "json",
					data:{
						apitoken:str
					},
					success:function(result){
						if(result==0){
							alert("Consumer 삭제가 정상적으로 처리되지 않았습니다.");	
							consumerOnOff();
							return 
						}
						alert("Consumer 정보 "+result+"건이 삭제 되었습니다.");
						consumerOnOff();
					}, error: function(error) {
						console.log(error)
					}
				})
			}
		}
		if (str == "") alert("선택된 노드 정보가 없습니다.")
	}
		
		

	//consumer 삭제 이벤트 
	function deleteConsumerEvent() {
		clickCss("consumer");
		searchConsumer(enroller.val(),true);
		var inp = $('input[type="checkbox"]');
		$(".delete-all").on("click", () => {

			for (let i = 0; i < inp.length; i++) {
				inp[i].checked = true;
			}
		})
		$(".delete-cancle").on("click", () => {
			for (let i = 0; i < inp.length; i++) {
				inp[i].checked = false;
			}
		})
		consumerSearchButton.off("click");
		consumerSearchButton.on("click", () => {
			cancleConsumerAlarm(cancleConsumerDelete);
		})
		consumerCancleButton.off("click");
		consumerCancleButton.on("click", () => {
			cancleConsumerAlarm(cancleConsumerDelete);
		})
		consumerSearchInput.off('keydown');
		consumerSearchInput.on('keydown',(e) =>{
			if(e.key==='Enter')cancleConsumerAlarm(cancleConsumerDelete);
		});
		consumerSaveButton.off("click");
		consumerSaveButton.on("click", () => {
			deleteConsumer();
		})	

	}

	//삭제 테이블 그리기
	function drawDeletConsumerTable(data) {
		var table = $(".data-table");
			table.empty();
		var trArr=[];
		var cnt=0;
			table.append($("<tr>"
				+ "<th colspan='16' class='table-title'><span style='position:relative;left:115px'>Consumer 정보</span>"
				+ " <input type='button' class='delete-all' value='전체 선택'>"
				+ "<input class='delete-cancle' type='button' value='선택 해제'>"
				+ "</th>"
				+ "</tr>"));
			table.append($("<tr class='table-column'>"
				+ "<th>선택</th>"
				+ "<th>API<br>TOKEN</th>"
				+ "<th>API<br>사용 업체</th>"
				+ "<th>담당자</th>"
				+ "<th>E-mail</th>"
				+ "<th>연락처</th>"
				+ "<th>API<br>사용 만료일</th>"
				+ "<th>등록 요청일</th>"
				+ "<th>등록자</th>"
				+ "<th>IP주소</th>"
				+ "<th>Client<br>유형</th>"
				+ "<th>Broker<br> ID</th>"
				+ "<th>Broker<br>Password</th>"
				+ "<th>Client<br>상태</th>"
				+ "<th>사용 여부</th>"
				+ "</tr>"))
		data.forEach((d) => {
			var tr = $("<tr>");
			tr.html(
				"<td><input type='checkbox' id='check" + cnt + "'></td>" 
				+ "<td class='token-td'>" + d.apitoken + "</td>"
				+ '<td style="max-width:150px;word-break:break-all;">' + d.company + '</td>'
				+ '<td style="max-width:150px;word-break:break-all;">' + d.manager + '</td>'
				+ '<td style="max-width:150px;word-break:break-all;">' + d.email + '</td>'
				+ '<td style="max-width:150px;word-break:break-all;">' + d.phone + '</td>'
				+ '<td style="max-width:150px;word-break:break-all;">' + d.expiredt + '</td>'
				+ '<td style="max-width:150px;word-break:break-all;">' + d.eventdt + '</td>'
				+ '<td style="max-width:150px;word-break:break-all;">' + d.enroller + '</td>'
				+ '<td style="max-width:200px;word-break:break-all;">' + d.ipaddr + '</td>'
				+ '<td style="max-width:150px;word-break:break-all;">' + d.clientType + '</td>'
				+ '<td style="max-width:150px;word-break:break-all;">' + d.brokerId + '</td>'
				+ '<td style="max-width:150px;word-break:break-all;">' + d.brokerPwd + '</td>'
				+ '<td style="max-width:150px;word-break:break-all;">' + d.state + '</td>'
				+ '<td style="max-width:150px;word-break:break-all;">' + d.useyn + '</td>'
			)
			trArr.push(tr);
			cnt++;
		})
		table.append(trArr);
	}
		
		
		
	//-----------------------------------------------[컨슈머 테이블 관련]-------------------------------------------------------------
	function drawConsumerTable(data){
		consumerTitile()
		var table = $(".data-table");
		var trArr = [];
		var cnt =0;
		data.forEach((d) => {
			var str=""
			str ="<input id='company"+cnt+"' type='checkbox' value='company'>"
					+ "<input id='manager"+cnt+"' type='checkbox' value='manager'>"
					+ "<input id='phone"+cnt+"' type='checkbox' value='phone'>"
					+ "<input id='email"+cnt+"' type='checkbox' value='email'>";
			if(!(d.tokenCrtTp == null || d.tokenCrtTp == "")){
				str="";
				var tokenCrtTpArr=d.tokenCrtTp.split(",");
				str+="<input id='company"+cnt+"' type='checkbox' value='company'";
				tokenCrtTpArr.includes("C")?str+= " checked>":str+=">";
				str+="<input id='manager"+cnt+"' type='checkbox' value='manager'";
				tokenCrtTpArr.includes("M")?str+=" checked>":str+=">";
				str+="<input id='phone"+cnt+"' type='checkbox' value='phone'";
				tokenCrtTpArr.includes("P")?str+=" checked>":str+=">";
				str+="<input id='email"+cnt+"' type='checkbox' value='email'";
				tokenCrtTpArr.includes("E")?str+=" checked>":str+=">";
			}
			var tr = $("<tr>");
			tr.html(
				 '<td class="token-td">' + d.apitoken + '</td>'
				+ "<td style='display:none;'>"
				+ str	
				+ "</td>"
				+ '<td style="max-width:150px;word-break:break-all;">' + d.company + '</td>'
				+ '<td style="max-width:150px;word-break:break-all;">' + d.manager + '</td>'
				+ '<td style="max-width:150px;word-break:break-all;">' + d.email + '</td>'
				+ '<td style="max-width:150px;word-break:break-all;">' + d.phone + '</td>'
				+ '<td style="max-width:150px;word-break:break-all;">' + d.expiredt + '</td>'
				+ '<td style="max-width:150px;word-break:break-all;">' + d.eventdt + '</td>'
				+ '<td style="max-width:150px;word-break:break-all;">' + d.enroller + '</td>'
				+ '<td style="max-width:200px;word-break:break-all;">' + d.ipaddr + '</td>'
				+ '<td style="max-width:150px;word-break:break-all;">' + d.clientType + '</td>'
				+ '<td style="max-width:150px;word-break:break-all;">' + d.brokerId + '</td>'
				+ '<td style="max-width:150px;word-break:break-all;">' + d.brokerPwd + '</td>'
				+ '<td style="max-width:150px;word-break:break-all;">' + d.state + '</td>'
				+ '<td style="max-width:150px;word-break:break-all;">' + d.useyn + '</td>'
			)
			trArr.push(tr);
			cnt++;
		})
		table.append(trArr);
	}
	function consumerTitile(){
		var table = $(".data-table");
			table.empty();
			table.append($("<tr>"
				+ "<th colspan='14' class='table-title'>Consumer 정보"+ "</th>"
				+ "</tr>"));
			table.append($("<tr class='table-column'>"
				+ "<th>API Token</th>"
				+ "<th>업체명</th>"
				+ "<th>담당자</th>"
				+ "<th>E-mail</th>"
				+ "<th>연락처</th>"
				+ "<th>API<br>사용 만료일</th>"
				+ "<th>등록 요청일</th>"
				+ "<th>등록자</th>"
				+ "<th>IP주소</th>"
				+ "<th>Client<br>유형</th>"
				+ "<th>Broker<br>ID</th>"
				+ "<th>Broker<br>Password</th>"
				+ "<th>Client<br>상태</th>"
				+ "<th>사용 여부</th>"
				+ "</tr>"))
	}
	//-----------------------------------------------[컨슈머 데이터 관련]-------------------------------------------------------------
		//검색한 데이터 가져오기
	function searchConsumer(company,deleteVal) {
		if (nullChecker(company)) url = consumerAllDataUri;
		if (!nullChecker(company)) url = consumerDataUri;
		$.ajax({
			url: url,
			async: false,
			cache: false,
			type: "get",
			dataType: "json",
			data: {
				company: company
			},
			success: function(result) {
				if(deleteVal)return drawDeletConsumerTable(result);
				if(!nullChecker(result))return drawConsumerTable(result);
				if(nullChecker(result))return alert("검색 결과가 없습니다.");
			}, error: function(error) {
				console.log(error)
			}

		})
	}

	//------------------------------------------------[컨슈머 관리]-----------------------------------------------------------------	
	//-----------------------------------------------[알람 정책 관리]----------------------------------------------------------------
	
	//알람 정책 초기화
	function alarmOnOff(){
		$(".data-table").empty();
		searchAlarm();
		noneClickCss("alarm");
		nomalCss();
		alarmSaveBtn.off("click");
		alarmCancelBtn.off("click");
		alarmUpdateBtn.off("click");
		alarmUpdateBtn.on("click",()=>{
			updateAlarmEvent();
		})
	}
	//취소시 발생이벤트
	function cancleAlarmConfirm(){
		if(confirm("알람 정책 수정을 취소하시겠습니까? 작성하신 내용은 모두 지워집니다."))alarmOnOff();
	}
	
	//css
	function none(item){
		item.css("display","none");
	}
	//css
	function block(item){
		item.css("display","block");
	}
	
	//알람 정책 수정 이벤트
	function updateAlarmEvent(){
		searchAlarm(true);
		clickCss("alarm");
		alarmSaveBtn.on("click",()=>{
			alarmUpdate();
		})
		alarmCancelBtn.on("click",()=>{
			cancleAlarmConfirm()
		})
	}
	
	function alarmUpdate(){
		var trArr=$(".data-table > tr");
		var updateArr=[];
		for(let i =2; i<trArr.length; i++){
			var alarmCode=trArr.eq(i).children().eq(0).text()
			var value=trArr.eq(i).children().eq(3).children().val();
			if(value === null || value === ""){
				alert("입력된 값이 없습니다. 값을 입력해주세요");
				trArr.eq(i).children().eq(3).children().focus();
				return
			}
			
			var useyn=trArr.eq(i).children().eq(4).children().children().first().is(":checked");
			useyn=useyn?'Y':'N';
			updateArr.push({
				alarmCode:alarmCode,
				value:value,
				useyn:useyn
			})
		}
		var jsonData = JSON.stringify(updateArr);
		jQuery.ajaxSettings.traditional = true;
		$.ajax({
			url: "/updateAlarm.do",
			async: false,
			cache: false,
			type: "get",
			dataType: "json",
			data:{
				jsonData: jsonData	
			},
			success: function(result) {
				if(result<=0){
					alert("변경 사항이 없습니다.");
					alarmOnOff();
					return 
				}
				alert("알람 정책 설정이 변경 되었습니다.");
				alarmOnOff();
			}, error: function(error) {
				console.log(error)
			}

		})
	}
	//알람 정책 데이터 가져오기
	function searchAlarm(update){
		$.ajax({
			url: "/getSearchAlarm.do",
			async: false,
			cache: false,
			type: "get",
			dataType: "json",
			success: function(result) {
				if(update)return drawUpdateAlarm(result);
				drawAlarmTable(result);
				
			}, error: function(error) {
				console.log(error)
			}

		})
	}
	
	//수정 테이블
	function drawUpdateAlarm(data){
		var table=$(".data-table")
		alarmTitle();
		data.forEach((d)=>{
			var tr=$("<tr>");
			
			for(key in d){
				if(key=='value')tr.append($("<td>").append($("<input class='alarm-size' name='value' value='"+d[key]+"'>")))
				if(key=='useyn'){
					var label = $("<label>");
					var input = $("<input>");
					var span = $("<span>");
					label.addClass("switch");
					span.addClass("slider");
					span.addClass("round");
					input.prop({"type":"checkbox","name":key,"value":key,"disabled":false})
					label.append(input,span);
					d[key]=="Y"?input.prop("checked",true):input.prop("checked",false);
					tr.append($("<td>").append(label));
				}
				if(!(key=='value' || key=='useyn' || key == 'edityn'))	tr.append($("<td>").text(d[key]))
				if(key == 'edityn') tr.append($("<td class='edityn' style='display:none'>"+d[key]+"<td>"));
			}
				table.append(tr);
		})
			for(let ii = 0; ii<$(".edityn").length; ii++){
				let edityn=$(".edityn").eq(ii);
				if(edityn.text()=='N'){
					edityn.prev().prev().children().prop("disabled",true);
				}
				
			}
			$(".alarm-size").css({'height':'29px','width':'95%'})	
	}
	
	//기본 테이블
	function drawAlarmTable(data){
		var table=$(".data-table")
		alarmTitle();
		
		data.forEach((d)=>{
			var tr=$("<tr>");
			for(key in d){
				if(key !=='useyn' && key !== 'edityn')tr.append($("<td>").text(d[key]))
				if(key==='useyn'){
					var label = $("<label>");
					var input = $("<input>");
					var span = $("<span>");
					label.addClass("switch");
					span.addClass("slider");
					span.addClass("round");
					input.prop({"type":"checkbox","name":key,"value":key,"disabled":true})
					label.append(input,span);
					d[key]=="Y"?input.prop("checked",true):input.prop("checked",false);
					tr.append($("<td>").append(label));
				}
				if(key == 'edityn')tr.append($("<td class='edityn' style='display:none'>"+d[key]+"</td>"))
			}
				table.append(tr)
		})
			
	}
	
	//테이블 타이틀
	function alarmTitle(){
		var table=$(".data-table")
			table.empty();
		var tableName=['알람 코드','알람 명칭','알람 설명','기준 값','사용 여부'];
		var tr = $("<tr>")
			table.append($("<tr>"
				+ "<th colspan='"+tableName.length+"' class='table-title'>알람 정책 관리"+ "</th>"
				+ "</tr>"));
			tableName.forEach((name)=>{
				var th=$("<th>");
				th.text(name);
				if(name==tableName[0])th.css('width','250px')
				if(name==tableName[1])th.css('width','520px')
				if(name==tableName[2])th.css('width','600px')
				if(name==tableName[3])th.css('width','220px')
				if(name==tableName[4])th.css('width','220px')
				tr.append(th);
				tr.addClass("table-column");
			})
			table.append(tr);
	}
	//-----------------------------------------------[알람 정책 관리]----------------------------------------------------------------
	//-------------------------------------------------[기타 함수]-------------------------------------------------------------------	

	//널체크 함수
	function nullChecker(item) {
		var result = (item == null || item == "" || item == undefined) ? true : false;
		return result;
	}
	//------------------------------------------[엑셀 다운로드]------------------------------------------------------------------
	function fnExcelReport(id, title) {
		var tab_text = '<html xmlns:x="urn:schemas-microsoft-com:office:excel">';
			tab_text += '<head><meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8">';
			tab_text += '<xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>'
			tab_text += '<x:Name>Test Sheet</x:Name>';
			tab_text += '<x:WorksheetOptions><x:Panes></x:Panes></x:WorksheetOptions></x:ExcelWorksheet>';
			tab_text += '</x:ExcelWorksheets></x:ExcelWorkbook></xml></head><body>';
			tab_text += "<table border='1px'>";
		var exportTable = $('.' + id).clone();
			if(title=='consumer-table'){
				for(let i =2; i<exportTable.children().length; i++){
					exportTable.children().eq(i).children().eq(1).remove();
				}
			}
			exportTable.find('input').each(function (index, elem) { $(elem).remove(); });
			tab_text += exportTable.html();
			tab_text += '</table></body></html>';
		var data_type = 'data:application/vnd.ms-excel';
		var ua = window.navigator.userAgent;
		var msie = ua.indexOf("MSIE ");
		var fileName = title + '.xls';
		//Explorer 환경에서 다운로드
		if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) {
			if (window.navigator.msSaveBlob) {
				var blob = new Blob([tab_text], {
					type: "application/csv;charset=utf-8;"
				});
				navigator.msSaveBlob(blob, fileName);
			}
		}else {
			var blob2 = new Blob([tab_text], {
				type: "application/csv;charset=utf-8;"
			});
			var filename = fileName;
			var elem = window.document.createElement('a');
				elem.href = window.URL.createObjectURL(blob2);
				elem.download = filename;
				document.body.appendChild(elem);
				elem.click();
				document.body.removeChild(elem);
			}
		}

})