let categoryList = []
let maxSeq = 1;
$(function (){
  getCategoryList();
})
$(document).on('click', '.categoryTr', function (){
  const chooseTr = $(this)
  chooseTr.parent().find(".trCheckBox").prop("checked", false);
  chooseTr.find(".trCheckBox").prop("checked", true);
  setCategoryTable(Number(chooseTr.attr("data-depth"))+1, Number(chooseTr.attr("data-categoryseq")));
})
$(document).on('change', '.categoryName, .sortCnt', function (){
  const categoryInfo = $(this).parents("tr");
  const changedValue = this.value;
  let sortCntFlag = this.className.includes("sortCnt")&&(changedValue !== categoryInfo.attr("data-sortcnt"));
  let categoryNameFlag = this.className.includes("categoryName")&&(changedValue !== categoryInfo.attr("data-categoryname"));
  if(sortCntFlag || categoryNameFlag){
    categoryList.forEach(function (category){
      if(category.categorySeq === Number(categoryInfo.attr("data-categoryseq"))){
        if(categoryNameFlag)
          category.categoryName = changedValue;
        if(sortCntFlag)
          category.sortCnt = changedValue;
        if(category.status !== "added")
          category.status = "modified";
      }
    })
    categoryInfo[0].className += "bg-warning bg-opacity-25";
  }
})
$(document).on('click', '.addCategoryBtn', function (){
  const depth = Number($(this).attr("data-depth"));
  const parentCategory = $("#depth"+(depth-1)+"Tbody").find(".trCheckBox:checked").parents("tr");
  if(depth!==1 && parentCategory.length===0){
    alert("상위 분류를 선택해 주세요.");
  }else if(parentCategory.attr("data-status")==="deleted"){
    alert("삭제될 상위 분류에는 추가할 수 없습니다.");
  }else{
    const parentSeq = parentCategory.attr("data-categoryseq");
    categoryList.push({
      categorySeq: maxSeq++,
      parentSeq: depth===1?null:Number(parentSeq),
      categoryName: "신규",
      sortCnt: 0,
      depth: depth,
      status: "added"
    })
    setCategoryTable(depth, depth===1?null:Number(parentSeq));
  }
})
$(document).on('click', '.copyCategory', function (){
  const copyInfo = $(this).parents("tr")
  if(confirm(copyInfo.attr("data-categoryname")+"을 복사하시겠습니까?")){
    const depth = Number(copyInfo.attr("data-depth"));
    const parentSeq = copyInfo.attr("data-parentseq");
    const lastSeq = maxSeq++;
    let copyList = [{
      categorySeq: lastSeq,
      parentSeq: depth===1?null:Number(parentSeq),
      categoryName: "복사된 분류",
      depth: depth,
      sortCnt: 0,
      status: "added"
    }];
    copyList = copyList.concat(getCopyData(depth+1, Number(copyInfo.attr("data-categoryseq")), lastSeq));
    categoryList = categoryList.concat(copyList);
    setCategoryTable(depth, depth===1?null:Number(parentSeq));
    $("[data-categoryseq="+copyInfo.attr("data-categoryseq")+"]").find(".trCheckBox").click();
  }
})
$(document).on('click', '.deleteCategory', function (){
  const categoryInfo = $(this).parents("tr");
  const categorySeq = categoryInfo.attr("data-categoryseq");
  if(categoryInfo.attr("data-status") !== "deleted"){
    if(confirm("선택된 분류와 하위 분류를 삭제하시겠습니까?\n등록된 자료가 모두 삭제됩니다.")){
      statusChange("deleted", Number(categorySeq));
    }
  }else{
    if(confirm("삭제를 취소 하시겠습니까?")){
      statusChange("saved", Number(categorySeq));
    }
  }
  const parentSeq = categoryInfo.attr("data-parentseq");
  setCategoryTable(Number(categoryInfo.attr("data-depth")), parentSeq!=="null"?Number(parentSeq):null);
  $("[data-categoryseq="+categorySeq+"]").find(".trCheckBox").prop("checked", true);
})

$(document).on('click', '#saveCategoryBtn', function (){
  const saveList = [];
  categoryList.forEach(function (category){
    // 변경 내용이 없는 분류, 추가 되었으면서 삭제된 분류 제외
    if(category.status !== "saved" &&
      !(category.status === "deleted" && category.originalName === undefined)){
      saveList.push(category);
    }
  })
  if(saveList.length !== 0) {
    if (confirm(saveList.length + "건을 저장하시겠습니까?")) {
      contentFade("in");
      $.ajax({
        type : 'POST',
        url : "/admin/insertCategory2",
        data : JSON.stringify(saveList),
        contentType: 'application/json',
        beforeSend: function (xhr){
          xhr.setRequestHeader($("[name='_csrf_header']").val(), $("[name='_csrf']").val());
        },
        success : function(data) {
          alert("저장되었습니다.");
          sessionReload();
        },
        error : function(xhr, status) {
          alert("저장에 실패하였습니다.")
          contentFade("out");
        }
      })
    }
  }else{
    alert("저장 대상이 없습니다.");
  }
})

function getCategoryList(){
  $.ajax({
    url: '/admin/getCategoryList',
    type: 'GET',
    success: function(data){
      data.forEach(function (category){
        categoryList.push({
          categorySeq: category.categorySeq,
          parentSeq: category.parentSeq,
          categoryName: category.categoryName,
          originalName: category.categoryName,
          depth: category.depth,
          sortCnt: category.sortCnt,
          status: "saved",
        })
        if(maxSeq<=category.categorySeq){
          maxSeq = category.categorySeq+1
        }
      })
      setCategoryTable(1, null);
    },
    error:function(){

    }
  });
}

function setCategoryTable(depth, parentSeq){
  let tbody = "";
  const tableData = getTableData(categoryList, depth, parentSeq);
  tableData.forEach(function (data){
    let statusColor = "";
    switch (data.status){
      case "modified": statusColor = "bg-warning bg-opacity-25"; break;
      case "added": statusColor = "bg-success bg-opacity-25"; break;
      case "deleted": statusColor = "bg-danger bg-opacity-25"; break;
    }
    tbody += "<tr class='categoryTr "+statusColor+"' data-categoryseq='"+data.categorySeq+"'" +
        " data-parentseq='"+data.parentSeq+"' data-categoryname='"+data.categoryName+"'" +
        " data-depth='"+data.depth+"' data-sortcnt='"+data.sortCnt+"' data-status='"+data.status+"'>";
    tbody += "<td><input type='checkbox' class='trCheckBox'></td>"
    tbody += "<td><input type='text' class='form-control form-control-sm categoryName' value='"+data.categoryName+"' "+(data.status==="deleted"?"readonly":"")+"></td>"
    tbody += "<td><input type='number' class='form-control form-control-sm sortCnt' value='"+data.sortCnt+"' "+(data.status==="deleted"?"readonly":"")+"></td>"
    tbody += "<td><a href='#' class='copyCategory'><i class='bi bi-journals text-success'></i></a></td>";
    tbody += "<td><a href='#' class='deleteCategory'><i class='bi bi-x-square text-danger'></i></a></td>";
    tbody += "</tr>";
  })
  clearChildTable(depth);
  $("#depth"+depth+"Tbody").append(tbody);
}

function getCopyData(depth, parentSeq, lastSeq){
  let copyList = getTableData(categoryList, depth, parentSeq);
  let childList = [];
  copyList.forEach(function (category){
    const tempSeq = maxSeq++;
    const tempList = getCopyData(category.depth+1, category.categorySeq, tempSeq)
    category.categorySeq = tempSeq;
    category.parentSeq = lastSeq;
    category.status = "added";
    childList = childList.concat(tempList);
  })
  copyList = copyList.concat(childList);
  return copyList;
}

function getTableData(categoryList, depth, parentSeq){
  let targetList = [];
  categoryList.forEach(function (category){
    if(category.depth===depth && category.parentSeq===parentSeq){
      targetList.push({
        categorySeq: category.categorySeq,
        parentSeq: category.parentSeq,
        categoryName: category.categoryName,
        depth: category.depth,
        sortCnt: category.sortCnt,
        status: category.status
      })
    }
  });
  return targetList;
}

function clearChildTable(depth){
  for(let i=depth; i<=4; i++){
    $("#depth"+i+"Tbody").empty();
  }
}

function statusChange(status, categorySeq){
  categoryList.forEach(function (category){
    if(category.categorySeq === categorySeq){
      if(status==="saved" && category.originalName===undefined){
        category.status = "added";
      }else if(status==="saved" && category.originalName !== category.categoryName){
        category.status = "modified";
      }else{
        category.status = status;
      }
    }
    if(category.parentSeq === categorySeq){
      statusChange(status, category.categorySeq)
    }
  })
}