var options="";
var k=0;
$(document).ready(function() {

	// 고객사 목록
	fncRetrieveOprMng($("#custCode"));

	$("#custCode").on('change', function() {
		fncRetrieveOprMng($(this));
	});
	
	//그롭 옵션만들기
	var custCode = $("#selectCustName").val();
	var serviceCode = $("#oprMngName option:selected").val();
	$.ajax({
		url: '/admin/conversation/dictionary/GroupNameList.do',
		type: "get",
		data: {
			custCode: custCode,
			serviceCode: serviceCode
		},
		success: function(data) {
			var list = data.list;
			for (var i of list) {
				options+= `<option value="${i.seq}">${i.groupName}</option>`;
			}
			
		}
	});
	//
	
	var opts = {
		columns: [{
			data: "groupName"
		}, {
			data: "repWord"
		}, {
			data: "dictionaryWords"
		},
		{
			data: "seq"
		},
		{
			data: "groupSeq"
		},
		{
			data: "dictionarySeqs"
		},],
		columnDefs: [{
			"defaultContent": "-",
			"targets": "_all",
			"className": "center"
		},
		{
			targets: 0,
			render: function(data, type, row, index) {
				var val = `value="${data}"`;
				if (data == undefined) val = '';
				return `<div class="sel_box" id="sel_box${index['row']}">
				<select class="wide" id="${index['row']}-group" name="groupName">
				</select>
				</div>`;
			}
		},
		{
			targets: 1,
			render: function(data, type, row, index) {
				var val = `value="${data}"`;
				if (data == undefined) val = '';
				return `<input name="repWord" type="text" id="${index['row']}-rep" ${val}>`;
			}
		},
		{
			targets: 2,
			render: function(data, type, row, index) {
				var val = `value="${data}"`;
				if (data == undefined) val = '';

				return `<div class="row no-gutters align-items-center">
				<div class="col">
					<div class="tag-input-area">
					<input type="text" placeholder="용어 입력 후 엔터를 눌러주세요" name="dictionaryWords" id="${index['row']}-dictionary" class="tag-input" ${val} >
					</div>
				</div>
				<div class="col-auto pl-2">
					<button type="button" class="btn grey" onclick="fnDeleteList('${row.seq}', this);">삭제</button>
				</div>
				</div>`;
			}
		},
		{
			targets: 3,
			visible: false
		},
		{
			targets: 4,
			visible: false
		},
		{
			targets: 5,
			visible: false
		}],
		createdRow: function(row, data, index, meta) {
			//$(`#${index}-group`).html('');
	//$(`.dictionary_list`).html('');
	// $(`#${index}-group`).append(options);
	//$(`#${index}-group`).niceSelect('update');
	//$(`#${index}-group`).val(data.groupSeq)
			initGroupName(index, data.groupSeq);
			// console.log();
		},
		drawCallback: function(settings) {
			$(`.sel_box select`).addClass('nice-select');
			var api = this.api();
			var row = api.rows()[0];
			var data = api.rows().data();
			 for (var r = 0; r < row.length; r++) {
				//$(`#${r}-group`).html('');
	//$(`.dictionary_list`).html('');
	//$(`#${r}-group`).append(options);
	//$(`#${r}-group`).niceSelect('update');
	//$(`#${r}-group`).val(data[r].groupSeq);
	if(k==0){
		initGroupName(r, data[r].groupSeq);
	}
	if(k!==0){
		if((r<row.length-k)){
		initGroupName(r, data[r+k].groupSeq);
	}else{
		initGroupName(r,data[row.length-1-r].groupSeq);
	}
	}
			}

			$('.tag-input').tagsinput({
				trimValue: true,
				'height': '100%',
				'width': '100%',
				onTagExists: function(item, $tag) {
					$.utils.warning("중복된 용어입니다.");
					$tag.hide().fadeIn();
				}
			});

			// 2022.06.28 개별 단건 저장하기
			$('.bootstrap-tagsinput').find('input').on("keyup", function() {
				if (event.keyCode === 13) {
					var idiv = $(this).closest("tr").find('.sel_box select').attr('id');
					var idx = idiv.replace('-group', '')
					fncSaveList_one("I", idx, "");
				}
			});

			// 2022.06.28 단건 삭제
			$("span[data-role=remove]").on("click", function() {
				var idiv = $(this).closest("tr").find('.sel_box select').attr('id');//yoo추가
				var idx = idiv.replace('-group', '')//yoo추가
				//var idx = $(this).closest("tr").index();
				var text = $(this).parent().text();
				var textSum = "";
				$(this).closest("div").find(".label-info").each(function() {
					var t = $(this).text();
					if (t != text) {
						textSum += t + ",";
					}
				});
				if (textSum.length > 0) textSum = textSum.substring(0, textSum.length - 1);
				fncSaveList_one("D", idx, textSum);
		
			});
		},
	}


	$.utils.dataTable.init('/admin/conversation/dictionary/dictionaryList.do', opts);
	search();
});

function groupNameChange() {

	var idx = $(this).closest("tr").index();
	var idiv = $(`#${idx}-group`).val();

	if (idiv != null) {
		fncSaveList_one("I", idx, "");
	} else {

		for (i = 10; $(`#${i}-group`).val() != null; i += 10) {
			fncSaveList_one("I", idx + i, "");
		}
	}
	// console.log(idx);

};

function fn_change_tag() {
	alert("tag");
}

// 서비스명
function fncServiceList() {
	var param = $("#selectCustName").val();

	$.ajax({
		type: "post",
		async: false,
		datatype: "text",
		url: "/admin/system/project/selectServiceNameList.do",
		data: {
			param: param
		},
		success: (function(data) {
			$("#oprMngName").html('')
			for (var k in data.nMap) {

				var obj = data.nMap[k];
				var serviceCode = obj.serviceCode;
				var serviceName = obj.serviceName;

				var laborOption = `<option value="${serviceCode}">${serviceName}</option>`;
				$("#oprMngName").append(laborOption);
			}
		})
	});
	$('#oprMngName').niceSelect('update');
}

// 조회
function fncSendData() {
	search();
}

function search() {
	var repWord = $('#oprMngName1').val();
	var custCode = $("#selectCustName").val();
	var serviceCode = $("#oprMngName option:selected").val();

	$.utils.dataTable.getListData({
		custCode: custCode,
		serviceCode: serviceCode,
		repWord: repWord
	}, function(data) {
		$("#resultTable").renderTable(data.list);
	});

	dictionaryGroup();
}

function initGroupName(index, groupSeq) {
	$(`#${index}-group`).html('');
	$(`.dictionary_list`).html('');
	$(`#${index}-group`).append(options);
	$(`#${index}-group`).val(groupSeq);
	$(`#${index}-group`).niceSelect('update');
	
	
/** 	var custCode = $("#selectCustName").val();
	var serviceCode = $("#oprMngName option:selected").val();
	$.ajax({
		url: '/admin/conversation/dictionary/GroupNameList.do',
		type: "get",
		data: {
			custCode: custCode,
			serviceCode: serviceCode
		},
		success: function(data) {
			var list = data.list;
			$(`#${index}-group`).html('')
			for (var i of list) {
				var selected = groupName == i.groupName ? 'selected' : '';
				var option = `<option value="${i.seq}" ${selected}>${i.groupName}</option>`;
				$(`#${index}-group`).append(option);
			}
			$(`#${index}-group`).niceSelect('update');
		}
	});
	*/
}

// 삭제
function fnDeleteList(data, t) {
	if (data == 'undefined' || data == 'null') {
		var td = $('#resultTable').DataTable();
		var tr = t.parentNode.parentNode.parentNode.parentNode;
		td.row(tr).remove().draw();
	} else {

		$.ajax({
			type: 'post',
			async: false,
			datatype: 'text',
			url: '/admin/conversation/dictionary/deletedictionary.do',
			data: { seq: data },
			success: function(data) {
				// console.log(data.result)
				if (data.result) {
					$.utils.success('정상적으로 삭제되었습니다.');
				} else {
					$.utils.warning("중복된 인텐트 입니다.");
				}
				search();
			}
		});

	}
}

// table row 추가버튼 클릭시
function fncAdd() {
	k++;
	/*
	var td = $('#resultTable').DataTable();
	td.row.add({
		"groupName": '',
		"repWord": '',
		"dictionaryWords": '',
		"seq": null
	}).draw();
	*/
	
	// 2022.07.05 수정
	var table = $("#resultTable").dataTable() //not DataTable() function
	var dt = table.api();
	var data = dt.rows().data();
	var obj = {
		"groupName": '',
		"repWord": '',
		"dictionaryWords": '',
		"seq": null
	}
	dt.row.add(obj);
	var aiDisplayMaster = table.fnSettings()["aiDisplayMaster"];
	var irow = aiDisplayMaster.pop();
	aiDisplayMaster.unshift(irow);
	dt.draw();
	/** 
	var row = dt.rows()[0];
	for (var r = 0; r < row.length; r++) {
		initGroupName(r, data[r].groupSeq);
	}
*/
}

var repArr = new Array();


// 중복확인
function fncDupCheck(data) {
	var custCode = $("#selectCustName").val();
	var serviceCode = $("#oprMngName option:selected").val();

	var result = false;

	var repArr = new Array();
	$('input[name=repWord]').each(function(index, item) {
		repArr.push($(item).val());
	});
	const setRep = new Set(repArr);

	var dictionaryArr = new Array();
	$('input[name=dictionaryWords]').each(function(index, item) {
		dictionaryArr.push(...$(item).tagsinput('items'));
	});
	const setDic = new Set(dictionaryArr);

	var rs = repArr.filter(it => data.dictionaryWords.includes(it));

	if (repArr.length != setRep.size) {
		$.utils.warning("중복된 대표어입니다.");
	} else if (rs.length > 0) {
		$.utils.error('이미 대표어로 등록된 키워드입니다.');
	} else if (dictionaryArr.length != setDic.size) {
		$.utils.warning("중복된 용어입니다.");
	} else {

		$.ajax({
			type: 'post',
			async: false,
			traditional: true,
			datatype: 'JSON',
			url: '/admin/conversation/dictionary/dupCheck.do',
			data: {
				custCode: custCode,
				serviceCode: serviceCode,
				repWord: data.repWord,
				groupSeq: data.groupSeq,
				dictionaryWords: JSON.stringify(data.dictionaryWords),
				seq: data.seq
			}, success: function(data) {
				result = data.result;
				if (!data.result) {
					$.utils.error(data.msg);
				}
			}
		});
	}
	return result;
}


// 저장
function fncSaveList() {
	var table = $('#resultTable').DataTable();
	var rdata = table.rows().data();

	var tdArr = new Array();
	for (var i = 0; i < rdata.length; i++) {
		var group = $(`#${i}-group`).val();
		var rep = $(`#${i}-rep`).val();
		var dictionaryArr = $(`#${i}-dictionary`).tagsinput('items');
		var data = { "groupSeq": group, "repWord": rep, "dictionaryWords": dictionaryArr, "seq": rdata[i].seq };

		var tr = $('#resultTable tbody tr').get(i)
		table.row(tr).data(data).draw();
		// console.log(data);

		if (group != null && rep != null && dictionaryArr != null) {
			tdArr.push(data);
			var result = fncDupCheck(data);
			if (result) {
				$.ajax({
					type: 'post',
					async: false,
					traditional: true,
					datatype: 'JSON',
					url: '/admin/conversation/dictionary/saveDictionaryList.do',
					data: {
						groupSeq: group,
						repWord: rep,
						dictionaryWords: JSON.stringify(dictionaryArr),
						seq: rdata[i].seq
					}, success: function(data) {
						if (data.result) {
							$.utils.success('정상적으로 저장되었습니다.');
						} else {
							$.utils.warning("저장 실패");
						}
					}
				});

			} else {
				break;
			}
		}

	}
	// console.log("이겁니다.")

	$('select[name=groupName]').niceSelect();
/*	$('select[name=groupName]').niceSelect('update');*/
	search();
}

var groupArray = new Array();
function dictionaryGroup() {

	var custCode = $("#selectCustName").val();
	var serviceCode = $("#oprMngName option:selected").val();
	$(`.dictionary_list`).html('');

	$.ajax({
		url: '/admin/conversation/dictionary/GroupNameList.do',
		type: "get",
		data: {
			custCode: custCode,
			serviceCode: serviceCode
		},
		success: function(data) {
			var list = data.list;
			for (var i of list) {
				groupArray.push(i.groupName);
				var li = `<li><div class="row no-gutters">
				<div class="col"><div class="ipt_box">
				<input type="text" name="mGroupName" id="${i.seq}-groupSeq" class="form-control" placeholder="금칙어 그룹명을 입력하세요." data-seq="${i.seq}" value="${i.groupName}">
				</div></div>
				<div class="col-auto"><div class="btn_wrap pl-2">
				<button type="button" id="" class="mentBtnAdd extraBox btn-outline-primary ment_btn" onclick="addGroup();">+</button>
				<button type="button" id="" class="mentBtnDel btn-outline-danger ment_btn" onclick="delGroup(this);">-</button>
				</div></div></div>
				</li>`;
				$('.dictionary_list').append(li)
			}
			addGroup();
		}
	});
}

function addGroup() {
	var li = `<li><div class="row no-gutters">
	<div class="col"><div class="ipt_box">
	<input type="text" name="mGroupName" class="form-control" placeholder="금칙어 그룹명을 입력하세요.">
	</div></div>
	<div class="col-auto"><div class="btn_wrap pl-2">
	<button type="button" class="mentBtnAdd extraBox btn-outline-primary ment_btn" onclick="addGroup();">+</button>
	<button type="button" class="mentBtnDel btn-outline-danger ment_btn" onclick="delGroup(this);">-</button>
	</div></div></div>
	</li>`;
	$('.dictionary_list').append(li)
}

function delGroup(ele) {
	ele.closest('li').remove();
}

function dupGroupName(groupName, seq) {
	var custCode = $("#selectCustName").val();
	var serviceCode = $("#oprMngName option:selected").val();

	var result = false;

	var mGroupNameArr = new Array();
	$('input[name=mGroupName]').each(function(index, item) {
		var gn = $(item).val().trim();
		if (gn != '') mGroupNameArr.push(gn);
	});
	const set = new Set(mGroupNameArr);

	var cnt = mGroupNameArr.filter(item => item == groupName);

	// mGroupNameArr.length != set.size
	if (cnt.length > 1) {
		//$(`input[value=${groupName}]`).last().val('');
		$.utils.error('이미 등록된 금칙어그룹명입니다.');
	} else {

		$.ajax({
			type: 'post',
			async: false,
			traditional: true,
			datatype: 'JSON',
			url: '/admin/conversation/dictionary/dupGroupName.do',
			data: {
				custCode: custCode,
				serviceCode: serviceCode,
				groupName: groupName,
				seq: seq
			}, success: function(data) {
				result = data.result
				if (data.result) {

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


	return result;
}

function fncGroupSave() {

	var custCode = $("#selectCustName").val();
	var serviceCode = $("#oprMngName option:selected").val();

	var result = false;
	var groupNames = new Array();

	$('.dictionary_list').find('li').each(function(item, index) {
		var groupName = $(this).children().find('input').val().trim();
		var seq = $(this).children().find('input').attr('data-seq');
		if (groupName != '') {
			var obj = new Object();
			obj.groupName = groupName;
			obj.seq = seq == undefined ? null : seq;
			groupNames.push(obj);
		}
	});

	for (var data of groupNames) {
		result = dupGroupName(data.groupName, data.seq);
		if (!result) break;
	}

	if (result) {
		$.ajax({
			type: 'post',
			async: false,
			traditional: true,
			datatype: 'JSON',
			url: '/admin/conversation/dictionary/saveGroupNameList.do',
			data: {
				custCode: custCode,
				serviceCode: serviceCode,
				groupNames: JSON.stringify(groupNames.map(row => row.groupName)),
			}, success: function(data) {
				if (data.result) {
					$.utils.success(data.msg);
				} else {
					$.utils.warning(data.msg);
				}
			}
		});

	}

	search();

}


function uploadFileChange(element) {
	var input = $(element)

	if ($.utils.isBlank(input.val())) return false;

	var files = input[0].files;

	for (var file of files) {

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

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

function downDictionary() {

	var service = $("#oprMngName option:selected").text();
	var table = $('#resultTable').DataTable();
	var rdata = table.rows().data();

	if (rdata.length == 0) {
		return false
	}
	var data = new Array();

	var row = ["금칙어그룹", "대표어", "용어"];
	data.push(row);
	for (var i = 0; i < rdata.length; i++) {
		row = [rdata[i].groupName, rdata[i].repWord, '"' + rdata[i].dictionaryWords + '"']
		data.push(row);
	}

	let csvContent = data.map(e => e.join(",")).join("\n");
	let blob = new Blob(["\ufeff" + csvContent], { type: 'text/csv;charset=utf-8;' });

	var url = URL.createObjectURL(blob);

	var link = document.createElement("a");
	link.setAttribute("href", url);
	link.setAttribute("download", `${service} 금칙어.csv`);
	document.body.appendChild(link);
	link.click();
}

// 파일 업로드
function fncUploadFile() {
	var serviceCode = $("#oprMngName").val();
	$('input[name=serviceCode]').val(serviceCode);

	if (serviceCode == null || serviceCode == '') {
		$.utils.warning("서비스를 선택해주세요");
		return false;
	}

	if ($.utils.isBlank($("input:file").val())) {
		$.utils.warning("파일을 선택해주세요.");
		return false;
	}

	$("form[name=fileUploadForm]").submit();
}

function fncRetrieveOprMng(e) {
	$('#oprMngName').empty();
	var param = "custCode=" + e.val();

	$.ajax({
		type: "post",
		async: false,
		datatype: "text",
		url: "/admin/retrieveOprMng.do",
		data: param,
		success: function(data) {

			$.each(data.nMap, function(i, val) {
				$('#oprMngName').append("<option value=" + val.oprMngCode + ">" + val.oprMngName + "</option>");
			});

			$('#oprMngName').niceSelect('update');
		}
	});
}

// 2022.06.28 단건 저장하기
function fncSaveList_one(saveType, i, text) {
	var table = $('#resultTable').DataTable();
	var rdata = table.rows().data();
	var tdArr = new Array();
	var serviceCode = $("#oprMngName").val();

	var group = $(`#${i}-group`).val();
	var rep = $(`#${i}-rep`).val();
	var dictionaryArr = $(`#${i}-dictionary`).tagsinput('items');
	if (saveType == "D") dictionaryArr = text.split(",");
	var data = { "groupSeq": group, "repWord": rep, "dictionaryWords": dictionaryArr, "seq": rdata[i].seq };
	var tr = $('#resultTable tbody tr').get(i)
	if (group != null && rep != null && dictionaryArr != null) {
		tdArr.push(data);
		var result = fncDupCheck(data);
		table.row(tr).data(data).draw();
		if (result||saveType == "D") {
			$.ajax({
				type: 'post',
				async: false,
				traditional: true,
				datatype: 'JSON',
				url: '/admin/conversation/dictionary/saveDictionaryList.do',
				data: {
					groupSeq: group,
					repWord: rep,
					dictionaryWords: JSON.stringify(dictionaryArr),
					seq: rdata[i].seq,
					serviceCode: serviceCode
				}, success: function(data) {
					if (data.result) {
						$.utils.success('정상적으로 저장되었습니다.');
						
					} else {
						$.utils.warning("저장 실패");
					}
				}
			});
		}
	}
	//search();
}