$(document).on('click', '#crackdownStatusAddBtn', function () {
    getCrackdownStatusEditModal(null);
});

$(document).on('click', '#crackdownStatusEditBtn', function () {
    $("#crackdownStatusViewModal").modal('hide');
    getCrackdownStatusEditModal(Number($("#icaViewBody").find("[name='cdsKey']").val()));
});


$(document).on('click', '#saveCrackdownStatusBtn', function (){
    saveCrackdownStatus('N')
});

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

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

$(document).on('click', '#sailorAddBtn', function (){
    $('#sailorDiv').append(
        '<div class="row">'
        + '<label class="col-sm-1 col-form-label text-center">선원이름</label>'
        + '<div class="col-sm-2">'
        + '<input class="form-control" name="sailorNameKr">'
        + '</div>'
        + '<div class="col-sm-2">'
        + '<select class="form-select form-select-sm" name="sailor">'
        + '<option value="">선택</option>'
        + '<option value="Y">구속</option>'
        + '<option value="N">불구속</option>'
        + '</select>'
        + '</div>'
        + '<button type="button" class="btn btn-primary col-auto" id="sailorRemoveBtn">-</button>'
        + '</div>'
    )
});


$(document).on('click', '#violationAddBtn', function (){
    let violation = '';
    commonCode.VT.forEach(function (item){
        violation += '<option value="'+ item.itemCd +'">' + item.itemValue +'</option>';
    })

    $('#violationDiv').append(
        '<div>'
        + '<select class="form-select form-select-sm" name="violation">'
        + '<option value="">선택</option>'
        + violation
        + '<option value="etc">직접입력</option>'
        + '</select>'
        + '<button type="button" class="btn btn-primary col-auto" id="violationRemoveBtn">-</button>'
        + '</div>'
    )
});


$(document).on('click', '#sailorRemoveBtn', function (){
    $(this).parent().remove();
});

$(document).on('click', '#violationRemoveBtn', function (){
    $(this).parent().remove();
});

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

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

function getCrackdownStatusEditModal(cdsKey){
    $.ajax({
        url: '/faStatistics/crackdownStatus/crackdownStatusEditModal',
        data: {
            cdsKey: cdsKey
        },
        type: 'GET',
        dataType:"html",
        success: function(html){
            $("#crackdownStatusViewBody").empty();
            $("#crackdownStatusEditModalContent").empty().append(html);
            $("#crackdownStatusEditModal").modal('show');

            $("#napoDt").datepicker({
                format: "yyyy-mm-dd",
                language: "ko"
            });
            $("#birthdate").datepicker({
                format: "yyyy-mm-dd",
                language: "ko"
            });
            $("#paymentPaymentDt").datepicker({
                format: "yyyy-mm-dd",
                language: "ko"
            });
            $("#consignmentStartDt").datepicker({
                format: "yyyy-mm-dd",
                language: "ko"
            });
            $("#consignmentEndDt").datepicker({
                format: "yyyy-mm-dd",
                language: "ko"
            });
            $("#evictionDt").datepicker({
                format: "yyyy-mm-dd",
                language: "ko"
            });
            $("#returnDt").datepicker({
                format: "yyyy-mm-dd",
                language: "ko"
            });
            $("#confiscationDt").datepicker({
                format: "yyyy-mm-dd",
                language: "ko"
            });
            $("#boatDisposalDt").datepicker({
                format: "yyyy-mm-dd",
                language: "ko"
            });
            $("#directHandoverDt").datepicker({
                format: "yyyy-mm-dd",
                language: "ko"
            });
            $("#fieldIvsgtNapoDt").datepicker({
                format: "yyyy-mm-dd",
                language: "ko"
            });
            $("#fieldIvsgtReleaseDt").datepicker({
                format: "yyyy-mm-dd",
                language: "ko"
            });
            $("#pressurizedStartDt").datepicker({
                format: "yyyy-mm-dd",
                language: "ko"
            });
            $("#pressurizedEndDt").datepicker({
                format: "yyyy-mm-dd",
                language: "ko"
            });

        },
        error:function(){

        }
    });
}

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

            let violationList = [];
            let sailorList = [];

            sailorList.push(
                { position: 'POS001', sailorNameKr: null, isRestriction: $("#cdsEditForm").find('select[name="captin"]').val() != '' ? $("#cdsEditForm").find('select[name="captin"]').val() : null },
                { position: 'POS002', sailorNameKr: null, isRestriction: $("#cdsEditForm").find('select[name="mate"]').val()  != '' ? $("#cdsEditForm").find('select[name="mate"]').val() : null },
                { position: 'POS003', sailorNameKr: null, isRestriction: $("#cdsEditForm").find('select[name="warden"]').val()  != '' ? $("#cdsEditForm").find('select[name="warden"]').val() : null }
            );

            $(".sailor-list").each(function (){
                sailorList.push({
                    sailorKey: $(this).parent().parent().find('input[name="sailorKey"]').val() != undefined ? Number($(this).find('input[name="sailorKey"]').val()) : null,
                    sailorNameKr: $(this).parent().parent().find('input[name="sailorNameKr"]').val(),
                    position: 'POS006',
                    isRestriction: $(this).val() != undefined ? $(this).val() : null
                });
            });

            for (let i=0; i < sailorList.length; i++) {
                if (sailorList[i].spiKey != null) {
                    formData.append(`sailorList[${i}].sailorKey`, sailorList[i].sailorKey);
                }
                if (sailorList[i].sailorNameKr != null) {
                    formData.append(`sailorList[${i}].sailorNameKr`, sailorList[i].sailorNameKr);
                }
                formData.append(`sailorList[${i}].position`, sailorList[i].position);
                if (sailorList[i].isRestriction != null) {
                    formData.append(`sailorList[${i}].isRestriction`, sailorList[i].isRestriction);
                }
            }

            $(".violation").each(function (){
                violationList.push({
                    violationKey: $(this).parent().find('input[name="violationKey"]').val() != undefined ? Number($(this).find('input[name="violationKey"]').val()) : null,
                    fbKey: $("#cdsEditForm").find('input[name="fbKey"]').val() != undefined ? Number($(this).find('input[name="fbKey"]').val()) : null,
                    violation: $(this).val() != '' ? $(this).val() : null,
                    violationEtc: $(this).parent().find('input[name="violationEtc"]').val() != undefined ? $(this).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/crackdownStatus/saveCrackdownStatus",
                processData: false,
                contentType: false,
                success : function(result) {
                    alert("저장되었습니다.");
                    contentFade("out");
                    $("#crackdownStatusEditModal").modal('hide');
                },
                error : function(xhr, status) {
                    alert("저장에 실패하였습니다.")
                    contentFade("out");
                }
            })
        }
    }
}

function contentCheck(){
    let flag = true;

    if(!$('input[name="boatNameKr"]').val()) {
        alert('선명을 입력해주세요.');
        $('input[name="boatNameKr"]').focus();
        return false;
    }

    if(!$('select[name="processStatus"]').val()) {
        alert('처리현황을 선택해주세요.');
        $('select[name="processStatus"]').focus();
        return false;
    }

    return flag;
}