
$(function(){
  $("#dateSelectorDiv").datepicker({
    format: "yyyy-mm-dd",
    language: "ko"
  });
})
$(document).on('click', '#affairTab', function (){
  location.href = "/affair/affairMgt?affairCategory="+$("#affairCategory").val();
})
$(document).on('click', '#stayTab', function (){
  location.href = "/affair/stayPage?affairCategory="+$("#affairCategory").val();
})
$(document).on('click', '#commitTab', function (){
  location.href = "/affair/commitPage?affairCategory="+$("#affairCategory").val();
})
$(document).on('click', '.affairTr', function (event){
  const target = event.target;
  if(!(target.className === "apprvTd" || $(target).parents(".apprvTd").length>0)){
    const chkBox = $(this).find(".rowChkBox");
    if(chkBox.length>0){
      $(".trChkBox").prop("checked", false);
      chkBox[0].checked = !chkBox[0].checked;
    }
    getAffairViewModal(Number($(this).find(".affairKey").val()));
  }
})
$(document).on('click', '#addAffairBtn', function (){
  getAffairEditModal(null)
})
$(document).on('click', '#editAffairBtn', function (){
  $("#affairViewModal").modal('hide');
  getAffairEditModal(Number($("#affairViewBody").find("[name='affairKey']").val()));
})

$(document).on('change', '#autoDeleteSelector', function (){
  let deleteDt = "";
  if(this.value !== ""){
    const nowDt = new Date();
    nowDt.setMonth(nowDt.getMonth()+Number(this.value));
    deleteDt = nowDt.getFullYear()
        +"-"+("0"+(nowDt.getMonth()+1)).slice(-2)
        +"-"+("0"+nowDt.getDate()).slice(-2);
  }
  $("#autoDelete").val(deleteDt);
})

$(document).on('click', '#saveAffairBtn', function (){
  saveAffair('DST002')
})
$(document).on('click', '#saveTempBtn', function (){
  saveAffair('DST001')
})
$(document).on('click', '.apprvBtn', function (){
  const affairState = $(this).attr("data-affairstate");
  let flag = true;
  if(affairState==="DST006"){ // 부장 승인
    if(!$("#affairRate").val()){
      alert("견문평가를 선택해주세요.")
      flag = false;
    }
  }else if(affairState==="DST005"){ // 부장 반려
    $("#organUp").prop("checked", false);
    $("#affairRate").val("");
  }
  if(flag){
    if(confirm($(this).val()+"하시겠습니까?")){
      const apprvType = $(this).attr("data-apprvtype");
      $((apprvType === "section"?"#sectionApprv":"#headApprv")).val(affairState)
      const formData = new FormData($("#apprvForm")[0]);
      const ratingList = [];
      const apprv = {}
      for (let data of formData.entries()) {
        if(data[0] !== undefined){
          apprv[data[0]] = data[1];
        }
      }
      ratingList.push(apprv);
      affairStateChange(ratingList);
    }
  }
})

$(document).on('click', '#tableApprvBtn', function (){
  const ratingList = [];
  const apprvAuth = $(this).attr("data-apprvauth")
  $.each($(".apprvTd"), function (idx, el) {
    if (apprvAuth === "APC003" || apprvAuth === "APC004") {
      const chkbox = $(el).find(".apprvChkbox:checked")
      if(chkbox.length>0){
        const affairRating = {};
        affairRating["affairKey"] = Number($(el).find(".affairKey").val());
        affairRating["sectionApprv"] = chkbox.val();
        ratingList.push(affairRating);
      }
    } else {
      const chkbox = $(el).find(".apprvChkbox:checked")
      const selectorValue = $(el).find(".ratingSelector").val()
      if(chkbox.length>0){
        const affairRating = {};
        affairRating["affairKey"] = Number($(el).find(".affairKey").val());
        affairRating["headApprv"] = chkbox.val();
        if(selectorValue !== ""){
          affairRating["affairRate"] = selectorValue;
          affairRating["organUp"] = $(el).find(".organUpChkBox").prop("checked")?"T":"F";
        }
        ratingList.push(affairRating);
      }
    }
  })
  affairStateChange(ratingList);
})

$(document).on('change', '.apprvChkbox', function (){
  if(this.value === "DST006"){
    const apprvTd = $(this).parents(".apprvTd");
    apprvTd.find(".ratingSelector").attr("disabled", false)
    apprvTd.find(".organUpChkBox").attr("disabled", false)
  }else if(this.value === "DST005"){
    const apprvTd = $(this).parents(".apprvTd");
    const ratingSelector = apprvTd.find(".ratingSelector")
    ratingSelector.val("");
    ratingSelector.attr("disabled", true)
    const organUpChkBox = apprvTd.find(".organUpChkBox")
    organUpChkBox.prop("checked", false);
    organUpChkBox.attr("disabled", true)
  }
})

function getAffairViewModal(affairKey){
  $.ajax({
    url: '/affair/affairViewModal',
    data: {
      affairKey: affairKey,
      affairCategory: $("#affairCategory").val()
    },
    type: 'GET',
    dataType:"html",
    success: function(html){
      $("#affairViewBody").empty().append(html)
      $("#affairViewModal").modal('show');
    },
    error:function(){

    }
  });
}

function getAffairEditModal(affairKey){
  $.ajax({
    url: '/affair/affairEditModal',
    data: {
      affairKey: affairKey,
      affairCategory: $("#affairCategory").val()
    },
    type: 'GET',
    dataType:"html",
    success: function(html){
      $("#affairEditModalContent").empty().append(html)
      $("#affairEditModal").modal('show');
      $("#reportDt").datepicker({
        format: "yyyy-mm-dd",
        language: "ko"
      });
      $("#autoDelete").datepicker({
        format: "yyyy-mm-dd",
        language: "ko"
      });
      $("#content").summernote({
        lang:'ko-KR',
        height: 270,
        disableDragAndDrop: true,
        toolbar: [
          ['style', ['style']],
          ['font', ['bold', 'underline', 'clear']],
          ['color', ['color']],
          ['para', ['ul', 'ol', 'paragraph']],
          ['table', ['table']]
        ]
      });
      setUploadDiv();
    },
    error:function(){

    }
  });
}
function saveAffair(affairStatus){
  if(contentCheck()){
    if(confirm("저장하시겠습니까?")){
      $("#affairStatus").val(affairStatus);
      contentFade("in");
      const formData = new FormData($("#affairEditForm")[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 : "/affair/saveAffair",
        processData: false,
        contentType: false,
        success : function(result) {
          alert("저장되었습니다.");
          contentFade("out");
          $("#affairEditModal").modal('hide');
          getAffairViewModal(result);
        },
        error : function(xhr, status) {
          alert("저장에 실패하였습니다.")
          contentFade("out");
        }
      })
    }
  }
}

function affairStateChange(ratingList){
  contentFade("in")
  $.ajax({
    type : 'POST',
    url : "/affair/affairStateChange",
    data : JSON.stringify(ratingList),
    contentType: 'application/json',
    beforeSend: function (xhr){
      xhr.setRequestHeader($("[name='_csrf_header']").val(), $("[name='_csrf']").val());
    },
    success : function(result) {
      alert("저장되었습니다")
      contentFade("out");
      if(result !== 0){
        getAffairViewModal(result);
      }else{
        location.reload()
      }
    },
    error : function(xhr, status) {
      alert("저장에 실패하였습니다.");
      contentFade("out");
    }
  })
}
function contentCheck(){
  let flag = true;
  if(!$("#title").val()){
    alert("제목을 입력해주세요.")
    flag = false;
  }
  if(!$("#affairType1").val()){
    alert("분야1을 입력해주세요.")
    flag = false;
  }
  if(!$("#affairType2").val()){
    alert("분야2을 입력해주세요.")
    flag = false;
  }
  if(!$("#affairType3").val()){
    alert("분야3을 입력해주세요.")
    flag = false;
  }
  if(!$("#affairType4").val()){
    alert("분야4을 입력해주세요.")
    flag = false;
  }
  if(!$("#viewStatus").val()){
    alert("공개여부를 입력해주세요.")
    flag = false;
  }
  if(!$("#hashTags").val()){
    alert("해시태그를 입력해주세요.")
    flag = false;
  }
  flag = fileCheck(flag, files);
  return flag;
}