$(document).ready(function() {

	initTag();

	$('select[name=nodeType]').each(function(index, item) {
		fncNodeType($(this)[0]);
		// SPLIT 이였다가 바뀐경우 숨김
	});

	$(document).on('change', 'select[name=nodeType]', function() {
		if ($(this).val() == "SLOT") {
			var $inputIN = $("input[name=inputIN]:not([value='0']):not([value=''])").val();
			initSlot($inputIN);
		}
		if ($(this).val() == "API") {
			initAPI();
		}
	});


	$('#btnMoveUp').on('click', function() {
		var index = $('input[name=seqNo]:checked').closest('li').index();
		var $li = $('input[name=seqNo]:checked').closest('li')
		$li.prev().before($li);
	});

	$('#btnMoveDown').on('click', function() {
		var index = $('input[name=seqNo]:checked').closest('li').index();
		var $li = $('input[name=seqNo]:checked').closest('li')
		$li.next().after($li);
	});

});

function refresh() {
	var inputSeq = $('#input[name=seq]');
	if (inputSeq.val() == null || inputSeq == '') {
		$.ajax({
			type: "post",
			async: false,
			datatype: "text",
			url: '/admin/conversation/scenario/selectScenarioMaster.do',
			data: {
				serviceCode: $('input[name=serviceCode]').val(),
				scenarioName: $('input[name=scenarioName]').val()
			}, success: function(data) {
				$('#input[name=seq]').val();
			}
		});

	}
	$('#reloadForm').attr("method", "post");
	$('#reloadForm').attr("action", "/admin/conversation/scenario/edit.do");
	$('#reloadForm').submit();
}


function fncNodeType(element, type) {
	var value = element.value;
	var $sub = $(element).closest('li').find('.addments')
	var li = $(element).closest('li')

	var nodeType = $('select[name=nodeType]').not(':disabled');
	var arr = nodeType.map(e => nodeType.eq(e).val()).get();
	var cnt = arr.filter(e => 'INTENT' == e).length;
	if (cnt > 1) {
		$.utils.error('이미 중복된 인텐트입니다.');
		$(element).closest('li').find('select[name=nodeType]').val('');
	};

	//initTag(element);

	switch (value) {
		case "INTENT":
			disabledTF(li, 'intent');
			intentMaster(element);
			$sub.hide();
			//inputMent(element);
			break;
		case "SLOT":

			/*
			disabledTF(li, 'slot');
			slotParam(element, type);
			$sub.hide();
			*/

			//inputMent(element);
			//inputNQC(element);
			break;
		case "SPLIT":
			disabledTF(li, 'split');
			if ($sub.length > 0) $sub.show();
			else fncAddSubList(element);
			break;
		case "API":

			/*
			disabledTF(li, 'api');
			api(element);
			$sub.hide();
			*/
			break;
		case "SPEAK":
			disabledTF(li, 'speak');
			$sub.hide();
			//inputMent(element);
			break;
		default:
			$sub.hide();
			break;
	}

}

function disabledTF(li, className) {
	li.find(`.${className}`).prop('disabled', false);
	li.find('.elements').not(`.${className}`).prop('disabled', true).val('');
	li.find('select').niceSelect('update');
}

// 멘트 input value 넣기
function inputMent(element) {
	var inputHidden = $(element).closest('li').find('input[name=inputMent]');
	var input = $(element).closest('li').find('input[name=nodeMent]');

	var value = inputHidden.val();
	input.val(value);
}

// 질의횟수 input value 넣기
function inputNQC(element) {
	var inputHidden = $(element).closest('li').find('input[name=nodeQstCnt]');
	var input = $(element).closest('li').find('input[name=nodeMent]');

	var value = Number(inputHidden.val());
	input.val(value);
}

// select, input 초기화
function initTag(element) {
	//var $select = $(element).closest('li').find('select[name=slotParamSeq], select[name=intentSeq], select[name=apiName]');
	var selects = $('select[name=slotParamSeq], select[name=intentSeq], select[name=apiName]');
	selects.html('');
	selects.append('<option value="">데이터 선택</option>');
	selects.niceSelect('update');

	//var $input = $(element).closest('li').find('input[name=nodeMent], input[name=nodeQstCnt]');
	//$input.val('');
}

function initAPI() {
	// function api 대응
	$.ajax({
		type: "post",
		async: false,
		datatype: "text",
		url: '/admin/conversation/scenario/selectAPI.do',
		data: {
			serviceCode: $('input[name=serviceCode]').val()
		},
		success: (function(data) {
			$("select[name=nodeType] option[value='API']:selected").parents("li").find("select[name=apiName]").each(function(idx, e) {
				var $li = $(this).parents("li");
				$inputAPI = $li.find("[name=inputAPI]").val();
				disabledTF($li, 'api');

				$(e).html('');
				$(e).append('<option value="">데이터 선택</option>');
				for (var i of data.list) {
					var selected = $inputAPI == i.minorCode ? 'selected' : '';
					var option = `<option value="${i.minorCode}" ${selected}>${i.description}</option>`
					$(e).append(option);
				}

				// $sub.hide 대응
				$li.find('.addments').hide();
				$(e).niceSelect('update');
			});
		})
	});
}

// 인텐트 로딩 후 슬롯 초기화
function initSlot($inputIN) {
	// function slotParam 대응
	$.ajax({
		type: "post",
		async: false,
		datatype: "text",
		url: '/admin/conversation/scenario/selectSlotParam.do',
		data: {
			serviceCode: $('input[name=serviceCode]').val(),
			intentSeq: $inputIN
		},
		success: (function(data) {
			$("select[name=nodeType] option[value='SLOT']:selected").parents("li").find("select[name=slotParamSeq]").each(function(idx, e) {
				var $li = $(this).parents("li");
				var $inputPN = $li.find("input[name=inputPN]");
				disabledTF($li, 'slot');

				$(e).html('');
				$(e).append('<option value="">데이터 선택</option>');
				for (var i of data.list) {
					var selected = Number($inputPN.val()) == i.seq ? 'selected' : '';
					var option = `<option value="${i.seq}" ${selected}>${i.paramName}</option>`;
					$(e).append(option);
				}
				//$inputPN.val('')

				// $sub.hide 대응
				$li.find('.addments').hide();
				$(e).niceSelect('update');
			});

		})
	});
}


// TB_SLOT_PARAMETER
function slotParam(element, type) {
	var select = $('select[name=slotParamSeq]').not(':disabled');
	if (type != undefined) {
		select = $(element).closest('li').find('select[name=slotParamSeq]');
	};
	var $inputIN = $('select[name=intentSeq]').not(':disabled').val();

	select.each(function(i, e) {
		var $inputPN = $(this).prev().val();

		$.ajax({
			type: "post",
			async: false,
			datatype: "text",
			url: '/admin/conversation/scenario/selectSlotParam.do',
			data: {
				serviceCode: $('input[name=serviceCode]').val(),
				intentSeq: $inputIN
			},
			success: (function(data) {
				$(e).html('');
				$(e).append('<option value="">데이터 선택</option>');
				for (var i of data.list) {
					var selected = Number($inputPN) == i.seq ? 'selected' : '';
					var option = `<option value="${i.seq}" ${selected}>${i.paramName}</option>`
					$(e).append(option);
				}
				$(e).niceSelect('update');
				$(this).prev().val('')
			})
		});

	});

	select.niceSelect('update');

}

function selectParam(ele, inputPN) {

	$.ajax({
		type: "post",
		async: false,
		datatype: "text",
		url: '/admin/conversation/scenario/selectSlotParam.do',
		data: {
			serviceCode: $('input[name=serviceCode]').val(),
			intentSeq: $inputIN
		},
		success: (function(data) {
			// console.log($(ele))
			$(ele).html('');
			$(ele).append('<option value="">데이터 선택</option>');
			for (var i of data.list) {
				// console.log(i);
				var selected = Number(inputPN) == i.seq ? 'selected' : '';
				var option = `<option value="${i.seq}" ${selected}>${i.paramName}</option>`
				$(ele).append(option);
			}
			$(ele).niceSelect('update');
		})
	});
}

// TB_INTENT_MASTER
function intentMaster(element) {
	var $selectIn = $(element).closest('li').find('select[name=intentSeq]');
	var $inputIN = $(element).closest('li').find('input[name=inputIN]').val();

	$.ajax({
		type: "post",
		async: false,
		datatype: "text",
		url: '/admin/conversation/scenario/selectIntentMaster.do',
		data: {
			serviceCode: $('input[name=serviceCode]').val()
		},
		success: (function(data) {
			$selectIn.html('');
			$selectIn.append('<option value="">데이터 선택</option>');
			for (var i of data.list) {
				var selected = Number($inputIN) == i.seq ? 'selected' : '';
				var option = `<option value="${i.seq}" ${selected}>${i.intentName}</option>`
				$selectIn.append(option);
			}
			$selectIn.niceSelect('update');
			initSlot($inputIN);
			initAPI();

		})
	});
}

// API
function api(element) {
	var $selectAPI = $(element).closest('li').find('select[name=apiName]');
	var $inputAPI = $(element).closest('li').find('input[name=inputAPI]').val();

	$.ajax({
		type: "post",
		async: false,
		datatype: "text",
		url: '/admin/conversation/scenario/selectAPI.do',
		data: {
			serviceCode: $('input[name=serviceCode]').val()
		},
		success: (function(data) {
			$selectAPI.html('');
			$selectAPI.append('<option value="">데이터 선택</option>');
			for (var i of data.list) {
				var selected = $inputAPI == i.minorCode ? 'selected' : '';
				var option = `<option value="${i.minorCode}" ${selected}>${i.description}</option>`
				$selectAPI.append(option);
			}
			$selectAPI.niceSelect('update');
		})
	});
}

// SPLIT, + 시 추가되는 서브 노드
function fncAddSubList(element) {

	//var $addments = $(element).closest('.addments').clone();
	//$addments.find('select, input').val('')
	var $addments = `<div class="addments">
	<div class="row no-gutters align-items-center mentsBox subMents" data-item-code="">
		<div class="col-auto stack">
			<i class="xi-subdirectory-arrow"></i>
		</div>

		<div class="col-auto min-width-50px ml-4 text-right">조건</div>
		<div class="col-3 ml-4">
			<input type="text" name="splitNodeCondition" value="" style="width: 100%; margin: 0;">
		</div>
		<div class="col-auto min-width-50px ml-4 text-right">멘트</div>
		<div class="col ml-4">
			<div class="row no-gutters">
				<div class="col">
					<input type="text" name="splitNodeMent" value="">
				</div>

			</div>
		</div>
		<div class="col-auto min-width-50px ml-4 text-right">다음노드</div>
		<div class="col-1 ml-4">
			<input type="text" name="splitNextNode" value="" style="width: 100%; margin: 0;">
		</div>
			<div class="col-auto ml-2">
					<button type="button" class="mentBtnAdd extraBox btn-outline-primary ment_btn" onclick="fncAddSubList(this);">+</button>
				</div>
				<div class="col-auto ml-2">
					<button type="button" class="mentBtnDel btn-outline-danger ment_btn" onclick="fncDelSubList(this);">-</button>
				</div>


	</div></div>`;

	var $li = $(element).closest('li')
	$li.append($addments)
	$('.sel_box select').niceSelect();
}

// 서브 노드 삭제
function fncDelSubList(element, seq) {

	var $addments = $(element).closest('.addments');
	var $yn = $(element).closest('.addments').find('input[name=useYn]').val();

	if ($yn == undefined) {
		$addments.remove();
	} else {
		$addments.find('input[name=useYn]').val('N');
		$addments.hide();
	}

}

// 노드 추가
function fncAddNode() {
	var isEmpty = $('.tbody > li').length > 0 ? false : true;

	var code = 1;
	if (isEmpty) {
		$('#emptyTable').remove();
		$('.tbody').html('');
	} else {
		var arr = new Array();
		$('input[name=nodeCode]').each(function(item, index) {
			arr.push($(this).val());
		});
		// 노드코드중 가장 큰 숫자 + 1
		code = Math.max(...arr) + 1;
	}

	code = String(code).padStart(4, '0');

	var $li = `<li class="ctLine">
	<div class="row no-gutters boder-b-1 align-items-center">
		<div class="col">
			<div class="rdo-group">
				<div class="rdo_box">
					<input id="seqNo_${code}" name="seqNo" class="rdo-tbl-slt" type="radio" value="">
					<label for="seqNo_${code}"></label>
				</div>
			</div>
		</div>
		<div class="col-1 border-left-1">
			<input type="text" name="nodeCode" value="${code}" readonly>
		</div>
		<div class="col-1 border-left-1">
			<input id="itemName_0" name="nodeName" type="text" value="">
		</div>
		<div class="col-1 border-left-1">
			<div class="sel_box">
				<select name="nodeType" class="wide" onchange="fncNodeType(this, 'slot');">
					<option value="">데이터 선택</option>
					<option value="INTENT">INTENT</option>
					<option value="SLOT">SLOT</option>
					<option value="SPLIT" >SPLIT</option>
					<option value="API">API</option>
					<option value="SPEAK">SPEAK</option>
				</select>
			</div>
		</div>
		<div class="col-1 border-left-1">
			<div class="sel_box">
				<input type="hidden" name="inputPN" value="">
				<select name="slotParamSeq" class="wide elements slot">
					<option value="">데이터 선택</option>
				</select>
			</div>
		</div>
		<div class="col-4 border-left-1">
			<!-- 멘트 -->
			<input name="inputMent" type="hidden" value="">
			<input name="nodeMent" type="text" class="elements intent slot speak" value="">
		</div>
		<div class="col border-left-1" style="min-width: 70px;">
			<!-- 질의횟수 -->
			<input name="inputNQC" type="hidden" value="">
			<input name="nodeQstCnt" type="number" class="text-center elements slot" value="">
		</div>
		<div class="col-1 border-left-1">
			<!-- 다음노드 -->
			<input type="text" name="nextNode" class="elements intent slot api speak" value="">
		</div>
		<div class="col-1 border-left-1">
			<div class="sel_box">
				<input type="hidden" name="inputIN" value="">
				<select name="intentSeq" class="wide elements intent" onchange="slotParam(this);">
					<option value="">항목 선택</option>
				</select>
			</div>
		</div>
		<div class="col-1 border-left-1">
			<div class="sel_box">
				<input type="hidden" name="inputAPI" value="">
				<select name="apiName" class="wide elements api">
					<option value="">항목 선택</option>
				</select>
			</div>
		</div>
	</div></li>`;

	$('.tbody').append($li);
	$('.sel_box select').niceSelect();
}

// 노드 삭제
function fncDelNode() {
	var seq = $('input[name=seqNo]:checked').val();
	//$.utils.confirm('삭제하시겠습니까?', result);

	var $li = $('input[name=seqNo]:checked').closest('li');

	var $yn = $li.find('input[name=nodeUseYn]').val();

	if ($yn == undefined) {
		$li.remove();
	} else {
		$li.find('select[name=nodeType]').prop('disabled', true);
		$li.find('select[name=intentSeq]').prop('disabled', true);
		$li.find('input[name=nodeUseYn]').val('N');
		$li.hide();
	}
}


// 취소 -> 시나리오관리 화면
function fncSave() {
	var scenarioName = $('input[name=scenarioName]').val();
	if (scenarioName != null && scenarioName != '') {
		try {
			var nodeArr = fncNodeArr();
			var spliArr = fncSplitArr();
			saveScenario(nodeArr, spliArr);
		} catch (err) {
			$.utils.info('필수항목을 입력해주세요');
		}

	} else {
		$.utils.info('시나리오명을 입력해주세요.');
	}
}

var required = {
	'INTENT': ['intentSeq'],
	'SLOT': ['slotParamSeq', 'nodeMent', 'nodeQstCnt'],
	'SPLIT': [],
	'API': ['apiName'],
	'SPEAK': ['nodeMent']
}

function fncNodeArr() {

	var nodeArr = new Array();
	$('.tbody > li').each(function(index, item) {
		var qst = $(this).find('input[name=nodeQstCnt]').val();
		var objNode = new Object();
		objNode.seq = $(this).find('input[name=seqNo]').val();
		objNode.nodeCode = $(this).find('input[name=nodeCode]').val();
		objNode.nodeName = $(this).find('input[name=nodeName]').val();
		objNode.nodeType = $(this).find('select[name=nodeType]').val();
		objNode.slotParamSeq = Number($(this).find('select[name=slotParamSeq]').val());
		objNode.nodeMent = $(this).find('input[name=nodeMent]').val();
		objNode.nodeQstCnt = Number(qst);
		objNode.nextNode = $(this).find('input[name=nextNode]').val().trim();
		objNode.intentSeq = Number($(this).find('select[name=intentSeq]').val());
		objNode.apiName = $(this).find('select[name=apiName]').val();
		objNode.nodeOrder = index + 1;
		objNode.useYn = $(this).find('input[name=nodeUseYn]').val();
		nodeArr.push(objNode);

		for (var i of required[objNode.nodeType]) {
			if ((objNode[i] == '' || objNode[i] == null) && objNode.useYn != 'N') {
				throw InputException($(this), i);
			}
		}
	});
	return nodeArr;
}

function fncSplitArr() {

	// 서브노드
	var splitArr = new Array();
	$('.tbody > li > .addments').each(function(index, item) {
		var objSplit = new Object();
		var condition = $(this).find('input[name=splitNodeCondition]').val();
		var ment = $(this).find('input[name=splitNodeMent]').val();
		objSplit.seq = $(this).find('input[name=splitSeq]').val();
		objSplit.nodeSeq = $(this).parent().find('input[name=seqNo]').val();
		objSplit.nodeCode = $(this).parent().find('input[name=nodeCode]').val();
		objSplit.nextNode = $(this).find('input[name="splitNextNode"]').val();
		objSplit.condition = `${condition}`;
		objSplit.ment = `${ment}`;
		objSplit.useYn = $(this).find('input[name=useYn]').val();
		if (objSplit.nextNode != null || objSplit.condition != '' || objSplit.ment != '') {
			splitArr.push(objSplit);
		}
	});
	return splitArr;
}



function saveScenario(nodeArr, splitArr) {

	var scenarioName = $('input[name=scenarioName]').val();

	var dup = duplicateSN();
	if (!dup) {
		$.utils.error('이미 중복된 시나리오명입니다.');
		$('input[name=scenarioName]').css('background', '#ffd7c0').focus();
		return false;
	} else {

		$.ajax({
			type: "post",
			async: false,
			datatype: "text",
			url: '/admin/conversation/scenario/saveScenarioNodeList.do',
			data: {
				seq: $('input[name=seq]').val(),
				scenarioName: scenarioName,
				serviceCode: $('input[name=serviceCode]').val(),
				scenarioNode: JSON.stringify(nodeArr),
				scenarioSplit: JSON.stringify(splitArr)
			}, success: function(data) {
				if (data.result) {
					$.utils.successAnd('정상적으로 저장되었습니다.', goBack);

				} else {
					$.utils.warning('저장 실패');
				}

			}
		});
	}


}

function goBack() {
	var serviceCode = $('input[name=serviceCode]').val();
	var custCode = $('input[name=custCode]').val();
	var obj = {
		serviceCode,
		custCode
	};
	// console.log(obj);

	var form = $('<form>');
	form.attr("method", "post");
	form.attr("action", "/admin/conversation/scenario/manage.do");

	$.each(obj, function(key, value) {
		var field = $('<input>');
		field.attr("type", "hidden");
		field.attr("name", key);
		field.attr("value", value);
		form.append(field);
	});

	$(document.body).append(form);
	form.submit();
}
function InputException(element, name) {

	var tagName = element.find(`[name=${name}]`);
	tagName.focus();
	tagName.find('select').niceSelect('update');
	/*	element.find(`select, input, .nice-select`).not(`[name=${name}]`).css('background', '#fff');*/
	if (tagName.next().hasClass('nice-select')) {
		tagName.next().css('background', '#ffd7c0');
	} else {
		tagName.css('background', '#ffd7c0');
	}
}

function fncCancel() {
	$.utils.confirm(`확인버튼을 누르시면 기존에 작업한 내용은 저장되지 않습니다.\n시나리오 관리 화면으로 이동하시겠습니까?`, goBack);
}

function duplicateSN() {
	var serviceCode = $('input[name=serviceCode]').val();
	var custCode = $('input[name=custCode]').val();
	var scenarioName = $('input[name=scenarioName]').val();
	var seq = $('input[name=seq]').val();

	var arr = new Array();
	$.ajax({
		type: 'post',
		async: false,
		datatype: 'text',
		url: '/admin/conversation/scenario/scenarioList.do',
		data: {
			custCode: custCode,
			serviceCode: serviceCode,
			scenarioName: ''
		},
		success: function(data) {
			for (d of data.list) {
				var obj = {
					seq: d.seq,
					scenarioName: d.scenarioName
				}
				arr.push(obj);
			}
		}
	});

	var obj = {
		seq: '',
		scenarioName: scenarioName
	}

	if (seq == '' || seq == undefined) arr.push(obj);
	else {
		for (var i in arr) {
			if (arr[i].seq == seq) arr[i].scenarioName = scenarioName;

		}
	}

	var cnt = arr.filter(e => scenarioName == e.scenarioName).length;

	if (cnt > 1) return false;
	else return true;
}
