
$(document).ready(function() {
	fncAuthCheck();
	// 고객사 목록
	getOpr();

    $("#custCode").on('change', function() {
        getOpr();
    });

	var opts = {
		columns: [{
			data: "idivWord"
		}, {
			data: "repWord"
		}, {
			data: "synonymWords"
		}, {
			data: "seq"
		}],
		columnDefs: [{
			"defaultContent": "-",
			"targets": "_all",
			"className": "center"
		},
		{
			targets: 0,
			render: function(data, type, row, index) {
				var val = `value="${data}"`;
				var idivWord;
				if (data == undefined) val = '';
				if (!checkPermissionPolicy("rcpconversationsynonymmanageFull")) {
					idivWord = `<input readonly name="idivWord" type="text" id="${index['row']}-idiv" ${val}>`;
				} else {
					idivWord = `<input name="idivWord" type="text" id="${index['row']}-idiv" ${val}>`;
				}
				return idivWord;
			}
		},
		{
			targets: 1,
			render: function(data, type, row, index) {
				var val = `value="${data}"`;
				var repWord;
				if (data == undefined) val = '';
				if (!checkPermissionPolicy("rcpconversationsynonymmanageFull")) {
					repWord = `<input readonly name="repWord" type="text" id="${index['row']}-rep" ${val}>`;
				} else {
					repWord = `<input name="repWord" type="text" id="${index['row']}-rep" ${val}>`;
				}
				return repWord;
			}
		},
		{
			targets: 2,
			render: function(data, type, row, index) {
				var val = `value="${data}"`;
				var deleteBtn;
				if (data == undefined) val = '';
				if (!checkPermissionPolicy("rcpconversationsynonymmanageFull")) {
					deleteBtn = `<div class="row no-gutters align-items-center">
									<div class="col">
										<div class="tag-input-area">
											<input readonly type="text" name="synonymWord" id="${index['row']}-synonym" class="tag-input" ${val}>
										</div>
									</div>
								</div>`;
				} else {
					deleteBtn = `<div class="row no-gutters align-items-center">
									<div class="col">
										<div class="tag-input-area">
											<input type="text" placeholder="동의어 입력 후 엔터를 눌러주세요" name="synonymWord" id="${index['row']}-synonym" class="tag-input" ${val}>
										</div>
									</div>
								<div class="col-auto pl-2">
									<button type="button" class="btn grey" onclick="fnDeleteList('${index['row']}', this);">삭제</button>
								</div>
								</div>`;
				}
				return deleteBtn;
			}
		},
		{
			targets: 3,
			visible: false
		}],
		createdRow: function(row, data, index, meta) {
			$(row).data('seq',  data.seq);
		},
		drawCallback: function(settings) {
			$('.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) {
					if (checkPermissionPolicy("rcpconversationsynonymmanageFull")) {
                        var idiv = $(this).closest("tr").find('input').attr('id');
                        var idx = idiv.replace('-idiv', '')
                        fncSaveList_one("I", idx, "");
					}else {
						$.utils.warning("권한이 없습니다.");
					}
				}
			});
//			$('.bootstrap-tagsinput').find('input').on("keydown", function () {
//                if (event.keyCode === 8 && $(this).val() === "") {
//                    event.preventDefault();
//                }
//            });
			if (!checkPermissionPolicy("rcpconversationsynonymmanageFull")) {
                $("span[data-role=remove]").hide();
                $("#resultTable .tag-input-area input").hide();
            }

			// 2022.06.28 단건 삭제
			/*$(document).on("click", "span[data-role=remove]", function(e) {
				var idx = $(this).parents("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);
				console.log(idx);
			});*/
		},
	}

	// tags input(동의어) 삭제 - 2022.07.29 수정

    $(document).on("beforeItemRemove", ".tag-input-area", function (e) {
        if (checkPermissionPolicy("rcpconversationsynonymmanageFull")) {
            var idiv = $(this).closest("tr").find('input').attr('id');//yoo추가
            var idx = idiv.replace('-idiv', '');
            var text = e.item;
            var textSum = "";
            $(this).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);
        }else {
            $.utils.warning("권한이 없습니다.");
        }
    });

	$.utils.dataTable.init('/admin/rcp/conversation/synonym/synonymList.do', opts);
	search();
});


function tagDraw() {              // draw a request on add or remove tag
	var v = $(".search-input-text").val();
	dataTable.search(v).draw();
}

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

	$.ajax({
		type: "post",
		async: false,
		datatype: "text",
		url: "/admin/rcp/conversation/synonym/synonymList.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 = $("#custCode").val();
	var serviceGroup = $("#serviceGroup").val();

	$.ajax({
		type: 'post',
		async: false,
		datatype: 'text',
		url: '/admin/rcp/conversation/synonym/synonymList.do',
		data: {
			custCode: custCode,
			serviceGroup: serviceGroup,
			repWord: repWord
		},
		success: function(data) {
			$("#resultTable").renderTable(data.list);
		}
	});
}

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

	formData.append('repWord', $('#oprMngName1').val());
	formData.append('custCode', $("#custCode").val());
	formData.append('serviceGroup', $("#serviceGroup").val());

	req.open("POST", '/admin/rcp/conversation/synonym/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_synonym.xls";
			link.click();
		}
	};
	req.send(formData);
}

// 삭제
function fnDeleteList(rData, t) {

	var data = $(`#${rData}-idiv`).closest("tr").data("seq");
	var custCode = $("#custCode").val();
	var serviceGroup = $("#serviceGroup").val();
	if (data == undefined || data == null) {
		var td = $('#resultTable').DataTable();
		var tr = t.parentNode.parentNode.parentNode.parentNode;
		td.row(tr).remove().draw();
	} else {
		swal("삭제요청", "삭제하시겠습니까?", "info", {
			buttons: ["취소", "저장"],
		}).then(function (ok) {
			if (ok) {

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

// 추가버튼 클릭시
function fncAdd() {

	// 2022.07.05 수정
	var table = $("#resultTable").dataTable(); //not DataTable() function
	var dt = table.api();
	var obj = {
		"idivWord": '',
		"repWord": '',
		"synonymWords": '',
		"seq": null
	}
	dt.row.add(obj);
	var aiDisplayMaster = table.fnSettings()["aiDisplayMaster"];
	var irow = aiDisplayMaster.pop();
	aiDisplayMaster.unshift(irow);
	dt.draw();
//	dt.draw();
}

// 중복확인
function fncDupCheck(data) {
	var custCode = $("#custCode").val();
	var serviceGroup = $("select[name=serviceGroup]").val();

	var result = false;
	var row = data.row;

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

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

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

	$.ajax({
		type: 'post',
		async: false,
		traditional: true,
		datatype: 'JSON',
		url: '/admin/rcp/conversation/synonym/dupCheck.do',
		data: {
			custCode: custCode,
			serviceGroup: serviceGroup,
			repWord: data.repWord,
			idivWord: data.idivWord,
			synonymWords: JSON.stringify(data.synonymWords),
			seq: data.seq
		}, success: function(data) {
			result = data.result;
			returnSeq = data.seq;
			if (returnSeq != -1) {
				$(`#${row}-idiv`).closest("tr").data("seq", returnSeq);
			}
			//saveWorkHst();
			if (!data.result) {
				$.utils.error(data.msg);
				search();
			}
		}
	});
	// if (idivArr.length != setIndiv.size) {
	// 	$.utils.warning("중복된 개체어입니다.");
	// } else if (repArr.length != setRep.size) {
	// 	$.utils.warning("중복된 대표어입니다.");
	// } else if (rs.length > 0) {
	// 	$.utils.error('이미 대표어로 등록된 키워드입니다.');
	// } else if (synonymArr.length != setSynonym.size) {
	// 	$.utils.warning("중복된 동의어 입니다.");
	// } else {
	//
	// 	$.ajax({
	// 		type: 'post',
	// 		async: false,
	// 		traditional: true,
	// 		datatype: 'JSON',
	// 		url: '/admin/rcp/conversation/synonym/dupCheck.do',
	// 		data: {
	// 			custCode: custCode,
	// 			serviceCode: serviceCode,
	// 			repWord: data.repWord,
	// 			idivWord: data.idivWord,
	// 			synonymWords: JSON.stringify(data.synonymWords),
	// 			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 result = false;

	var tdArr = new Array();
	for (var i = 0; i < rdata.length; i++) {
		var idiv = $(`#${i}-idiv`).val();
		var rep = $(`#${i}-rep`).val();
		var synonymArr = $(`#${i}-synonym`).tagsinput('items');
		var data = { "idivWord": idiv, "repWord": rep, "synonymWords": synonymArr, "seq": rdata[i].seq };

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

		if (idiv != "" && rep != "" && synonymArr != null) {
			tdArr.push(data);
			result = fncDupCheck(data);
			if (result) {
				$.ajax({
					type: 'post',
					async: false,
					traditional: true,
					datatype: 'JSON',
					url: '/admin/rcp/conversation/synonym/saveSynonymList.do',
					data: {
						idivWord: idiv,
						repWord: rep,
						synonymWords: JSON.stringify(synonymArr),
						seq: rdata[i].seq
					}, success: function(data) {
						if (data.result) {
							$.utils.success('정상적으로 저장되었습니다.');
							//saveWorkHst();
						} else {
							$.utils.warning("저장 실패");
						}
					}
				});
			} else {
				break;
			}

		}

	}
	search();
}

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

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

	var file = input[0].files[0];

		// 파일 명 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 fncUploadFile() {
	var serviceGroup = $("#serviceGroup").val();
	var custCode = $("#custCode").val();
	$('input[name=serviceGroup]').val(serviceGroup);
	$('input[name=custCode]').val(custCode);

	var img = $(".loading-img");

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

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

	if ($.utils.isBlank($("input:file").val())) {
		$.utils.warning("파일을 선택해주세요.");
		img.hide()
		img.parent().find("span").text("저장");
		return false;
	}

	//	var input = $('input[name=csvFile]');
	//	var files = input[0].files;
	//	console.log(files);
	$("form[name=fileUploadForm]").submit();
}

function fncDelScenarioList(seq) {

	$.utils.confirm('삭제하시겠습니까?', result);

	function result() {
		$.ajax({
			type: "post",
			async: false,
			datatype: "text",
			url: '/admin/rcp/conversation/scenario/deleteScenarioList.do',
			data: {
				seq: seq
			},
			success: (function(data) {
				if (data.result) {
					$.utils.success('정상적으로 삭제되었습니다.');
				} else {
					$.utils.warning('삭제 실패');
				}
			})
		});

		search();
	}
}

function getOpr() {
	$.ajax({
		type: "GET",
		async: false,
		datatype: "JSON",
		url: /*commonUtil.getContextPath() + */"/adm/menu/oprmng" + "?menuval=rcpconversationsynonymmanage",
		success: function (data) {
			data.forEach(function (e, f) {
				//console.log("e - "+e.custCode)
				$('#custCode').val(e.custCode);
				$('#serviceGroup').append("<option value=" + e.serviceGroup + ">" + e.serviceGroupName + "</option>");
				$('#serviceGroup').niceSelect('update');

			});
		}
	})
};

/*function saveWorkHst() {

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

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

// 2022.06.28 단건 저장하기
function fncSaveList_one(saveType, i, text) {

	var table = $('#resultTable').DataTable();
	var rdata = table.rows().data();
	var serviceGroup = $("select[name=serviceGroup]").val();
	var custCode = $("#custCode").val();

	var idiv = $(`#${i}-idiv`).val();
	var rep = $(`#${i}-rep`).val();
	var synonymArr = $(`#${i}-synonym`).tagsinput('items');
	var seq = $(`#${i}-idiv`).closest("tr").data("seq");
	if(saveType=="D") synonymArr = text.split(",");
	var dataForCheck = { "idivWord": idiv, "repWord": rep, "synonymWords": synonymArr, "seq": seq, "row": i };
	var data = { "idivWord": idiv, "repWord": rep, "synonymWords": synonymArr, "seq": seq};
	var tr = $('#resultTable tbody tr').get(i)

	if (idiv != null && rep != null && synonymArr != null) {
		if (idiv != "" && rep != "" && synonymArr.length > 0) {
			if (saveType=="D") {
				$.ajax({
					type: 'post',
					async: false,
					traditional: true,
					datatype: 'JSON',
					url: '/admin/rcp/conversation/synonym/saveSynonymList.do',
					data: {
						idivWord: idiv,
						repWord: rep,
						synonymWords: JSON.stringify(synonymArr),
						seq: rdata[i].seq,
						serviceGroup: serviceGroup,
						custCode: custCode
					}, success: function(data) {
						if (data.result) {
							$.utils.success('정상적으로 삭제되었습니다.');
							//saveWorkHst();
						} else {
							$.utils.warning("삭제 실패");
						}
					}
				});
			} else {
				if (fncDupCheck(dataForCheck)) {
					$.utils.success('정상적으로 저장되었습니다.');
					// table.row(tr).data(data).draw();
				}
			}
		} else {
			$.utils.warning("개체어, 대표어, 동의어를 모두 입력해주세요.");
		}
	}
}

function fncAuthCheck() {
	if (!checkPermissionPolicy("rcpconversationsynonymmanageFull")) {
		$("#btnExcelUp, #btnSave").hide();
	}
}
