
$(document).on('click', '#addPartInfo', function (){
   $.ajax({
    url: '/target/partInfoEditModal',
    type: 'GET',
    dataType:"html",
    success: function(html){
      $("#partInfoEditModalEditModalContent").empty().append(html);
      $("#partInfoEditModal").modal('show');
      $("#rentPrice").hide();
      $("#utilityPrice").hide();
      changeManager($("#mgtOrgan").val());
      setUploadDiv();
    },
    error:function(){

    }
  });
})

$(document).on('change', '#rentType', function (){
	if($("#rentType").val() == 'Y'){
		$("#rentPrice").show();
	}else{
		$("#rentPrice").hide();
		$("#rentPrice").val('');
	}		
});

$(document).on('change', '#utilityType', function (){
	if($("#utilityType").val() == 'Y'){
		$("#utilityPrice").show();
	}else{
		$("#utilityPrice").hide();
		$("#utilityPrice").val('');
	}		
});

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


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

$(document).on('change', '#mMgtOrgan', function (){
	const ogCd = $(this).val();
	if(ogCd != ''){
		$.ajax({
		    url: '/target/partInfoSelecBox',
		    data: {
					ogCd,
					},
		    type: 'GET',
		    dataType:"html",
		    success: function(html){
		      $("#mPiUserSeq").empty().append(html);
		      $("#mPiUserSeq").prop('disabled',false);
		    },
		    error:function(){		
		    }
	  });
  }else{
	$("#mPiUserSeq").prop('disabled',true);
	$("#mPiUserSeq").val('');
  }
});

$(document).on('click', '#savePartInfo', function (){
   if($('#mgtOrgan').val() == ''){
		alert('해경서를 선택해주세요');
		$('#mgtOrgan').focus();
		return false;
   }
   if($('#piUserSeq').val() == ''){
		alert('담당자를 선택해주세요');
		$('#piUserSeq').focus();
		return false;
   }
   if($('#terminalNm').val() == ''){
		alert('터미널명을 입력해주세요');
		$('#terminalNm').focus();
		return false;
   }
   if($('#mpWorkType').val() != ''){
	if($('#mpPeopleCnt').val() == ''){
		alert('해경 인원수를 입력해주세요');
		$('#mpPeopleCnt').focus();
		return false;
	}
   }
   if($('#plWorkType').val() != ''){
	if($('#plPeopleCnt').val() == ''){
		alert('육경 인원수를 입력해주세요');
		$('#plPeopleCnt').focus();
		return false;	
	}
   }
   if($("#rentType").val() == 'Y'){
		if($("#rentPrice").val() == ''){
			alert("임차료를 입력해주세요.");
			$('#rentPrice').focus();
			return false;
		}
   }
   if($("#utilityType").val() == 'Y'){
		if($("#utilityPrice").val() == ''){
			alert("공공요금을 입력해주세요.");
			$('#utilityPrice').focus();
			return false;
		}
   }
   if(confirm("저장하시겠습니까?")){
	  document.getElementById("mgtOrgan").disabled = false;
      contentFade("in");
      const formData = new FormData($("#partInfoSave")[0]);
      for(const file of files) {
        if(!file.isDelete)
          formData.append('uploadFiles', file, file.name);
      }
      $.ajax({
        type : 'POST',
        data : formData,
        url : "/target/savePartInfo",
        processData: false,
        contentType: false,
        success : function(result) {
          alert("저장되었습니다.");
          contentFade("out");
		  location.reload();
        },
        error : function(xhr, status) {
          alert("저장에 실패하였습니다.")
          contentFade("out");
        }
      })
    }
})

$(document).on('click', '.partInfoTr', function (){
	const piSeq = (Number($(this).find(".piSeq").val()));
    showModal(piSeq);
})

function showModal(piSeq){
	$.ajax({
    url: '/target/updatePartInfoPage',
    data: {
			piSeq: piSeq
			},
    type: 'GET',
    dataType:"html",
    success: function(html){
      $("#partInfoEditModalEditModalContent").empty().append(html);
      $("#partInfoEditModal").modal('show');
      if($("#mRentType").val() != 'Y'){
		 $("#mRentPrice").hide();
	  }
	  if($("#mUtilityType").val() != 'Y'){
		 $("#mUtilityPrice").hide();
	  }
      setUploadDiv();
    },
    error:function(){

    }
  });
}

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

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

$(document).on('change', '#mRentType', function (){
	if($("#mRentType").val() == 'Y'){
		$("#mRentPrice").show();
	}else{
		$("#mRentPrice").hide();
		$("#mRentPrice").val('');
	}		
});

$(document).on('change', '#mUtilityType', function (){
	if($("#mUtilityType").val() == 'Y'){
		$("#mUtilityPrice").show();
	}else{
		$("#mUtilityPrice").hide();
		$("#mUtilityPrice").val('');
	}		
});

$(document).on('click', '#updatePartInfo', function (){
   if($('#mMgtOrgan').val() == ''){
		alert('해경서를 선택해주세요');
		$('#mMgtOrgan').focus();
		return false;
   }
   if($('#mPiUserSeq').val() == ''){
		alert('담당자를 선택해주세요');
		$('#mPiUserSeq').focus();
		return false;
   }
   if($('#mTerminalNm').val() == ''){
		alert('터미널명을 입력해주세요');
		$('#mTerminalNm').focus();
		return false;
   }
   if($('#mMpWorkType').val() != ''){
	if($('#mMpPeopleCnt').val() == ''){
		alert('해경 인원수를 입력해주세요');
		$('#mMpPeopleCnt').focus();
		return false;
	}
   }
   if($('#mPlWorkType').val() != ''){
	if($('#mPlPeopleCnt').val() == ''){
		alert('육경 인원수를 입력해주세요');
		$('#mPlPeopleCnt').focus();
		return false;	
	}
   }
   if($("#mRentType").val() == 'Y'){
		if($("#mRentPrice").val() == ''){
			alert("임차료를 입력해주세요.");
			$('#mRentPrice').focus();
			return false;
		}
   }
   if($("#mUtilityType").val() == 'Y'){
		if($("#mUtilityPrice").val() == ''){
			alert("공공요금을 입력해주세요.");
			$('#mUtilityPrice').focus();
			return false;
		}
   }
   if(confirm("수정하시겠습니까?")){
	  document.getElementById("mMgtOrgan").disabled = false;
      contentFade("in");
      const formData = new FormData($("#partInfoUpdate")[0]);
      for(const file of files) {
        if(!file.isDelete)
          formData.append('uploadFiles', file, file.name);
      }
      $(".text-decoration-line-through").each(function (idx, el){
        formData.append('fileSeq', $(el).attr("data-fileseq"));
      })
      $.ajax({
        type : 'POST',
        data : formData,
        url : "/target/updatePartInfo",
        processData: false,
        contentType: false,
        success : function(result) {
          alert("수정되었습니다.");
          contentFade("out");
		  showModal(result);
        },
        error : function(xhr, status) {
          alert("수정에 실패하였습니다.")
          contentFade("out");
        }
      })
    }
})

function showHistory(piSeq){
	$.ajax({
    url: '/target/PartInfoHistoryPage',
    data: {
			piSeq: piSeq
			},
    type: 'GET',
    dataType:"html",
    success: function(html){
      $("#partInfoEditModalEditModalContent").empty().append(html);
      $("#partInfoEditModal").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: '/target/partInfoHistoryView',
    data: {
			piSeq: Number($(this).find(".piSeq").val()),
			versionNo : Number($(this).find(".verNo").val())
			},
    type: 'GET',
    dataType:"json",
    success: function(data){
		$('#hMgtOrgan').val(data.mgtOrgan);
		$('#hLandPolice').val(data.landPolice);
		$('#hPiUserSeq').val(data.piManagerName);
		$('#hMpWorkType').val(data.mpWorkType);
		$('#hMpPeopleCnt').val(data.mpPeopleCnt);
		$('#hMpDescription').val(data.mpDescription);
		$('#hPlWorkType').val(data.plWorkType);
		$('#hPlPeopleCnt').val(data.plPeopleCnt);
		$('#hPlDescription').val(data.plDescription);
		$('#hTerminalNm').val(data.terminalNm);
		$('#hRentType').val(data.rentType);
		$('#hRentPrice').val(data.rentPrice);
		$('#hUtilityType').val(data.utilityType);
		$('#hUtilityPrice').val(data.utilityPrice);
		if(data.fileList[0].origNm != null){
			$('#historyFile').empty();
			for(var i=0;i<data.fileList.length;i++){			
				$('#historyFile').append(
					'<input type="text" class="form-control" value="'+data.fileList[i].origNm+'.'+data.fileList[i].fileExtn+'" readonly>'
				);	
			}
		}else{
			$('#historyFile').empty().append(
				'<input type="text" class="form-control" value="업로드 파일없음" readonly>'
			);
		}
    },
    error:function(){

    }
  });
})

$(document).on('click', '#deletePartInfo', function (){
	const piSeq = $('input[name=piSeq]').val();
   if(confirm("삭제하시겠습니까?")){
      contentFade("in");
      $.ajax({
	    type : 'POST',
	    url : "/target/deletePartInfo",
	    data : JSON.stringify({piSeq:piSeq}),
	    contentType: 'application/json',
	    beforeSend: function (xhr){
	      xhr.setRequestHeader($("[name='_csrf_header']").val(), $("[name='_csrf']").val());
	    },
	    success : function(data) {
	      alert("삭제 처리되었습니다.");
	      location.reload();
	    },
	    error : function(xhr, status) {
	      alert("삭제 처리에 실패하였습니다");
	    }
	  })

	}
})

$(document).on('click', '.fileDownPartInfo', function (){
  const target = $(this)
  let url = "/target/partInfoFileDownload?"
  url += "&fileSeq="+target.attr("data-fileSeq");
  url += "&piSeq="+target.attr("data-piSeq");
  url += "&versionNo="+target.attr("data-verNo");
  window.open(encodeURI(url));
})

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

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



