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

$(document).on('click', '#addPvre', function (){
	const useType = "PVRE";
	showEditModal(useType);
})

$(document).on('click', '#addQir', function (){
	const useType = "QIR";
	showEditModal(useType);
})

function showEditModal(useType){
	$.ajax({
    url: '/equip/useEditModal',
     data: {useType: useType},
    type: 'GET',
    dataType:"html",
    success: function(html){
      $("#useEditModalContent").empty().append(html);
      $("#useEditModal").modal('show');
      $("#useDt").datepicker({
                format: "yyyy-mm-dd",
                language: "ko"
      });
      $('#detailSelf').hide();
    },
    error:function(){

    }
  });
}

$(document).on('click', '#saveUse', function (){
	   if($('#mgtOrgan').val() == ""){
			alert("사용관서를 선택해주세요.");
			$('#mgtOrgan').focus();
			return false;
	   }
	   if(confirm("저장하시겠습니까?")){
		  document.getElementById("mgtOrgan").disabled = false;
	      contentFade("in");
	      const formData = new FormData($("#useFm")[0]);
	      $.ajax({
	        type : 'POST',
	        data : formData,
	        url : "/equip/saveUse",
	        processData: false,
	        contentType: false,
	        success : function(result) {
	          alert("저장되었습니다.");
	          contentFade("out");
			  location.reload();
	        },
	        error : function(xhr, status) {
	          alert("저장에 실패하였습니다.")
	          contentFade("out");
	        }
	      })
	    }  
})

$(document).on('change', '#detailType', function (){
	if($(this).val() == 'PVREUSE007' || $(this).val() == 'QIRUSE006'){
		$('#detailSelf').show();
	}else{
		$('#detailSelf').hide();
		$('#detailSelf').val('');
	}	
});

$(document).on('click', '.useTr', function (event){
	const target = event.target;
	if(!(target.className === "useChk" ||$(target).parents("td").length>0)){
		const useNo = $(target).parent('tr').data("useno");
		const useType = $(target).parent('tr').data("usetype");
		const mgtOrgan = $(target).parent('tr').data("mgtorgan");
		showMdifyModal(useNo,useType,mgtOrgan);
	}
});

function showMdifyModal(useNo,useType,mgtOrgan){
	$.ajax({
    url: '/equip/useModifyModal',
     data: {useNo: useNo,
     		useType: useType,
     		mgtOrgan: mgtOrgan},
    type: 'GET',
    dataType:"html",
    success: function(html){
      $("#useEditModalContent").empty().append(html);
      $("#useEditModal").modal('show');
      $("#mUseDt").datepicker({
                format: "yyyy-mm-dd",
                language: "ko"
      });
      if($('#mDetailType').val() != 'PVREUSE007' && $('#mDetailType').val() != 'QIRUSE006'){
		$('#mDetailSelf').hide();
	  }else{
		$('#mDetailSelf').show();
	  }
    },
    error:function(){

    }
  });
}

$(document).on('change', '#mDetailType', function (){
	if($(this).val() == 'PVREUSE007' || $(this).val() == 'QIRUSE006'){
		$('#mDetailSelf').show();
	}else{
		$('#mDetailSelf').hide();
		$('#mDetailSelf').val('');
	}	
});

$(document).on('click', '#updateUse', function (){

	   if(confirm("수정하시겠습니까?")){
		  document.getElementById("mMgtOrgan").disabled = false;
	      contentFade("in");
	      const formData = new FormData($("#useUpdateFm")[0]);
	      $.ajax({
	        type : 'POST',
	        data : formData,
	        url : "/equip/updateUse",
	        processData: false,
	        contentType: false,
	        success : function(data) {
	          alert("수정되었습니다.");
	          contentFade("out");
			      showMdifyModal(data.useNo,data.useType,data.mgtOrgan);
	        },
	        error : function(xhr, status) {
	          alert("수정에 실패하였습니다.")
	          contentFade("out");
	        }
	      })
	    }  
})

$(document).on('click', '#historyBtn', function (){
	  if($('input:checkbox[name=useChk]:checked').length < 1){
		alert("게시물을 선택해주세요")
		return false;
	  }
	  if($('input:checkbox[name=useChk]:checked').length > 1){
		alert("한개만 선택해주세요")
		return false;
	  }
	  const target = $('input:checkbox[name=useChk]:checked');
	  const useNo = $(target).parent().parent('tr').data("useno");
	  const useType = $(target).parent().parent('tr').data("usetype");
	  const mgtOrgan = $(target).parent().parent('tr').data("mgtorgan");
	  $.ajax({
	    url: '/equip/useHistory',
	     data: {useNo: useNo,
	     		useType: useType,
	     		mgtOrgan: mgtOrgan},
	    type: 'GET',
	    dataType:"html",
	    success: function(html){
	      $("#useEditModalContent").empty().append(html);
	      $("#useEditModal").modal('show');
	      $('#vDetailSelf').hide();
	    },
	    error:function(){
	
	    }
	  });		  
})

$(document).on('click', '.historyTr', function (event){
	const target = event.target;
	$(this).find('.hisChk').prop('checked',true) 
    if($(this).find('.hisChk').prop('checked')){
   		$('.hisChk').prop('checked',false);
   		$(this).find('.hisChk').prop('checked',true)
   }
   $.ajax({
    url: '/equip/HistoryView',
    data: {
			useNo: $(target).parents('tr').data("useno"),
			versionNo : Number($(target).parents('tr').data("verno")),
			useType :  $(target).parents('tr').data("usetype"),
			mgtOrgan : $(target).parents('tr').data("mgtorgan")
			},
    type: 'GET',
    dataType:"json",
    success: function(data){
	$('#vSosok').val(data.sosok);
	$('#vUseDt').val(data.useDt);
	$('#vDetailType').val(data.detailTypeName);
	if(data.detailType != 'PVREUSE007' && data.detailType != 'QIRUSE006'){
		$('#vDetailSelf').hide();
		$('#vDetailSelf').val('');
	}else{
		$('#vDetailSelf').show();
		$('#vDetailSelf').val(data.detailSelf);
	}
	$('#vCnt').val(data.peopleCnt);
	$('#vDescription').val(data.description);
    },
    error:function(){

    }
  });	
})

$(document).on('click', '#deleteUse', function (){
	if($('input:checkbox[name=useChk]:checked').length < 1){
		alert("삭제할 게시물을 선택해주세요")
		return false;
	 }
	if(confirm("선택한 대상을 삭제처리 하시겠습니까?")){
	 const checkArr = [];
		$('input:checkbox[name=useChk]:checked').each(function (idx, el){
	      checkArr.push({});
	      const target = $(el);
	      checkArr[idx].useNo = target.parents('tr').data("useno");
	      checkArr[idx].mgtOrgan = target.parents('tr').data("mgtorgan");  
	      checkArr[idx].useType = target.parents('tr').data("usetype");       
   		})
   		deleteUse(checkArr);	
	}	
})

function deleteUse(checkArr){
	$.ajax({
		    type : 'POST',
		    url : "/equip/useDelete",
		    data : JSON.stringify(checkArr),
		    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("삭제처리에 실패하였습니다");
		    }
   })	
}

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

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

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