$(function(){
  setSearchCondition();

  $("#dateSelectorDiv").datepicker({
    format: "yyyy-mm-dd",
    language: "ko"
  });
})
$(document).on('click', '.userInfoTr', function (){
  $(".userInfoCheckBox").prop('checked', false);
  const target = $(this).find(".userInfoCheckBox")[0];
  target.checked = true;
  const selectedTab = $(".nav-tabs").find(".active")[0].id;
  if(selectedTab === "infoTab"){
    getUserInfo(target.value);
  }else if(selectedTab === "categoryTab"){
    getCategoryRole(target.value);
  }
})

$(document).on('click', '#infoTab', function (){
  getUserInfo(getUserSeq())
})
$(document).on('click', '#categoryTab', function (){
  getCategoryRole(getUserSeq())
})

$(document).on('click', '.page-item', function (){
  $("#pageIndex").val($(this).attr("data-pageindex"));
  $("#searchBtn").click();
})

$(document).on('change', '#searchConditionSelector', function (){
  setSearchCondition();
})
$(document).on('change', '#passwordUpdateFlag', function (){
  const passwordDiv = $(".passwordDiv");
  if(this.checked){
    passwordDiv.show();
    passwordDiv.find("input").removeAttr("disabled");
  }else{
    passwordDiv.hide();
    passwordDiv.find("input").attr("disabled", "disabled");
  }
})
$(document).on('click', '#saveBtn', function (){
  if(valueCheck("userInfoInsert")){
    if(confirm("저장하시겠습니까?")){
      const formData = new FormData($("#userInfoInsert")[0]);
      $.ajax({
        type : 'POST',
        data : formData,
        url : "/admin/insertUserInfo",
        processData: false,
        contentType: false,
        success : function(data) {
          alert("저장되었습니다.")
          $("#closeModalBtn").click();
          $("#searchBtn").click();
        },
        error : function(xhr, status) {

        }
      })
    }
  }
})

$(document).on('click', '#updateBtn', function (){
  if(valueCheck("userInfoUpdate")){
    if(confirm("저장하시겠습니까?")){
      const formData = new FormData($("#userInfoUpdate")[0]);
      $.ajax({
        type : 'POST',
        data : formData,
        url : "/admin/updateUserInfo",
        processData: false,
        contentType: false,
        success : function(data) {
          alert("저장되었습니다.")
          $("#searchBtn").click();
        },
        error : function(xhr, status) {

        }
      })
    }
  }
})

$(document).on('change', '.parentSeq', function (){
  const categorySeq = $(this).attr("data-categoryseq")
  childCategoryStatusChange(categorySeq, this.checked);
})

$(document).on('click', '#saveCategoryRoleBtn', function (){
  const categoryRoleList = [];
  const userSeq = Number($(".userInfoCheckBox:checked").val());
  $(".categoryCheckBox:checked").each(function (idx, el){
    categoryRoleList.push({
      userSeq : userSeq,
      categorySeq : Number($(el).attr("data-categoryseq")),
      categoryRole: 'T'
    });
  })
  $.ajax({
    type : 'POST',
    url : "/admin/insertCategoryRole",
    data : JSON.stringify({categoryRoleList: categoryRoleList, userSeq: userSeq}),
    contentType: 'application/json',
    beforeSend: function (xhr){
      xhr.setRequestHeader($("[name='_csrf_header']").val(), $("[name='_csrf']").val());
    },
    success : function(data) {
      alert("저장되었습니다.");
    },
    error : function(xhr, status) {

    }
  })
})

function valueCheck(form){
  const targetForm = $("#"+form);
  const userId = targetForm.find("#userId").val();
  const password = targetForm.find("#password");
  const passwordConfirm = targetForm.find("#passwordConfirm");
  const name = targetForm.find("#name").val()
  let returnFlag = true;

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

function getUserSeq(){
  return $(".userInfoCheckBox:checked").val();
}

function getUserInfo(userSeq){
  if(userSeq !== undefined){
    $.ajax({
      url: '/admin/selectUserInfo',
      data: {userSeq: userSeq},
      type: 'GET',
      dataType:"html",
      success: function(html){
        $("#userContent").empty().append(html)
      },
      error:function(){

      }
    });
  }
}
function getCategoryRole(userSeq){
  if(userSeq !== undefined){
    $.ajax({
      url: '/admin/selectCategoryRole',
      data: {userSeq: userSeq},
      type: 'GET',
      dataType:"html",
      success: function(html){
        $("#userContent").empty().append(html)
      },
      error:function(){

      }
    });
  }
}

function childCategoryStatusChange(parentSeq, flag){
  const target = $("[data-parentseq='"+parentSeq+"']");
  if(target.length>0){
    target.prop("checked", flag);
    target.each(function(idx, el){
      childCategoryStatusChange($(el).attr("data-categoryseq"), flag);
    })
  }
}

function setSearchCondition(){
  const searchConditionSelector = $("#searchConditionSelector").val();
  const searchTextDiv = $("#searchTextDiv");
  const dateSelectorDiv = $("#dateSelectorDiv");
  if(searchConditionSelector === "createDate"){
    dateSelectorDiv.show();
    dateSelectorDiv.children().removeAttr("disabled");
    searchTextDiv.hide();
    searchTextDiv.children().attr("disabled", "disabled");
  }else{
    $("#textSearch").attr("name", searchConditionSelector);
    searchTextDiv.show();
    searchTextDiv.children().removeAttr("disabled");
    dateSelectorDiv.hide();
    dateSelectorDiv.children().attr("disabled", "disabled");
  }
}