let trCarrerList=[];
let selectedIdx=0;

$(document).on('click', '.userInfoTr', function (event){
	$("#selectedKey").val($(this).find(".trKey").val())
	$("#selectedVerNo").val($(this).find(".verNo").val())
	const x = event.clientX;
	const y = event.clientY;
	const dropdown = $(".dropdown-menu.show")
	if(dropdown.length>0){		
		dropdown[0].style.inset = "0px auto auto "+(x-event.currentTarget.getBoundingClientRect().x)+"px";
	}
})

$(document).on('click', '.translatorInfo', function (){
	document.getElementById('accessTab').classList.add('active');
	document.getElementById('approvalTab').classList.remove('active');
	const trKey = Number($("#selectedKey").val());
	const verNo = Number($("#selectedVerNo").val());
	const url = '/translator/translatorEditModal';
	revisionHistory(trKey,verNo,url);
	var html="";
	html += '<input type="hidden" class="tapTrKey" value="'+trKey+'">';
	html += '<input type="hidden" class="tapVerNo" value="'+verNo+'">';
	$("#KeyValue").empty().html(html)
})

$(document).on('click', '#trView', function (){
	document.getElementById('accessTab').classList.add('active');
	document.getElementById('approvalTab').classList.remove('active');
	const trKey = (Number($(this).find(".trKey").val()));
	const verNo = (Number($(this).find(".verNo").val()));
	const url = '/translator/translatorEditModal';
	revisionHistory(trKey,verNo,url);
	var html="";
	html += '<input type="hidden" class="tapTrKey" value="'+trKey+'">';
	html += '<input type="hidden" class="tapVerNo" value="'+verNo+'">';
	$("#KeyValue").empty().html(html);
})

$(document).on('click', '#updateBtn', function (){
	if($('#eOgdp1').val() == ''){
		alert("관서를 선택해주세요.");
		$('#eOgdp1').focus();
		return false;
	}
	
	if($('#trLang').val() == ''){
		alert("언어를 선택해주세요.");
		$('#trLang').focus();
		return false;
	}
	
	if($('#trEname').val() == ''){
		alert("성명을 입력해주세요.");
		$('#trEname').focus();
		return false;
	}
	
    if(confirm("수정하시겠습니까?")){
	  document.getElementById("eOgdp1").disabled = false;
	  const url = '/translator/translatorEditModal';
      contentFade("in");
      const formData = new FormData($("#trInfoUpdate")[0]);
      $.ajax({
        type : 'POST',
        data : formData,
        url : "/translator/updateTranslatorInfo",
        processData: false,
        contentType: false,
        success : function(data) {
          alert("수정되었습니다.");
          contentFade("out");
          revisionHistory(data.translatorKey,data.versionNo,url);
        },
        error : function(xhr, status) {
          alert("수정에 실패하였습니다.");
          contentFade("out");
        }
      })    
  }
})

$(document).on('click', '#saveBtn', function (){
	if($('#ogdp1').val() == ''){
		alert("관서를 선택해주세요.");
		$('#ogdp1').focus();
		return false;
	}
	
	if($('#lang').val() == ''){
		alert("언어를 선택해주세요.");
		$('#lang').focus();
		return false;
	}
	
	if($('#trName').val() == ''){
		alert("성명을 입력해주세요.");
		$('#trName').focus();
		return false;
	}
	
	if($('#dmlYn').val() == ''){
		alert("해촉여부를 선택해주세요.");
		$('#dmlYn').focus();
		return false;
	}
	
    if(confirm("저장하시겠습니까?")){
	  document.getElementById("ogdp1").disabled = false;
      contentFade("in");
      const formData = new FormData($("#translatorInsert")[0]);
      $.ajax({
        type : 'POST',
        data : formData,
        url : "/translator/insertTranslatorInfo",
        processData: false,
        contentType: false,
        success : function(result) {
          alert("저장되었습니다.")
          contentFade("out");
          location.reload();
        },
        error : function(xhr, status) {
          alert("저장에 실패하였습니다.")
          contentFade("out");
        }
      })
    }
})

$(document).on('click', '.historyInfoTr', function (){
	$(this).find('.hisChk').prop('checked',true) 
   if($(this).find('.hisChk').prop('checked')){
   		$('.hisChk').prop('checked',false);
   		$(this).find('.hisChk').prop('checked',true)
   }	
  $.ajax({
    url: '/translator/HistoryView',
    data: {
			translatorKey: Number($(this).find(".trKey").val()),
			versionNo : Number($(this).find(".verNo").val())
			},
    type: 'GET',
    dataType:"json",
    success: function(data){
	$("#ogdp1V").val(data.ogdp1);
	$("#trLangV").val(data.trLang);
	$("#trCareerV").val(data.trCareer);
	$("#trNameV").val(data.trName);
	$("#trSexV").val(data.trSex);
	$("#trPhoneV").val(data.trPhone);
	$("#trNnyV").val(data.trNny);
	$("#trAgeV").val(data.trAge);
	$("#trVisaV").val(data.trVisa);
	$("#trEduV").val(data.trEdu);
	$("#trCftV").val(data.trCft);
	$("#aptDtV").val(data.aptDt);
	$("#dmlYnV").val(data.dmlYn);
	$("#remarkV").val(data.remark);
    },
    error:function(){

    }
  });
})
$(document).ready( function() {
  $("#aptDt").datepicker({
                format: "yyyy-mm-dd",
                language: "ko"
            });
  $(".tcDt").datepicker({
                format: "yyyy-mm-dd",
                language: "ko"
            });
});

$(document).on('click', '#approvalTab', function (){
	const trKey = (Number($('.tapTrKey').val()));
	const verNo = (Number($('.tapVerNo').val()));
	const url = '/translator/revisionHistory';
	revisionHistory(trKey,verNo,url);
	document.getElementById('accessTab').classList.remove('active');
	document.getElementById('approvalTab').classList.add('active');
})

$(document).on('click', '#accessTab', function (){
	const trKey = (Number($('.tapTrKey').val()));
	const verNo = (Number($('.tapVerNo').val()));
	const url = '/translator/translatorEditModal';
	revisionHistory(trKey,verNo,url);
	document.getElementById('approvalTab').classList.remove('active');
	document.getElementById('accessTab').classList.add('active');
})

function revisionHistory(trKey,verNo,url){
	$.ajax({
    url: url,
    data: {
			translatorKey: trKey,
			versionNo : verNo
			},
    type: 'GET',
    dataType:"html",
    success: function(html){
      $("#configInfo").empty().append(html)
      $("#translatorEditModal").modal('show');
      $("#viewAptDt").datepicker({
                format: "yyyy-mm-dd",
                language: "ko"
      });
    },
    error:function(){

    }
  });
}

$(document).on('change', '#trNny', function (){
	if($(this).val() == "NNY001"){
		$("#trVisa").attr("disabled",true);
	}else{
		$("#trVisa").removeAttr("disabled");
	}
});

$(document).on('click', '#crrAddBtn', function (){
	const trKey = (Number($('#tcInsertKey').val()));
  $('#insertCareer').append(
        '<div class="mb-12 row" id="crrDiv">'+
        '<div class="col-sm-1">'+
        '<button type="button" class="btn btn-sm btn-outline-danger rowDeleteBtn"><i class="bi bi-x"></i></button>'+
		'</div>'+        
        '<label for="ogCd" class="col-sm-2 col-form-label text-center">경력구분</label>'+
        '<div class="col-sm-2">'+
        '<select class="form-select form-select-sm crrInput" name="hisGubun">'+
        '<option value="">선택</option>'+
        '<option value="Y">해양경찰청</option>'+
        '<option value="N">타기관</option>'+
        '</select>'+
        '</div>'+
        '<label for="ofcCd" class="col-sm-1 col-form-label text-center">날짜</label>'+
        '<div class="col-sm-2">'+
        '<input type="text" class="form-control tcDt crrInput" id="tcDt" name="tcDt">'+
        '</div>'+
        '<label for="ofcCd" class="col-sm-1 col-form-label text-center">내용</label>'+
        '<div class="col-sm-2">'+
        '<input type="text" class="form-control crrInput" id="contents" name="contents">'+
        '</div>'+
        '<label for="ofcCd" class="col-sm-1 col-form-label text-center">비고</label>'+
        '<div class="col-sm-2">'+
        '<input type="text" class="form-control crrInput" id="remark" name="remark">'+
        '</div>'+
        '</div>'
  )
  $(".tcDt").datepicker({
                format: "yyyy-mm-dd",
                language: "ko"
            });
  trCarrerList.push({translatorKey:trKey, hisGubun:"",tcDt:"",contents:"",remark:""});
})

$(document).on('click', '.rowDeleteBtn', function (){
	selectedIdx = $(this).parents("#crrDiv").index()-1;
	trCarrerList.splice(selectedIdx,1);	
	$(this).parents('#crrDiv').remove();
})

$(document).on('change', '.crrInput', function (){
  selectedIdx = $(this).parents("#crrDiv").index()-1;
  const target = trCarrerList[selectedIdx];
  switch (this.name){
    case "hisGubun":
      target.hisGubun = this.value
      break;
    case "tcDt":
      target.tcDt = this.value
      break;
    case "contents":
      target.contents = this.value
      break;
    case "remark":
      target.remark = this.value
      break;
  }
})

$(document).on('click', '.careerInfo', function (){
	const trKey = Number($("#selectedKey").val());
	showCareer(trKey);
})

function showCareer(trKey){	
	$.ajax({
    url: '/translator/careerView',
    data: {
			translatorKey: trKey,
			},
    type: 'GET',
    dataType:"html",
    success: function(html){
      $("#careerView").empty().append(html)
      $("#translatorCareerModal").modal('show');
    },
    error:function(){

    }
  });	
}


$(document).on('click', '#crrInsertBtn', function (){
	const trKey = Number($("#tcmKey").val());
	$.ajax({
    url: '/translator/careerInsertPage',
    data: {
			translatorKey: trKey,
			},
    type: 'GET',
    dataType:"html",
    success: function(html){
      $("#careerView").empty().append(html)
      $("#translatorCareerModal").modal('show');
    },
    error:function(){

    }
  });
})

$(document).on('click', '#crrSaveBtn', function (){
    if(confirm("저장하시겠습니까?")){
      contentFade("in");
      $.ajax({
        type : 'POST',
        data : JSON.stringify(trCarrerList),
        url : "/translator/insertTranslatorCareer",
       contentType: 'application/json',
	    beforeSend: function (xhr){
	      xhr.setRequestHeader($("[name='_csrf_header']").val(), $("[name='_csrf']").val());
	    },
	    success : function(data) {
		 contentFade("out");
	      alert("이력등록이 완료되었습니다.");
	      showCareer(data);
	      trCarrerList.length = 0;
	    },
	    error : function(xhr, status) {
		  contentFade("out");
	      alert("이력등록을 실패하였습니다");
	    }
      })
    }
})

function deleteCareerBtn(crrSeq,trKey){
	if(confirm("삭제하시겠습니까?")){
		$.ajax({
	    type : 'POST',
	    url : "/translator/deleteCareer",
	    data : JSON.stringify({careerSeq:crrSeq,
	    		translatorKey:trKey}),
	    contentType: 'application/json',
	    beforeSend: function (xhr){
	      xhr.setRequestHeader($("[name='_csrf_header']").val(), $("[name='_csrf']").val());
	    },
	    success : function(data) {
	      alert("삭제 처리되었습니다.");
	      showCareer(data);
	    },
	    error : function(xhr, status) {
	      alert("삭제 처리에 실패하였습니다");
	    }
	  })
   }
}

$(document).on('click', '.btn-close', function (){
	  trCarrerList.length = 0;
	  location.reload();
})

$(document).on('click', '#closeModalBtn', function (){
	  location.reload();
})

$(document).on('click', '#trDeleteBtn', function (){
    if(confirm("해임 하시겠습니까?")){
      contentFade("in");
      const trKey = Number($(".translatorKey").val());
      $.ajax({
        type : 'POST',
        data : JSON.stringify(trKey),
        url : "/translator/deleteTranslatorInfo",
        contentType: 'application/json',
        beforeSend: function (xhr){
	      xhr.setRequestHeader($("[name='_csrf_header']").val(), $("[name='_csrf']").val());
	    },
        success : function() {
          alert("해임되었습니다.");
          contentFade("out");
          location.reload();
        },
        error : function(xhr, status) {
          alert("해임을 실패하였습니다.");
          contentFade("out");
        }
      })    
  }
})

$(document).on('click', '#goExcel', function (){
	if(confirm("엑셀로 다운로드 하시겠습니까?")){
		$('input[name=excel]').val('Y');
		$('#searchFm').submit();
		$('input[name=excel]').val('');
	}else{
		false;
	}
})

$(document).on('click', '#excelDown', function (){
	if(confirm("엑셀로 다운로드 하시겠습니까?")){
		location.href='/translator/statisticsExcelDown';
	}else{
		false;
	}
})




