<%@ 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" %>
	</head>
	<body>
		<%-- 공통 S --%>
		<h1>ICOMSYS ADMIN</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" />
		<%-- 공통 E --%>

		<script>
		    $(document).ready( function() {
		        // 권한에 따라 버튼, 입력창 숨김
                if (!checkPermissionPolicy("rcpconversationintentmanageFull")) {
                    $("#btnIntentRegistration").hide();
                    $("#btnIntentUpload").hide();

                    $("button[data-role=update]").hide();
                    $("#intent_update_modal input:first-child").attr("readonly",true);
                    $(".insert_step1").attr("disabled", "disabled");
                }
            });

			var oprMngCodeList = [];
			var fullOprMngCode = '';

			<%-- 업로드 결과 --%>
			<c:if test="${not empty message}">
				<c:if test="${result}">
					$.utils.success('${message}');
				</c:if>
				<c:if test="${!result}">
					$.utils.error('${message}');
				</c:if>
			</c:if>

        	// 예문 목록(검색용)
        	var examples = [];
	        $(document).ready(function () {

	            // Datatable 초기화
	            var opts = {
	            		columns: [
	    	            	{data: "intentName"},
	    	                {data: "exampleCnt"},
	    	                {data: "codeName"},
	    	                {data: ''}
	    	            ],
	    	            columnDefs: [{
	    	                    "defaultContent": "-",
	    	                    "targets": "_all",
	    	                    "className": "center"
	    	                },
	    	                {
	    	                	targets: 3,
	    	                	render: function(data, type, row) {
	    	                	    if (!checkPermissionPolicy("rcpconversationintentmanageFull")) {
                                        return '';
                                    } else {
	    	                		    return '<a href="#" class="btn grey" data-role="deleteIntent" data-seq="' + row.seq + '" ' +
											'data-serviceGroup= '+ $("select[name=serviceGroup]").val() +' >삭제</a>';
	    	                	    }
	    	                	},
	    	                },
	    	            ],
	    	            createdRow: function (row, data, index) {
	    	                $(row).addClass("modalLoad");
	    	                $(row).attr("rel", "intent_update_modal");
	    	            },
	    	            drawCallback: function (settings) {
	    	                // scripts.js : 조회list modal 연결
	    	                modalUi();
	    	            }
	            }
	            $.utils.dataTable.init('<c:url value="/admin/rcp/conversation/intent/search.do"/>', opts);

	            // 인텐트 카테고리 초기화
	            //initCategory();

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

	            // 수정 조회 데이터
	            $("#resultTable").DataTable().on('select.dt', function (e, dt, type, indexes) {
                    //수정 모달창 초기화
	                var modal = $("#intent_update_modal");
	                modal.find(".err-text").hide();
	                $("#intent_update_modal").find("button[data-role=update]").removeClass("disabled");
                    $("#intent_update_modal").find("button[data-role=update]").prop("disabled", false);

	                var rowData = $("#resultTable").DataTable().row(indexes).data();
	                $.ajax({
	                	url: '<c:url value="/admin/rcp/conversation/intent/examples.do"/>',
	                	data: {intentSeq: rowData.seq},
	                	success: function(d) {
	                		$("#intent_update_modal").find("input[name=intentName]").val(rowData.intentName);
	                		$("#intent_update_modal").find("select[name=category]").val(rowData.category);
	                		$("#intent_update_modal").find("select[name=category]").niceSelect("update");
	                		$("#intent_update_modal").find("input[name=seq]").val(rowData.seq);
	                		$("#intent_update_modal").find("input[name=originalName]").val(rowData.intentName);
	                		examples = d.list;
	                		renderExamples("intent_update_modal", examples);
	                	}
	                });
	            });

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

				$('#serviceGroup').change(function () {
					initCategory();
				});

	            // 초기 리스트 조회
	            // search(); getOpr에서 함

	            // 인텐트 명 중복체크
	            $("input[name=intentName]").keyup(function() {
	            	var modal = $(this).parents(".modal");
	            	if($(this).isNotBlank()) {
		            	var intentName = $(this).val();

		            	$.ajax({
		            		url: "<c:url value='/admin/rcp/conversation/intent/check.do'/>",
		            		data: {intentName: intentName.trim()},
		            		success: function(d) {
		            			if(!d.result) {
		            				var originalName = modal.find("input[name=originalName]");

		            				// 기존 이름으로 다시 바꾼 경우 텍스트 노출 안함
		            				if($.utils.isNotBlank(originalName) && originalName.val() == intentName) {
			            				modal.find(".err-text").hide();
			            				$("#intent_update_modal").find("button[data-role=update]").removeClass("disabled");
			            				$("#intent_update_modal").find("button[data-role=update]").prop("disabled", false);

		            				} else {
			            				modal.find(".err-text").show();
			            				$("#intent_update_modal").find("button[data-role=update]").addClass("disabled");
			            				$("#intent_update_modal").find("button[data-role=update]").prop("disabled", true);
		            				}
		            			} else {
		            				modal.find(".err-text").hide();
		            				$("#intent_update_modal").find("button[data-role=update]").removeClass("disabled");
		            				$("#intent_update_modal").find("button[data-role=update]").prop("disabled", false);
		            			}
		            		}
		            	});
	            	} else {
          				modal.find(".err-text").hide();
          				$("#intent_update_modal").find("button[data-role=update]").removeClass("disabled");
                        $("#intent_update_modal").find("button[data-role=update]").prop("disabled", false);
	            	}
	            });

	            // 예문 입력창 클릭시
	            $("input[name=exampleIpt]").keyup(function(e) {
	            	var btn = $(this).parents("div.row").find("button[data-role=addExample]");
	            	var saveType = $(this).attr("saveType");
	            	if($(this).isBlank()) {
	            		btn.addClass("disabled");
	            		btn.attr("disabled", true);
	            	} else {
	            		btn.removeClass("disabled");
	            		btn.attr("disabled", false);
		            	if(e.keyCode == 13) {
		            		btn.click();
		            	}
	            	}
	            });

	            // 예문 추가
	            $("button[data-role=addExample]").click(function() {
	            	var modal = $(this).parents(".modal");
	            	var modalId = modal.attr("id");
	            	var exampleIpt = modal.find("input[name=exampleIpt]");

	            	if(exampleIpt.isNotBlank()) {
	            		var v = exampleIpt.val();
	            		// 중복 예문 체크
	            		var cnt = examples.filter(function(e) {
		            		return e.exampleText == v;
		            	}).length;
						if(exampleIpt.val().includes(',')) {
							$.utils.warning("예문 추가 시 [ , ]는 입력할 수 없습니다.");
							exampleIpt.val('');
							return false;
						}
	            		if(cnt > 0) {
	            			$.utils.warning('중복된 예문입니다.');
		            		exampleIpt.val('');
	            			return false;
	            		}
	            		//addExample(modalId, v);
	            		exampleIpt.val('');
	            		exampleIpt.trigger("keyup");
	            		//examples = [];
						var exam = {seq: '', exampleText: v};
	            		examples.push(exam); 	// 단건저장
	            		save_example("I", modalId, [exam], v);  			// 2022.06..28 단건 추가로 수정
	            	}
	            });

	            // 단건,저장, 삭제 저장하기 2022.06.28 추가
	            function save_example(saveType, modalId, exampleList, v){
	            	var data = {}
					var menuVal = "rcpconversationintentmanage";
	            	if(saveType == "I"){
	            		var modal =  $("#"+modalId);
		            	var serviceGroup = $("select[name=serviceGroup]");
		            	var seq = modal.find("input[name=seq]");
		            	var intentName = modal.find("input[name=intentName]");
		            	var category = modal.find("select[name=category]");
						var custCode = $("#custCode").val();

	            		data = {
		            			seq: seq.val(),
								menuVal: menuVal,
		            			intentSeq: seq.val(),
								serviceGroup: serviceGroup.val(),
		            			intentName: intentName.val(),
		            			category: category.val(),
		            			exampleList: exampleList,
		            			saveType : saveType,
								custCode: custCode
		            	};

	            	}else if(saveType == "D"){
	            		data = {
		            		seq: modalId,
							menuVal: menuVal,
							serviceGroup: $("select[name=serviceGroup]").val(),
		            		saveType : saveType,
							custCode: $("#custCode").val()
		            	};
	            	}

	            	$.ajax({
	            		url: '<c:url value="/admin/rcp/conversation/intent/insertExample.do"/>',
	            		type: "POST",
	            		data: JSON.stringify(data),
	            		contentType: "application/json",
	            		success: function(d) {
	            			if(d.result) {
	            				$.utils.success(d.message);
	            				search();
	            				if(saveType == "I") {
									var seq = d.seq;
									$("#" + modalId).find("input[name=exampleSeq]:eq(0)").val(seq);
									addExample(modalId, v);
									// img.hide();
									// img.parent().find("span").text("저장");
								}
	            			} else {
	            				$.utils.error(d.message);
								examples.pop();
	            			}
	            		}
	            	});
	            }

	            // 예문 삭제 2022.06..28 단건 추가로 수정
	            $(document).on("click", "button[data-role=deleteExample]", function() {
	            	var container = $(this).parents(".border-container");
	            	var seq = container.find("input[name=exampleSeq]").val();
					//console.log(seq);
					for (var i=0; i<examples.length; i++){
						if (examples[i].seq == seq){
							examples.splice(i, 1);
							i--;
							break;
						}
					}
					save_example("D", seq, null, null);
					container.remove();
	            });

	            // 예문 검색
	            $("input[name=searchUpdateExample]").keyup(function() {
	            	var modal = $(this).parents(".modal");
	            	var modalId = modal.attr("id");
	            	if(examples.length < 1) {
	            		return false;
	            	}
	            	var v = $(this).val();
	            	var result = examples.filter(function(o) {
	            		return (o.exampleText.indexOf(v) > -1);
	            	});
	            	renderExamples(modalId, result);
	            });

	            // 인텐트 수정
	            $("button[data-role=update]").click(function() {
	            	var modal = $(this).parents(".modal");

	            	// 기본 인텐트 데이터
	            	var serviceGroup = $("select[name=serviceGroup]");
					var custCode = $("#custCode").val();
	            	var seq = modal.find("input[name=seq]");
	            	var intentName = modal.find("input[name=intentName]");
	            	var category = modal.find("select[name=category]");

					//console.log(serviceGroup);
					//console.log(seq.val());

	            	if(serviceGroup.isBlank()) {
	            		$.utils.warning("서비스를 선택해주세요.");
	            		return false;
	            	}
	            	if(intentName.isBlank()) {
	            		$.utils.warning("인텐트명을 입력해주세요.");
	            		return false;
	            	}
	            	if(modal.find('.err-text').css("display") != "none") {
	            		$.utils.warning("중복된 인텐트 입니다.");
	            	}
	            	if(category.isBlank()) {
	            		$.utils.warning("분류를 선택해주세요.");
	            		return false;
	            	}

	            	// 인텐트 예문 데이터
	            	var exampleList = new Array();
	            	/* 단건입력으로 변경 2022.06.28
	            	var container = modal.find('.border-container');
	            	container.each(function() {
	            		var example = {
	            				seq: $(this).find("input[name=exampleSeq]").val(),
			            		exampleText: $(this).find("input[name=exampleText]").val()
	            		};
	            		exampleList.push(example);
	            	});
	            	*/

	            	// 전송 데이터
	            	var data = {
	            			seq: seq.val(),
	            			intentSeq: seq.val(),
	            			serviceGroup: serviceGroup.val(),
							custCode: custCode,
	            			intentName: intentName.val(),
	            			category: category.val(),
	            			exampleList: exampleList
	            	};

	            	$.ajax({
	            		url: '<c:url value="/admin/rcp/conversation/intent/update.do"/>',
	            		type: "POST",
	            		data: JSON.stringify(data),
	            		contentType: "application/json",
	            		success: function(d) {
	            			if(d.result) {

								updateSearch();
	            				$.utils.success(d.message);
								//saveWorkHst();
	            				/*
	            				$.utils.successAnd(d.message, function() {
	            					location.href = '/admin/conversation/intent/manage.do';
	            				});
	            				modal.find(".btn.close").click();
	            				search(true);
	            				*/
	            			} else {
	            				$.utils.error(d.message);
	            			}
	            		}
	            	});
	            });

				//var data = {oprMngCode: $("#custCode").val() + "_RCP_" + $("select[name=serviceGroup]").val()};
	            // 인텐트 삭제
	            $(document).on("click", "a[data-role=deleteIntent]", function(e) {
	            	var data = $(this).data();
					//var oprMngCode = $("#custCode").val() + "_RCP_" + $("select[name=serviceGroup]").val();
	            	swal("삭제요청", "삭제하시겠습니까?", "info", {
		                buttons: ["취소", "저장"],
		            }).then(function (ok) {
		                if (ok) {
		                	$.ajax({
		                		url: '<c:url value="/admin/rcp/conversation/intent/delete.do"/>',
		                		type: 'POST',
		                		data: data,
		                		success: function(d) {
		                			if(d.result) {
		                				$.utils.success(d.message);
										//saveWorkHst();
		                				search();
		                			} else {
		                				$.utils.error(d.message);
		                			}
		                		}
		                	});
		                }
		            });
	            });

	            // 인텐트 등록
	            $("button[data-role=enroll]").click(function() {
	            	var modal = $(this).parents(".modal");

	            	// 기본 인텐트 데이터
	            	var serviceGroup = /*$("#custCode").val() + "_RCP_" + */$("select[name=serviceGroup]");
					var custCode = $("#custCode").val();
	            	var intentName = modal.find("input[name=intentName]");
	            	var category = modal.find("select[name=category]");

	            	if(serviceGroup.isBlank()) {
	            		$.utils.warning("서비스를 선택해주세요.");
	            		return false;
	            	}
	            	if(intentName.isBlank()) {
	            		$.utils.warning("인텐트명을 입력해주세요.");
	            		return false;
	            	}
	            	if(modal.find('.err-text').css("display") != "none") {
	            		$.utils.warning("중복된 인텐트 입니다.");
	            	}
	            	if(category.isBlank()) {
	            		$.utils.warning("분류를 선택해주세요.");
	            		return false;
	            	}

	            	var exampleList = new Array();
	            	/*
	            	// 인텐트 예문 데이터 2022.06.28 단건 처리로 변경
	            	var container = modal.find('.border-container');
	            	container.each(function() {
	            		var example = {exampleText: $(this).find("input[name=exampleText]").val()};
	            		exampleList.push(example);
	            	});
	            	*/

	            	// 전송 데이터
	            	var data = {
						serviceGroup: serviceGroup.val(),
						custCode: custCode,
						intentName: intentName.val(),
						category: category.val(),
						exampleList: exampleList
	            	};

	            	$.ajax({
	            		url: '<c:url value="/admin/rcp/conversation/intent/insert.do"/>',
	            		type: "POST",
	            		data: JSON.stringify(data),
	            		contentType: "application/json",
	            		success: function(d) {
	            			//console.log(d);

	            			if(d.result) {
	            				search();
	            				$.utils.success(d.message);

	            				// modal.find(".close").click();
								//saveWorkHst();
	            				// 2022.06.28 먼저 저장한 후에 하단 예문 등록함  intent_enroll_modal
	            				$("#intent_enroll_modal").find(".insert_step1").prop("disabled", true);
	            				$("#intent_enroll_modal").find(".insert_step2").css("display", "");
	            				$("#intent_enroll_modal").css("margin-top", "-250px");

	            				var seq = d.seq;
	            				$("#intent_enroll_modal").find("seq").val(seq);

	            			} else {
	            				$.utils.error(d.message);
	            			}
	            		}
	            	});
	            });

	            $("a[rel=intent_enroll_modal]").click(function() {
	            	var modal = $("#intent_enroll_modal");
	            	modal.find("input:text").val('');
	            	modal.find("select[name=category]").val('').niceSelect('update');
	            	modal.find(".insert-example-list .border-container").remove();
	            	modal.find(".non-content").show();
	            	examples = new Array();

	            	$(".insert_step1").prop("disabled", false);  	// 2022.06.28 추가
	            	$(".insert_step2").css("display", "none");   	// 2022.06.28 추가
	            });

	            $("a[rel=intent_upload_modal]").click(function() {
					for (var i=0; i<oprMngCodeList.length; i++) {
						if (oprMngCodeList[i].serviceGroup == $("select[name=serviceGroup]").val()) {
							fullOprMngCode = oprMngCodeList[i].fullCode;
						}
					}

					$(".target-service-name").text($("select[name=serviceGroup]").find("option:selected").text());
	            });

	            // 파일 선택
	            $("input:file").change(function() {
	            	if($.utils.isBlank($(this).val())) return false;

	            	var file = $(this)[0].files[0];

	            	// 파일 명 validation
	            	var filename = file.name;
	            	if(filename.length+1 > 70) {
	            		$.utils.warning("파일명은 최대 70자까지 허용합니다.");
	            		$(this).val('');
	            		$("input.upload_name").val('');
	            		return false;
	            	}

	            	// 파일 size validation
	            	var max = (1024 * 1024 * 3);
	            	if(file.size > max) {
	            		$.utils.warning("파일은 최대 3MB까지 업로드 할 수 있습니다.");
	            		$(this).val('');
	            		$("input.upload_name").val('');
	            		return false;
	            	}

	            	// 확장자 체크
	            	var ext = filename.substr(filename.lastIndexOf('.') + 1).toLowerCase();
	            	if(ext != "xls" && ext != "xlsx") {
	            		$.utils.warning("업로드는 Excel 파일만 가능합니다.");
	            		$(this).val('');
	            		$("input.upload_name").val('');
	            		return false;
	            	}

	            });

	            // 등록 파일 삭제
	            $("[data-role=deleteFile]").click(function() {
	            	$("input:file").val('');
	            	$("input.upload_name").val('');
	            });

	            // 파일 업로드
	            $("[data-role=uploadFile]").click(function() {
					var img = $(".loading-img");

					img.show();
					img.parent().find("span").text("");

	            	if($.utils.isBlank($("input:file").val())) {
	            		$.utils.warning("파일을 선택해주세요.");
						img.hide()
						img.parent().find("span").text("저장");
	            		return false;
	            	}
	            	// $("form[name=uploadForm] input[name=oprMngCode]").val($("select[name=oprMngCode]").val());
	            	$("form[name=uploadForm] input[name=oprMngCode]").val(fullOprMngCode);
	            	$("form[name=uploadForm] input[name=custCode]").val(fullOprMngCode.split('_')[0]);
					$("form[name=uploadForm] input[name=serviceGroup]").val(fullOprMngCode.split('_')[2]);
	            	$("form[name=uploadForm]").submit();
	            });

	            // 서비스 선택시 안내문구 변경
	            // $("select[name=oprMngCode]").change(function() {
	            $("select[name=serviceGroup]").change(function() {
	            	var txt = $(this).find("option:selected").text();
	            	$(".target-service-name").text(txt);
	            });

	        });

	        /*   // 리스트 검색
	        function search(isModify) {
	        	console.log($("input[name=intentName]").val());
	        	
	        	$.utils.dataTable.getListData({
	        			oprMngCode: $("select[name=oprMngCode]").val(),
	        			category: $("select[name=category]").val(),
	        			intentName: $("input[name=intentName]").val()

	            }, function(d) {
	            	// 수정한 경우 고객사 변경 후 조회 버튼을 누르지 않았을때 기존 리스트 노출을 위함.
	            	$("#intent_update_modal input[name=oprMngCode]").val($("select[name=oprMngCode]").val());
	            	$("#resultTable").renderTable(d.list);
	            	initCategory();
	            });
	        } */

	        function search() {
	        	var serviceGroup = $("select[name=serviceGroup]").val();
				var custCode = $("#custCode").val();

	        	$.ajax({
	        		type: 'post',
	        		async: false,
	        		datatype: 'text',
	        		url: '<c:url value="/admin/rcp/conversation/intent/search.do"/>',
	        		data: {
						serviceGroup: serviceGroup,
						custCode: custCode,
	        			category: $("select[name=category]").val(),
	        			intentName: $("input[name=intentName]").val()
	        		},
	        		success: function(d) {
	        			// 수정한 경우 고객사 변경 후 조회 버튼을 누르지 않았을때 기존 리스트 노출을 위함.
		            	$("#intent_update_modal input[name=oprMngCode]").val($("select[name=oprMngCode]").val());
		            	$("#resultTable").renderTable(d.list);
	        		}
	        	});
	        }

			function updateSearch() {
				var serviceGroup = $("select[name=serviceGroup]").val();
				var custCode = $("#custCode").val();

				$.ajax({
					type: 'post',
					async: false,
					datatype: 'text',
					url: '<c:url value="/admin/rcp/conversation/intent/search.do"/>',
					data: {
						serviceGroup: serviceGroup,
						custCode: custCode,
						category: $("select[name=category]").val(),
						intentName: $("input[name=intentName]").val()
					},
					success: function(d) {
						// 수정한 경우 고객사 변경 후 조회 버튼을 누르지 않았을때 기존 리스트 노출을 위함.
						$("#intent_update_modal input[name=oprMngCode]").val($("select[name=oprMngCode]").val());
						$("#resultTable").renderTable(d.list);
					}
				});
			}

	        // 모달 예문 로드
	        function renderExamples(modalId, d) {
	        	var modal = $("#" + modalId);
	        	modal.find(".border-container").remove();

	        	if(d.length > 0) {
            		for(var i in d) {
            			var item = d[i];
                		var template = $(".example-template").clone().html();
                		template = template.replaceAll("{{exampleText}}", item.exampleText);
                		template = template.replaceAll("{{role}}", "deleteExample");
                		template = template.replaceAll("{{exampleSeq}}", item.seq);
                		modal.find(".content-scroll").append(template);
            		}
            		modal.find(".non-content").hide();
        		} else {
        			modal.find(".non-content").show();
        		}
        		if (!checkPermissionPolicy("rcpconversationintentmanageFull"))
                    $("button[data-role=deleteExample]").hide();
	        }

	        // 예문 추가
	        function addExample(modalId, v) {
	        	var modal = $("#" + modalId);
	        	var template = $(".example-template").clone().html();
        		template = template.replaceAll("{{exampleText}}", v);
        		template = template.replaceAll("{{role}}", "deleteExample");
        		template = template.replaceAll("{{exampleSeq}}", '');
        		$(template).insertAfter(modal.find(".non-content"));
        		modal.find(".non-content").hide();
	        }

	        // 서비스명 초기화
	        function initCategory() {
	        	$.ajax({
	        		url: '<c:url value="/admin/rcp/conversation/intent/category.do"/>',
	        		type: "GET",
	        		data: {
						custCode: $("#custCode").val(),
						serviceGroup: $("select[name=serviceGroup]").val()
					},
		            success: function(d) {
		            	var list = d.categoryList;
		            	var html = '<option value="">선 택</option>';

		            	for(var i in list) {
		            		var item = list[i];
		            		html += '<option value="' + item.minorCode + '">' + item.codeName + '</option>';
		            	}
		            	$("select[name=category]").html(html);
		            	$("select[name=category]").niceSelect('update');
		            },
					error: function (){
						//console.log("error");
					}
	        	});
	        }

			function getOpr() {
				$.ajax({
					type: "GET",
					contentType: "application/json; charset=utf-8",
					datatype: "JSON",
					url: "<c:url value='/adm/menu/oprmng'/>" + "?menuval=rcpconversationintentmanage",
					success: function (data) {
						data.forEach(function (e, f) {
							$('#custCode').val(e.custCode);
							$('#serviceGroup').append("<option value=" + e.serviceGroup + ">" + e.serviceGroupName + "</option>");
							$('#serviceGroup').niceSelect('update');

							oprMngCodeList.push({
								'serviceGroup': e.serviceGroup,
								'fullCode': e.custCode + '_RCP_' + e.serviceGroup
							});

						});
						search();
						initCategory();
					}
				})
			};

			/*function saveWorkHst() {

				var param = {};
				param.actionCode = "0minorCode17";
				param.serviceGroup = $("#serviceGroup option:selected").val();
				param.menuAuth =  "rcpconversationintentmanage";
				param.remark =  "-";

				$.ajax({
					type : "post",
					async : false,
					datatype : "json",
					contentType: "application/json; charset=utf-8",
					url : '<c:url value="/admin/rcp/statistics/monitoring/insert/workHst.do"/>',
					data: JSON.stringify( param )
				});
			}*/

			function fncIntentExcelDown(){
				const req = new XMLHttpRequest();
				const formData = new FormData();

				formData.append('custCode', $("#custCode").val());
				formData.append('category', $("select[name=category]").val());
				formData.append('intentName', $("input[name=intentName]").val());
				formData.append('serviceGroup', $("#serviceGroup").val());

				req.open("POST", '/admin/rcp/conversation/intent/download.do', true);
				req.responseType = "arraybuffer";
				req.onload = function() {
					const arrayBuffer = req.response;
					if (arrayBuffer) {
						var blob = new Blob([arrayBuffer], { type: "application/octetstream" });
						var link=document.createElement('a');
						link.href=window.URL.createObjectURL(blob);
						link.download="excel_intent.xls";
						link.click();
					}
				};
				req.send(formData);
			}
	        
	        function initenroll (){
	        	$("#intent_enroll_modal").find(".insert_step1").prop("disabled", false);
                $("#intent_enroll_modal").find(".err-text").hide();
	        }

	    </script>

		<%-- 컨텐츠 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="#">인텐트 관리</a></li>
	                </ul>
					<%--<a href="#" class="gui-ico">
						<img src="/lib/assets/images/ico-page-tooltip.png" alt="툴팁">
						<div class="info_hover">
							인텐트 관리 페이지 입니다 인텐트 관리 페이지 입니다 인텐트 관리 페이지 입니다 인텐트 관리 페이지 입니다
						</div>
					</a>--%>
	            </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">
	                            <a href="#" class="btn" data-role="search">조회</a>
	                        </div>
	                    </div>
	                </div>
	                <div class="tbl">
	                    <form id="searchInfo">
	                        <table class="search">
	                            <colgroup>
	                                <col width="130px">
									<col width="15%">
	                                <col width="130px">
	                                <col width="130px">
	                                <col>
	                            </colgroup>
	                            <tbody>
	                                <tr>
	                                    <th class="tl">시나리오그룹</th>
	                                    <td class="tl">
	                                        <div class="sel_box">
	                                            <!-- <select class="wide" id="oprMngName" name="oprMngName">
	                                                <option value="">서비스 선택</option>
	                                            </select> -->
												<select class="wide" id="serviceGroup" name="serviceGroup">

				                                </select>
	                                        </div>
	                                    </td>
	                                     <th class="tl">분류</th>
	                                    <td class="tl">
	                                        <div class="sel_box" id="selCategory">
	                                            <select class="wide" id="category" name="category">
				                                    <option value="">서비스 선택</option>
				                                </select>
	                                        </div>
	                                    </td>
	                                     <th class="tl">인텐트 명</th>
										<td class="tl">
											<input type="text" id="intentName" name="intentName" placeholder="인텐트 명">
										</td>
	                                    
	                                </tr>
	                            </tbody>
	                        </table>
	                    </form>
	                </div>
	            </div>
	            <div class="cont_box">
	                <div class="box_title">
	                    <div class="fl">
	                        <h2 class="mt12">인텐트 리스트</h2>
	                    </div>
	                    <div class="btn_wrap fr">
	                        <a id="btnIntentRegistration" href="#" rel="intent_enroll_modal" class="btn line modalLoad">등록</a>
	                        <a id="btnIntentUpload" href="#" rel="intent_upload_modal" class="btn excel modalLoad">업로드</a>
	                        <a id="btnIntentDownload" href="#" onclick="fncIntentExcelDown();" class="btn excel">다운로드</a>
	                    </div>
	                </div>
	                <div class="tbl">
	                    <div id="resultTable_wrapper" class="dataTables_wrapper form-inline dt-bootstrap no-footer">
	                        <table id="resultTable" class="click dataTable no-footer" aria-describedby="resultTable_info" role="grid">
	                            <colgroup>
	                                <col width="70%">
	                                <col width="10%">
	                                <col width="10%">
	                                <col width="10%">
	                            </colgroup>
	                            <thead>
	                                <tr role="row">
	                                    <th class="center" rowspan="1" colspan="1">인텐트명</th>
	                                    <th class="center" rowspan="1" colspan="1">학습 예문 수</th>
	                                    <th class="center" rowspan="1" colspan="1">분류</th>
	                                    <th class="center" rowspan="1" colspan="1">삭제</th>
	                                </tr>
	                            </thead>
	                            <tbody>
	                                <!-- 내용 없을 경우 -->
	                                <!-- <tr>
	                                    <td valign="middle" colspan="4" class="dataTables_empty">No data available in table</td>
	                                </tr> -->

	                                <!-- 내용 있을 경우  -->
	                                <!-- <tr>
	                                    <td class="tl">
	                                        예약@예약가능여부_문의
	                                    </td>
	                                    <td class="center">3</td>
	                                    <td class="center">예약</td>
	                                    <td class="center">
	                                        <a href="#" class="btn grey" onclick=" return false;">삭제</a>
	                                    </td>
	                                </tr> -->
	                            </tbody>
	                        </table>

	                        <div class="clear"></div>
	                    </div>
	                </div>
	            </div>
	        </div>
	    </section>
	     <!--  modal :: 인텐트 생성 팝업-->
	    <div class="modal" id="intent_enroll_modal" tabindex="-1">
	        <div class="modal-dialog modal-lg">
	            <div class="modal_header">
	                <h3>인텐트 등록</h3>
	            </div>
	            <div class="modal_body">
	            	<input type="hidden" name="seq" value="">
	            	<input type="hidden" name="oprMngCode" value="">
	            	<input type="hidden" name="originalName" value="">

	                <div class="modal_cont">
	                    <dl>
	                        <dt>
	                            <h4>
	                                <em class="important">인텐트</em>
	                            </h4>
	                        </dt>
	                        <dd>
	                            <div class="ipt_box">
	                                <input type="text" placeholder="인텐트명을 입력하세요" name="intentName" class="insert_step1">
	                            </div>
	                            <div class="text-danger err-text" style="display: none;">중복된 인텐트 명입니다.</div>
	                        </dd>
	                    </dl>
	                    <!-- 2022.06.28 변경
	                    <dl>
	                        <dt>
	                            <h4>
	                                <em class="">등록 대상 서비스</em>
	                            </h4>
	                        </dt>
	                        <dd>
	                        	<h4 class="target-service-name" style="line-height: 37px; color: #333; font-size: 16px; font-weight: 300;"></h4>
	                        </dd>
	                    </dl>
	                    <dl class="">
	                        <dt>
	                            <h4>
	                                <em class="important">분류</em>
	                            </h4>
	                        </dt>
	                        <dd>
	                            <div class="sel_box" id="">
	                                <select class="wide" name="category">
	                                    <option value="">전 체</option>
	                                </select>
	                            </div>
	                        </dd>
	                    </dl>
	                    -->
	                    <dl class="">
	                        <dt>
	                            <h4>
	                                <em class="important">분류</em>
	                            </h4>
	                        </dt>
	                        <dd>
	                            <!-- 수정/추가 시작-->
	                            <div class="d-flex no-gutters justify-content-between">
	                                <div class="sel_box" id="">
	                                    <select class="wide insert_step1" name="category">
	                                        <option value="">인텐트 분류를 선택하세요</option>
	                                    </select>
	                                    <div class="nice-select wide" tabindex="0">
	                                    	<span class="current">인텐트 분류를 선택하세요</span>
	                                    	<ul class="list">
	                                    		<li data-value="" class="option selected">인텐트 분류를 선택하세요</li>
	                                    	</ul>
	                                    </div>
	                                </div>
	                                <button type="button" class="btn btn-lg insert_step1" data-role="enroll">저장</button>
	                            </div>
	                            <!-- 수정/추가 끝-->
	                        </dd>
	                    </dl>

	                    <dl class="insert_step2" style="display:none">
	                        <dt>
	                            <h4><em class="">예문추가</em></h4>
	                        </dt>
	                        <dd>
	                            <div class="row no-gutters">
	                                <div class="col">
	                                    <div class="ipt_box">
	                                        <input type="text" placeholder="사용자가 입력할 것으로 예상되는 문장을 입력하고 [Enter] 또는 추가 버튼을 누르세요" name="exampleIpt" class="min-height-37px">
	                                    </div>
	                                </div>
	                                <div class="col-auto">
	                                    <button type="button" class="btn btn-lg disabled" data-role="addExample" >+ 추가</button>
	                                </div>
	                            </div>
	                        </dd>
	                    </dl>
	                    <div class="insert_step2" style="display:none">
		                    <div class="row no-gutters align-items-center justify-content-between mt-5">
		                        <div class="col">
		                            <div class="title-sm font-weight-light">예문 목록</div>
		                            <div class="text-gray font-size-14px font-weight-light">다양한 예문을 등록하여 추론문을 높입니다.</div>
		                        </div>
		                        <div class="col-auto">
		                            <div class="search-input">
		                                <button type="button">
		                                    <i class="icon-search" style="top:62%;"></i>
		                                </button>
		                                <input type="text" placeholder="사용자 입력 예문 검색" class="form-control min-height-37px disabled" name="searchUpdateExample">
		                            </div>
		                        </div>
		                    </div>
		                    <div class="content-scroll min mt-3 insert-example-list" style="max-height: 350px;height: auto;min-height: auto;">
		                        <%-- 내용 없을 때 --%>
		                        <div class="non-content" style="display: none;">
		                            <div class="min-height-150px border d-flex justify-content-center align-items-center text-gray font-weight-light font-size-14px">
		                                등록되어 있는 예문이 없습니다.
		                            </div>
		                        </div>
		                    </div>
		              </div>
	                </div>
	            </div>
	            <div class="modal_footer">
	                <div class="btn_wrap fr">
	                    <a href="#" onclick="initenroll();" class="btn grey close">취소</a>
	                    <!-- <a href="#" data-role="enroll" class="btn">저장</a> -->
	                </div>
	            </div>
	            <div class="modal_controller">
	                <a href="#"  onclick="initenroll();" class="close">close</a>
	            </div>
	        </div>
	    </div>
	    <!--  modal :: 인텐트 생성 팝업 end -->

	    <!--  modal :: 인텐트 수정 팝업-->
	    <div class="modal" id="intent_update_modal" tabindex="-1">
	        <div class="modal-dialog modal-lg">
	            <div class="modal_header">
	                <h3>인텐트 수정</h3>
	            </div>
	            <div class="modal_body">
	            	<input type="hidden" name="seq" value="">
	            	<input type="hidden" name="oprMngCode" value="">
	            	<input type="hidden" name="originalName" value="">
	                <div class="modal_cont">
	                    <dl>
	                        <dt>
	                            <h4>
	                                <em class="important">인텐트</em>
	                            </h4>
	                        </dt>
	                        <dd>
	                            <div class="ipt_box">
	                                <input type="text" placeholder="인텐트명을 입력하세요" name="intentName">
	                            </div>
	                            <div class="text-danger err-text" style="display: none;">중복된 인텐트 명입니다.</div>
	                        </dd>
	                    </dl>
	                    <!--
	                    <dl class="">
	                        <dt>
	                            <h4>
	                                <em class="important">분류</em>
	                            </h4>
	                        </dt>
	                        <dd>
	                            <div class="sel_box" id="">
	                                <select class="wide" name="category">
	                                    <option value="">전 체</option>
	                                </select>
	                            </div>
	                        </dd>
	                    </dl>
	                    -->
	                    <dl class="">
	                        <dt>
	                            <h4>
	                                <em class="important">분류</em>
	                            </h4>
	                        </dt>
	                        <dd>
	                            <!-- 수정/추가 시작-->
	                            <div class="d-flex no-gutters justify-content-between">
	                                <div class="sel_box" id="">
	                                    <select class="wide insert_step1" name="category">
	                                        <option value="">인텐트 분류를 선택하세요</option>
	                                    </select>
	                                    <div class="nice-select wide" tabindex="0">
	                                    	<span class="current">인텐트 분류를 선택하세요</span>
	                                    	<ul class="list">
	                                    		<li data-value="" class="option selected">인텐트 분류를 선택하세요</li>
	                                    	</ul>
	                                    </div>
	                                </div>
	                                <button type="button" class="btn btn-lg insert_step1"  data-role="update">저장</button>
	                            </div>
	                            <!-- 수정/추가 끝-->
	                        </dd>
	                    </dl>

	                    <dl>
	                        <dt>
	                            <h4><em class="">예문추가</em></h4>
	                        </dt>
	                        <dd>
	                            <div class="row no-gutters">
	                                <div class="col">
	                                    <div class="ipt_box">
	                                        <input type="text" placeholder="사용자가 입력할 것으로 예상되는 문장을 입력하고 [Enter] 또는 추가 버튼을 누르세요" name="exampleIpt" id="" class="min-height-37px">
	                                    </div>
	                                </div>
	                                <div class="col-auto">
	                                    <button type="button" class="btn btn-lg disabled" data-role="addExample" disabled>+ 추가</button>
	                                </div>
	                            </div>
	                        </dd>
	                    </dl>

	                    <div class="row no-gutters align-items-center justify-content-between mt-5">
	                        <div class="col">
	                            <div class="title-sm font-weight-light">예문 목록</div>
	                            <div class="text-gray font-size-14px font-weight-light">다양한 예문을 등록하여 추론문을 높입니다.</div>
	                        </div>
	                        <div class="col-auto">
	                            <div class="search-input">
	                                <button type="button">
	                                    <i class="icon-search" style="top:62%;"></i>
	                                </button>
	                                <input type="text" placeholder="사용자 입력 예문 검색" class="form-control min-height-37px" name="searchUpdateExample">
	                            </div>
	                        </div>
	                    </div>
	                    <div class="content-scroll min mt-3 update-example-list" style="max-height: 350px;height: auto;min-height: auto;">
	                        <%-- 내용 없을 때 --%>
	                        <div class="non-content" style="display: none;">
	                            <div class="min-height-150px border d-flex justify-content-center align-items-center text-gray font-weight-light font-size-14px">
	                                등록되어 있는 예문이 없습니다.
	                            </div>
	                        </div>
	                    </div>
	                </div>
	            </div>
	            <div class="modal_footer">
	                <div class="btn_wrap fr">
	                    <a href="#" onclick="" class="btn grey close">취소</a>
	                    <!-- <a href="#" data-role="update" class="btn">저장</a> -->
	                </div>
	            </div>
	            <div class="modal_controller">
	                <a href="#" class="close">close</a>
	            </div>
	        </div>
	    </div>
	    <!--  modal :: 인텐트 수정 팝업 end -->

	    <!--  modal :: 인텐트 업로드 안내 팝업-->
	    <div class="modal" id="intent_upload_modal" tabindex="-1">
	        <div class="modal-dialog modal-lg">
	            <div class="modal_header">
	                <h3>인텐트 업로드 안내</h3>
	            </div>
	            <div class="modal_body">
	                <div class="modal_cont">
	                    <div class="text-right">
	                       <a href="/document/intent.xls" class="btn excel" download="인텐트 샘플">샘플 다운로드</a>
	                    </div>

	                    <div class="my-5">
	                        <ul class="dot-list">
	                            <li>업로드는 Excel 파일만 가능합니다.</li>
	                            <li>파일 작성 방법은 [샘플 다운로드] 버튼을 선택하시고 샘플 파일을 다운받아 [작성방법] sheet를 참고해주세요.</li>
	                            <li>파일은 최대 3MB까지 업로드 할 수 있습니다.</li>
	                            <li>파일명은 최대 70자까지 허용합니다.</li>
								<li>파일 내 인텐트는 50개, 인텐트당 예문은 200개까지 허용합니다.</li>
	                        </ul>
	                    </div>

	                    <div class="title-sm">인텐트 파일 업로드</div>
	                    <div class="tbl">
	                        <form id="uploadForm" method="POST" enctype="multipart/form-data" name="uploadForm" action="<c:url value='/admin/rcp/conversation/intent/upload.do'/>">
	                        	<input type="hidden" name="oprMngCode">
	                        	<input type="hidden" name="custCode">
								<input type="hidden" name="serviceGroup">
	                            <table class="search">
	                                <colgroup>
	                                    <col width="130px">
	                                    <col>
	                                </colgroup>
	                                <tbody>
	                                    <tr>
	                                        <th class="tl">시나리오 그룹</th>
	                                        <td class="tl target-service-name"></td>
	                                    </tr>
	                                    <tr>
	                                        <th class="tl">파일선택</th>
	                                        <td class="tl">
	                                            <div class="file_upload">
                                                    <!-- view input -->
                                                    <input class="upload_name" value="파일을 선택해주세요" disabled="disabled">

                                                    <!-- upload input -->
                                                    <input name="upFile" type="file" id="file" class="upload_hidden">
                                                    <label for="file" class="btn line">파일선택</label>

                                                    <button type="button" class="btn ml-1" data-role="deleteFile">삭제</button>
	                                            </div>
	                                        </td>
	                                    </tr>
	                                </tbody>
	                            </table>
	                        </form>
	                    </div>
	                </div>
	            </div>
	            <div class="modal_footer">
	                <div class="btn_wrap fr">
	                    <a href="#" onclick="" class="btn grey close">취소</a>
	                    <a href="#" class="btn" data-role="uploadFile">
							<span>저장</span>
							<img class="loading-img" alt="loading" src="/images/loading.gif" style="display: none;">
						</a>
	                </div>
	            </div>
	            <div class="modal_controller">
	                <a href="#" class="close">close</a>
	            </div>
	        </div>
	    </div>
	    <!--  modal :: 인텐트 업로드 안내 end -->


	    <div class="clone-box hide">
		    <!-- 예문 템플릿 -->
		    <div class="example-template">
		    	<div class="border-container">
		    		<input type="hidden" name="exampleText" value="{{exampleText}}">
		    		<input type="hidden" name="exampleSeq" value="{{exampleSeq}}">
		            <div class="row no-gutters align-items-center justify-content-between">
		                <div class="col">
		                    <div class="font-weight-light font-size-14px my-2">{{exampleText}}</div>
		                </div>
		                <div class="col-auto">
		                	<%-- data-example-seq="{{exampleSeq}}" --%>
		                    <button type="button" class="btn red" data-role="{{role}}">삭제</button>
		                </div>
		            </div>
		        </div>
		    </div>
	    </div>

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

	</body>
</html>
