
$(document).on('click', '#apprvTab', function (){
  location.href='/userMgt/userMgtPage?userStatus=USC003';
})
$(document).on('click', '#stayTab', function (){
	location.href='/userMgt/userMgtPage?userStatus=USC002';
})

$(document).on('click', '.userInfoTr', function (event){
  if(!event.target.className.includes("heckBox")){
    openEditModal($(this).find(".userSeq").val())
  } 
})

$(document).on('click', '#approvalBtn', function (){
	if(confirm("선택한 대상을 승인처리 하시겠습니까?")){
	 const checkArr = [];
		$('input:checkbox[name=userChk]:checked').each(function (idx, el){
	      checkArr.push({});
	      const target = $(el);
	      checkArr[idx].userSeq = Number(target.parents('tr').find('.userSeq').val());
	      checkArr[idx].userStatus = "USC003"
    })
		userApproval(checkArr);
	}	
})

$(document).on('click', '#notPoliceBtn', function (){
	if(confirm("선택한 대상을 비외사경찰승인 처리 하시겠습니까?")){
	 const checkArr = [];
		$('input:checkbox[name=userChk]:checked').each(function (idx, el){
	      checkArr.push({});
	      const target = $(el);
	      checkArr[idx].userSeq = Number(target.parents('tr').find('.userSeq').val());
	      checkArr[idx].userStatus = "USC007"
    })
		userApproval(checkArr);
	}	
})

$(document).on('click', '.statusBtn', function (){
  const userInfoList = [];
  userInfoList.push({
    userSeq: $("#userSeq").val(),
    userStatus: $(this).attr("data-status")
  })
  userApproval(userInfoList);
})
$(document).on('click', '#updateBtn', function (){
  saveUserInfo();
})

$(document).on('click', '#deleteBtn', function (){
  if(confirm("삭제 하시겠습니까?")){
    deleteUser([{userSeq: Number($("#userSeq").val())}])
  }
})
$(document).on('click', '#syncToKwmsBtn', function (){
  const dicCode = $("#dicCode").val();
  if(!dicCode){
    alert("공무원식별번호가 없습니다.")
  }else{
    syncUserInfoToKwms([{
      userSeq: $("#userSeq").val(),
      dicCode: dicCode
    }]);
  }
})
$(document).on('click', '#syncToKwmsAllBtn', function (){
  const userList = [];
  $.each($(".userInfoCheckBox:checked"), function (idx, chkBox){
    const tr = $(chkBox).parents(".userInfoTr");
    if(tr.find(".dicCode").val()!==""){
      userList.push({
        userSeq: tr.find(".userSeq").val(),
        dicCode: tr.find(".dicCode").val()
      })
    }
  })
  if(confirm(userList.length+"건의 정보를 갱신하시겠습니까?")){
    syncUserInfoToKwms(userList);
  }
})

$(document).on('click', '#companionBtn', function (){
  if(confirm("선택한 대상을 반려처리 하시겠습니까?")){
    const checkArr = [];
    $('input:checkbox[name=userChk]:checked').each(function (idx, el){
      checkArr.push({});
      const target = $(el);
      checkArr[idx].userSeq = Number(target.parents('tr').find('.userSeq').val());
      checkArr[idx].userStatus = "USC005"
    })
    userCompanion(checkArr);
  }
})

function syncUserInfoToKwms(userList){
  $.ajax({
    type : 'POST',
    url : "/userMgt/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){
        openEditModal(userList[0].userSeq);
      }
      alert("갱신 되었습니다.");
    },
    error : function(xhr, status) {
      alert("갱신에 실패하였습니다");
    }
  })
}
function userApproval(checkArr){
	$.ajax({
    type : 'POST',
    url : "/userMgt/userApproval",
    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("승인처리에 실패하였습니다");
    }
  })	
}

function userCompanion(checkArr){
	$.ajax({
    type : 'POST',
    url : "/userMgt/userCompanion",
    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("반려처리에 실패하였습니다");
    }
  })	
}


function saveUserInfo(){
  if(confirm("저장하시겠습니까?")){
    contentFade("in");
    const formData = new FormData($("#userInfoUpdate")[0]);
    $.ajax({
      type : 'POST',
      data : formData,
      url : "/userMgt/updateUserInfo",
      processData: false,
      contentType: false,
      success : function() {
        alert("저장되었습니다.");
        contentFade("out");
        location.reload();
      },
      error : function(xhr, status) {
        alert("저장에 실패하였습니다.");
        contentFade("out");
      }
    })
  }
}
function deleteUser(userList){
	$.ajax({
    type : 'POST',
    url : "/userMgt/userDelete",
    data : JSON.stringify(userList),
    contentType: 'application/json',
    beforeSend: function (xhr){
      xhr.setRequestHeader($("[name='_csrf_header']").val(), $("[name='_csrf']").val());
    },
    success : function() {
      alert("삭제 처리되었습니다.");
      location.reload();
    },
    error : function(xhr, status) {
      alert("삭제 처리에 실패하였습니다");
    }
  })	
}

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

    }
  });
}