
$(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('change', '#clearTitle', function (){
  $("#resultTitle").val(this.value)
})
$(document).on('change', '#workStartDt', function (){
  $(".workStartDtCopy").val(this.value)
})
$(document).on('change', '#workEndDt', function (){
  $(".workEndDtCopy").val(this.value)
})
$(document).on('change', '#usePrice', function (){
  $("#usePriceCopy").val(this.value)
})

$(document).on('click', '#affairModalBtn', function (){
  const workStartDt = $("#workStartDt").val()
  const workEndDt = $("#workEndDt").val()
  if(!workStartDt||!workEndDt){
    alert("청산보고서의 사업기간을 입력해주세요.");
  }else{
    $.ajax({
      url: '/affairResult/affairListModal',
      data: {
        startDate: workStartDt,
        endDate: workEndDt
      },
      type: 'GET',
      dataType:"html",
      success: function(html){
        $("#affairListModalContent").empty().append(html)
        $("#affairListModal").modal('show');
      },
      error:function(){

      }
    });
  }
})
$(document).on('click', '#getAffairBtn', function (){
  let affairListTbody = "";
  $.each($(".rowChkBox:checked"), function (idx, chkBox){
    const affairTr = $(chkBox).parents(".affairTr")
    affairListTbody += "<tr>";
    affairListTbody += "<input type='hidden' name='affairList["+idx+"].affairKey' value='"+chkBox.value+"'>";
    affairListTbody += "<td>"+affairTr.find(".wrtDt")[0].innerText+"</td>";
    affairListTbody += "<td>"+affairTr.find(".title")[0].innerText+"</td>";
    if(affairTr.find(".affairRate").length>0){
      affairListTbody += "<td>"+(affairTr.find(".affairRate")[0].innerText+(affairTr.find(".organUp")[0].innerText==="O"?"(상보)":""))+"</td>";
    }else{
      affairListTbody += "<td></td>";
    }
    affairListTbody += "</tr>";
  })
  $("#affairListTbody").empty().append(affairListTbody);
  $("#affairListModal").modal("hide");
})

$(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 (){
  const chkBox = $(this).find(".rowChkBox");
  if(chkBox.length>0){
    $(".trChkBox").prop("checked", false);
    chkBox[0].checked = !chkBox[0].checked;
  }
  getResultViewModal(Number($(this).find(".resultKey").val()));
})

$(document).on('click', '.apprvBtn', function (){
  $("#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');
      $("#useDateSelectorDiv").datepicker({
        format: "yyyy-mm-dd",
        language: "ko"
      });
      $("#workDateSelectorDiv").datepicker({
        format: "yyyy-mm-dd",
        language: "ko"
      });
      $(".contactInfo").summernote({
        lang:'ko-KR',
        height: 60,
        disableDragAndDrop: true,
        toolbar: [
          ['style', ['style']],
          ['font', ['bold', 'underline', 'clear']],
          ['color', ['color']],
          ['para', ['ul', 'ol', 'paragraph']],
          ['table', ['table']]
        ]
      });
      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"+idx;
      $.each(infoRow.find("input"), function (idx2, input){
        input.name = input.name.replace("["+childInfoSeq+"]", "["+idx+"]");
        if(input.name.indexOf("infoSeq")>0){
          input.value -= input.value;
        }
      })
      $.each(infoRow.find("select"), function (idx2, select){
        select.name = select.name.replace("["+childInfoSeq+"]", "["+idx+"]");
      })
      $.each(infoRow.find("textarea"), function (idx2, textarea){
        if(textarea.id !== ''){
          textarea.id = "contactInfo"+idx;
        }
        if(textarea.name !== ''){
          textarea.name = textarea.name.replace("["+childInfoSeq+"]", "["+idx+"]");
        }
      })
    }
  })
}

function contentCheck(){
  let flag = true;
  if(!$("#clearTitle").val()){
    alert("청산보고서 제목을 입력해주세요.")
    flag = false;
  }
  if(!$("#workStartDt").val()){
    alert("사업기간 시작일을 입력해주세요.")
    flag = false;
  }
  if(!$("#workEndDt").val()){
    alert("사업기간 종료일을 입력해주세요.")
    flag = false;
  }
  if(!$("#planPrice").val()){
    alert("계획금액을 입력해주세요.")
    flag = false;
  }
  if(!$("#usePrice").val()){
    alert("집행액을 입력해주세요.")
    flag = false;
  }
  if($(".clearInfoSeq").length<=0){
    alert("세부 집행내역을 입력해주세요.")
    flag = false;
  }
  if($(".resultInfoSeq").length<=0){
    alert("활동내용을 입력해주세요.")
    flag = false;
  }
  flag = fileCheck(flag, files);
  return flag;
}
