$(function() {
	var cpuUseArr = [];
	var kafkaArr = [];
	var commArr = [];
	var alarmArr = [];
	var serverStatArr = [];
	var alarmWN=[];
	var cpuUrl = "/getUseCpuVo.do"
	var cpuUseWN;
	var memUseWN;
	var diskUseWN;
	var kafkaWN;
	getData("/getUseCpuVo.do", cpuUseArr);
	getData("/getKafkaStatus.do", kafkaArr);
	getData("/getCommuticationVO.do", commArr);
	getData("/getAlarmVO.do", alarmArr);
	getData("/getServerStat.do", serverStatArr);
	getData("/getAlarmWarning.do",alarmWN);
	
	alarmWN.map((item)=>{
		if(item.alarmCode=='SYS_01')cpuUseWN=item.value;
		if(item.alarmCode=='SYS_02')memUseWN=item.value;
		if(item.alarmCode=='SYS_03')diskUseWN=item.value;
		if(item.alarmCode=='KAFKA_02')kafkaWN=item.value;
		 
	})
	
	function getData(url, arr) {
		$.ajax({
			url: url,
			async: false,
			cache: false,
			type: "get",
			dataType: "json",
			success: function(result) {
				result.forEach((el) => {
					arr.push(el);
				});

			}, error: function(error) {
				console.log(error)
			}

		})
	}

	var gaugeOptions = {
		chart: {
			type: 'solidgauge',
			marginTop: -200,
			marginLeft: -5,
			width:200,
			height:170,
			backgroundColor: 'rgb(24 26 27 / 75%)'
		},
		title: null,
		pane: {
			center: ['50%', '85%'],
			size: '90%',
			innerSize: '10%',
			startAngle: -110,
			endAngle: 110,
			background: {
				backgroundColor: '#22252b',
				innerRadius: '60%',
				outerRadius: '100%',
				shape: 'arc',
				borderColor: '#22252b',
				borderWidth: 1
			}
		},

		exporting: {
			enabled: false
		},

		tooltip: {
			enabled: false
		},

		// the value axis
		yAxis: {
			stops: [//백분율로 색상 분류
				[0.8, 'rgb(115, 191, 105)'], // green
				[1, 'red'], // red,
			],
			plotBands: [{//해당 값까지 바깥쪽 선 그리기
				from: 0,
				to: cpuUseWN,
				color: 'rgb(115, 191, 105)', // red
				thickness: '-5%',
				borderColor:'#22252b',
				borderWidth: 1
			}, {
				from: 80,
				to: 100,
				color: 'red', // red
				thickness: '-5%',
				borderColor:'#22252b',
				borderWidth: 1
			}]
			,
			lineWidth: 0,
			tickWidth: 0,
			minorTickInterval: null,
			tickAmount: 0,
			title: '',
			labels: {
				enabled: false
			}
		},
		plotOptions: {
			solidgauge: {
				dataLabels: {
					y: 1,
					borderWidth: 0,
					useHTML: true,
				}
			}
		}
	};

	// The speed gauge
	var chartSpeed = Highcharts.chart('container-speed', Highcharts.merge(gaugeOptions, {
		yAxis: {
			min: 0,
			max: 100,
			title: {
				text: ''
			}
		},

		credits: {
			enabled: false
		},

		series: [{
			name: cpuUseArr[0].hostName,
			data: [cpuUseArr[0].useCpuRate],
			dataLabels: {
				format:
					'<div style="text-align:center">' +
					'<span class="overPoint1" style="font-size:28px;color:rgb(115, 191, 105);">{y}</span><br><br>'
					+ '<span style="font-size:14px;color:rgb(204, 204, 220);">' + cpuUseArr[0].hostName + '</span></div>'
			},
			tooltip: {

			}
		}]

	}));
	var chartSpeed2 = Highcharts.chart('container-speed2', Highcharts.merge(gaugeOptions, {
		yAxis: {
			min: 0,
			max: 100,
			title: {
				text: ''
			}
		},

		credits: {
			enabled: false
		},

		series: [{
			name: cpuUseArr[1].hostName,
			data: [cpuUseArr[1].useCpuRate],
			dataLabels: {
				format:
					'<div style="text-align:center">' +
					'<span class="overPoint2" style="font-size:28px;color:rgb(115, 191, 105);">{y}</span><br><br>'
					+ '<span style="font-size:14px;color:rgb(204, 204, 220);">' + cpuUseArr[1].hostName + '</span></div>'
			},
			tooltip: {

			}
		}]

	}));
	var chartSpeed3 = Highcharts.chart('container-speed3', Highcharts.merge(gaugeOptions, {
		yAxis: {
			min: 0,
			max: 100,
			title: {
				text: ''
			}
		},

		credits: {
			enabled: false
		},

		series: [{
			name: cpuUseArr[2].hostName,
			data: [cpuUseArr[2].useCpuRate],
			dataLabels: {
				format:
					'<div style="text-align:center">' +
					'<span class="overPoint3" style="font-size:28px;color:rgb(115, 191, 105);">{y}</span><br><br>'
					+ '<span style="font-size:14px;color:rgb(204, 204, 220);">' + cpuUseArr[2].hostName + '</span></div>'
			},
			tooltip: {

			}
		}]

	}));
	var chartSpeed4 = Highcharts.chart('container-speed4', Highcharts.merge(gaugeOptions, {
		yAxis: {
			min: 0,
			max: 100,
			title: {
				text: ''
			}
		},

		credits: {
			enabled: false
		},

		series: [{
			name: cpuUseArr[3].hostName,
			data: [cpuUseArr[3].useCpuRate],
			dataLabels: {
				format:
					'<div style="text-align:center">' +
					'<span class="overPoint3" style="font-size:28px;color:rgb(115, 191, 105);">{y}</span><br><br>'
					+ '<span style="font-size:14px;color:rgb(204, 204, 220);">' + cpuUseArr[3].hostName + '</span></div>'
			},
			tooltip: {

			}
		}]

	}));
	cnt = 0;


	if (chartSpeed.series[0].yData > 80) $(".overPoint1").css("color", 'red')
	if (chartSpeed.series[0].yData <= 80) $(".overPoint1").css("color", 'rgb(115, 191, 105)')
	if (chartSpeed2.series[0].yData > 80) $(".overPoint2").css("color", 'red')
	if (chartSpeed2.series[0].yData <= 80) $(".overPoint2").css("color", 'rgb(115, 191, 105)')
	if (chartSpeed3.series[0].yData > 80) $(".overPoint3").css("color", 'red')
	if (chartSpeed4.series[0].yData > 80) $(".overPoint3").css("color", 'red')
	if (chartSpeed3.series[0].yData <= 80) $(".overPoint3").css("color", 'rgb(115, 191, 105)')
	if (chartSpeed4.series[0].yData <= 80) $(".overPoint3").css("color", 'rgb(115, 191, 105)')

	
	setInterval(function() {
		var cpuUseArr=[]
		getData(cpuUrl, cpuUseArr);
			if (chartSpeed) { chartSpeed.series[0].points[0].update(cpuUseArr[0].useCpuRate); }
			if (chartSpeed2) { chartSpeed2.series[0].points[0].update(cpuUseArr[1].useCpuRate); }
			if (chartSpeed3) { chartSpeed3.series[0].points[0].update(cpuUseArr[2].useCpuRate); }
			if (chartSpeed4) { chartSpeed4.series[0].points[0].update(cpuUseArr[3].useCpuRate); }
	}, 10000)

	//---------------------------------------------------------------------------------------------------------------------------------------------------------------------------

	var proData = [];
	var conData = [];
	var perData = [];
	var clctData = [];
	
	for (let i = kafkaArr.length - 1; i >= 0; i--) {
		clctData.push(kafkaArr[i].clctDt.substring(0, 19));
		proData.push(kafkaArr[i].producer);
		conData.push(kafkaArr[i].consumer);
		perData.push(kafkaArr[i].performance);
	}
	
	Highcharts.setOptions({

			lang: {

				thousandsSep: ','

			}
	});
	
	Highcharts.chart('kafka', {
		chart: {
			type: 'area',
			backgroundColor: '',
			animation: Highcharts.svg,
			events: {
				load: function() {
					var series1 = this.series[0];
					var series2 = this.series[1];
					var series3 = this.series[2];
					var xa = this.xAxis[0];
					setInterval(function() {
						$.ajax({
							url: "/oneKafakaStatus.do",
							async: false,
							type: "get",
							dataType: "json",
							success: function(result) {
								xa.categories.push(result.clctDt)
								series1.addPoint(result.producer, true, true);
								series2.addPoint(result.consumer, true, true);
								series3.addPoint(result.performance, true, true);
							}, error: function(error) {
								console.log(error)
							}

						})

					}, 10000);
				}
			},
			time: {
				useUTC: false
			},
			width: 900,
			height: 200,
			style: {
				color: 'white'
			}
		},
		exporting: {
			enabled: false
		},
		credits: {
			enabled: false
		},
		accessibility: {
			announceNewData: {
				enabled: true,
			}
		},
		title: {
			text: 'Kafka Transaction Performance (milliseconds)',
			style: {
				color: 'rgb(204, 204, 220)',
				fontSize: 14
			}
		},
		xAxis: {
			categories: clctData,
			tickInterval: 6,
			labels: {
				style: {
					color: 'rgb(204, 204, 220)'
				},
				formatter: function() {
					return this.value.substring(10, 19)
				}
			}
		},

		tooltip: {
			borderColor: 'rgb(34, 37, 43)',
			backgroundColor: 'rgb(47, 49, 62,1)',
			style: {
				color: 'rgb(204, 204, 220)'
			},
			headerFormat: '<b>{series.name}</b><br/>',
			pointFormat: '{point.category}<br/>{point.y}'
		},
		legend: {
			itemStyle: {
				color: 'rgb(204, 204, 220)'
			},
		},
		yAxis: {
			min: 0,
			allowDecimals: false,
			startOntick: false,
			endOntick: false,
			title: '',
			labels: {
				format: '{value:,.0f}',
				style: {
					color: 'rgb(204, 204, 220)'
				}
			},
			plotLines: [{
				value: kafkaWN,
				color: 'red',
				width: 3
			}]
		},
		series: [{
			name: 'producer',
			color: 'rgb(115, 191, 105)',
			fillOpacity: 0.4,
			data: proData
		}, {
			name: 'consumer',
			color: 'rgb(242, 204, 12)',
			fillOpacity: 0.4,
			data: conData
		}, {
			name: 'performence',
			color: 'rgb(138, 184, 255)',
			fillOpacity: 0.4,
			data: perData
		}]
	});
	//---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

	var commXaxis = [];
	var commSessionArr = [];
	var commBytesArr = [];
	var commTransArr = [];

	for (let i = commArr.length - 1; i >= 0; i--) {
		commSessionArr.push(commArr[i].sessions);
		commBytesArr.push(commArr[i].bytes);
		commTransArr.push(commArr[i].trans);
		commXaxis.push(commArr[i].prcnDt)
	}
	Highcharts.chart('communication-transaction', {
		chart: {
			type: 'area',
			backgroundColor: '',
			width: 900,
			height: 200,
			animation: Highcharts.svg,
			events: {
				load: function() {
					var series1 = this.series[0];
					var series2 = this.series[1];
					var xa = this.xAxis[0];
					setInterval(function() {
						$.ajax({
							url: "/oneCommuticationStatus.do",
							async: false,
							type: "get",
							dataType: "json",
							success: function(result) {
								xa.categories.push(result.prcnDt)
								series1.addPoint(result.trans, true, true);
								series2.addPoint(result.bytes, true, true);
							}, error: function(error) {
								console.log(error)
							}
						})
					}, 10000);
				}
			},
		},
		exporting: {
			enabled: false
		},
		credits: {
			enabled: false
		},
		legend: {
			itemStyle: {
				color: 'rgb(204, 204, 220)'
			},
		},
		tooltip: {
			borderColor: 'rgb(34, 37, 43)',
			backgroundColor: 'rgb(47, 49, 62,1)',
			style: {
				color: 'rgb(204, 204, 220)'
			},
			pointFormat: '<span style="color:{series.color}">\u25CF</span> {series.name}: <b>{point.y}</b><br/>'
		},
		title: {
			text: 'Communication-Transaction',
			style: {
				color: 'rgb(204, 204, 220)',
				fontSize: 14
			}
		},
		xAxis: {
			categories: commXaxis,
			tickInterval: 6,
			labels: {
				style: {
					color: 'rgb(204, 204, 220)'
				},
				formatter: function() {
					return this.value.substring(10, 19)
				}
			}
		},
		yAxis: {
			startOntick: false,
			endOntick: false,
			title: '',
			labels: {
				style: {
					color: 'rgb(204, 204, 220)'
				}
			}
		},
		series: [{
			name: 'trans',
			color: 'rgb(242, 204, 12)',
			fillOpacity: 0.4,
			data: commTransArr
		},{
			name: 'bytes',
			color: '#73bf69',
			fillOpacity: 0.4,
			data: commBytesArr
		}]
	});
	
	Highcharts.chart('communication-session', {
		chart: {
			type: 'area',
			backgroundColor: '',
			width: 699,
			height: 186,
			animation: Highcharts.svg,
			events: {
				load: function() {
					var series1 = this.series[0];
					var xa = this.xAxis[0];
					setInterval(function() {
						$.ajax({
							url: "/oneCommuticationStatus.do",
							async: false,
							type: "get",
							dataType: "json",
							success: function(result) {
								xa.categories.push(result.prcnDt)
								series1.addPoint(result.sessions, true, true);
							}, error: function(error) {
								console.log(error)
							}
						})
					}, 10000);
				}
			},
		},
		exporting: {
			enabled: false
		},
		credits: {
			enabled: false
		},
		legend: {
			itemStyle: {
				color: 'rgb(204, 204, 220)'
			},
		},
		tooltip: {
			borderColor: 'rgb(34, 37, 43)',
			backgroundColor: 'rgb(47, 49, 62,1)',
			style: {
				color: 'rgb(204, 204, 220)'
			},
			pointFormat: '<span style="color:{series.color}">\u25CF</span> {series.name}: <b>{point.y}</b><br/>'
		},
		title: {
			text: 'Communication-Session',
			style: {
				color: 'rgb(204, 204, 220)',
				fontSize: 14
			}
		},
		xAxis: {
			categories: commXaxis,
			tickInterval: 6,
			labels: {
				style: {
					color: 'rgb(204, 204, 220)'
				},
				formatter: function() {
					return this.value.substring(10, 19)
				}
			}
		},
		yAxis: {
			startOntick: false,
			endOntick: false,
			title: '',
			labels: {
				style: {
					color: 'rgb(204, 204, 220)'
				}
			}
		},
		series: [{
			name: 'session',
			color: '#73eaf8',
			fillOpacity: 0.4,
			data: commSessionArr
		}]
	});

	//---------------------------------------------------------------------------------------------------------------------------------------------------------------------

	var useCpuRate=[];
	var useMemRate=[];
	var useDiskRate=[];
	var data1=[];
	var data2=[];
	var data3=[];
	var serverCategories1=[];
	var serverCategories2=[];
	var serverCategories3=[];
	
	var hostNames=
		Array
		.from(new Set(serverStatArr
		.map((item)=>{return item.hostName
		})))
	
	var result=
		Array.from(new Set(serverStatArr
			 .map((item)=>{
					if(item.clctDt !== null){
						return item.clctDt.substring(0, 10) + " " + item.clctDt.substring(11, item.clctDt.length);
					}
			})))
	result.forEach((category)=>{
		if(category !== undefined){
			serverCategories1.push(category)
			serverCategories2.push(category)
			serverCategories3.push(category)
		}
	})
	
	
	var color = 
			[
				'rgb(115, 191, 105)'
				,'rgb(242, 204, 12)'
				,'rgb(138, 184, 255)'
				,'orange'
				,'#0d53a5'
				,'rgb(115 234 248)'
			];
			
	for(let i=0; i< hostNames.length; i++){
		serverStatArr.forEach((item)=>{
			if(item.hostName==hostNames[i]){
				data1.push(item.useCpuRate);
				data2.push(item.useMemRate);
				data3.push(item.useDiskRate);
			}
		})
		useCpuRate.push({
			name:hostNames[i],
			color:color[i],
			fillOpacity: 0.4,
			data:data1
		})
		useMemRate.push({
			name:hostNames[i],
			color:color[i],
			fillOpacity: 0.4,
			data:data2
		})
		useDiskRate.push({
			name:hostNames[i],
			color:color[i],
			fillOpacity: 0.4,
			data:data3
		})
		data1=[];
		data2=[];
		data3=[];
	}
	
	serverCategories1.sort();
	serverCategories2.sort();
	serverCategories3.sort();
	Highcharts.chart('cpu-use1', {
		chart: {
			backgroundColor: '',
			width: 699,
			height: 186,
			animation: Highcharts.svg,
			marginRight: 10,
			events: {
				load: function() {
					serverStat("/getOneCpuUse.do","useCpuRate",this.series,this.xAxis[0].categories);
				}
			},
			time: {
				useUTC: false
			},
			style: {
				color: 'white'
			}
		},
		exporting: {
			enabled: false
		},
		credits: {
			enabled: false
		},
		legend: {
			itemStyle: {
				color: 'rgb(204, 204, 220)'
			},
		},
		tooltip: {
			borderColor: 'rgb(34, 37, 43)',
			backgroundColor: 'rgb(47, 49, 62,1)',
			style: {
				color: 'rgb(204, 204, 220)'
			},
			pointFormat: '<span style="color:{series.color}">\u25CF</span> {series.name}: <b>{point.y}%</b><br/>'
		},
		title: {
			text: 'CPU Use(%)',
			style: {
				color: 'rgb(204, 204, 220)',
				fontSize: 14
			}
		},
		xAxis: {
			tickInterval: 3,
			startOntick: false,
			endOntick: false,
			categories: serverCategories1,
			labels: {
				style: {
					color: 'rgb(204, 204, 220)',
					fontSize: '10px'
				},
				formatter: function() {
					return this.value.substring(10, 19)
				}
			}
		},
		yAxis: {
			min: 0,
			max: 100,
			tickInterval: 50,
			startOntick: false,
			endOntick: false,
			title: '',
			labels: {
				style: {
					color: 'rgb(204, 204, 220)'
				},
				format: '{value}%'
			},
			plotLines: [{
				value: cpuUseWN,
				color: 'red',
				width: 1
			}]
		},
		series: useCpuRate
	});
	
	Highcharts.chart('memory-use1', {
		chart: {
			backgroundColor: '',
			width: 699,
			height: 186,
			animation: Highcharts.svg,
			marginRight: 10,
			events: {
				load: function() {
					serverStat("/getOneMemUse.do","useMemRate",this.series,this.xAxis[0].categories);
				}
			},
			time: {
				useUTC: false
			},
			style: {
				color: 'white'
			}
		},
		exporting: {
			enabled: false
		},
		credits: {
			enabled: false
		},
		legend: {
			itemStyle: {
				color: 'rgb(204, 204, 220)'
			},
		},
		tooltip: {
			borderColor: 'rgb(34, 37, 43)',
			backgroundColor: 'rgb(47, 49, 62,1)',
			style: {
				color: 'rgb(204, 204, 220)'
			},
			pointFormat: '<span style="color:{series.color}">\u25CF</span> {series.name}: <b>{point.y}%</b><br/>'
		},
		title: {
			text: 'Memory Use(%)',
			style: {
				color: 'rgb(204, 204, 220)',
				fontSize: 14
			}
		},
		xAxis: {
			tickInterval: 3,
			startOntick: false,
			endOntick: false,
			categories: serverCategories2,
			labels: {
				style: {
					color: 'rgb(204, 204, 220)',
					fontSize: '10px'
				},
				formatter: function() {
					return this.value.substring(10, 19)
				}
			}
		},
		yAxis: {
			min: 0,
			max: 100,
			tickInterval: 50,
			startOntick: false,
			endOntick: false,
			title: '',
			labels: {
				style: {
					color: 'rgb(204, 204, 220)'
				},
				format: '{value}%'
			},
			plotLines: [{
				value: memUseWN,
				color: 'red',
				width: 1
			}]
		},
		series: useMemRate
	});
	
	Highcharts.chart('disk-use1', {
		chart: {
			backgroundColor: '',
			width: 699,
			height: 186,
			animation: Highcharts.svg,
			marginRight: 10,
			events: {
				load: function() {
					serverStat("/getOneDiskUse.do","useDiskRate",this.series,this.xAxis[0].categories);
				}
			},
			time: {
				useUTC: false
			},
			style: {
				color: 'white'
			}
		},
		exporting: {
			enabled: false
		},
		credits: {
			enabled: false
		},
		legend: {
			itemStyle: {
				color: 'rgb(204, 204, 220)'
			},
		},
		tooltip: {
			borderColor: 'rgb(34, 37, 43)',
			backgroundColor: 'rgb(47, 49, 62,1)',
			style: {
				color: 'rgb(204, 204, 220)'
			},
			pointFormat: '<span style="color:{series.color}">\u25CF</span> {series.name}: <b>{point.y}%</b><br/>'
		},
		title: {
			text: 'Disk Use(%)',
			style: {
				color: 'rgb(204, 204, 220)',
				fontSize: 14
			}
		},
		xAxis: {
			tickInterval: 3,
			startOntick: false,
			endOntick: false,
			categories: serverCategories3,
			labels: {
				style: {
					color: 'rgb(204, 204, 220)',
					fontSize: '10px'
				},
				formatter: function() {
					return this.value.substring(10, 19)
				}
			}
		},
		yAxis: {
			min: 0,
			max: 100,
			tickInterval: 50,
			startOntick: false,
			endOntick: false,
			title: '',
			labels: {
				style: {
					color: 'rgb(204, 204, 220)'
				},
				format: '{value}%'
			},
			plotLines: [{
				value: diskUseWN,
				color: 'red',
				width: 1
			}]
		},
		series: useDiskRate
	});
	
	
	//서버 cpu,mem,disk 최근 데이터 가져오는 함수
	function serverStat(url,dataName,series,xAxis){
		var seriesArr=[];
		
		for(let i=0; i< series.length;i++){
			seriesArr.push(series[i])
		}
		setInterval(function() {
		$.ajax({
			url: url,
			async: false,
			type: "get",
			dataType: "json",
			success: function(result) {
				var clctDt=[];
				      clctDt=Array.from(
								new Set(
									result.map((item)=>{
									       var time =item.clctDt
										if(!(time == undefined || time == null || time == "")){
											return time.substring(0, 10) + " " + time.substring(11, time.length);
										}
									})
							))
				clctDt.forEach((c)=>{
					if(c !== undefined){
							xAxis.push(c);
					}				
				})
								
				for(let ii = 0; ii<result.length; ii++){
					if(dataName==="useMemRate"){
						result[ii].useDiskRate == -1? 
							seriesArr[ii].addPoint(0,true,true):
								seriesArr[ii].addPoint(result[ii].useMemRate,true,true);
					}
					if(dataName==="useCpuRate"){
						seriesArr[ii].addPoint(result[ii].useCpuRate, true, true);
					}
					if(dataName==="useDiskRate"){
						seriesArr[ii].addPoint(result[ii].useDiskRate, true, true);
					}
				}
								
			}, error: function(error) {
							console.log(error)
			}})}, 10000);
	}
	
	const table=$(".data-table");
	const slideBtn=$(".slide-button");
	const alarmEvent = $(".alarm-event");
	const api = $(".api");
	const searchBar = $(".search-bar");
	//알람 이벤트 관련
	function init(){
		settingAlarms()
		var interval;
		alarmEvent.on("click",()=>{
			settingAlarms()
			clearInterval(interval);
			interval=setInterval(alarmInterval,10000);
		})
		api.on("click",()=>{
			settingApi();
			clearInterval(interval);
			interval=setInterval(apiInterval,10000);
		})
		
			//animate(슬라이드 버튼)
		slideBtn.on("click",function(){
			if($(this).text()=="^"){
				return upSlide()
			}
				downSlide();
		})
		
		interval=setInterval(alarmInterval,10000);
	}		
	
	init();	
	function alarmInterval(){
		alarmSet()
	}
	
	function apiInterval(){
		setApiTable();
	}
	
	//api 테이블 세팅
	function settingApi(){
		classToggle(api,alarmEvent);
		searchBar.empty();
		setApiTable();		
	}
	
	//api 테이블 그리기
	function setApiTable(){
		table.empty();
		var tr = $("<tr>");
		table.append($("<tr><th colspan='5' class='title'>실시간 API 인증/호출 모니터링</th></tr>"))
		var thText=
					[
						"apiid"
						,"apitoken"
						,"ip 주소"
						,"호출 발생 시각"
						,"오류 여부"
					]
		tr.addClass("table-column");
		for(let ii = 0; ii < 5; ii++){
			var th = $("<th>");
			th.text(thText[ii]);
			tr.append(th);
		}
		table.append(tr);
		$.ajax({
				url:"/getApiInvoke.do",
				async:false,
				type: "get",
				dataType: "json",
				success:function(result){
					drawApiTable(result);
				}, error: function(error) {
					console.log(error)
				}
			
			})
		
	}
	
	function drawApiTable(data){
		data.forEach((d)=>{
			//데이터 중복 안되게 쓰기
			var {apiid,apitoken,ipaddr,eventdt,error}=d;
			
			eventdt=eventdt.substr(0,eventdt.indexOf('T'))
					+" "
					+eventdt.substr(eventdt.indexOf('T')+1,eventdt.length);
			
			var column =[];

			column.push(apiid,apitoken,ipaddr,eventdt,error);

			var tr=$("<tr>")

			for(let ii = 0; ii < 5; ii++){

				tr.append($("<td>").text(column[ii]))

			}

			table.append(tr)
		})
	}
	//css 변경 함수
	function classToggle(on,off){
		on.removeClass("menu-off");
		off.removeClass("menu-on");
		on.addClass("menu-on");
		off.addClass("menu-off");
	}
	
	//알람 테이블 세팅
	function settingAlarms(){
		//css 세팅
		classToggle(alarmEvent,api);
		
		//search-bar 세팅
		setSearchBar();
		
		//셀렉트 박스 코드 이름 세팅
		settingCode();
		
		//테이블 세팅
		setAlarmTable(alarmArr);
		
		//셀렉트 박스 이벤트
		$(".search-select").on("change",function(){
			//select box에 밸류가 있을 경우 실행
			$(this).val().length>0?
								searchCode($(this).val(),table)
									:setAlarmTable(alarmArr);
		})
		
		//알람 확인 변경 버튼
		$(".all-update-button").on("click",function(){
			alarmCheck();
		})
	
	}
	
	function setSearchBar(){
		//select-bar 초기화
		searchBar.empty();
		
		//span 생성
		var span=$("<span>");
		span.text("CODE : ");
		
		//select 생성
		var select=$("<select>");
		select.prop({name:"search",class:"search-select"})
		select.append($("<option value=''>알람 코드(선택)</option>"));
		
		//버튼 생성
		var allSelectBtn=$("<div class='all-select'>전체 선택</div>")
		var cancelBtn=$("<div class='all-cancle'>선택 해제</div>")
		var updateBtn=$("<div class='all-update-button'>알람 확인</div>")
		
		//select-bar에 append
		searchBar.append(span
						,select
						,allSelectBtn
						,cancelBtn
						,updateBtn);
		
	}
	
	//테이블 늘리기
	function upSlide(){
			$(".event-box")
				.animate({margin:'-400px auto',height:'718px',},800)
			slideBtn
				.animate({top:'-400px',},800);
			$(".alarm-container")
				.animate({height:'666px',},800);
			$(".table-round")
				.animate({height:'547px',},800);
			$(".table-box")
				.animate({height:'632px',},800);
			slideBtn.text("∨")
	}
	
	//테이블 줄이기
	function downSlide(){
			slideBtn.text("^")
			$(".event-box")
				.animate({margin:'0px auto',height:'338px',},800)
			slideBtn
				.animate({top:'0px',},800);
			$(".alarm-container")
				.animate({height:'286px',},800);
			$(".table-round")
				.animate({height:'172px',},800);
			$(".table-box")
				.animate({height:'257px',},800);
	}
	
	function alarmCheck(){
		var checkBoxArr=$("input[type='checkbox']");
		
		var result=checkBoxArr.map((item,index,array)=>{
			if(index.checked){
				var code=index
						.parentNode
						.nextElementSibling;
				var target=code
						.nextElementSibling
						.nextElementSibling;
				var time = target
						 .nextElementSibling
						 .nextElementSibling;
				return {code:code.innerText
						,target:target.innerText
						,time:time.innerText}	
			}
		})
		
		if(result.length == 0) return alert("선택 된 대상이 없습니다.");
		
		result=Array.from(result);
		
		var jsonData = JSON.stringify(result);
		
		jQuery.ajaxSettings.traditional = true;
		
		if (confirm("알람을 확인 처리 하시겠습니까?")) {
			$.ajax({
				url:"/getUpdateAlarm.do",
				async:false,
				type: "get",
				dataType: "json",
				data:{
					jsonData:jsonData
				},
				success:function(result){
					if(result==0){
						alert("정삭으로 처리되지 않았습니다.");	
						alarmSet();
						return 
					}
					alert("정상적으로 처리되었습니다.");
					alarmSet();
				}, error: function(error) {
				console.log(error)
				}
			
			})
		}
	}
	
	function alarmSet(){
		var arr = [];
		if($(".search-select").val().length>0){
			searchCode($(".search-select").val());
			return
		}
		
		getData("/getAlarmVO.do", arr);
		
		setAlarmTable(arr);
	}
	
	//알람 테이블 만들기
	function setAlarmTable(dataArr) {
		var Thead = $('<tr><th class="title" colspan="7">알람 목록</th>'
				+'</tr>'
				+'<tr class="table-column">'
				+ '<th style="width: 50px">선택</th>'
				+ '<th style="width: 150px;">알람 코드</th>'
				+ '<th style="width: 200px;">알람 명칭</th>'
				+ '<th style="width: 200px;">알람 발생 대상</th>'
				+ '<th style="width: 500px;">알람 발생 값</th>'
				+ '<th style="width: 200px;">알람 발생 시각</th>'
				+ '<th style="width: 125px;">알람 확인 여부</th>'
				+ '</tr>')
		
		var nullData = $('<tr>'
					+'<td rowspan="4" colspan="8" style="text-align:center;font-size:20px;font-weight:bold;">'
					+'알람 데이터가 없습니다.</td>'
					+'</tr>');
					
		table.empty();
		table.append(Thead);
		!(dataArr == null || dataArr == "") ? setTableBuild(dataArr) : table.append(nullData);
		
	}
	
	
	//해당 데이터를 가지고 테이블 만들기
	function setTableBuild(dataArr) {
		dataArr.forEach((alarm) => {
			var tr = $("<tr>")
			var td=$("<td>");
			var input = $("<input>");
			var column=[];
			var {alarmCode,alarmName,alarmTarget,alarmValue,occrDt,cnfmyn}=alarm;
			
			occrDt=occrDt.substr(0, occrDt.indexOf('T')) 
						 + " " 
					     + occrDt.substring(occrDt.indexOf('T')+1, occrDt.length) 
			
			column.push(alarmCode
						,alarmName
						,alarmTarget
						,alarmValue
						,occrDt
						,cnfmyn)
			
			input.prop({type:"checkbox",name:"checkValue",value:""});
			
			input.on("click",()=>{
				event.cancelBubble=true;
			})
			
			td.append(input);
			tr.append(td);		
			
			for(let ii = 0; ii < column.length; ii++){
				var td=$("<td>")
				tr.append(td.text(column[ii]));
			}
			
			table.append(tr);
		})
			
		var cancelBtn=$(".all-cancle");
		var allSelectBtn=$(".all-select");	
		allSelectBtn.off('click');
		$(".all-cancle").off('click');
		
		allSelectBtn.on('click',()=>{
			$('input[type="checkbox"]').prop("checked",true);
		})

		cancelBtn.on('click',()=>{
			$('input[type="checkbox"]').prop("checked",false);
		})
		
		$(".data-table > tr").off('click');
		
		for(let i = 2 ; i< $(".data-table > tr").length; i++){
			
			$(".data-table > tr").eq(i).on("click",function(){
				var input =	$(this)
								.children()
								.first()
								.children()
				input
					.is(":checked")
					?input.prop("checked",false)
					:input.prop("checked",true);
			})
		}	
	}

	
	//코드 데이터 가져오기
	function settingCode(){
		$.ajax({
			url: "/getAllAlarmCode.do",
			async: false,
			cache: false,
			type: "get",
			dataType: "json",
			success: function(result) {
				setOption(result);
			}, error: function(error) {
				console.log(error)
			}

		})
	}
	
	//셀렉트 박스 옵션 추가 작업
	function setOption(data){
		var searchSelect=$(".search-select");
		data.forEach((d)=>{
			var option=$("<option>");
			option.css('text-align','left');
			option.prop("value",d.alarmCode);
			option.html('&nbsp;&nbsp;&nbsp;'+d.alarmCode+" : "+d.alarmName);
			searchSelect.append(option);
		})
		
	}
	
	//셀렉트 박스 선택 코드 정보
	function searchCode(inputValue) {
		$.ajax({
			url: "/search.do",
			async: false,
			cache: false,
			type: "get",
			dataType: "json",
			data: {
				inputVal: inputValue
			},
			success: function(result) {
				setAlarmTable(result);
			}, error: function(error) {
				console.log(error)
			}

		})
	}


})
