$(function(){

})

$(document).on('click', '.categoryTr', function (){
  const target = $(this).find(".trCheckBox");
  const depth = Number(target.val());
  const parentSeq = checkBoxAction(target);
  if(depth !== 4){
    getCategoryTable(parentSeq, depth+1);
  }
})
$(document).on('click', '.insertTr', function (){
  const target = $(this).find(".trCheckBox");
  checkBoxAction(target);
})
$(document).on('click', '.addCategoryBtn', function (){
  const depth = Number($(this).attr("data-depth"));
  const appendTr = $("#appendTr").children().clone();
  if(Number(depth)>1){
    const parentSeq = $(".trCheckBox:checked[value='"+(depth-1)+"']").parent().find(".categorySeq").val()
    if(parentSeq === undefined){
      alert("선택된 상위 메뉴가 없습니다.")
      return false;
    }
    appendTr.find(".parentSeq").val(parentSeq);
  }
  appendTr[0].className = "insertTr";
  appendTr.find(".trCheckBox").val(depth);
  appendTr.find(".depth").val(depth);
  $("#depth"+depth+"Category").append(appendTr);
})

$(document).on('click', '.deleteCategoryBtn', function (){
  let depth = Number($(this).attr("data-depth"));
  const target = $(".trCheckBox:checked[value='"+depth+"']");
  if(target.length>0){
    const category = depth===1?"대분류":(depth===2?"연도":(depth===3?"중분류":(depth===4?"소분류":'')));
    const categorySeq = target.parent().find(".categorySeq").val()
    if(categorySeq===undefined || categorySeq===''){
      // DB에 등록되지 않은 분류
      deleteTr(target.parent().parent());
    }else{
      let msg = "";
      if(category!=="소분류"){
        msg = "\n하위 모든 분류가 삭제됩니다."
      }
      if(confirm(category+"의 선택된 분류를 삭제하시겠습니까?"+msg)){
        $.ajax({
          type : 'DELETE',
          url : "/admin/deleteCategory",
          data : {categorySeq: categorySeq, depth: depth},
          beforeSend: function (xhr){
            xhr.setRequestHeader($("[name='_csrf_header']").val(), $("[name='_csrf']").val());
          },
          success : function(data) {
            alert("저장되었습니다.");
            const target = $(".categorySeq[value='"+data+"']")
            deleteTr(target.parent().parent());
          },
          error : function(xhr, status) {

          }
        })
      }

    }
  }
})

$(document).on('click', '#saveCategoryBtn', function (){
  const categoryList = [];
  $(".insertTr").each(function (idx, el){
    categoryList.push({});
    const target = $(el);
    categoryList[idx].depth = target.find(".depth").val();
    categoryList[idx].parentSeq = target.find(".parentSeq").val();
    categoryList[idx].categoryName = target.find(".categoryName").val();
  })

  if(categoryList.length !== 0) {
    if (confirm(categoryList.length + "건을 저장하시겠습니까?")) {
      $.ajax({
        type : 'POST',
        url : "/admin/insertCategory",
        data : JSON.stringify(categoryList),
        contentType: 'application/json',
        beforeSend: function (xhr){
          xhr.setRequestHeader($("[name='_csrf_header']").val(), $("[name='_csrf']").val());
        },
        success : function(data) {
          alert("저장되었습니다.");
          const depth = data;
          const parentSeq = $(".trCheckBox:checked[value='"+(depth-1)+"']").parent().find(".categorySeq").val()
          getCategoryTable(parentSeq, depth);
        },
        error : function(xhr, status) {

        }
      })
    }
  }
})

function checkBoxAction(target){
  const depth = Number(target.val());
  const parentSeq = Number($(target).parent().find(".categorySeq").val());
  $(".trCheckBox[value='"+depth+"']").prop("checked", false);
  target[0].checked = true;
  return parentSeq;
}

function getCategoryTable(parentSeq, depth){
  $.ajax({
    url: '/admin/getChildCategoryTable',
    type: 'GET',
    data : {parentSeq: parentSeq, depth: depth},
    dataType:"html",
    success: function(html){
      let depth = Number($(html).find("thead").attr("data-depth"));
      $("#depth"+depth+"Div").empty().append(html);
      childTableReset(depth);
    },
    error:function(){

    }
  });
}

function deleteTr(target){
  childTableReset(Number(target.find(".trCheckBox").val()))
  target.remove();
}

function childTableReset(depth){
  let childTbody
  do{
    depth++;
    childTbody = $("#depth"+depth+"Category")
    childTbody.empty();
  }while (childTbody.length>0)
}