let selectedList = [];
let fileList = [];
$(document).on('click', '#getFishingBoatEditModalBtn', function (){
  getFishingBoatEditModal(null);
})
$(document).on('click', '.crackdownStatusTr', function (){
  getFishingBoatViewModal($(this).find(".cdsKey").val())
})
$(document).on('click', '#editFishingBoatBtn', function (){
  getFishingBoatEditModal($("#fishingBoatViewModalContent").find(".cdsKey").val());
  $("#fishingBoatViewModal").modal('hide');
})
$(document).on('change', '#caseNum', function (){
  $.ajax({
    url: '/faStatistics/checkCaseNum',
    type: 'GET',
    data: {caseNum: $("#caseNum").val()},
    dataType:"json",
    success: function(data){
      if(data===1){
        alert("일치하는 사건번호가 등록되어 있습니다.");
        $("#caseNum").val("");
      }
    },
    error:function(){

    }
  });
})
$(document).on('click', '#caseNumBtn', function (){
  searchModalSubmit(1);
  $("#crackdownSubModal").modal('show');
})
$(document).on('click', '.crackdownTr', function (){
  $(".crackdownTr").prop("checked", false);
  const chkbox = $(this).find('.crackdownChkbox')[0]
  chkbox.checked = !chkbox.checked;
})
$(document).on('click', '#getCrackdownBtn', function (){
  getFishingBoatEditModal($(".crackdownChkbox:checked").parents(".crackdownTr").attr("data-key"));
  $("#crackdownSubModal").modal('hide');
})
$(document).on('change', '#crackdownPolice', function (){
  getCrackdownBoatOption(this.value);
})
$(document).on('change', '#violationSelector', function (){
  if(this.selectedOptions[0].value !== ""){
    if($(".violationCd[value='"+this.selectedOptions[0].value+"']").length===0){
      $("#violationDiv").append(
          '<div class="col-6 violation">\n' +
          '  <div class="input-group w-auto">\n' +
          '    <input type="hidden" class="form-control form-control-sm fishingBoatInfo violationCd" value="'+this.selectedOptions[0].value+'">\n' +
          '    <input type="text" class="form-control form-control-sm" value="'+this.selectedOptions[0].innerText+'">\n' +
          '    <button type="button" class="btn btn-sm btn-outline-secondary opacity-75 violationRemoveBtn">\n' +
          '      <i class="bi bi-dash-square text-danger"></i>\n' +
          '    </button>\n' +
          '  </div>\n' +
          '</div>'
      )
    }
  }
})
$(document).on('click', '.versionInfoTr', function (){
  $(".versionInfoChkbox").prop("checked", false);
  $(this).find(".versionInfoChkbox")[0].checked = true
  $.ajax({
    url: '/faStatistics/fishingBoatVersionInfo',
    data: {
      fbKey: $(this).find(".fbKey").val(),
      versionNo: $(this).find(".versionNo").val()
    },
    type: 'GET',
    dataType:"html",
    success: function(html){
      $("#fishingBoardVersionInfoDiv").empty().append(html);
    },
    error:function(){

    }
  });
})
$(document).on('click', '.violationRemoveBtn', function (){
  $(this).parents(".violation").remove();
})
$(document).on('change', '.boatNameKr', function (){
  $(".boatNameKr").val(this.value);
})
$(document).on('change', '#equalCaptain', function (){
  if(this.checked){
    $.each($("#captainDiv :input"), function (idx, input){
      $("#shipOwnerDiv").find("#"+input.id+"2").val(input.value)
    })
  }else{
    $("#shipOwnerDiv :input").val("");
  }
})
$(document).on('change', '#captainDiv :input', function (){
  if($("#equalCaptain").prop("checked")){
    $("#shipOwnerDiv").find("#"+this.id+"2").val(this.value)
  }
})
$(document).on('click', '#sailorAddBtn', function (){
  $("#sailorRestrictionHome").append(
      '<div class="col-4 sailorRestriction">\n' +
      '  <div class="input-group">\n' +
      '    <select class="form-select form-select-sm isRestriction normalSailorPosition" style="width: 75px">\n' +
      '      <option value="">직책</option>\n' +
      '      <option value="POS005">기타 간부선원</option>\n' +
      '      <option value="POS006">일반선원 또는 확인불가</option>\n' +
      '    </select>\n' +
      '    <select class="form-select form-select-sm isRestriction w-auto normalSailorRestriction">\n' +
      '      <option value="">선택</option>\n' +
      '      <option value="Y">O</option>\n' +
      '      <option value="N">X</option>\n' +
      '    </select>\n' +
      '    <input type="text" class="form-control form-control-sm sailorInfo normalSailorNm w-auto" placeholder="이름">\n' +
      '    <button type="button" class="btn btn-sm btn-outline-secondary w-auto opacity-75 sailorRemoveBtn">\n' +
      '      <i class="bi bi-dash-square text-danger"></i>\n' +
      '    </button>\n' +
      '  </div>\n' +
      '</div>'
  )
})
$(document).on('click', '.sailorRemoveBtn', function (){
  $(this).parents(".sailorRestriction").remove();
})
$(document).on('click', '#saveTempBtn', function (){
  saveFishingBoatInfo("N")
})
$(document).on('click', '#saveResultBtn', function (){
  saveFishingBoatInfo("Y")
})
$(document).on('change', '.pressurizedTimeTaken', function (){
  $("#pressurizedTimeTaken").val($("#pressurizedTimeTakenDate").val()+"일 "+$("#pressurizedTimeTakenTime").val())
})
$(document).on('change', '.warrantReqTake', function (){
  $("#warrantReqTake").val($("#warrantReqTakeDate").val()+"일 "+$("#warrantReqTakeTime").val())
})
$(document).on('click', '#captainPhoto', function (){
  const fileDownloadDiv = $("#fileDownloadDiv")[0]
  if(fileDownloadDiv.className==="d-none"){
    fileDownloadDiv.className="";
  }else{
    fileDownloadDiv.className="d-none"
  }
})
$(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));
})
function getFishingBoatEditModal(cdsKey){
  $.ajax({
    url: '/faStatistics/fishingBoatEditModal',
    data: {cdsKey: cdsKey},
    type: 'GET',
    dataType:"html",
    success: function(html){
      $("#fishingBoatEditModalContent").empty().append(html)
      $(".dateSelector").datepicker({
        format: "yyyy-mm-dd",
        language: "ko",
        autoclose: true
      });
      $(".dateTimeSelector").datetimepicker({
        format:'Y-m-d H:i',
        lang:'kr',
        step:20
      });
      $(".timeSelector").datetimepicker({
        datepicker:false,
        format:'H시간i분',
        lang:'kr',
        step:20
      });
      const crackdownPolice = $("#crackdownPolice").val()
      if(crackdownPolice){
        getCrackdownBoatOption(crackdownPolice)
      }
      if(cdsKey !== null){
        $(".crackdownStatusInfo").attr("disabled", "disabled")
        $(".sailorInfo").attr("disabled", "disabled")
        $(".processResultInfo").attr("disabled", "disabled")
      }else{
        setUploadDiv();
      }
      $("#fishingBoatEditModal").modal('show');
    },
    error:function(){

    }
  });
}
function getFishingBoatViewModal(cdsKey){
  $.ajax({
    url: '/faStatistics/fishingBoatViewModal',
    data: {cdsKey: cdsKey},
    type: 'GET',
    dataType:"html",
    success: function(html){
      $("#fishingBoatViewModalContent").empty().append(html)
      const crackdownPolice = $("#crackdownPolice").val()
      if(crackdownPolice){
        getCrackdownBoatOption(crackdownPolice)
      }
      $("#fishingBoatViewModal").modal('show');
    },
    error:function(){

    }
  });
}
function getCrackdownBoatOption(categoryCd){
  $.ajax({
    url: '/selectBoxOptions',
    data: {categoryCd: categoryCd, selectedCd: $("#crackdownBoat").attr("data-boatcode")},
    type: 'GET',
    dataType:"html",
    success: function(html){
      const crackdownBoat = $("#crackdownBoat");
      crackdownBoat.empty().append(html);
      if(!$("#cdsKey").val()){
        crackdownBoat.removeAttr("disabled");
      }
    },
    error:function(){

    }
  });
}

function saveFishingBoatInfo(saveYn){
  if(confirm("저장하시겠습니까?")){
    $("#saveYn").val(saveYn)
    contentFade("in");
    const formData = new FormData($("#fishingBoatEditForm")[0]);
    for(const file of files) {
      if(!file.isDelete)
        formData.append('uploadFiles', file, file.name);
    }
    $.each($(".violationCd"), function (idx, input){
      formData.append('violationList['+idx+'].violation', $(input).val());
    });
    let sailorCnt=0;
    // 선장 정보 입력
    const sailorNameKr = $("#sailorNameKr").val();
    if(sailorNameKr){
      formData.append('sailorList['+sailorCnt+'].sailorNameKr', sailorNameKr);
      formData.append('sailorList['+sailorCnt+'].sailorNameCn', $("#sailorNameCn").val());
      formData.append('sailorList['+sailorCnt+'].sailorNamePinyin', $("#sailorNamePinyin").val());
      formData.append('sailorList['+sailorCnt+'].birthdate', $("#birthdate").val());
      formData.append('sailorList['+sailorCnt+'].sailorContact', $("#sailorContact").val());
      formData.append('sailorList['+sailorCnt+'].residence', $("#residence").val());
      formData.append('sailorList['+sailorCnt+'].arrestHistory', $("#arrestHistory").val());
      formData.append('sailorList['+sailorCnt+'].note', $("#note").val());
      formData.append('sailorList['+sailorCnt+'].isRestriction', $("#captainRestriction").val());
      formData.append('sailorList['+sailorCnt+'].position', "POS001");
      //선장 사진 파일 붙임 필요.
      sailorCnt++;
    }
    // 선주 정보 입력
    const sailorNameKr2 = $("#sailorNameKr2").val();
    if(sailorNameKr) {
      formData.append('sailorList[' + sailorCnt + '].sailorNameKr', sailorNameKr2);
      formData.append('sailorList[' + sailorCnt + '].sailorNameCn', $("#sailorNameCn2").val());
      formData.append('sailorList[' + sailorCnt + '].sailorNamePinyin', $("#sailorNamePinyin2").val());
      formData.append('sailorList[' + sailorCnt + '].birthdate', $("#birthdate2").val());
      formData.append('sailorList[' + sailorCnt + '].sailorContact', $("#sailorContact2").val());
      formData.append('sailorList[' + sailorCnt + '].residence', $("#residence2").val());
      formData.append('sailorList[' + sailorCnt + '].note', $("#note2").val());
      formData.append('sailorList[' + sailorCnt + '].position', "POS004");
      sailorCnt++;
    }
    const navigatingOfficerRestriction = $("#navigatingOfficerRestriction").val()
    if(navigatingOfficerRestriction){
      formData.append('sailorList['+sailorCnt+'].isRestriction', navigatingOfficerRestriction);
      formData.append('sailorList['+sailorCnt+'].position', "POS002");
      sailorCnt++;
    }
    const chiefEngineerRestriction = $("#chiefEngineerRestriction").val();
    if(chiefEngineerRestriction){
      formData.append('sailorList['+sailorCnt+'].isRestriction', chiefEngineerRestriction);
      formData.append('sailorList['+sailorCnt+'].position', "POS003");
      sailorCnt++;
    }
    $.each($(".sailorRestriction"), function (idx, div){
      const position = $(div).find(".normalSailorPosition").val();
      if(position===""){
        alert("선원의 직책이 선택되지 않았습니다.")
        return false
      }
      formData.append('sailorList['+(idx+sailorCnt)+'].isRestriction', $(div).find(".normalSailorRestriction").val());
      formData.append('sailorList['+(idx+sailorCnt)+'].sailorNameKr', $(div).find(".normalSailorNm").val());
      formData.append('sailorList['+(idx+sailorCnt)+'].position', position);
    });
    $.ajax({
      type : 'POST',
      data : formData,
      url : "/faStatistics/saveFishingBoat",
      processData: false,
      contentType: false,
      success : function() {
        alert("저장되었습니다.");
        contentFade("out");
        location.reload();
      },
      error : function(xhr, status) {
        alert("저장에 실패하였습니다.");
        contentFade("out");
      }
    })
  }
}