<%@ 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>시뮬레이터</title>
<%@ include file="/WEB-INF/jsp/adm/include/topLinkTag.jsp"%>
<script src="<c:url value='/js/adm/rcp/conversation/common.js' />"></script>
<script src="<c:url value='/js/lib/crypto-js/aes.js' />"></script>
<style>
	.dx-dropdowneditor-overlay {
		z-index: 99999 !important;
	}

	.dx-field-value {
		margin-bottom: 20px;
		text-align: left;
	}

	.jsArea {
		height: 200px;
	}
</style>
</head>
<body>

	<h1>ICOMSYS ADMIN</h1>
	<h1>API NODE</h1>
	<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" />

	<!-- 컨텐트 시작 -->
	<section id="Content" class="test">
		<div class="cont_top">
			<div class="location">
				<ul>
					<li class="home"><a href="#">HOME</a></li>
					<li><a href="#">학습 및 테스트</a></li>
					<li><a href="#">시뮬레이터</a></li>
				</ul>
			</div>
		</div>
		<div class="sub_cont">
			<div class="cont_box">
				<div class="box_title">
					<div class="fl">
						<h2 class="mt12">시뮬레이터 관리</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="#" id="dummyModal" rel="dummy_modal" class="btn modalLoad">Dummy 관리</a>
							<a href="#" class="btn" data-role="search">새 대화</a>
						</div>
					</div>
				</div>
				<div class="tbl">
					<form id="searchInfo">
						<table class="search table-fixed">
							<colgroup>
								<col width="130px">
								<col>
							</colgroup>
							<tbody>
							<tr>
								<th class="tl">매장번호</th>
								<td class="tl">
									<div class="sel_box" id="selOprMng">
										<select class="wide" id="callNum" name="callNum">
											<option value="">매장번호 선택</option>
										</select>
									</div>
								</td>
							</tr>
							</tbody>
						</table>
					</form>
				</div>
			</div>

			<div class="cont_box">
				<div class="row">
					<div class="col-6">
						<div class="cont_box">
							<!-- 기존 소스[ 무인접수Bot > 실시간 모니터링] 에서 가져왔어요 -->
							<div class="content-scroll max-height-300px chat-container">
								<div id="detailTalk" class="monitering-chat"></div>
							</div>
							<!-- 기존 소스[ 무인접수Bot > 아웃바운드 모니터링] 에서 입력란만  가져왔어요 -->
							<textarea id="blockingMent" name="userTalk" placeholder="대화를 입력해주세요." class="bt-type mt-3"></textarea>
						</div>
					</div>
					<div class="col-6">
						<div class="cont_box mb-6">
							<div class="tbl bt-type">
								<table class="edit table-fixed">
									<colgroup>
										<col width="25%">
										<col>
									</colgroup>
									<tbody>
									<tr>
										<th class="tl">인텐트명</th>
										<td>
											<input type="text" value="" id="" name="intentName" data-intent-id="" readonly class="px-2">
										</td>
									</tr>
									<tr>
										<th class="tl">의도추론율</th>
										<td>
											<input type="text" value="" id="" name="intentScore" readonly class="px-2">
										</td>
									</tr>
									</tbody>
								</table>
							</div>
						</div>
						<div class="cont_box">
							<div class="box_title">
								<h2>파라미터</h2>
							</div>
							<div class="content-scroll min">
								<div class="tbl">
									<table class="edit table-fixed parameter-table">
										<colgroup>
											<col width="25%">
											<col>
										</colgroup>
										<tbody>
										</tbody>
									</table>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
		<%-- 현재 선택(조회)된 코드들로 조회하기 위함. --%>
		<input type="hidden" name="oprMngCode">
		<input type="hidden" name="custCode">
	</section>
	<!-- 컨텐트 끝 -->
	<div class="clone-box hide">
		<div class="msg-admin">
			<div class="monitering-msg admin">
				<div class="msg-img"> <img src="https://cinnamon.icomsys.co.kr//BotMain_VM/lib/assets/images/img-bot.png" alt=""> </div>
				<div class="msg-desc gray2">
					<p style="font-size:1.1rem;">$$text$$</p>
				</div>
			</div>
		</div>
		<div class="msg-user">
			<div class="monitering-msg user">
				<div class="msg-desc gray">
					<p style="font-size:1.1rem;">$$text$$</p>
				</div>
				<div class="msg-img"> <img src="https://cinnamon.icomsys.co.kr//BotMain_VM/lib/assets/images/img-user.png" alt=""> </div>
			</div>
		</div>
	</div>


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

	<div class="modal" id="dummy_modal">
		<div class="modal_header">
			<h3>Dummy 데이터 관리</h3>
		</div>
		<div class="modal_body">
			<div class="modal_cont">
				<div class="dx-field-label" style="width: 20%">API</div>
				<div class="dx-field-value">
					<div id="apiList"></div>
				</div>
				<textarea id="dummyJson" checksum="" class="jsArea" style="height: 450px"></textarea>
			</div>
		</div>
		<div class="modal_footer">
			<div class="btn_wrap fr">
				<a href="#" class="btn grey close">취소</a>
				<a href="#" class="btn" onclick="fnSaveDummyJson()">저장</a>
			</div>
		</div>
		<div class="modal_controller">
			<a href="#" class="close">close</a>
		</div>
	</div>


</body>
<script type="text/javascript">
	// 초기 input값 세팅용
	var isInit = true;
	let today = new Date();
	let year = today.getFullYear(); // 년도
	let month = today.getMonth() + 1;  // 월
	let date = today.getDate();  // 날짜
	let yyyyMMdd = year.toString() + month.toString() + date.toString();

	var callId = "";
	var cinnamonToken = "";
	var methodType = "";
	var dnis = "";

	$(function() {

		// Dummy 관리
		commonUtil.doAction({
			"url": commonUtil.getContextPath()+ "/admin/rcp/conversation/selectApiNodeList",
			"data" : {},
			"callBack" : function (data) {
				$("#apiList").dxSelectBox({
					dataSource: data.getList,
					displayExpr: function(items){
						if($.utils.isBlank(items)) {
							return ""
						} else {
							return "[" + items.serviceGroupName + "] " +  items.nodeName;
						}
					},
					valueExpr: "seq",
					searchEnabled: true,
					onValueChanged: function(data) {
						// console.log($("#apiList").dxSelectBox("instance"));
						// console.log($("#apiList").dxSelectBox("instance").option("value"));
						if (data.value != null && data.value != undefined) {
							fnLoadDummyJson(data.value);
						}
					},
				});
			}
		});

		$(".jsArea").on("keydown", function (e) {
			let tabSize = 4; // 공백 대체 크기 (4칸)
			if(e.keyCode === 9) {
				let start = this.selectionStart;
				let end = this.selectionEnd;
				let value = $(this).val();
				let textBeforeCursor = value.substring(0, start); // 커서 이전 텍스트
				let textAfterCursor = value.substring(end); // 커서 이후 텍스트
				let tabSpaces = " ".repeat(tabSize); // 탭 대체 공백 문자열
				let replacedText = textBeforeCursor + tabSpaces + textAfterCursor; // 대체된 텍스트
				this.value = replacedText; // 입력 필드에 대체된 텍스트 설정
				this.selectionStart = start + tabSize; // 커서 위치 이동
				this.selectionEnd = start + tabSize; // 커서 위치 이동
				e.preventDefault();
			}
		});



		// 고객사 목록
		fncRetrieveOprMng($("#custCode"));
		$("#custCode").on('change', function() {
			fncRetrieveOprMng($(this));
		});

		// 채팅 전송
		$("textarea[name=userTalk]").keyup(function(e) {
			if(e.keyCode == 13) {
				var v = $(this);
				if(!v.isBlank()) {
					// 사용자 채팅 출력
					appendUserMsg(v.val());

					// API 호출
					callAPI(v.val());

					// 입력영역 초기화
					v.val('');
				}
			}
		});

		// 조회
		$("a[data-role=search]").click(function(e) {
			e.preventDefault();
			// 조회 버튼을 누를때 해당 값을 저장하기 위함.
			// 조회를 누르지 않은 상태에서 SELECT 값만 변경하고 API 요청시 버그 방지.
			$("input[name=oprMngCode]:hidden").val($('#callNum').val());
			$("input[name=custCode]:hidden").val($('#custCode').val());
			clearAll();
		});

	});


	// 우측영역 파라미터 테이블 HTML
	function setParamTable(obj) {
		var tableBody = $(".parameter-table tbody");
		tableBody.html('');

		if(!$.utils.isBlank(obj)) {
			var keys = Object.keys(obj);
			for(var i in keys) {
				var key = keys[i];
				var val = obj[key];
				val = val.replace(/\"/g,"&quot;").replace(/&lt;/g, "<").replace(/&gt;/g, ">");
				var html = `<tr>
					<th class="tl">\${key}</th>
					<td>
						<input type="text" value="\${val}" readonly class="px-2">
					</td>
					</tr>`;
				tableBody.append(html);
			}
		}
	}

	// 관리자(봇) 채팅 append
	function appendAdminMsg(text) {
		$("#detailTalk").append($(".clone-box > .msg-admin").clone().html().replace("$$text$$", text));
	}

	// 사용자 채팅 append
	function appendUserMsg(text) {
		$("#detailTalk").append($(".clone-box > .msg-user").clone().html().replace("$$text$$", text));
	}

	// API 호출
	function callAPI(userTalk) {
		// var custCode = $("input[name=custCode]:hidden").val();
		var oprMngCode = $("input[name=custCode]:hidden").val() + "_RCP_" + $("#mainOpr").val();
		dnis = $("input[name=oprMngCode]:hidden").val();
		var min = Math.ceil(0);
		var max = Math.floor(100000);
		if (cinnamonToken === null || cinnamonToken === '') {
			callId = oprMngCode + '_' + yyyyMMdd + '_' + Math.floor(Math.random() * (max - min)) + min;
		}
		if (cinnamonToken != '') {
			methodType = 'STT';
		} else {
			methodType = 'INIT';
		}

		$.ajax({
			url: '<c:url value="/admin/rcp/learningTest/simulator/call-api.do"/>',
			data: {
				oprMngCode: oprMngCode,
				callId: callId,
				token: cinnamonToken,
				userTalk: userTalk.replace(/\n/g, ""),  // 엔터키 제거하고 넘기기
				methodType: methodType,
				dnis: dnis
			},
			success: function(d) {
				var result = d.result;
				// console.log(d);
				if(result.returnCode == "200" || result.returnCode == "500") {
					cinnamonToken = result.token;
					// BOT 채팅 append
					appendAdminMsg(result.botTalk);

					/*
                     * 우측 영역 인텐트 정보 Setting
                     * 인텐트 정보가 없는 경우 기존 값 노출
                     */
					var intentName = result.intentName;
					if($.utils.isNotBlank(intentName)) {
						$("input[name=intentName]").val(intentName);
						$("input[name=intentName]").data("intentId", result.intentId);
						$("input[name=intentScore]").val(result.intentScore);
					}

					// 파라미터 Setting
					setParamTable(result.parameter);

					// 대화창 스크롤 최하단으로 이동
					$("#detailTalk").parents("div.content-scroll").scrollTop($("#detailTalk").height());
				} else {
					// alert(result.returnMsg);
					$.utils.warning("API 연동 오류가 발생하였습니다.");
				}
			}
		});
	}

	// 고객사, 서비스 변경 시 초기화를 위한 함수
	function clearAll() {
		// 채팅 박스
		$("#detailTalk").html('');

		// intent
		$("input[name=intentName]").val('');
		$("input[name=intentName]").data("intentId", "");
		$("input[name=intentScore]").val('');

		// parameter
		$(".parameter-table tbody").html('');

		// 전역변수 초기화
		callId = "";
		cinnamonToken = "";
		methodType = "INIT";

		// API 호출
		callAPI("");
	}

	function fncRetrieveOprMng(e) {
		$('#callNum').empty();
		var data = {
			custCode : e.val(),
			serviceGroup : $("#mainOpr").val()
		};

		$.ajax({
			type: "POST",
			contentType: "application/json; charset=utf-8",
			datatype: "JSON",
			data: JSON.stringify(data),
			async: false,
			url: "<c:url value='/admin/rcp/learningTest/simulator/custCallNumlist.do'/>",
			success: function (data) {
				// console.log(JSON.stringify(data));

				data.getList.forEach(function (e, f) {
					// $('#callNum').append("<option value=" + e.oprMngCode + ">" + e.attribute1  + "</option>");
					$('#callNum').append($("<option></option>").attr("value",e.attribute1).text(e.attribute1 + " (" + e.codeName + ")"));
				});

				$('#callNum').niceSelect('update');
				if(isInit) {
					setTimeout(function() {
						$("a[data-role=search]").trigger("click");
					}, 100);

					isInit = false;
				}
				$("input[name=oprMngCode]:hidden").val($("#callNum").val());

			}
		});
	}

	// Dummy Json 불러오기
	function fnLoadDummyJson(apiSeq){
		commonUtil.doActionGet({
			"url": commonUtil.getContextPath() + "/admin/rcp/learningTest/simulator/select/dummy",
			"data": {
				seq: apiSeq
			},
			"callBack" : function (data) {
				$("#dummyJson").val(data.jsonContents);
				$("#dummyJson").attr("checksum", data.checksum);
			}
		});
	}

	// Dummy Json 저장
	function fnSaveDummyJson(){
		// 1. checksum 검사
		if ( $.utils.getStringToChecksum($("#dummyJson").val()) == $("#dummyJson").attr("checksum")) {
			$.utils.info("변경된 내용이 없습니다.");
			return;
		}

		// 2. 서버로 저장 요청
		commonUtil.doAction({
			"url": commonUtil.getContextPath() + "/admin/rcp/learningTest/simulator/save/dummy",
			"data": {
				apiSeq: $("#apiList").dxSelectBox("instance").option("value"),
				jsonContents: $("#dummyJson").val(),
				checksum: $("#dummyJson").attr("checksum"),
			},
			"callBack" : function (data) {
				switch (data) {
					case 0:
						$.utils.info("정상적으로 저장되었습니다.");
						fnLoadDummyJson($("#apiList").dxSelectBox("instance").option("value"));
						break;
					case 1:
						$.utils.warning("변경된 값이 없습니다.");
						break;
					default:
						$.utils.error("정의되지 않은 오류 발생");
				}
			}
		});
	}
</script>
</html>
