$(function (){
  $("#selectedCategoryDiv").sortable();
})
$(document).on('click', '#categoryName', function (){
  $("#categorySelectModalBtn").click();
})

$(document).on('click', '.categoryTr', function (){
  const checkBox = $(this).find(".categoryCheckBox");
  const depth = Number(checkBox.attr("data-depth"));
  const categorySeq = checkBox.attr("data-categoryseq");
  $(".depth"+depth+"Tr").find(".categoryCheckBox").prop("checked", false);
  checkBox[0].checked = true;
  setCategoryTable(depth+1, categorySeq);
})

$(document).on('click', '#categoryDownBtn', function (){
  const selectedCategory = getSelectedCategory();
  const categorySeq = selectedCategory.attr("data-categoryseq");
  if(parentCheck(categorySeq)){
    childCheck(categorySeq);
    const categoryName = selectedCategory.attr("data-categoryname");
    const depth = selectedCategory.attr("data-depth");
    let categoryHtml = "<li class='nav-item mx-3 btn btn-secondary btn-sm selectedCategory'" +
        " id='selectedCategory"+categorySeq+"' data-categoryseq='"+categorySeq+"'" +
        " data-categoryname='"+categoryName+"' data-depth='"+depth+"'>" +
        "<input type='radio' class='categoryRadio' id='categoryRadio"+categorySeq+"' name='categoryRadio'>"+
        "<label for='categoryRadio"+categorySeq+"'> "+categoryName+"</label></li>";
    $("#selectedCategoryDiv").append(categoryHtml);
  }
})

$(document).on('click', '#categoryUpBtn', function (){
  $(".categoryRadio:checked").parent().remove();
})

$(document).on('click', '#categorySelectBtn', function (){
  const selectedCategory = $(".selectedCategory");
  let categorySeq = "";
  let categoryNames = "";
  selectedCategory.each(function (idx, el){
    categorySeq += $(el).attr("data-categoryseq")+",";
    categoryNames += $(el).attr("data-categoryName")+", ";
  })
  $("#searchCategorySeq").val(categorySeq.slice(0, -1));
  $("#categoryName").val(categoryNames.slice(0, -2));
  $("#categorySelectModal").find(".btn-close").click();
})

$(document).on('click', '#searchBtn', function (){
  if(searchParamCheck()){
    const formData = new FormData($("#searchForm")[0])
    $.ajax({
      type: "POST",
      url: '/board/fullSearchBoardContent',
      data: formData,
      processData: false,
      contentType: false,
      beforeSend: function (xhr){
        xhr.setRequestHeader($("[name='_csrf_header']").val(), $("[name='_csrf']").val());
      },
      success: function (html) {
        $("#searchResultDiv").empty().append(html)
      },
      error: function () {

      }
    });
  }
})

function searchParamCheck(){
  if(!$("#searchCategorySeq").val()){
    alert("분류를 하나 이상 선택해주셔야 합니다.")
    return false;
  }
  let emptyCnt = 0;
  if(!$("#title").val()){
    emptyCnt++;
  }
  if(!$("#createName").val()){
    emptyCnt++;
  }
  if(!$("#tagName").val()){
    emptyCnt++;
  }
  if(!$("#startDate").val() || !$("#endDate").val()){
    emptyCnt++;
  }
  if(!$("#originalName").val()){
    emptyCnt++;
  }
  if(emptyCnt>4){
    alert("분류를 제외한 조건 중 1가지 이상 입력해주세요.")
    return false;
  }else{
    return true;
  }
}

function parentCheck(categorySeq){
  const radio = $("#categoryRadio"+categorySeq);
  if(radio.length>0){
    alert("상위 분류 "+radio.parent().attr("data-categoryname")+"이(가) 선택되어 있습니다.")
    return false;
  }else{
    const parentseq = $("[data-categoryseq='"+categorySeq+"']").parents("tr").attr("data-parentseq");
    if(!parentseq){
      return true;
    }else{
      return parentCheck(parentseq);
    }
  }
}
function childCheck(parentSeq){
  const childCategorys = $("[data-parentseq='"+parentSeq+"']");
  childCategorys.each(function (idx, el){
    const categorySeq = $(el).find(".categoryCheckBox").attr("data-categoryseq");
    const radio = $("#categoryRadio"+categorySeq)
    if(radio.length>0){
      alert("하위분류 "+radio.parent().attr("data-categoryname")+"가 삭제되었습니다.");
      radio.parent().remove();
    }
    childCheck(categorySeq);
  })
}

function setCategoryTable(depth, parentSeq){
  setTableDefault(depth);
  let childCategoryIsNull = true;
  const nextTr = $(".depth"+depth+"Tr");
  nextTr.each(function (idx, el){
    const tr = $(el)
    if(tr.attr("data-parentseq")===parentSeq){
      tr.show();
      childCategoryIsNull = false;
    }else{
      tr.hide();
    }
  })
  if(childCategoryIsNull){
    $(nextTr[0]).show();
  }
}

function setTableDefault(depth){
  for(let i=depth; i<=4; i++){
    const nextDepthTr = $(".depth"+i+"Tr");
    nextDepthTr.hide();
    nextDepthTr.find(".categoryCheckBox").prop("checked", false);
    $(nextDepthTr[0]).show();
  }
}

function getSelectedCategory(){
  for(let i=4; i>0; i--){
    const checkBox = $(".depth"+i+"Tr").find(".categoryCheckBox:checked")
    if(checkBox.length>0){
      return checkBox;
    }
  }
}