$(document).on('click', '.policeTr', function (event){
	const target = event.target;
	if(!(target.className === "checkBoxTd" ||$(target).parents("td").length>0)){
		const userSeq = (Number($(this).find(".userSeq").val()));
		showModal(userSeq);
	}
});

function showModal(userSeq){
	$.ajax({
    url: '/police/policeEditModal',
     data: {userSeq: userSeq},
    type: 'GET',
    dataType:"html",
    success: function(html){
      $("#policeEditModalContent").empty().append(html);
      $(".dateSelector").datepicker({
        format: "yyyy-mm-dd",
        language: "ko",
        autoclose: true
      });
      $("#policeEditModal").modal('show');
    },
    error:function(){

    }
  });
}

$(document).on('click', '#syncToKwmsBtn', function (){
  const dicCode = $("#dicCode").val();
  if(!dicCode){
    alert("공무원식별번호가 없습니다.")
  }else{
    syncUserInfoToKwms([{
      userSeq: $("#userSeq").val(),
      dicCode: dicCode
    }]);
  }
})

function syncUserInfoToKwms(userList){
  $.ajax({
    type : 'POST',
    url : "/police/syncUserInfoToKwms",
    data : JSON.stringify(userList),
    contentType: 'application/json',
    beforeSend: function (xhr){
      xhr.setRequestHeader($("[name='_csrf_header']").val(), $("[name='_csrf']").val());
    },
    success : function(data) {
      if(userList.length===1){
        showModal(userList[0].userSeq);
      }
      alert("갱신 되었습니다.");
    },
    error : function(xhr, status) {
      alert("갱신에 실패하였습니다");
    }
  })
}

$(document).on('click', '#updateBtn', function (){
  if(confirm("수정하시겠습니까?")){
    contentFade("in");
    const formData = new FormData($("#userInfoUpdate")[0]);
    $.ajax({
      type : 'POST',
      data : formData,
      url : "/police/updateUserInfo",
      processData: false,
      contentType: false,
      success : function(data) {
        alert("수정되었습니다.");
        contentFade("out");
        showModal(data);
      },
      error : function(xhr, status) {
        alert("수정에 실패하였습니다.");
        contentFade("out");
      }
    })
  }
})

$(document).on('click', '#historyTab', function (){
	const userSeq = (Number($(this).data('userseq')));
  $.ajax({
    url: '/police/policeHistory',
     data: {userSeq: userSeq},
    type: 'GET',
    dataType:"html",
    success: function(html){
      $("#policeEditModalContent").empty().append(html);
      $("#policeEditModal").modal('show');
    },
    error:function(){

    }
  });
})

$(document).on('click', '#editTab', function (){
	const userSeq = (Number($(this).data('userseq')));
  	showModal(userSeq);
})

$(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: '/police/policeHistoryView',
    data: {
			userSeq: Number($(this).find(".userSeq").val()),
			versionNo : Number($(this).find(".verNo").val())
			},
    type: 'GET',
    dataType:"json",
    success: function(data){
		$('#vDicCode').val(data.dicCode);
		$('#vUserId').val(data.userId);
		$('#vUserNm').val(data.userNm);
		$('#vPhone').val(data.phoneNo);
		$('#vEmail').val(data.email);
		$('#vSex').val(data.sex);
		$('#vBirth').val(data.birthDate);
		$('#vPoliceInDate').val(data.policeInDate);
		$('#vOgCd').val(data.ogCd);
		$('#vOrganInDate').val(data.organInDate);
		$('#vOfcCd').val(data.ofcCd);
		$('#vOfcInDate').val(data.ofcInDate);
		$('#vTitleCd').val(data.titleCd);
		$('#vTitleInDate').val(data.titleInDate);
		$('#vOutturnCd').val(data.outturnCd);
		$('#vSeriesCd').val(data.seriesCd);
		$('#vLanguageCd').val(data.languageCd);		
    },
    error:function(){

    }
  });
})

$(document).on('click', '#previousTab', function (){
	const userStatus = $(this).data('userstatus');
  	 location.href = "/police/policeList?userStatus="+userStatus;
})

$(document).on('click', '#presentTab', function (){
	const userStatus = $(this).data('userstatus');
  	 location.href = "/police/policeList?userStatus="+userStatus;
})
$(document).on('click', '#notPoliceTab', function (){
	const userStatus = $(this).data('userstatus');
  	 location.href = "/police/policeList?userStatus="+userStatus;
})

$(document).on('click', '#outBtn', function (){
  if($('input:checkbox[name=policeChk]:checked').length < 1){
		alert("전출대상을 선택해주세요")
		return false;
  }
  if(confirm("선택한 대상을 전출처리 하시겠습니까?")){
    const checkArr = [];
    $('input:checkbox[name=policeChk]:checked').each(function (idx, el){
      checkArr.push({});
      const target = $(el);
      checkArr[idx].userSeq = Number(target.parents('tr').find('.userSeq').val());
      checkArr[idx].userStatus = "USC006"
    })
	    $.ajax({
	    type : 'POST',
	    url : "/police/policeStatusUpdate",
	    data : JSON.stringify(checkArr),
	    contentType: 'application/json',
	    beforeSend: function (xhr){
	      xhr.setRequestHeader($("[name='_csrf_header']").val(), $("[name='_csrf']").val());
	    },
	    success : function(data) {
	      alert(data+"건이 전출 처리되었습니다.");
	      location.reload();
	    },
	    error : function(xhr, status) {
	      alert("전출처리에 실패하였습니다");
	    }
	  })
  }
})

$(document).on('click', '#inBtn', function (){
  if($('input:checkbox[name=policeChk]:checked').length < 1){
		alert("전입대상을 선택해주세요")
		return false;
  }
  if(confirm("선택한 대상을 전입처리 하시겠습니까?")){
    const checkArr = [];
    $('input:checkbox[name=policeChk]:checked').each(function (idx, el){
      checkArr.push({});
      const target = $(el);
      checkArr[idx].userSeq = Number(target.parents('tr').find('.userSeq').val());
      checkArr[idx].userStatus = "USC003"
    })
	    $.ajax({
	    type : 'POST',
	    url : "/police/policeStatusUpdate",
	    data : JSON.stringify(checkArr),
	    contentType: 'application/json',
	    beforeSend: function (xhr){
	      xhr.setRequestHeader($("[name='_csrf_header']").val(), $("[name='_csrf']").val());
	    },
	    success : function(data) {
	      alert(data+"건이 전입 처리되었습니다.");
	      location.reload();
	    },
	    error : function(xhr, status) {
	      alert("전입처리에 실패하였습니다");
	    }
	  })
  }
})

$(document).ready( function() {
  $('#chk-all').click( function() {
    $('.policeCheckBox').prop('checked',this.checked);
  });
});

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

