$(document).on('click', '#addCellPhone', function (){
   showModal(null);
})

$(document).on('change', '#mgtOrgan', function (){
	const ogCd = $(this).val();
	if(ogCd != ''){
		changeManager(ogCd);		
  }else{
	$("#pUserSeq").prop('disabled',true);
	$("#pUserSeq").val('');
  }
});


function changeManager(ogCd){
	$.ajax({
		    url: '/equip/cellPhoneSelecBox',
		    data: {
					ogCd,
					},
		    type: 'GET',
		    dataType:"html",
		    success: function(html){
		      $("#pUserSeq").empty().append(html);
		      $("#pUserSeq").prop('disabled',false);
		    },
		    error:function(){		
		    }
	  });
}

$(document).on('click', '#saveCellPhone', function (){
   if(Validation()){
	   if(confirm("저장하시겠습니까?")){
		  document.getElementById("mgtOrgan").disabled = false;
	      contentFade("in");
	      const formData = new FormData($("#cellPhoneEditFm")[0]);
	      $.ajax({
	        type : 'POST',
	        data : formData,
	        url : "/equip/saveCellPhone",
	        processData: false,
	        contentType: false,
	        success : function(result) {
	          alert("저장되었습니다.");
	          contentFade("out");
			      location.reload();
	        },
	        error : function(xhr, status) {
	          alert("저장에 실패하였습니다.")
	          contentFade("out");
	        }
	      })
	    }
    }
})

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

function showModal(phoneKey){	
	$.ajax({
    url: '/equip/cellPhoneEditModal',
    data: {phoneKey: phoneKey},
    type: 'GET',
    dataType:"html",
    success: function(html){
      $("#cellPhoneEditModalContent").empty().append(html);
      $("#cellPhoneEditModal").modal('show');
      if(phoneKey == null){
      	changeManager($("#mgtOrgan").val());
      }
    },
    error:function(){

    }
  });
}

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

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

$(document).on('click', '#deleteCellPhone', function (){
	if($('input:checkbox[name=cpChk]:checked').length < 1){
		alert("게시물을 선택해주세요")
		return false;
	}
	if(confirm("선택한 대상을 삭제처리 하시겠습니까?")){
	 const checkArr = [];
		$('input:checkbox[name=cpChk]:checked').each(function (idx, el){
	      checkArr.push({});
	      const target = $(el);
	      checkArr[idx].phoneKey = Number(target.parents('tr').find('.phoneKey').val());	      
    	})
    	deleteCellPhone(checkArr);	

	}	
})

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

function deleteCellPhone(checkArr){
	$.ajax({
		    type : 'POST',
		    url : "/equip/deleteCellPhone",
		    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;
	}
})

function Validation(){
	let flag = true;
 	const emailRule = /^[0-9a-zA-Z]([-_.]?[0-9a-zA-Z])*@[0-9a-zA-Z]([-_.]?[0-9a-zA-Z])*.[a-zA-Z]{2,3}$/i;
	const regExp = /^\d{2,3}-\d{3,4}-\d{4}$/;
	if($('#mgtOrgan').val() == ""){
		alert("관리처를 선택해주세요.");
		$('#mgtOrgan').focus();
		flag = false;
	}
	if($('#pUserSeq').val() == ""){
		alert("사용자를 선택해주세요.");
		$('#pUserSeq').focus();
		flag = false;
	}
	if($('#telNo').val() != ""){
		if(!regExp.test($("input[id='telNo']").val())) {
			alert("전화번호 형식이 맞지않습니다.");
			$('#telNo').focus();
			flag = false;	
		}
	}
	if($('#extMail').val() != ""){
		if(!emailRule.test($("input[id='extMail']").val())) {
			alert("이메일 형식이 맞지않습니다.");
			$('#extMail').focus();
			flag = false;	
		}
	}
  return flag;
}

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