let files = [];

function contentFade(action){
  if(action === "in"){
    $("#fadeDiv").show()
  }else{
    $("#fadeDiv").hide()
  }
}

function searchFade(action){
  if(action === "in"){
    $("#fadeSearchDiv").show()
  }else{
    $("#fadeSearchDiv").hide()
  }
}

$(document).on('click', '.allChk', function (){
  $(this).parents('table').find('[type="checkbox"]').prop("checked", this.checked);
})
$(document).on('click', '.page-item', function (){
  if(!this.className.includes("modalPage")){
    searchFormSubmit($(this).attr("data-pageindex"))
  }else{
    searchModalSubmit($(this).attr("data-pageindex"))
  }
})
$(document).on('click', '#searchModalBtn', function (){
  searchModalSubmit(1);
})
$(document).on('change', '#rowCnt', function (){
  searchFormSubmit(1)
})
function searchFormSubmit(pageIndex){
  $("#pageIndex").val(pageIndex);
  $("#searchBtn").click();
}
function searchModalSubmit(pageIndex){
  $("#modalPageIndex").val(pageIndex);
  $.ajax({
    url: $("#modalUrl").val(),
    data : $("#modalSearchForm").serialize(),
    type: 'GET',
    contentType: false,
    dataType:"html",
    success: function(html){
      $("#subModalBody").empty().append(html)
      if(selectedList !== undefined && selectedList.length>0){
        setSelectedChkBox();
      }
    },
    error:function(){
    }
  });
}


$(document).on('mouseenter', '.firstMenuLink', function (event){
  $(".secondMenu").hide();
  const targetMenu = $(this).parent().find(".secondMenu");
  targetMenu.show()
  targetMenu.find("ul").css("padding-top",(event.clientY-20)+"px")
})
$(document).on('mouseenter', '.secondMenuLink', function (event){
  $(".thirdMenu").hide();
  const targetMenu = $(this).parent().find(".thirdMenu");
  targetMenu.show()
  targetMenu.find("ul").css("padding-top",(event.clientY-20)+"px")
})
$(document).on('mouseleave', '.menuDiv', function (){
  $(".secondMenu").hide();
  $(".thirdMenu").hide();
})

$(document).on('change', '#fileInputer', function (){
  for(const file of this.files){
    setFileDiv(file, files.push(file));
  }
  this.value = null;
})

function byteCalculation(size) {
  const bytes = parseInt(size);
  const s = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB'];
  const e = Math.floor(Math.log(bytes)/Math.log(1024));

  if(e === "-Infinity") return "0 "+s[0];
  else return (bytes/Math.pow(1024, Math.floor(e))).toFixed(2)+" "+s[e];

}

$(document).on('click', '.fileDelete', function (){
  const target = $(this);
  files[Number(target.attr("data-fileidx"))].isDelete = true;
  target.parent().remove();
  const uploadDiv = $("#uploadDiv");
  if(uploadDiv.children().length === 0){
    uploadDiv.append("<br>파일을 업로드 해주세요.");
  }
})
$(document).on('click', '.uploadedFileDelete', function (){
  const target = $(this).parent().find("span")[0];
  if(target.className===""){
    target.className = "text-decoration-line-through";
  }else{
    target.className = "";
  }
})

$(document).on('click', '.fileDownLink', function (){
  const target = $(this)
  let url = "/file/fileDownload?"
  url += "board="+target.attr("data-board");
  url += "&parentKey="+target.attr("data-parentkey");
  url += "&fileSeq="+target.attr("data-fileseq");
  window.open(encodeURI(url));
})

//Bootstrap multiple modal
let count = 0; // 모달이 열릴 때 마다 count 해서  z-index값을 높여줌
$(document).on('show.bs.modal', '.modal', function () {
  let zIndex = 1040 + (10 * count);
  $(this).css('z-index', zIndex);
  setTimeout(function() {
    $('.modal-backdrop').not('.modal-stack').css('z-index', zIndex - 1).addClass('modal-stack');
  }, 0);
  count = count + 1
});
// multiple modal Scrollbar fix
$(document).on('hidden.bs.modal', '.modal', function(){
  $('.modal:visible').length && $(document.body).addClass('modal-open');
});

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){
      if(e.target.className.indexOf("artInfo")<0){
        if(e.target.className.indexOf("artWork")<0){
          $("#fileInputer").click();
        }
	    }
    }
  });
}

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 fileCheck(flag, files){
  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;
}

function dynamicOption(targetTagName, code, defaultOptionName='') {
  $(targetTagName).empty();
  let option = '';

  if (code) {
    commonCode[code].forEach(function (item) {
      option += '<option value="' + item.itemCd + '">' + item.itemValue + '</option>';
    });
  }

  $(targetTagName).append('<option value="">' +defaultOptionName + '선택</option>' + option);
}

function departmentDynamicOption(targetTagName, code, defaultOptionName='') {
  $(targetTagName).empty();
  let option = '';
  organConfigList.forEach(function (organConfig) {
    if (organConfig.parentOrgan != null && organConfig.organType !== 'OGC002' && organConfig.parentOrgan === code) {
      option += '<option value="' + organConfig.organCd + '">' + organConfig.organNm + '</option>';
    }
  });
  $(targetTagName).append('<option value="">' + defaultOptionName + ' 선택</option>' + option);
}

function dateTimeCalc(startDateTime, endDateTime) {
  if (startDateTime !== '' &&endDateTime !== '' && startDateTime !== undefined && endDateTime !== undefined) {
    const startDate = new Date(startDateTime);
    const endDate = new Date(endDateTime);

    let diffTime = endDate.getTime() - startDate.getTime();

    const day = Math.floor(diffTime / (1000* 60 * 60 * 24));
    const hour = Math.floor((diffTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    const minute = Math.floor((diffTime % (1000 * 60 * 60)) / (1000 * 60));

    return day + '일' + hour + '시간' + minute + '분';
  }

  return null;
}

function exportExcel(name, tableId){
  var excelHandler = {
    getExcelFileName : function(){
      return name+'_'+getToday()+'.xlsx';	//파일명
    },
    getSheetName : function(){
      return name;
    },
    getExcelData : function(){
      return document.getElementById(tableId); 	//TABLE id
    },
    getWorksheet : function(){
      return XLSX.utils.table_to_sheet(this.getExcelData());
    }
  }
  // step 1. workbook 생성
  var wb = XLSX.utils.book_new();

  // step 2. 시트 만들기
  var newWorksheet = excelHandler.getWorksheet();

  // step 3. workbook에 새로만든 워크시트에 이름을 주고 붙인다.
  XLSX.utils.book_append_sheet(wb, newWorksheet, excelHandler.getSheetName());

  // step 4. 엑셀 파일 만들기
  var wbout = XLSX.write(wb, {bookType:'xlsx',  type: 'binary'});

  // step 5. 엑셀 파일 내보내기
  saveAs(new Blob([s2ab(wbout)],{type:"application/octet-stream"}), excelHandler.getExcelFileName());
}

function s2ab(s) {
  var buf = new ArrayBuffer(s.length); //convert s to arrayBuffer
  var view = new Uint8Array(buf);  //create uint8array as viewer
  for (var i=0; i<s.length; i++) view[i] = s.charCodeAt(i) & 0xFF; //convert to octet
  return buf;
}

function getToday(){
  var date = new Date();
  var year = date.getFullYear();
  var month = ("0" + (1 + date.getMonth())).slice(-2);
  var day = ("0" + date.getDate()).slice(-2);

  return year + "-" + month + "-" + day;
}