const files = [];

$(function(){
  if(pageType === "modify"){
    $(".categorySelector").removeAttr("disabled");
    setParentCategory(4, $("#categorySeq").find("[selected]").attr("data-parentseq"));
  }

  $("#uploadDiv").on("dragenter", function(e) {
    // $(this).addClass('drag-over');
  }).on("dragleave", function(e) {
    // $(this).removeClass('drag-over');
  }).on("dragover", function(e) {
    e.stopPropagation();
    e.preventDefault();
  }).on('drop', function(e) {
    e.preventDefault();
    // $(this).removeClass('drag-over');
    for(const file of e.originalEvent.dataTransfer.files){
      setFileDiv(file, files.push(file));
    }
  }).on('click', function (e){
    if(e.target.className.indexOf("ileDelete")<0){
      $("#fileInputer").click();
    }
  });

  $("#description").summernote({
    lang:'ko-KR',
    height: 120,
    disableDragAndDrop: true,
    toolbar: [
      ['style', ['style']],
      ['font', ['bold', 'underline', 'clear']],
      ['color', ['color']],
      ['para', ['ul', 'ol', 'paragraph']],
      ['table', ['table']]
    ]
  })
})
$(document).on('change', '#fileInputer', function (){
  for(const file of this.files){
    setFileDiv(file, files.push(file));
  }
  this.value = null;
})
$(document).on('click', '.fileDelete', function (){
  const target = $(this);
  files[Number(target.attr("data-fileidx"))].isDelete = true;
  target.parent().remove();
  const uploadDiv = $("#uploadDiv");
  if(uploadDiv.children().length === 0){
    uploadDiv.append("<br>파일을 업로드 해주세요.");
  }
})
$(document).on('click', '.uploadedFileDelete', function (){
  const target = $(this).parent().find("span")[0];
  if(target.className===""){
    target.className = "text-decoration-line-through";
  }else{
    target.className = "";
  }
})
$(document).on('click', '#saveBtn', function (){
  if(contentCheck()){
    if(confirm("저장하시겠습니까?")){
      let ajaxUrl = "/board/saveContent";
      const formData = new FormData($("#contentForm")[0]);
      const status = $("#status:checked").val()
      formData.append("status", status===undefined?"B":status);

      for(const file of files) {
        if(!file.isDelete)
          formData.append('uploadFiles', file, file.name);
      }
      if(pageType==='modify'){
        ajaxUrl = "/board/updateContent";
        $(".text-decoration-line-through").each(function (idx, el){
          formData.append('fileSeq', $(el).attr("data-fileseq"));
        })
      }
      $.ajax({
        type : 'POST',
        data : formData,
        url : ajaxUrl,
        processData: false,
        contentType: false,
        success : function(result) {
          if(result>0){
            alert("저장되었습니다.");
            location.href = "/board/contentList?categorySeq="+$("#categorySeq").val();
          }
        },
        error : function(xhr, status) {

        }
      })
    }
  }
})
$(document).on('change', '.categorySelector', function (){
  const categorySeq = Number(this.value);
  const depth = Number($(this).attr("data-depth"));
  if(!isNaN(categorySeq)){
    setCategorySelector(depth+1, categorySeq);
  }else{
    selectorDisabler(depth);
  }
  if(this.id === "categorySeq"){
    categoryRoleCheck($(this).find(":selected")[0].className);
  }
})

function categoryRoleCheck(optionClass){
  if(optionClass.indexOf("success")<0){
    // 권한이 없을경우
    alert("해당 분류에 작성 권한이 없습니다. \n관리자에게 요청 권한을 요청해주시기 바랍니다.");
    $("#categorySeq").children()[0].selected = true;
  }
}
function setCategorySelector(depth, categorySeq){
  selectorDisabler(depth);
  $("[data-depth='"+depth+"']").children().each(function (){
    const option = $(this)
    const parentSeq = Number(option.attr("data-parentseq"));
    if(!isNaN(parentSeq)){
      if(parentSeq === categorySeq){
        option.removeAttr("style");
      }else{
        option.css("display", "none");
      }
    }
  })
}

function selectorDisabler(depth){
  $(".categorySelector").each(function(){
    const selector = $(this)
    const selectorDepth = Number(selector.attr("data-depth"));
    selector.attr("disabled", (selectorDepth>depth));
    if(selectorDepth>=depth){
      this[0].selected = true;
    }
  })
}

function setParentCategory(depth, parentSeq){
  $(".categorySelector[data-depth='"+depth+"']").children().each(function (){
    const option = $(this)
    if(parentSeq === option.attr("data-parentseq")){
      option.removeAttr("style");
    }else{
      option.css("display", "none");
    }
  })
  const nextTarget = $("option[value='"+parentSeq+"']");
  nextTarget.attr("selected", "selected");
  if(depth!==1){
    setParentCategory(depth-1, nextTarget.attr("data-parentseq"));
  }
}

function setFileDiv(file, idx){
  const uploadDiv = $("#uploadDiv");
  if($(".uploadedFileDelete").length===0 && $(".fileDelete").length === 0){
    uploadDiv.empty();
  }
  let fileInfo = "<div class='row-col-6'>";
  fileInfo += file.name+" "+byteCalculation(file.size)+" ";
  fileInfo += "<a href='#' class='fileDelete text-danger text-decoration-none' data-fileidx='"+(idx-1)+"'>삭제</a>";
  fileInfo += "</div>";
  uploadDiv.append(fileInfo);
}

function contentCheck(){
  let flag = true;
  if(!$("#categorySeq").val()){
    alert("분류 선택이 되지 않았습니다.")
    flag = false;
  }
  if(!$("#title").val()){
    alert("제목을 입력해주세요.")
    flag = false;
  }
  if(pageType === "new"){
    if($(".fileDelete ").length===0){
      alert("업로드 할 파일이 없습니다.")
      flag = false;
    }
    let totalSize = 0;
    for(const file of files) {
      if(!file.isDelete){
        totalSize+=file.size;
        if(file.size>20971520){
          alert("파일당 사이즈는 20MB을 넘길 수 없습니다.")
        }
      }
    }
    if(totalSize>104857600){
      alert("첨부파일의 용량 합은 100MB를 넘길 수 없습니다.")
    }
  }
  return flag;
}

function byteCalculation(size) {
  const bytes = parseInt(size);
  const s = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB'];
  const e = Math.floor(Math.log(bytes)/Math.log(1024));

  if(e === "-Infinity") return "0 "+s[0];
  else return (bytes/Math.pow(1024, Math.floor(e))).toFixed(2)+" "+s[e];

}