let codeCategoryList=[];
let selectedCategoryIdx=0;
let selectedItemIdx=0;

$(function(){
  $.ajax({
    url: '/codeMgt/selectCodeCatgList',
    type: 'GET',
    dataType:"json",
    success: function(data){
      codeCategoryList = data;
      makeCategoryTr();
    },
    error:function(){

    }
  });
});

$(document).on('click', '#categoryAddBtn', function (){
  $('#categoryTable').find('tbody').append(
      '<tr class="categoryTr">' +
        '<td><button class="btn btn-sm btn-outline-danger rowDeleteBtn"><i class="bi bi-x"></i></button></td>'+
        '<td><input type="text" class="form-control form-control-sm categoryInput" name="categoryCd"></td>'+
        '<td><input type="text" class="form-control form-control-sm categoryInput" name="categoryValue"></td>'+
        '<td><input type="text" class="form-control form-control-sm categoryInput" name="description"></td>'+
      '</tr>'
  )
  codeCategoryList.push({categoryCd:"", categoryValue: "", description: "", status:"new", itemList: []})
})
$(document).on('click', '#itemAddBtn', function (){
  $('#itemTable').find('tbody').append(
      '<tr class="itemTr">' +
        '<td><button class="btn btn-sm btn-outline-danger rowDeleteBtn"><i class="bi bi-x"></i></button></td>'+
        '<td><input type="text" class="form-control form-control-sm itemInput" name="itemCd" value="'+codeCategoryList[selectedCategoryIdx].categoryCd+'"></td>'+
        '<td><input type="text" class="form-control form-control-sm itemInput" name="itemValue"></td>'+
        '<td></td>'+
      '</tr>'
  )
  codeCategoryList[selectedCategoryIdx].itemList
      .push({categoryCd:codeCategoryList[selectedCategoryIdx].categoryCd, itemCd:codeCategoryList[selectedCategoryIdx].categoryCd, itemValue: "", useChk: "T", status:"new"})
})

$(document).on('click', '.rowDeleteBtn', function (){
  switch ($(this).parents("table")[0].id){
    case "categoryTable":
      selectedCategoryIdx = $(this).parents('tr')[0].rowIndex-1;
      codeCategoryList.splice(selectedCategoryIdx, 1);
      $("#emptyTr").show();
      $("#itemBtnRow").hide();
      break;
    case "itemTable":
      selectedItemIdx = $(this).parents('tr')[0].rowIndex-1;
      codeCategoryList[selectedCategoryIdx].itemList.splice(selectedItemIdx, 1);
      break;
  }
  $(this).parents('tr').remove();
})

$(document).on('click', '.categoryTr', function (event){
  $("#itemTable").find("tbody").find("tr").remove();
  if(event.target.classList.value === "bi bi-x"
      || event.target.classList.value.includes("rowDeleteBtn")) {
  }else{
    selectedCategoryIdx = this.rowIndex-1;
    $("#itemBtnRow").show();
    $("#emptyTr").hide();

    if(codeCategoryList[selectedCategoryIdx]!==undefined
        && codeCategoryList[selectedCategoryIdx].itemList.length>0){
      makeItemTr(codeCategoryList[selectedCategoryIdx].itemList);
    }
  }
})

$(document).on('click', '.itemTr', function (){
  selectedItemIdx = this.rowIndex-1;
})

$(document).on('change', '.categoryInput', function (){
  selectedCategoryIdx = $(this).parents('tr')[0].rowIndex-1;
  const target = codeCategoryList[selectedCategoryIdx];
  switch (this.name){
    case "categoryCd":
      target.categoryCd = this.value
      break;
    case "categoryValue":
      target.categoryValue = this.value
      break;
    case "description":
      target.description = this.value
      break;
  }
})

$(document).on('change', '.itemInput', function (){
  selectedItemIdx = $(this).parents('tr')[0].rowIndex-1;
  const target = codeCategoryList[selectedCategoryIdx].itemList[selectedItemIdx];
  switch (this.name){
    case "itemCd":
      target.itemCd = this.value
      break;
    case "itemValue":
      target.itemValue = this.value
      break;
    case "useChk":
      target.useChk = this.checked?"T":"F"
      break;
  }
})

$(document).on('click', '#codeSaveBtn', function (){
  contentFade("in");
  $.ajax({
    type : 'POST',
    url : "/codeMgt/saveCode",
    data : JSON.stringify(codeCategoryList),
    contentType: 'application/json',
    beforeSend: function (xhr){
      xhr.setRequestHeader($("[name='_csrf_header']").val(), $("[name='_csrf']").val());
    },
    success : function(data) {
      alert("저장되었습니다.");
      contentFade("out");
      location.reload();
    },
    error : function(xhr, status) {
      alert("저장에 실패하였습니다.")
      contentFade("out");
    }
  })
})

function makeCategoryTr(){
  codeCategoryList.forEach(function (category, idx){
    $("#categoryTable").find('tbody').append(
        '<tr class="categoryTr" '+(category.status==="delete"?'style="display:none;"':'')+'>' +
        '<td>'+(category.status==="new"?'<button class="btn btn-sm btn-outline-danger rowDeleteBtn"><i class="bi bi-x"></i></button>':'')+'</td>'+
        '<td><input type="text" class="form-control form-control-sm categoryInput" name="categoryCd" value="'+category.categoryCd+'"></td>'+
        '<td><input type="text" class="form-control form-control-sm categoryInput" name="categoryValue" value="'+category.categoryValue+'"></td>'+
        '<td><input type="text" class="form-control form-control-sm categoryInput" name="description" value="'+category.description+'"></td>'+
        '</tr>'
    )
  });
}
function makeItemTr(itemList){
  itemList.forEach(function (item, idx){
    $("#itemTable").find('tbody').append(
        '<tr class="itemTr" '+(item.status==="delete"?'style="display:none;"':'')+'>' +
        '<td>'+(item.status==="new"?'<button class="btn btn-sm btn-outline-danger rowDeleteBtn"><i class="bi bi-x"></i></button>':'')+'</td>'+
        '<td><input type="text" class="form-control form-control-sm itemInput" name="itemCd" value="'+item.itemCd+'"></td>'+
        '<td><input type="text" class="form-control form-control-sm itemInput" name="itemValue" value="'+item.itemValue+'"></td>'+
        '<td>'+(item.status==="new"?'':'<input type="checkbox" class="itemInput" name="useChk" '+(item.useChk==="T"?'checked':'')+'>')+'</td>'+
        '</tr>'
    )
  });
}