let selectedList = [];
$(function (){
  $.ajax({
    type : 'GET',
    url : "/myInfo/getDashBoardConfig",
    dataType:"json",
    success : function(data) {
      selectedList = data;
    },
    error : function(xhr, status) {

    }
  })
})

$(document).on('click', '.configTr', function (event){
  const target = event.target;
  if(!(target.className === "moveTd" || $(target).parents(".moveTd").length>0)){
    const chkBox = $(this).find(".configChkBox")[0];
    chkBox.checked = !chkBox.checked;
  }
})
$(document).on('click', '#configAddBtn', function (){
  searchModalSubmit(1);
  $("#menuModal").modal('show');
})
$(document).on('click', '#configDeleteBtn', function (){
  $.each($(".configChkBox:checked"), function (idx, chkBox){
    $(chkBox).parents(".configTr").remove();
  })
  const tempList = [];
  $.each($(".configChkBox"), function (idx, chkBox){
    $.each(selectedList, function (idx, menu){
      if(menu.menuKey === Number($(chkBox).attr('data-menukey'))){
        tempList.push(menu);
      }
    })
  })
  selectedList = tempList;
  orderNumSort();
})

$(document).on('click', '.menuTr', function (){
  const checkBox = $(this).find(".menuCheckBox")[0]
  checkBox.checked = !checkBox.checked;
  if(checkBox.checked){
    selectedList.push({
      menuKey: Number(checkBox.value),
      orderNum: selectedList.length+1,
      cat1Cd: $(this).find(".cat1Cd").val(),
      cat2Cd: $(this).find(".cat2Cd").val(),
      cat3Cd: $(this).find(".cat3Cd").val(),
      menuUrl: $(this).find(".menuUrl").val()
    });
  }else{
    const tempList = [];
    $.each(selectedList, function (idx, menu){
      if(menu.menuKey !== Number(checkBox.value)){
        menu.orderNum = idx+1;
        tempList.push(menu);
      }
    })
    selectedList = tempList;
  }
})

$(document).on('click', '#getMenuBtn', function (){
  $.ajax({
    type : 'POST',
    url : "/myInfo/selectedMenuTable",
    data : JSON.stringify(selectedList),
    contentType: 'application/json',
    dataType:"html",
    beforeSend: function (xhr){
      xhr.setRequestHeader($("[name='_csrf_header']").val(), $("[name='_csrf']").val());
    },
    success : function(html) {
      $("#dashboardConfigTbody").empty().append($(html)[1].children[0].children);
      $("#menuModal").modal("hide");
    },
    error : function(xhr, status) {

    }
  })
})

$(document).on('click', '#savePasswordBtn', function (){
  if(passwordCheck()){
    const formData = new FormData($("#modifyPasswordForm")[0]);
    contentFade("in")
    $.ajax({
      type : 'PUT',
      data : formData,
      url : "/info/passwordModify",
      processData: false,
      contentType: false,
      success : function(result) {
        if(result==="OK"){
          alert("저장되었습니다.");
          $("#passwordModifyModal").find(".btn-close").click();
        }else if(result==="passwordNotMatch"){
          alert("현재 비밀번호가 맞지 않습니다.");
        }
        contentFade("out");
      },
      error : function(xhr, status) {
        alert("저장에 실패하였습니다.");
        contentFade("out");
      }
    })
  }
})
$(document).on('click', '.upBtn', function (){
  const targetTr = $(this).parents('tr');
  targetTr.prev().before(targetTr);
  orderNumSort();
})
$(document).on('click', '.downBtn', function (){
  const targetTr = $(this).parents('tr');
  targetTr.next().after(targetTr);
  orderNumSort();
})

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

function orderNumSort(){
  $.each($(".configTr"), function(idx, tr){
    $(tr).find(".orderNumInput").val(idx+1);
    for(const menu of selectedList){
      if(Number($(tr).find(".configChkBox").attr("data-menukey"))===menu.menuKey){
        menu.orderNum = Number($(tr).find(".orderNumInput").val());
      }
    }
  })
  selectedList.sort(function(a,b){
    if (a.orderNum > b.orderNum) {
      return 1;
    }
    if (a.orderNum < b.orderNum) {
      return -1;
    }
    return 0;
  })
}
function setSelectedChkBox(){
  $.each(selectedList, function (idx, item){
    $("[value="+item.menuKey+"]").prop("checked", true);
  })
}

function passwordCheck(){
  let returnFlag = true;
  const password = $("#password");
  const modifyPassword =$("#modifyPassword");
  const passwordConfirm = $("#passwordConfirm");
  if(!password.val()){
    alert("비밀번호를 입력해주세요.");
    returnFlag = false;
  }
  if(!modifyPassword.val()){
    alert("새 비밀번호를 입력해주세요.");
    returnFlag = false;
  }
  if(!passwordConfirm.val()){
    alert("비밀번호 확인을 입력해주세요.");
    returnFlag = false;
  }
  if(returnFlag){
    const passwordReg = /^(?=.*[a-zA-z])(?=.*[0-9])(?=.*[$`~!@$!%*#^?&\\(\\)\-_=+]).{8,16}$/;
    if(!passwordReg.test(modifyPassword.val())){
      alert("비밀번호 조건이 맞지 않습니다.")
      returnFlag = false;
    }else{
      if(modifyPassword.val() !== passwordConfirm.val()){
        alert("비밀번호가 같지 않습니다.");
        returnFlag = false;
      }
    }
  }
  return returnFlag;
}