var CrossEditor
$(document).on('click', '#commentSaveBtn', function (){
  if(!$("#comment").val()) {
    alert("댓글을 입력해주세요.")
  }else{
    if (confirm("등록하시겠습니까?")) {
      contentFade("in")
      const formData = new FormData($("#commentForm")[0]);
      $.ajax({
        type : 'POST',
        data : formData,
        url : "/publicBoard/saveComment",
        processData: false,
        contentType: false,
        dataType:"html",
        beforeSend: function (xhr){
          xhr.setRequestHeader($("[name='_csrf_header']").val(), $("[name='_csrf']").val());
        },
        success : function(html) {
          $("#commentDiv").append(html)
          $("#comment").summernote('code', '')
          const parentComment = $("#parentComment");
          if(parentComment.val()){
            parentComment.val('');
            $("#commentFormHome").append($("#commentForm"))
          }
          alert("저장되었습니다.");
          contentFade("out");
        },
        error : function(xhr, status) {
          alert("저장에 실패하였습니다.")
          contentFade("out");
        }
      })
    }
  }
})

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

$(document).on('click', '.childCommentBtn', function (){
  const childCommentDiv = $(this).parents(".commentRow").find(".childCommentDiv")
  childCommentDiv.show();
  $("#parentComment").val($(this).parents(".commentRow").find(".commentKey").val());
  childCommentDiv.empty().append($("#commentForm"))
})
$(document).on('click', '.deleteCommentBtn', function (){
  const commentRow = $(this).parents(".commentRow");
  const publicKey = Number(commentRow.find(".publicKey").val());
  const commentKey = Number(commentRow.find(".commentKey").val());
  $.ajax({
    type : 'POST',
    data : JSON.stringify({publicKey: publicKey, commentKey: commentKey}),
    url : "/publicBoard/deleteComment",
    contentType: 'application/json',
    beforeSend: function (xhr){
      xhr.setRequestHeader($("[name='_csrf_header']").val(), $("[name='_csrf']").val());
    },
    success : function(result) {
      commentRow.remove();
      alert("삭제되었습니다.");
      contentFade("out");
    },
    error : function(xhr, status) {
      alert("삭제를 실패하였습니다.")
      contentFade("out");
    }
  })
})

function getEditModal(publicKey, publicType){
  $.ajax({
    url: '/publicBoard/editModal',
    data: {publicKey: publicKey, publicType: publicType},
    type: 'GET',
    dataType:"html",
    success: function(html){
      $("#editContent").empty().append(html)
      /*$("#content").summernote({
        lang:'ko-KR',
        height: 350,
        disableDragAndDrop: true,
        toolbar: [
          ['style', ['style']],
          ['font', ['bold', 'underline', 'clear']],
          ['color', ['color']],
          ['para', ['ul', 'ol', 'paragraph']],
          ['table', ['table']]
        ]
      });*/
      setUploadDiv();
      CrossEditor = new NamoSE('editor');
      CrossEditor.params.ParentEditor = document.getElementById("editor");
      CrossEditor.params.Width = "100%";
      CrossEditor.params.UserLang = "auto";
      CrossEditor.params.NewToolbar = true;
      CrossEditor.params.UploadFileExecutePath = "/Crosseditor/uploadImg";


      CrossEditor.params.FullScreen = false;
      $("#editor").show();
      /*CrossEditor.OnInitCompleted(function (e){
        e.editorTarget.SetBodyValue(document.getElementById("pe_bhr").value);
      })*/
      CrossEditor.EditorStart();
      
      

      $("#editModal").modal('show');
    },
    error:function(){

    }
  });
}

function getViewModal(publicKey, publicType){
  $.ajax({
    url: '/publicBoard/viewModal',
    data: {publicKey: publicKey, publicType: publicType},
    type: 'GET',
    dataType:"html",
    success: function(html){
      $("#viewContent").empty().append(html)
      $("#comment").summernote({
        lang:'ko-KR',
        height: 100,
        disableDragAndDrop: true,
        toolbar: [
          ['style', ['style']],
          ['font', ['bold', 'underline', 'clear']],
          ['color', ['color']],
          ['para', ['ul', 'ol', 'paragraph']],
          ['table', ['table']]
        ]
      });
      $("#viewModal").modal('show');
    },
    error:function(){

    }
  });
}

function savePublicBoard(formId, publicType){
  if(contentCheck(formId)){
    if(confirm("저장하시겠습니까?")){
      contentFade("in");
      $("#content").val("");
      const formData = new FormData($("#"+formId)[0]);
      for(const file of files) {
        if(!file.isDelete)
          formData.append('uploadFiles', file, file.name);
      }
      $(".text-decoration-line-through").each(function (idx, el){
        formData.append('fileSeq', $(el).attr("data-fileseq"));
      })
      formData.append('content', CrossEditor.GetBodyValue());
      $.ajax({
        type : 'POST',
        data : formData,
        url : "/publicBoard/saveContent",
        processData: false,
        contentType: false,
        success : function(result) {
          alert("저장되었습니다.");
          contentFade("out");
          $("#editModal").modal('hide');
          getViewModal(result, publicType);
        },
        error : function(xhr, status) {
          alert("저장에 실패하였습니다.")
          contentFade("out");
        }
      })
    }
  }
}

function contentCheck(formId){
  let flag = true;
  if(!$("#title").val()){
    alert("제목을 입력해주세요.")
    flag = false;
  }
  if($("#publicType").val()==="PLB003"){
    if(!$("#tabStatus").val()){
      alert("분류를 선택해주세요.")
      flag = false;
    }
  }
  flag = fileCheck(flag, files);
  return flag;
}

function OnInitCompleted(e){
  e.editorTarget.SetBodyValue(document.getElementById("content").value);

}
