$(document).on('click', '#sailorAddBtn', function () {
    getSailorAddModal(null);
});

$(document).on('click', '#sailorEditBtn', function () {
    $("#sailorViewModal").modal('hide');
    getSailorEditModal(Number($("#sailorViewBody").find("[name='sailorKey']").val()));
});

$(document).on('click', '#saveSailorBtn', function (){
    saveSailor('N')
});

$(document).on('click', '#saveTempBtn', function (){
    saveSailor('Y')
});

$(document).on('click', '.tr', function (){
    getSailorViewModal($(this).data('key'));
});

$(document).on('click', '#history-tab', function (){
    const sailorKey = $('#sailorEditForm').find('input[name="sailorKey"]').val();
    const cdsKey = $('#sailorEditForm').find('input[name="cdsKey"]').val();
    const fbKey = $('#sailorEditForm').find('input[name="fbKey"]').val();
    getSailorHistoryViewModal(sailorKey, cdsKey, fbKey);
});

$(document).on('click', '#sailor-tab', function (){
    getSailorViewModal($('#sailorEditForm').find('input[name="sailorKey"]').val());
});

$(document).on('click', '.version-tr', function (){
    $(this).find('input[name="versionNo"]').prop('checked', true);
    const versionNo = $(this).find('input[name="versionNo"]').val();
    const sailorKey = $('#sailorEditForm').find('input[name="sailorKey"]').val();
    const cdsKey = $('#sailorEditForm').find('input[name="cdsKey"]').val();
    const fbKey = $('#sailorEditForm').find('input[name="fbKey"]').val();
    getSailorHistoryDetail(versionNo, sailorKey, cdsKey, fbKey);
});

$(document).on('change', '.violation', function (){
    if ($(this).val() == 'etc') {
        $(this).after(
            '<div class="row col-auto etcDiv">'
            + '<input type="text" class="form-control" name="violationEtc">'
            + '</div>'
        );
    } else {
        $(this).next('.etcDiv').remove();
    }
});

$(document).on('change', '#crackdownPolice', function (){
    if ($(this).val() == 'etc') {
        $(this).after(
            '<div class="col-auto">'
            + '<input type="text" class="form-control" name="crackdownPoliceEtc">'
            + '</div>'
        );
    } else {
        $(this).next().remove();
    }
});

$(document).on('change', '#crackdownBoat', function (){
    if ($(this).val() == 'etc') {
        $(this).after(
            '<div class="col-auto">'
            + '<input type="text" class="form-control" name="crackdownBoatEtc">'
            + '</div>'
        );
    } else {
        $(this).next().remove();
    }
});

$(document).on('change', 'select[name="crackdownPolice"]', function (){
    dynamicOption('select[name="crackdownBoat"]', $(this).val());
});

$(document).on('change', 'select[name="boatNameKr"]', function (){
    $('input[name="fbKey"]').val($('select[name="boatNameKr"] option:selected').data('key'));
    $('input[name="cdsKey"]').val($('select[name="boatNameKr"] option:selected').data('key2'));
});


$(document).on('click', '#sailorDownExcel', function (){
    exportExcel('불법조업 불법어선 선원세부현황', 'sailorTable');
});

function getSailorHistoryDetail(versionNo, sailorKey, cdsKey, fbKey){
    $.ajax({
        url: '/faStatistics/sailor/sailorHistoryDetail',
        data: {
            versionNo : versionNo,
            sailorKey: sailorKey,
            cdsKey : cdsKey,
            fbKey : fbKey
        },
        type: 'GET',
        dataType:"html",
        success: function(html){
            $("#historyDetailDiv").empty().append(html);
        },
        error:function(){

        }
    });
}


function getSailorViewModal(sailorKey){
    $.ajax({
        url: '/faStatistics/sailor/sailorViewModal',
        data: {sailorKey: sailorKey},
        type: 'GET',
        dataType:"html",
        success: function(html){
            $("#sailorAddModalContent").empty();
            $("#sailorViewBody").empty().append(html);
            $("#sailorViewModal").modal('show');
        },
        error:function(){

        }
    });
}

function getSailorHistoryViewModal(sailorKey, cdsKey, fbKey){
    $.ajax({
        url: '/faStatistics/sailor/sailorHistoryViewModal',
        data: {
            sailorKey : sailorKey,
            cdsKey : cdsKey,
            fbKey : fbKey
        },
        type: 'GET',
        dataType:"html",
        success: function(html){
            $("#sailorViewBody").empty().append(html)
            $("#sailorViewModal").modal('show');
        },
        error:function(){

        }
    });
}


function getSailorEditModal(sailorKey){
    $.ajax({
        url: '/faStatistics/sailor/sailorEditModal',
        data: {
            sailorKey: sailorKey
        },
        type: 'GET',
        dataType:"html",
        success: function(html){
            $("#sailorViewBody").empty();
            $("#sailorEditModalContent").empty().append(html);
            $("#sailorEditModal").modal('show');

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

        }
    });
}

function getSailorAddModal(){
    $.ajax({
        url: '/faStatistics/sailor/sailorAddModal',
        type: 'GET',
        dataType:"html",
        success: function(html){
            $("#sailorAddModalContent").empty().append(html);
            $("#sailorAddModal").modal('show');

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

        }
    });
}

function saveSailor(saveYn){
    /*$('input[name="warrantReqTakeTime"]').val(dateTimeCalc($("#consignmentStartDt").val(), $("#consignmentEndDt").val()));*/

    if(contentCheck()){
        if(confirm("저장하시겠습니까?")){
            $("#saveYn").val(saveYn);
            contentFade("in");
            const formData = new FormData($("#sailorEditForm")[0]);

            let violationList = [];

            $(".violation").each(function (){
                violationList.push({
                    violationKey: $(this).parent().find('input[name="violationKey"]').val() != undefined ? Number($(this).parent().find('input[name="violationKey"]').val()) : null,
                    fbKey: $("#sailorEditForm").find('input[name="fbKey"]').val() != undefined ? Number($("#sailorEditForm").find('input[name="fbKey"]').val()) : null,
                    violation: $(this).val() != '' ? $(this).val() : null,
                    violationEtc: $(this).parent().find('input[name="violationEtc"]').val() != undefined ? $(this).parent().find('input[name="violationEtc"]').val() : null
                });
            });

            for (let i=0; i < violationList.length; i++) {
                if (violationList[i].violationKey != null) {
                    formData.append(`violationList[${i}].violationKey`, violationList[i].violationKey);
                }
                if (violationList[i].fbKey != null) {
                    formData.append(`violationList[${i}].fbKey`, violationList[i].fbKey);
                }
                if (violationList[i].violation != null) {
                    formData.append(`violationList[${i}].violation`, violationList[i].violation);
                }
                if (violationList[i].violationEtc != null) {
                    formData.append(`violationList[${i}].violationEtc`, violationList[i].violationEtc);
                }
            }

            $.ajax({
                type : 'POST',
                data : formData,
                url : "/faStatistics/sailor/saveSailor",
                processData: false,
                contentType: false,
                success : function(result) {
                    alert("저장되었습니다.");
                    contentFade("out");
                    $("#sailorEditModal").modal('hide');
                    $("#sailorAddModal").modal('hide');
                },
                error : function(xhr, status) {
                    alert("저장에 실패하였습니다.")
                    contentFade("out");
                }
            })
        }
    }
}

function contentCheck(){
    let flag = true;
    return flag;
}

