<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>NLP SETTING</title>
<%@ include file="/WEB-INF/jsp/adm/include/topLinkTag.jsp"%>
</head>

<script>

	<%-- 업로드 결과 --%>


	// 예문 목록(검색용)

	$(document).ready(function () {


		getOpr();
		// 검색
		$("[data-role=search]").click(function() {
			search();
		});

		if (!checkPermissionPolicy("rcpoprmanagenlpSettingmanageFull")) {
			$("#btnLearn").hide();
			$("#btnApply").hide();
			$("#btnSave").hide();
		}

		// 초기 리스트 조회
		search();

		// 학습
		$("a[data-role=learn]").click(function() {
			toggleLoading();
			learn();
		});

		// 반영
		$("a[data-role=apply]").click(function() {
			apply();
		});

		function learn() {

			$.ajax({
				url: '<c:url value="/admin/rcp/oprmanage/nlpSetting/trainingStart.do"/>',
				data: {
					serviceGroup: $("select[name=serviceGroup]").val(),
					custCode: $("#custCode").val()
				},
				success: function(d) {
					var result = d.result;
					// console.log(d);
					if (result.returnCode == "000") {
						toggleLoading();
					} else {
						// alert(result.returnMsg);
						$.utils.warning("API 연동 오류가 발생하였습니다.");
						toggleLoading();
					}
				}
			});
		}

		function apply() {

			$.ajax({
				url: '<c:url value="/admin/rcp/oprmanage/nlpSetting/trainingApply.do"/>',
				data: {
					serviceGroup: $("select[name=serviceGroup]").val(),
					custCode: $("#custCode").val()
				},
				success: function(d) {
					var result = d.result;
					// console.log(d);
					if (result.returnCode == "000") {
						$.utils.info('반영되었습니다.');
					} else {
						// alert(result.returnMsg);
						$.utils.warning("API 연동 오류가 발생하였습니다.");
					}
				}
			});
		}

	});

	$("[data-role=search]").click(function() {
		search();
	});

	function search() {

		$.ajax({
			type: 'post',
			async: false,
			datatype: 'text',
			url: '<c:url value="/admin/rcp/oprmanage/nlpSetting/selectSimilarityCriteria.do"/>',
			data: {
				serviceGroup: $("select[name=serviceGroup]").val(),
				custCode: $("#custCode").val()
			},
			success: function(data) {

				$('.search_list_container').show();

				if(data.nMap.length > 0) {
					for(var k of data.nMap){
						$('.search_list_container').show();
						$('.dataEmpty').hide();
						$('#similarity_criteria').val(k.similarityCriteria)
						$('#class_criteria').val(k.classCriteria)
						$('#class_result_criteria').val(k.classResultCriteria)
						$('#fallback_msg').val(k.fallbackMsg)
						$('#greeting_msg').val(k.greetingMsg)
					}
				}else{
					$('.dataEmpty').show();
					$('.search_list_container').hide();
				}

			},error : function(XMLHttpRequest, textStatus, errorThrown){
				//console.log(XMLHttpRequest);
				//console.log(textStatus);
				//console.log(errorThrown);
			}
		});
	}

	function uServiceInfo(jobCudType){
		var param = "&jobCudType="+jobCudType;

		if($("#selectCustName").val()==""||$("#selectCustName").val()=="undefined"||
				$("#similarity_criteria").val()==""||$("#similarity_criteria").val()=="undefined"||
				$("#class_criteria").val()==""||$("#class_criteria").val()=="undefined"||
				$("#class_result_criteria").val()==""||$("#class_result_criteria").val()=="undefined"||
				$("#fallback_msg").val()==""||$("#fallback_msg").val()=="undefined"||
				$("#greeting_msg").val()==""||$("#greeting_msg").val()=="undefined"
		) {
			$.utils.warning('필수 항목을 확인 후 진행해 주세요.');
			return false;
		}

        // 질의의도 이해 판단기준 체크
		if(criteriaRange($("#similarity_criteria").val()) === false) {
		    $.utils.warning('유사도 판단 기준 범위 확인');
		    return false;
		}
		if(criteriaRange($("#class_criteria").val()) === false) {
            $.utils.warning('분류 1차 판단 기준 범위 확인');
            return false;
        }
        if(criteriaRange($("#class_result_criteria").val()) === false) {
            $.utils.warning('분류 결과 1,2위간 차이 판단 기준 범위 확인');
            return false;
        }

		param += "&siteCode="+$("#selectCustName").val();
		param += "&serviceCode="+$("#serviceGroup option:selected").val();
		param += "&similarityCriteria="+$('#similarity_criteria').val();
		param += "&classCriteria="+$('#class_criteria').val();
		param += "&classResultCriteria="+$('#class_result_criteria').val();
		param += "&fallbackMsg="+$('#fallback_msg').val();
		param += "&greetingMsg="+$('#greeting_msg').val();
		param += "&custCode="+$("#custCode").val();

		$.ajax({
			type : "post",
			async : false,
			datatype : "text",
			url : '<c:url value="/admin/rcp/oprmanage/nlpSetting/updateSimilarityCriteria.do"/>',
			data : param,
			success : function(data) {
				//console.log(data.nMap)
				if(data.nMap.resultCode == "fail.common.login"){
					$.utils.info('로그인한 후에 진행해 주세요.');
				} else if(data.nMap.resultCode == "success.common.update" || data.nMap.resultCode == "success.common.insert") {
					$.utils.success('저장되었습니다');
					$('a.close').trigger('click');
					search(data.nMap);
				} else {
					$.utils.error('처리도중 오류가 발생했습니다.');
				}
			},
			error : function(data) {
				$.utils.error('처리도중 오류가 발생했습니다.');
			}
		});
	}

	// Loading gif 토글
	function toggleLoading() {
		var img = $(".loading-img");
		if(img.css("display") == "none") {
			img.show();
			img.parent().find("span").text("");
		} else {
			img.hide();
			img.parent().find("span").text("학습");
		}
	}

    // 질의의도 이해 판단 기준 범위 체크 : 0.01 ~ 1
	function criteriaRange(numString) {
	    let result = true;
	    let num = parseFloat(numString);

	    if(isNaN(num)) {
            // 숫자가 아닐때
	        result = false;
	    } else if(num > 1 || num < 0.01) {
            // 범위 체크
            result = false;
	    }

	    return result;
	}

	function getOpr() {

		$.ajax({
			type: "GET",
			contentType: "application/json; charset=utf-8",
			datatype: "JSON",
			url: "<c:url value='/adm/menu/oprmng'/>"  + "?menuval=rcpoprmanagenlpSettingmanage",
			success: function (data) {

				data.forEach(function (e, f) {
					$('#custCode').val(e.custCode);
					$('#serviceGroup').append("<option value=" + e.serviceGroup + ">" + e.serviceGroupName + "</option>");
					$('#serviceGroup').niceSelect('update');
					$("select[name=serviceGroup]").change();
				});
				search();
			}
		});
	}

</script>

<body>

<div class="skip_navigation">
<ul>
	<li>
		<a href="#Content" class="go_content">본문 바로가기</a>
	</li>
	<li>
		<a href="#Gnb">메뉴 바로가기</a>
	</li>
</ul>
</div>

<header id="header">
<%@ include file="/WEB-INF/jsp/adm/include/header.jsp"%>
</header>
<c:import url="/adm/menu/getLnbMenu.do" />

<%-- 컨텐츠 S --%>
<section id="Content" class="conversation">
	<div class="cont_top">
		<div class="location">
			<ul>
				<li class="home"><a href="#">HOME</a></li>
				<li><a href="#">운영관리</a></li>
				<li><a href="#">NLP 설정</a></li>
			</ul>
		</div>
	</div>
	<div class="sub_cont">
		<div class="cont_box">
			<div class="box_title">

				<div class="fl">
					<h2 class="mt12">NLP 설정</h2>
				</div>
				<div class="fr">
					<dl class="customer fl">
						<dt class="fl">
							<c:if test="${'SYS_ADMIN'==LoginVO.authCode}">
								고객사 :
							</c:if>
						</dt>
						<dd class="fl">
							<div class="sel_box">
								<c:choose>
									<c:when test="${'SYS_ADMIN'==LoginVO.authCode}">
										<select class="top" name="custCode" id="custCode">
											<c:forEach var="siteInfo" items="${siteLists}" varStatus="status">
												<option value="<c:out value="${siteInfo.custCode}"/>"><c:out value="${siteInfo.custName}"/></option>
											</c:forEach>
										</select>
									</c:when>
									<c:otherwise>
										<input name="custCode" id="custCode"  type="hidden" value="${LoginVO.siteCode}"/>
									</c:otherwise>
								</c:choose>
							</div>
						</dd>
					</dl>
					<div class="btn_wrap fr">
						<a href="#" class="btn" data-role="search">조회</a>
					</div>
				</div>
			</div>
			<div class="tbl">
				<form id="searchInfo">
					<table class="search">
						<colgroup>
							<col width="16.6%">
							<col>
						</colgroup>
						<tbody>
						<tr>
							<th class="tl">시나리오그룹</th>
							<td class="tl" colspan="5">
								<div class="sel_box">
									<select class="wide" id="serviceGroup" name="serviceGroup">

									</select>
								</div>
								<a href="#" class="btn fr" id="btnApply" data-role="apply">반영</a>
								<a href="#" class="btn fr" id="btnLearn" data-role="learn" style="margin-right: 5px;">
									<span>학습</span>
									<img class="loading-img" alt="loading" src="/images/loading.gif" style="display: none;">
								</a>
							</td>
						</tr>
						</tbody>
					</table>
				</form>
			</div>
		</div>


		<div class="dataEmpty tbl" style="text-align:center; display:none; padding:20px;">
			<table class="search">
				<colgroup>
					<col width="130px">
					<col width="42%">
					<col width="130px">

				</colgroup>
				<thead>
				<tr role="row">
					<th class="center sorting_disabled" rowspan="1" colspan="1">고객사명</th>
					<th class="center sorting_disabled" rowspan="1" colspan="1">서비스명</th>
					<th class="center sorting_disabled" rowspan="1" colspan="1">등록일시</th>
				</tr>
				</thead>
				<tbody>
				<!-- 내용 없을 경우 -->
				<tr>
					<td valign="middle" colspan="4" class="dataTables_empty">No data available in table</td>
				</tr>
				</tbody>
			</table>
		</div>
		<div class="search_list_container mt-6">
			<div class="cont_box">
				<div class="box_title">
					<div class="fl">
						<h2 class="mt12">질의의도 이해 판단기준</h2>
					</div>
				</div>
				<div class="tbl">
					<table class="edit table-fixed">
						<tbody>
						<tr>
							<th class="tl">유사도 판단 기준 </th>
							<td><input type="text" id="similarity_criteria" maxlength="4"></td>
							<th class="tl">분류 1차 판단 기준</th>
							<td><input type="text" id="class_criteria" maxlength="4"></td>
							<th class="tl">분류 결과 1, 2위간 차이 판단 기준</th>
							<td><input type="text" id="class_result_criteria" maxlength="4"></td>
						</tr>
						</tbody>
					</table>
				</div>
			</div>
			<div class="cont_box  mt-6 pt-3 border-t-1">
				<div class="box_title">
					<h2>Fallback 메시지</h2>
				</div>
				<div class="ipt_box">
					<input type="text" id="fallback_msg" placeholder="Fallback 메시지를 입력해주세요">
				</div>
			</div>
			<div class="cont_box  mt-6 pt-3 border-t-1">
				<div class="box_title">
					<h2>Greeting 메시지</h2>
				</div>
				<div class="ipt_box">
					<input type="text" id="greeting_msg" placeholder="Greeting 메시지를 입력해주세요">
				</div>
			</div>
			<div class="btn-side">
				<div class="fr">
					<a href="#" class="btn" id="btnSave" onclick="uServiceInfo(); return false;">저장</a>
				</div>
			</div>
		</div>
	</div>
</section>

<ul class="vakata-context"></ul>
<div id="jstree-marker" style="display: none;">&nbsp;</div>
<%-- 컨텐츠 E --%>


</body>
</html>