let organList = [];
let selectedMiddleOrganCd = "";

$(function (){
  $.ajax({
    url: '/organMgt/selectOrganList',
    type: 'GET',
    dataType:"json",
    success: function(data){
      organList = data;
      setUsedOrganTr("OG001", "OGC002");
    },
    error:function(){

    }
  });
})

$(document).on('click', '#middleAddBtn', function (){
  addTr('middleTbody')
})

$(document).on('click', '#bottomAddBtn', function (){
  addTr('bottomTbody')
})

$(document).on('click', '.rowDeleteBtn', function (){
  const targetTr = $(this).parents('tr');
  const selector = targetTr.find("select");
  organList.forEach(function (organ, idx){
    if(organ.organCd === selector.val() //해당관서
        || organ.parentOrgan === selector.val()){ // 해당 지방청을 상위로 둔 관할 서
      organ.useState = "F";
    }
  })
  targetTr.remove();
})

$(document).on('change', '.organSelector', function () {
  const selector = this;
  const selectedItemCd = selector.value;
  const tbodyId = $(this).parents('tbody')[0].id
  organList.forEach(function (organ, idx){
    if(organ.organCd === selectedItemCd){
      switch (organ.useState){
        case "T":
          selector[0].selected = true;
          alert("다른 위치에 등록된 관서입니다.")
          $(selector).find("[value='"+selectedItemCd+"']").remove()
          break;
        case "F":
          for(var i=0; i<selector.options.length; i++){
            if(selector.options[i].index !== selector.options.selectedIndex){
              selector.options[i].remove();
            }
          }
          organ.parentOrgan = tbodyId==='middleTbody'?'OG001':selectedMiddleOrganCd;
          organ.organType = tbodyId==='middleTbody'?'OGC002':'OGC003';
          organ.useState = "T";
          break;
      }
    }
  })
})
$(document).on('click', '.middleTr', function (){
  const activeTr = $(".activeTr");
  if(activeTr.length>0){
    activeTr[0].className = "middleTr";
  }
  this.className = "middleTr activeTr"
  $("#bottomTbody").empty();
  selectedMiddleOrganCd = $(this).find("select").val();
  setUsedOrganTr(selectedMiddleOrganCd, "OGC003")
  $("#bottomBtnRow").show();
  $("#emptyTr").hide();
})
$(document).on('click', '#organSaveBtn', function (){
  contentFade("in");
  const saveList = [];
  organList.forEach(function (organ) {
    if(organ.useState==="T")
      saveList.push(organ);
  });
  $.ajax({
    type : 'POST',
    url : "/organMgt/saveOrganConfig",
    data : JSON.stringify(saveList),
    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 addTr(tbody){
  let options = '';
  organList.forEach(function (organ) {
    if(organ.useState==="F")
      options+= '<option value="'+organ.organCd+'">'+organ.organNm+'</option>'
  });
  if(options===''){
    alert("배정되지 않은 관서가 없습니다.");
  }else{
    $('#'+tbody).append(
        '<tr '+(tbody==="middleTbody"?'class="middleTr"':'')+'>' +
        '<td><button class="btn btn-sm btn-outline-danger rowDeleteBtn"><i class="bi bi-x"></i></button></td>' +
        '<td><select class="organSelector form-select-sm">' +
        '<option value="">선택해주세요</option>' +
        options+
        '</select></td>' +
        '</tr>'
    )
  }
}

function setUsedOrganTr(parentOrgan, organType){
  const target = organType==="OGC002"?$("#middleTbody"):$("#bottomTbody")
  organList.forEach(function (organ){
    if(organ.useState === "T"){
      if(organ.parentOrgan===parentOrgan && organ.organType===organType){
        target.append(
            '<tr '+(organType==="OGC002"?'class="middleTr"':'')+'>' +
            '<td><button class="btn btn-sm btn-outline-danger rowDeleteBtn"><i class="bi bi-x"></i></button></td>' +
            '<td><select class="organSelector form-select-sm">' +
            '<option value="'+organ.organCd+'">'+organ.organNm+'</option>' +
            '</select></td>' +
            '</tr>'
        )
      }
    }
  })
}