
$(document).ready(function(){
	$(".table_id").each(function(){
		var rows = $(".table_id:contains('"+$(this).text()+"')");
		
		if(rows.length > 1){
			rows.eq(0).attr("rowspan", rows.length);
			rows.not(":eq(0)").remove();
		}
	})
	
});
	
$(document).on('click', '#addEquip', function (){
   $.ajax({
    url: '/equip/equipEditModal',
    type: 'GET',
    dataType:"html",
    success: function(html){
      $("#equipEditModalContent").empty().append(html);
      $("#equipEditModal").modal('show');
      $(".storedYear").datepicker({
				 minViewMode: 'years',
                format: "yyyy",
                language: "ko"
      })
    },
    error:function(){

    }
  });
})

$(document).on('change', '#equType', function (){
	const equType = $(this).val();
	
	$.ajax({
    url: '/equip/equipTypeSelecBox',
    data: {
			equType,
			},
    type: 'GET',
    dataType:"html",
    success: function(html){
      $("#detailType").empty().append(html)
    },
    error:function(){

    }
  });
});
  
$(document).on('click', '#saveEquip', function (){
	if($('#mgtOrgan').val() == ''){
		alert("관리처를 선택해주세요.");
		$('#mgtOrgan').focus();
		return false;
	}
	if($('#equType').val() == ''){
		alert("분류를 선택해주세요.");
		$('#equType').focus();
		return false;
	}
	if($('#detailType').val() == ''){
		alert("세부분류를 선택해주세요.");
		$('#detailType').focus();
		return false;
	}
	if($('#itemQty').val() == ''){
		alert("수량을 입력해주세요.");
		$('#itemQty').focus();
		return false;
	}
	if(confirm("저장하시겠습니까?")){
	  document.getElementById("mgtOrgan").disabled = false;
      let ajaxUrl = "/equip/saveEquip";
      const formData = new FormData($("#equipEditForm")[0]);
      contentFade("in");
      $.ajax({
        type : 'POST',
        data : formData,
        url : ajaxUrl,
        processData: false,
        contentType: false,
        success : function() {
            alert("저장되었습니다.");
            location.reload();
            contentFade("out");
        },
        error : function(xhr, status) {
          alert("저장에 실패하였습니다.")
          contentFade("out");
        }
      })
    }
   
});

$(document).on('click', '#equUpdateBtn', function (){
	  if($('input:checkbox[name=equChk]:checked').length < 1){
		alert("게시물을 선택해주세요")
		return false;
	  }
	  if($('input:checkbox[name=equChk]:checked').length > 1){
		alert("한개만 선택해주세요")
		return false;
	  }
	  const target = $('input:checkbox[name=equChk]:checked');
	  const equKey = Number(target.parents('tr').find('.equKey').val());
	  showUpdateModal(equKey);  
})

function showUpdateModal(equKey){
	$.ajax({
		    url: '/equip/updatePage',
		    data: {equKey: equKey},
		    type: 'GET',
		    dataType:"html",
		    success: function(html){
		      $("#equipEditModalContent").empty().append(html)
		      $("#equipModifyModal").modal('show');
		      $(".mStoredYear").datepicker({
						 minViewMode: 'years',
		                format: "yyyy",
		                language: "ko"
		      })
		    },
		    error:function(){
		
		    }
	  });		
}

$(document).on('click', '#addImgBtn', function (){
	$("#imgUpload").remove();
	$("#addImgBtn").hide();
	$("#imgUpdate").show();
 
})

function deleteImg(equKey,versionNo){
	$('#equipModifyForm').append('<input type="hidden" name="deleteFileKey" value="'+equKey+'">',
								 '<input type="hidden" name="deleteFileVnum" value="'+versionNo+'">');
	$("#imgUpload").remove();
	$("#deleteImgBtn").hide();
	$("#imgUpdate").show();
}

$(document).on('click', '#updateEquip', function (){
	if($('#mMgtOrgan').val() == ''){
		alert("관리처를 선택해주세요.");
		$('#mMgtOrgan').focus();
		return false;
	}
	if($('#mItemQty').val() == ''){
		alert("수량을 입력해주세요.");
		$('#mItemQty').focus();
		return false;
	}
	if(confirm("수정하시겠습니까?")){
	  document.getElementById("mMgtOrgan").disabled = false;
      let ajaxUrl = "/equip/updateEquip";
      const formData = new FormData($("#equipModifyForm")[0]);
      contentFade("in");
      $.ajax({
        type : 'POST',
        data : formData,
        url : ajaxUrl,
        processData: false,
        contentType: false,
        success : function(data) {
            alert("수정되었습니다.");
            showUpdateModal(data); 
            contentFade("out");
        },
        error : function(xhr, status) {
          alert("수정에 실패하였습니다.")
          contentFade("out");
        }
      })
    }
   
});

$(document).on('click', '#historyBtn', function (){
	  if($('input:checkbox[name=equChk]:checked').length < 1){
		alert("게시물을 선택해주세요")
		return false;
	  }
	  if($('input:checkbox[name=equChk]:checked').length > 1){
		alert("한개만 선택해주세요")
		return false;
	  }
	  const target = $('input:checkbox[name=equChk]:checked');
	  const equKey = Number(target.parents('tr').find('.equKey').val());
	  $.ajax({
		    url: '/equip/historyView',
		    data: {equKey: equKey},
		    type: 'GET',
		    dataType:"html",
		    success: function(html){
		      $("#configEqu").empty().append(html)
		      $("#equipModifyModal").modal('show');
		    },
		    error:function(){
		
		    }
	  });		  
})

$(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: '/equip/HistoryDetail',
	    data: {
				equKey : Number($(this).find(".equKey").val()),
				versionNo : Number($(this).find(".verNo").val())
				},
	    type: 'GET',
	    dataType:"json",
	    success: function(data){
			$('#vSosok').val(data.sosok);
			$('#vEquType').val(data.equType);
			$('#vDetailType').val(data.detailType);
			$('#vStoredYear').val(data.storedYear);
			$('#vItemQty').val(data.itemQty);
			$('#vItemCondition').val(data.itemCondition);
			$('#vNote').val(data.note);
			$('#vImgName').val(data.origNm);
		
	    },
	    error:function(){
	
	    }
  });
})

$(document).on('click', '#equDeleteBtn', function (){
	if(confirm("선택한 대상을 삭제처리 하시겠습니까?")){
	 const checkArr = [];
		$('input:checkbox[name=equChk]:checked').each(function (idx, el){
	      checkArr.push({});
	      const target = $(el);
	      checkArr[idx].equKey = Number(target.parents('tr').find('.equKey').val());     
   		})
   		deleteEquip(checkArr);	

	}	
})

$(document).on('click', '#deleteEquip', function (){
	if(confirm("선택한 대상을 삭제처리 하시겠습니까?")){
	 const checkArr = [];
	      checkArr.push({});
	      checkArr[0].equKey = Number($('#mEquKey').val());	
	      deleteEquip(checkArr);
	}	
})

function deleteEquip(checkArr){
	$.ajax({
		    type : 'POST',
		    url : "/equip/epuipDelete",
		    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).ready( function() {
  $('#chk-all').click( function() {
    $('.equInfoCheckBox').prop('checked',this.checked);
  });
});

$(document).on('click', '#statusExcel', function (){
	if(confirm("엑셀로 다운로드 하시겠습니까?")){
		location.href='/equip/statusExcelDown'
	}
})

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