let selectedList = [];
$(function(){
  $("#dateSelectorDiv").datepicker({
    format: "yyyy-mm-dd",
    language: "ko",
    autoclose: true
  });
})

$(document).on('click', '#sendTab', function (){
  location.href = "/faRpt/faRptBoard?activeTab=send";
})
$(document).on('click', '#receiveTab', function (){
  location.href = "/faRpt/faRptBoard?activeTab=receive";
})
$(document).on('click', '#allTab', function (){
  location.href = "/faRpt/faRptBoard?activeTab=all";
})

$(document).on('click', '#addFaRptBtn', function (){
  getFaRptEditModal({faRptKey: null})
})
$(document).on('click', '#editFaRptBtn', function (){
  $("#faRptViewModal").modal('hide');
  getFaRptEditModal({faRptKey: Number($(this).attr("data-farptkey"))});
})

$(document).on('click', '#addReadUserBtn', function (){
  searchModalSubmit(1);
  $("#userModal").modal('show');
})
$(document).on('click', '.rowDeleteBtn', function (){
  $(this).parents(".readUserRow").remove()
  setReadUserRowNum();
})
$(document).on('click', '#getMenuBtn', function (){
  $.ajax({
    type : 'POST',
    url : "/faRpt/selectedUserTable",
    data : JSON.stringify(selectedList),
    contentType: 'application/json',
    dataType:"html",
    beforeSend: function (xhr){
      xhr.setRequestHeader($("[name='_csrf_header']").val(), $("[name='_csrf']").val());
    },
    success : function(html) {
      $("#readUserRow").empty().append(html);
      setReadUserRowNum();
      $("#userModal").modal("hide");
    },
    error : function(xhr, status) {

    }
  })
})

$(document).on('click', '#saveFaRptBtn', function (){
  saveFaRpt('DST007')
})

$(document).on('click', '#saveTempBtn', function (){
  saveFaRpt('DST001')
})

$(document).on('click', '.faRptTr', function (){
  const chkBox = $(this).find(".rowChkBox");
  if(chkBox.length>0){
    $(".trChkBox").prop("checked", false);
    chkBox[0].checked = !chkBox[0].checked;
  }
  getFaRptViewModal(Number($(this).find(".faRptKey").val()));
})
$(document).on('click', '#reSendBtn', function (){
  $("#faRptViewModal").modal('hide');
  const faRpt = {
    refKey: Number($(this).attr("data-farptkey")),
    wrtUserSeq: $("#wrtUserSeq").val(),
    wrtOrgan: $("#wrtOrgan").val(),
    wrtPart: $("#wrtPart").val(),
    wrtUserGrd: $("#wrtUserGrd").val(),
    wrtUserNm: $("#wrtUserNm").val()
  }
  getFaRptEditModal(faRpt);
})

function getFaRptViewModal(faRptKey){
  $.ajax({
    url: '/faRpt/faRptViewModal',
    data: {faRptKey: faRptKey},
    type: 'GET',
    dataType:"html",
    success: function(html){
      $("#faRptViewBody").empty().append(html)
      $("#faRptViewModal").modal('show');
    },
    error:function(){

    }
  });
}

function getFaRptEditModal(faRpt){
  $.ajax({
    url: '/faRpt/faRptEditModal',
    data: faRpt,
    type: 'GET',
    dataType:"html",
    success: function(html){
      $("#faRptEditModalContent").empty().append(html)
      $("#faRptEditModal").modal('show');
      $("#faRptDt").datepicker({
        format: "yyyy-mm-dd",
        language: "ko",
        autoclose: true
      });
      $("#content").summernote({
        lang:'ko-KR',
        height: 300,
        disableDragAndDrop: true,
        toolbar: [
          ['style', ['style']],
          ['font', ['bold', 'underline', 'clear']],
          ['color', ['color']],
          ['para', ['ul', 'ol', 'paragraph']],
          ['table', ['table']]
        ]
      });
      setUploadDiv();
    },
    error:function(){

    }
  });
}
function saveFaRpt(faRptState){
  if(contentCheck()){
    if(confirm("저장하시겠습니까?")){
      $("#status").val(faRptState);
      contentFade("in");
      const formData = new FormData($("#faRptEditForm")[0]);
      for(const file of files) {
        if(!file.isDelete)
          formData.append('uploadFiles', file, file.name);
      }
      $.each($(".readUserRow"), function (idx, row){
        formData.append('readUserList['+idx+'].userSeq', $(row).find('.userSeq').val());
        formData.append('readUserList['+idx+'].ogCd', $(row).find('.ogCd').val());
        formData.append('readUserList['+idx+'].ofcCd', $(row).find('.ofcCd').val());
        formData.append('readUserList['+idx+'].titleCd', $(row).find('.titleCd').val());
        formData.append('readUserList['+idx+'].userNm', $(row).find('.userNm').val());
      });
      $(".text-decoration-line-through").each(function (idx, el){
        formData.append('fileSeq', $(el).attr("data-fileseq"));
      })
      $.ajax({
        type : 'POST',
        data : formData,
        url : "/faRpt/saveFaRpt",
        processData: false,
        contentType: false,
        success : function(result) {
          alert("저장되었습니다.");
          contentFade("out");
          $("#faRptEditModal").modal('hide');
          getFaRptViewModal(result);
        },
        error : function(xhr, status) {
          alert("저장에 실패하였습니다.")
          contentFade("out");
        }
      })
    }
  }
}

function setReadUserRowNum(){
  $.each($(".readUserRow"), function (idx, row){
    $(row).find(".rowSeq")[0].innerText = idx+1;
  })
}

function contentCheck(){
  let flag = true;
  if(!$("#faRptType").val()){
    alert("분류를 선택해주세요.")
    flag = false;
  }
  if(!$("#title").val()){
    alert("제목을 입력해주세요.")
    flag = false;
  }
  if($("#readUserRow").children().length===0){
    alert("수신자를 입력해주세요.")
    flag = false;
  }
  flag = fileCheck(flag, files);
  return flag;
}