$(function() {


	function getData(url, arr) {
		$.ajax({
			url: url,
			async: false,
			cache: false,
			type: "get",
			dataType: "json",
			success: function(result) {
				console.log(result);
				result.forEach((el) => {
					arr.push(el);
				});

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

		})
	}

	function getDataAsync(url, param, callBackFunc, errorFunc) {
		$.ajax({
			url: url,
			type: "get",
			dataType: "json",
			data: param,
			success: function(result) {
				if (callBackFunc) {
					callBackFunc(result);
				}
			}, error: function(error) {
				if (errorFunc) {
					errorFunc(error);
				}
				else {
					console.log(error)
				}
			}

		})
	}

	const alarmTable = $('.alarm-table');
	const apiTable = $('.api-table');
	const slideBtn=$(".slide-button");
	const alarmEvent = $(".alarm-event");
	const api = $(".api");
	const searchBar = $(".search-bar");
	const alarmContent = $('.alarm-table .content');
	const apiContent   = $('.api-table .content');
	let _BeforeAlarmData = [];
	let _AlarmInterval = null;

	//알람 이벤트 관련
	function init(){
		settingCode();
		settingAlarms();
		const cancelBtn=$(".all-cancle");
		const allSelectBtn=$(".all-select");

		allSelectBtn.on('click',()=>{
			$('.alarm-table .content input[type="checkbox"]').prop("checked",true);
		})

		cancelBtn.on('click',()=>{
			$('.alarm-table .content input[type="checkbox"]').prop("checked",false);
		})

		// getDataAsync('/getAlarmVO.do', null, drawAlarmTable, null);
		//
		// setInterval(()=>{
		// 	getDataAsync('/getAlarmVO.do', null, drawAlarmTable, null);
		// }, 10000);
		setAlarmInterval('/getAlarmVO.do', null);
		setApiInterval();
		setInterval(setApiInterval, 10000);
		//var interval;
		alarmEvent.on("click",()=>{
			settingAlarms();
		//	clearInterval(interval);
		})
		api.on("click",()=>{
			settingApi();
		//	clearInterval(interval);
		//	interval=setInterval(apiInterval,10000);
		})

		//animate(슬라이드 버튼)
		slideBtn.on("click",function(){
			if($(this).text()=="^"){
				return upSlide()
			}
			downSlide();
		});

		$(".search-select").on("change",function(){
			//select box에 밸류가 있을 경우 실행
			let param = null;
			let url = '/getAlarmVO.do';
			_BeforeAlarmData = [];
			if ($(this).val().length) {
				url = '/search.do';
				param = { inputVal : $(this).val() }
			}

			setAlarmInterval(url, param);
		});


		// interval=setInterval(alarmInterval,10000);
	}

	function setAlarmInterval(url, param) {
		if (_AlarmInterval) {
			clearInterval(_AlarmInterval);
			_AlarmInterval = null;
		}
		getDataAsync(url, param, drawAlarmTable, null);

		_AlarmInterval = setInterval(()=>{
			getDataAsync(url, param, drawAlarmTable, null);
		}, 10000);
	}

	function setApiInterval() {
		getDataAsync("/getApiInvoke.do", null, drawApiTable, null);
	}

	init();


	//api 테이블 세팅
	function settingApi(){
		if (!apiTable.hasClass('on')) {
			classToggle(api,alarmEvent);
			$('.alarm-area').removeClass('on');
			$('.search-bar .title').text('실시간 API 인증/호출 모니터링');
			apiTable.addClass('on');
			alarmTable.removeClass('on');
		}
		//searchBar.empty();
		//searchBar.append($("<div class='title'>실시간 API 인증/호출 모니터링</div>"))

	}

	function drawApiTable(data){
		// const $tbody = apiContent;
		let str = '';
		apiContent.empty();
		if (!data || data.length === 0) {
			apiContent.append($('<tr><td class="empty-box" rowspan="4" colspan="8">API 데이터가 없습니다.</td></tr>'));
			return
		}
		data.forEach((d)=>{
			//데이터 중복 안되게 쓰기
			let {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);

			const tr=$("<tr>")

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

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

			}

			apiContent.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 세팅
		if (!alarmTable.hasClass('on')) {
			classToggle(alarmEvent, api);
			$('.alarm-area').addClass('on');
			$('.search-bar .title').text('알람 목록');
			alarmTable.addClass('on');
			apiTable.removeClass('on');
		}
		//search-bar 세팅
		//setSearchBar();

		//셀렉트 박스 코드 이름 세팅
		//settingCode();

		//테이블 세팅
		//setAlarmTable(alarmArr);

		//셀렉트 박스 이벤트

		//
		// //알람 확인 변경 버튼
		// $(".all-update-button").on("click",function(){
		// 	alarmCheck();
		// })

	}


	//테이블 늘리기
	function upSlide(){
		$(".event-box").animate({
			margin:'-400px auto',
			height:'776px'
		},800);
		// $(".alarm-container").animate({
		// 	height:'733px'
		// },800);
		// $(".table-round").animate({
		// 	height:'682px'
		// },800);
		// $(".table-box").animate({
		// 	height:'723px'
		// },800);
		slideBtn.text("∨")
	}

	//테이블 줄이기
	function downSlide(){
		slideBtn.text("^")
		$(".event-box")
			.animate({margin:'0px auto',height:'377px',},800)
		// $(".alarm-container")
		// 	.animate({height:'335px',},800);
		// $(".table-round")
		// 	.animate({height:'284px',},800);
		// $(".table-box")
		// 	.animate({height:'327px',},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 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; height: 264px;">'
		// 	+'알람 데이터가 없습니다.</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 drawAlarmTable(data) {

		if (_BeforeAlarmData && _BeforeAlarmData.length) {
			let sameIndex = [];
			let removeIndex = [];
			_BeforeAlarmData.forEach((obj, idx)=>{
				let cnt = 0;
				for (let ii = 0; ii < data.length; ii++) {
					if (
						obj.alarmCode === data[ii].alarmCode &&
						obj.alarmName === data[ii].alarmName &&
						obj.alarmTarget ===	data[ii].alarmTarget &&
						obj.alarmValue === data[ii].alarmValue &&
						obj.occrDt === data[ii].occrDt &&
						obj.cnfmyn === data[ii].cnfmyn ) {
						cnt++;
						sameIndex.push(ii);
						break;
					}
				}

				if (cnt === 0) {
					removeIndex.push(idx);
				}
			});

			if (removeIndex.length > 0) {
				for (let ii = removeIndex.length -1; ii >= 0; ii--) {
					alarmContent.children().eq(removeIndex[ii]).remove();
				}
			}

			if (sameIndex[0] > 0) {
				let str = '';
				for (let ii = 0; ii < sameIndex[0]; ii++) {
					let {alarmCode, alarmName, alarmTarget, alarmValue, occrDt, cnfmyn} = data[ii];
					occrDt = occrDt.replace('T', ' ');
					str += `<tr class="tr">
									<td>
										<input type="checkbox" name="checkValue" value=""  onclick="(event)=>{event.cancelBubble = true}">
									</td>
									<td>${alarmCode}</td>
									<td>${alarmName}</td>
									<td>${alarmTarget}</td>
									<td>${alarmValue}</td>
									<td>${occrDt}</td>
									<td>${cnfmyn}</td>
								</tr>`;
				}
				if (str) {
					alarmContent.prepend($(str));
				}
			}

		}
		else {
			let str = '';
			if (data && data.length) {
				data.forEach((obj)=>{
					let {alarmCode, alarmName, alarmTarget, alarmValue, occrDt, cnfmyn} = obj;
					occrDt = occrDt.replace('T', ' ');
					str += `<tr class="tr">
								<td>
									<input type="checkbox" name="checkValue" value="" onclick="event.stopPropagation()">
								</td>
								<td>${alarmCode}</td>
								<td>${alarmName}</td>
								<td>${alarmTarget}</td>
								<td>${alarmValue}</td>
								<td>${occrDt}</td>
								<td>${cnfmyn}</td>
							</tr>`;
				})
			}
			else {
				str = `<tr>
							<td class="empty-box" rowspan="4" colspan="8">
								알람 데이터가 없습니다.
							</td>
						</tr>`;
			}
			alarmContent.html(str);
		}
		$('.tr').off('click');
		$('.tr').on('click', function() {
			rowClick(this);
		})
		_BeforeAlarmData = data;
	}

	function rowClick(el) {
		const input = $(el).children().eq(0).children();
		input.prop("checked", !input.is(':checked'));
	}

	//코드 데이터 가져오기
	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) {
		getDataAsync('/search.do', {inputVal : inputValue}, drawAlarmTable, null);
		// $.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)
		// 	}
		//
		// })
	}

	var card = document.querySelector('.card');
	var cardIcon = document.querySelectorAll('.card .card-grid i');

	cardIcon.forEach((v, i) => {
		v.addEventListener( 'click', function() {
			card.classList.toggle('is-flipped');
		});
	})
})
function dropDown(){
	const $drop = $('.drop');
	$drop.toggleClass('on');
	$('.drop-box').toggleClass('on');
	if (!$drop.hasClass('on')) {
		const $from = $('.from-dt');
		const $to   = $('.to-dt');
		let idx = findRangeSelectIndex();
		const $toDtText = $('.to-dt-text');
		const $fromDtText = $('.from-dt-text');
		if ($fromDtText.hasClass('on')) {
			$fromDtText.removeClass('on');
		}
		if ($toDtText.hasClass('on')) {
			$toDtText.removeClass('on');
		}
		if (idx >= 0) {
			$from.val(fromData[idx]);
			$to.val(toData[idx]);
		}
		else {
			const dateVal = $('.date-change').text();
			if (dateVal.includes('to')) {
				const dateArray = dateVal.split('to');
				$from.val(dateArray[0].trim());
				$to.val(dateArray[1].trim());
			}
		}
	}
}

function findRangeSelectIndex() {
	const divArr = $('.range-select > div');
	for (let ii = 0; ii < divArr.length; ii++) {
		if (divArr.eq(ii).hasClass('on')) {
			return ii;
		}
	}
}
