let files = [];

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

$(document).on('click', '#resultTab', function (){
  location.href = "/affairResult/resultMgt";
})
$(document).on('click', '#stayTab', function (){
  location.href = "/affairResult/stayPage";
})
$(document).on('click', '#commitTab', function (){
  location.href = "/affairResult/commitPage";
})

$(document).on('click', '#addResultBtn', function (){
  getResultEditModal(null)
})
$(document).on('click', '#editResultBtn', function (){
  $("#resultViewModal").modal('hide');
  getResultEditModal(Number($("#resultViewBody").find("[name='resultKey']").val()));
})

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

$(document).on('click', '.rowDeleteBtn', function (){
  const isClearInfo = $(this).parents("#clearInfoRow").length !== 0;
  const infoSeq = $(this).parents(".infoRow").find(".infoSeq").val();
  $(this).parents(".infoRow").remove();
  if(isClearInfo){
    setInfoSeq($("#clearInfoRow"), infoSeq);
  }else{
    setInfoSeq($("#resultInfoRow"), infoSeq);
  }
})

$(document).on('click', '#clearInfoAddBtn', function (){
  const infoRow = $("#clearInfoRow");
  $.ajax({
    url: '/affairResult/getClearInfoRow',
    data: {infoSeq: $(".clearInfoSeq").length},
    type: 'GET',
    dataType:"html",
    success: function(html){
      infoRow.append(html);
    },
    error:function(){

    }
  });
})
$(document).on('click', '#resultInfoAddBtn', function (){
  const infoRow = $("#resultInfoRow");
  const infoSeq = $(".resultInfoSeq").length;
  $.ajax({
    url: '/affairResult/getResultInfoRow',
    data: {infoSeq: infoSeq},
    type: 'GET',
    dataType:"html",
    success: function(html){
      infoRow.append(html);
      $("#contactInfo"+infoSeq).summernote({
        lang:'ko-KR',
        height: 60,
        disableDragAndDrop: true,
        toolbar: [
          ['style', ['style']],
          ['font', ['bold', 'underline', 'clear']],
          ['color', ['color']],
          ['para', ['ul', 'ol', 'paragraph']],
          ['table', ['table']]
        ]
      });
    },
    error:function(){

    }
  });
})

$(document).on('click', '#saveResultBtn', function (){
  saveResult('DST002')
})

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

$(document).on('click', '.resultTr', function (){
  $(".trChkBox").prop("checked", false);
  $(this).find(".trChkBox").prop("checked", true);
  getResultViewModal(Number($(this).find(".resultKey").val()));
})

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

function getResultViewModal(resultKey){
  $.ajax({
    url: '/affairResult/resultViewModal',
    data: {resultKey: resultKey},
    type: 'GET',
    dataType:"html",
    success: function(html){
      $("#resultViewBody").empty().append(html)
      $("#resultViewModal").modal('show');
    },
    error:function(){

    }
  });
}

function getResultEditModal(resultKey){
  $.ajax({
    url: '/affairResult/resultEditModal',
    data: {resultKey: resultKey},
    type: 'GET',
    dataType:"html",
    success: function(html){
      $("#resultEditModalContent").empty().append(html)
      $("#resultEditModal").modal('show');
      $("#resultDt").datepicker({
        format: "yyyy-mm-dd",
        language: "ko"
      });
      setUploadDiv();
    },
    error:function(){

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

function setInfoSeq(target, infoSeq){
  $.each(target.find("div.infoSeq"), function (idx, child) {
    let childInfoSeq = Number(child.innerText);
    if(childInfoSeq-->Number(infoSeq)){
      const infoRow = $(child).parent(".infoRow")
      child.innerText = childInfoSeq;
      infoRow[0].id = "row"+childInfoSeq;
      debugger
    }
  })
}

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