let files = [];

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

$(document).on('click', '#planTab', function (){
  location.href = "/affairPlan/planMgt";
})
$(document).on('click', '#stayTab', function (){
  location.href = "/affairPlan/stayPage";
})
$(document).on('click', '#commitTab', function (){
  location.href = "/affairPlan/commitPage";
})

$(document).on('click', '#addPlanBtn', function (){
  getPlanEditModal(null)
})
$(document).on('click', '#editPlanBtn', function (){
  $("#planViewModal").modal('hide');
  getPlanEditModal(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')
})

$(document).on('click', '.planTr', function (){
  $(".trChkBox").prop("checked", false);
  $(this).find(".trChkBox").prop("checked", true);
  getPlanViewModal(Number($(this).find(".planKey").val()));
})

$(document).on('click', '.apprvBtn', function (){
  $("#apprvFormPlanKey").val($("#viewModalPlanKey").val());
  $("#viewModalApprvValue").val($(this).attr("data-planstate"));
  if(confirm($(this).val()+"하시겠습니까?")){
    const formData = new FormData($("#apprvForm")[0]);
    contentFade("in")
    $.ajax({
      type : 'POST',
      data : formData,
      url : "/affairPlan/planStateChange",
      processData: false,
      contentType: false,
      beforeSend: function (xhr){
        xhr.setRequestHeader($("[name='_csrf_header']").val(), $("[name='_csrf']").val());
      },
      success : function(result) {
        alert("저장되었습니다")
        getPlanViewModal(result);
        contentFade("out");
      },
      error : function(xhr, status) {
        alert("저장에 실패하였습니다.");
        contentFade("out");
      }
    })
  }
})

function getPlanViewModal(planKey){
  $.ajax({
    url: '/affairPlan/planViewModal',
    data: {planKey: planKey},
    type: 'GET',
    dataType:"html",
    success: function(html){
      $("#planViewBody").empty().append(html)
      $("#planViewModal").modal('show');
    },
    error:function(){

    }
  });
}

function getPlanEditModal(planKey){
  $.ajax({
    url: '/affairPlan/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 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 : "/affairPlan/savePlan",
        processData: false,
        contentType: false,
        success : function(result) {
          alert("저장되었습니다.");
          contentFade("out");
          $("#planEditModal").modal('hide');
          getPlanViewModal(result);
        },
        error : function(xhr, status) {
          alert("저장에 실패하였습니다.")
          contentFade("out");
        }
      })
    }
  }
}


function contentCheck(){
  let flag = true;
  if(!$("#contentTitle").val()){
    alert("제목을 입력해주세요.")
    flag = false;
  }
  if(!$("#planDt").val()){
    alert("시행일자를 입력해주세요.")
    flag = false;
  }
  flag = fileCheck(flag, files);
  return flag;
}