$(function(){
  const commonCodeModal = document.getElementById('commonCodeModal')
  commonCodeModal.addEventListener('hidden.bs.modal', function (event) {
    formReset();
  })
})

$(document).on('change', '#inputSelector', function (){
  $("#category").val("");
  const categorySelectDiv = $("#categorySelectDiv");
  const categoryInputDiv = $("#categoryInputDiv");
  categorySelectDiv.children().val("");
  categoryInputDiv.children().val("");
  if(this.checked){
    categorySelectDiv.hide();
    categoryInputDiv.show();
  }else{
    categorySelectDiv.show();
    categoryInputDiv.hide();
  }
})

$(document).on('change', '#categorySelector, #categoryInput', function (){
  $("#category").val(this.value);
})

$(document).on('click', '.categoryTr', function (event){
  const checkBox = $(this).find(".categoryCheckBox")[0];
  categoryCheckBoxReset();
  $("#allValueCheckBox")[0].checked = false;
  checkBox.checked = true;
  getValues(checkBox.value);
})
$(document).on('click', '.valueTr', function (event) {
  if(event.target.className!=="valueCheckBox"){
    const checkBox = $(this).find(".valueCheckBox")[0];
    checkBox.checked = !checkBox.checked;
  }
})
$(document).on('click', '#allValueCheckBox', function (event){
  const flag = $("#allValueCheckBox")[0].checked;
  $(".valueCheckBox").prop("checked", flag);
})
$(document).on('click', '#saveBtn', function (){
  if(valueCheck()){
    if(confirm("저장하시겠습니까?")){
      const formData = new FormData($("#commonCodeForm")[0]);
      $.ajax({
        type : 'POST',
        data : formData,
        url : "/admin/insertCode",
        processData: false,
        contentType: false,
        success : function(data) {
          alert("저장되었습니다.")
          $("#closeModalBtn").click();
          categoryCheck(data.category);
        },
        error : function(xhr, status) {

        }
      })
    }
  }
})
$(document).on('click', '#deleteCommonCodeBtn', function (){
  const codeList = [];
  $(".valueCheckBox:checked").each(function (idx, el){
    codeList.push({});
    const target = $(el);
    codeList[idx].codeSq = Number(target.attr("data-codesq"));
    codeList[idx].category = target.attr("data-category");
    codeList[idx].value = target.attr("data-value");
    codeList[idx].description = target.attr("data-description");
    codeList[idx].isDeleted = 'Y';
  })
  if(codeList.length !== 0){
    if(confirm(codeList.length+"건을 삭제하시겠습니까?")){
      $.ajax({
        type : 'PUT',
        url : "/admin/deleteCode",
        data : JSON.stringify(codeList),
        contentType: 'application/json',
        beforeSend: function (xhr){
          xhr.setRequestHeader($("[name='_csrf_header']").val(), $("[name='_csrf']").val());
        },
        success : function(data) {
          alert("삭제되었습니다.");
          getValues($(".categoryCheckBox:checked").val());
        },
        error : function(xhr, status) {

        }
      })
    }
  }else{
    alert("삭제할 값을 선택해주세요.")
  }
})

function getValues(category){
  $.ajax({
    url: '/admin/codeValue',
    data: {category: category},
    type: 'GET',
    dataType:"html",
    success: function(html){
      $("#valueDiv").empty().append(html)
    },
    error:function(){

    }
  });
}
function categoryCheck(category){
  categoryCheckBoxReset();
  $(".categoryCheckBox").each(function (idx,el){
    if(el.value===category){
      el.checked = true;
    }
  })
  getValues(category);
}
function valueCheck(){
  const category = $("#category").val();
  const value = $("#value").val();
  let returnFlag = true;
  if(!category){
    alert("분류를 선택(또는 입력) 해야합니다.");
    returnFlag = false;
  }
  if(!value){
    alert("값이 비어있습니다.");
    returnFlag = false;
  }
  return returnFlag;
}
function categoryCheckBoxReset(){
  $(".categoryCheckBox").prop("checked", false);
}
function formReset(){
  document.getElementById('commonCodeForm').reset();
}