let selectedList = [];

$(document).on('click', '#addSriBtn', function (){
  getSriEditModal({faSriKey: null})
})

function getSriEditModal(faSriKey){
  $.ajax({
    url: '/sri/sriEditModal',
    data: faSriKey,
    type: 'GET',
    dataType:"html",
    success: function(html){
      $("#sriEditModalContent").empty().append(html)
      $("#faSriEdate").datepicker({
        format: "yyyy-mm-dd",
        language: "ko",
        autoclose: true
      });
      CrossEditor = new NamoSE('editor');
      CrossEditor.params.ParentEditor = document.getElementById("editor");
      CrossEditor.params.Width = "100%";
      CrossEditor.params.UserLang = "auto";
      CrossEditor.params.NewToolbar = true;
      CrossEditor.params.UploadFileExecutePath = "/Crosseditor/uploadImg";
      CrossEditor.params.FullScreen = false;
      $("#editor").show();
      /*CrossEditor.OnInitCompleted(function (e){
        e.editorTarget.SetBodyValue(document.getElementById("pe_bhr").value);
      })*/
      CrossEditor.EditorStart();
      setUploadDiv();
      $("#sriEditModal").modal('show');
    },
    error:function(){

    }
  });
}

$(document).on('click', '#addReadUserBtn', function (){
  searchModalSubmit(1);
  $("#userModal").modal('show');
})

$(document).on('click', '#getMenuBtn', function (){
  $.ajax({
    type : 'POST',
    url : "/sri/selectedUserTable",
    data : JSON.stringify(selectedList),
    contentType: 'application/json',
    dataType:"html",
    beforeSend: function (xhr){
      xhr.setRequestHeader($("[name='_csrf_header']").val(), $("[name='_csrf']").val());
    },
    success : function(html) {
      $("#readUserRow").empty().append(html);
      setReadUserRowNum();
      $("#userModal").modal("hide");
    },
    error : function(xhr, status) {

    }
  })
})

$(document).on('click', '#saveSriBtn', function (){
  saveSri('DST007')
})

function saveSri(faSriState){
  if(faSriState == 'DST001'){
	if(confirm("임시저장하시겠습니까?")){
      save(faSriState);
    }
	
  }else{
	if(contentCheck()){
      if(confirm("저장하시겠습니까?")){
      	save(faSriState);
      }
    }	
  }  
}

function save(faSriState){
	$("#status").val(faSriState);
      contentFade("in");
      const formData = new FormData($("#sriEditForm")[0]);
      for(const file of files) {
        if(!file.isDelete)
          formData.append('uploadFiles', file, file.name);
      }
      formData.append('content', CrossEditor.GetBodyValue());
      $.each($(".readUserRow"), function (idx, row){
        formData.append('readUserList['+idx+'].userSeq', $(row).find('.userSeq').val());
        formData.append('readUserList['+idx+'].ogCd', $(row).find('.ogCd').val());
        formData.append('readUserList['+idx+'].ofcCd', $(row).find('.ofcCd').val());
        formData.append('readUserList['+idx+'].titleCd', $(row).find('.titleCd').val());
        formData.append('readUserList['+idx+'].userNm', $(row).find('.userNm').val());
      });
      $(".text-decoration-line-through").each(function (idx, el){
        formData.append('fileSeq', $(el).attr("data-fileseq"));
      })
      $.ajax({
        type : 'POST',
        data : formData,
        url : "/sri/saveSri",
        processData: false,
        contentType: false,
        success : function(result) {
		  if(faSriState == 'DST001'){			
			 alert("임시저장되었습니다.");	
		  }else{
			alert("저장되었습니다.");
		  }
          contentFade("out");
          $("#sriEditModal").modal('hide');
          getSriViewModal(result);
        },
        error : function(xhr, status) {
		  if(faSriState == 'DST001'){
			 alert("임시저장에 실패하였습니다.")	
		  }else{
			 alert("저장에 실패하였습니다.")
		  }
          contentFade("out");
        }
      })	
}

$(document).on('click', '.faSriTr', function (event){
  const target = event.target;
	if(!(target.className === "sriChk" ||$(target).parents("td").length>0)){
		getSriViewModal(Number($(this).find(".faSriKey").val()));
	}
})

function getSriViewModal(faSriKey){
  $.ajax({
    url: '/sri/sriViewModal',
    data: {faSriKey: faSriKey},
    type: 'GET',
    dataType:"html",
    success: function(html){
      $("#sriViewBody").empty().append(html)
      $("#sriViewModal").modal('show');
    },
    error:function(){

    }
  });
}

$(document).on('click', '#sendTab', function (){
  location.href = "/sri/sriBoard?activeTab=send";
})
$(document).on('click', '#receiveTab', function (){
  location.href = "/sri/sriBoard?activeTab=receive";
})
$(document).on('click', '#allTab', function (){
  location.href = "/sri/sriBoard?activeTab=all";
})

$(document).on('click', '#editFaSriBtn', function (){
  $("#sriViewModal").modal('hide');
  getSriEditModal({faSriKey: Number($(this).attr("data-fasrikey"))});
})

function OnInitCompleted(e){
  e.editorTarget.SetBodyValue(document.getElementById("content").value);

}

$(document).on('click', '#reSendBtn', function (){
  $("#sriViewModal").modal('hide');
  const faSri = {
    refKey: Number($(this).attr("data-fasrikey")),
    wrtUserSeq: $("#wrtUserSeq").val(),
    wrtOrgan: $("#wrtOrgan").val(),
    wrtPart: $("#wrtPart").val(),
    wrtTitle: $("#wrtTitle").val(),
    wrtUserNm: $("#wrtUserNm").val()
  }
  getSriEditModal(faSri);
})

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

$(document).on('click', '#sriDeleteBtn', function (){
	if($('input:checkbox[name=sriChk]:checked').length < 1){
		alert("게시물을 선택해주세요");
		return false;
	}
	if(confirm("삭제시 되돌릴 수 없습니다. 대상을 삭제처리 하시겠습니까?")){
	 const checkArr = [];
		$('input:checkbox[name=sriChk]:checked').each(function (idx, el){
	      checkArr.push({});
	      const target = $(el);
	      checkArr[idx].faSriKey = Number(target.parents('tr').find('.faSriKey').val());     
   		})
   		deleteSri(checkArr);	

	}	
})

$(document).on('click', '#deleteSri', function (){
	if(confirm("삭제시 되돌릴 수 없습니다. 대상을 삭제처리 하시겠습니까?")){
	 const checkArr = [];
	      checkArr.push({});
	      checkArr[0].faSriKey = Number($(this).attr("data-fasrikey"));	
	      deleteSri(checkArr);
	}	
})

function deleteSri(checkArr){
	$.ajax({
		    type : 'POST',
		    url : "/sri/sriDelete",
		    data : JSON.stringify(checkArr),
		    contentType: 'application/json',
		    beforeSend: function (xhr){
		      xhr.setRequestHeader($("[name='_csrf_header']").val(), $("[name='_csrf']").val());
		    },
		    success : function() {
		      alert("삭제처리 되었습니다.");
		      location.reload();
		    },
		    error : function(xhr, status) {
		      alert("삭제처리에 실패하였습니다");
		    }
   })	
}

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


$(document).on('click', '.rowDeleteBtn', function (){
  $(this).parents(".readUserRow").remove()
  setReadUserRowNum();
})




function setReadUserRowNum(){
  $.each($(".readUserRow"), function (idx, row){
    $(row).find(".rowSeq")[0].innerText = idx+1;
  })
}

function contentCheck(){
  let flag = true;
  if(!$("#faSriType").val()){
    alert("분류를 선택해주세요.")
    flag = false;
  }
  if(!$("#title").val()){
    alert("제목을 입력해주세요.")
    flag = false;
  }
  if($("#readUserRow").children().length===0){
    alert("수신자를 입력해주세요.")
    flag = false;
  }
  flag = fileCheck(flag, files);
  return flag;
}