let files = [];

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

$(document).on('click', '.planTr', function (){
  $(".trChkBox").prop("checked", false);
  $(this).find(".trChkBox").prop("checked", true);
  getViewModal(Number($(this).find(".planKey").val()));
})
$(document).on('click', '#addPlanBtn', function (){
  getEditModal(null)
})
$(document).on('click', '#editPlanBtn', function (){
  $("#planViewModal").modal('hide');
  getEditModal(Number($("#planViewBody").find("[name='planKey']").val()));
})

$(document).on('click', '#planAddBtn', function (){
  $("#planDiv").append("<input type='text' class='form-control' name='planInfos'>")
})

$(document).on('click', '#detailPlanAddBtn', function (){
  const detailPlanDiv = $("#detailPlanDiv");
  detailPlanDiv.append("<textarea type='text' name='detailPlanInfos'></textarea>");
  const lastAppendTextarea = detailPlanDiv.children()[detailPlanDiv.children().length-1];
  $(lastAppendTextarea).summernote({
    lang:'ko-KR',
    height: 120,
    disableDragAndDrop: true,
    toolbar: [
      ['style', ['style']],
      ['font', ['bold', 'underline', 'clear']],
      ['color', ['color']],
      ['para', ['ul', 'ol', 'paragraph']],
      ['table', ['table']]
    ]
  });
})

$(document).on('click', '#savePlanBtn', function (){
  savePlan('DST002')
})
$(document).on('click', '#saveTempBtn', function (){
  savePlan('DST001')
})

function getEditModal(planKey){
  $.ajax({
    url: '/fpiMgt/planEditModal',
    data: {planKey: planKey},
    type: 'GET',
    dataType:"html",
    success: function(html){
      $("#planEditModalContent").empty().append(html)
      $("#planEditModal").modal('show');
      $("#planDt").datepicker({
        format: "yyyy-mm-dd",
        language: "ko"
      });
      $("[name='detailPlanInfos']").summernote({
        lang:'ko-KR',
        height: 120,
        disableDragAndDrop: true,
        toolbar: [
          ['style', ['style']],
          ['font', ['bold', 'underline', 'clear']],
          ['color', ['color']],
          ['para', ['ul', 'ol', 'paragraph']],
          ['table', ['table']]
        ]
      });
      setUploadDiv();
    },
    error:function(){

    }
  });
}
function setUploadDiv(){
  files = [];
  $("#uploadDiv").on("dragenter", function(e) {
    // $(this).addClass('drag-over');
  }).on("dragleave", function(e) {
    // $(this).removeClass('drag-over');
  }).on("dragover", function(e) {
    e.stopPropagation();
    e.preventDefault();
  }).on('drop', function(e) {
    e.preventDefault();
    // $(this).removeClass('drag-over');
    for(const file of e.originalEvent.dataTransfer.files){
      setFileDiv(file, files.push(file));
    }
  }).on('click', function (e){
    if(e.target.className.indexOf("ileDelete")<0){
      $("#fileInputer").click();
    }
  });
}
function savePlan(planState){
  if(contentCheck()){
    if(confirm("저장하시겠습니까?")){
      $("#planState").val(planState);
      contentFade("in");
      const formData = new FormData($("#planEditForm")[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"));
      })
      $.ajax({
        type : 'POST',
        data : formData,
        url : "/fpiMgt/savePlan",
        processData: false,
        contentType: false,
        success : function(result) {
          alert("저장되었습니다.");
          contentFade("out");
          $("#planEditModal").modal('hide');
          getViewModal(result);
        },
        error : function(xhr, status) {
          alert("저장에 실패하였습니다.")
          contentFade("out");
        }
      })
    }
  }
}

function setFileDiv(file, idx){
  const uploadDiv = $("#uploadDiv");
  if($(".uploadedFileDelete").length===0 && $(".fileDelete").length === 0){
    uploadDiv.empty();
  }
  let fileInfo = "<div class='row-col-6'>";
  fileInfo += file.name+" "+byteCalculation(file.size)+" ";
  fileInfo += "<a href='#' class='fileDelete text-danger text-decoration-none' data-fileidx='"+(idx-1)+"'>삭제</a>";
  fileInfo += "</div>";
  uploadDiv.append(fileInfo);
}

function contentCheck(){
  let flag = true;
  if(!$("#contentTitle").val()){
    alert("제목을 입력해주세요.")
    flag = false;
  }
  if(!$("#planDt").val()){
    alert("시행일자를 입력해주세요.")
    flag = false;
  }
  let totalSize = 0;
  for(const file of files) {
    if(!file.isDelete){
      totalSize+=file.size;
      if(file.size>209715200){
        alert("파일당 사이즈는 200MB을 넘길 수 없습니다.")
        flag = false;
      }
    }
  }
  if(totalSize>524288000){
    alert("첨부파일의 용량 합은 500MB를 넘길 수 없습니다.")
    flag = false;
  }
  return flag;
}