$(function(){
    $("#napoDate").datepicker({
        format: "yyyy-mm-dd",
        language: "ko"
    });
    $("#paymentPaymentDate").datepicker({
        format: "yyyy-mm-dd",
        language: "ko"
    });
    $("#consignmentStartDate").datepicker({
        format: "yyyy-mm-dd",
        language: "ko"
    });
    $("#consignmentEndDate").datepicker({
        format: "yyyy-mm-dd",
        language: "ko"
    });
    $("#confiscationDate").datepicker({
        format: "yyyy-mm-dd",
        language: "ko"
    });
    $("#boatDisposalDate").datepicker({
        format: "yyyy-mm-dd",
        language: "ko"
    });
    $("#directHandoverDate").datepicker({
        format: "yyyy-mm-dd",
        language: "ko"
    });
    $("#fieldIvsgtNapoDate").datepicker({
        format: "yyyy-mm-dd",
        language: "ko"
    });
    $("#fieldIvsgtReleaseDate").datepicker({
        format: "yyyy-mm-dd",
        language: "ko"
    });
    $("#pressurizedStartDate").datepicker({
        format: "yyyy-mm-dd",
        language: "ko"
    });
    $("#pressurizedEndDate").datepicker({
        format: "yyyy-mm-dd",
        language: "ko"
    });
});
$(document).on('click', '#crackdownStatusAddBtn', function () {
    getCrackdownStatusEditModal(null);
});

$(document).on('click', '#cdsEditBtn', function () {
    $("#crackdownStatusViewModal").modal('hide');
    getCrackdownStatusEditModal(Number($("#crackdownStatusViewBody").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', '#history-tab', function (){
    getCrackdownStatusHistoryViewModal($('#cdsEditForm').find('input[name="cdsKey"]').val());
});

$(document).on('click', '#crackdownStatus-tab', function (){
    getCrackdownStatusViewModal($('#cdsEditForm').find('input[name="cdsKey"]').val());
});

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


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

$(document).on('click', '#sailorAddBtn', function (e){
    e.preventDefault();
    $('#sailorDiv').append(
        '<div class="row">'
        + '<label class="col-sm-1 col-form-label col-form-label-sm text-center">선원이름</label>'
        + '<div class="col-sm-2">'
        + '<input class="form-control form-control-sm" 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-sm btn-outline-secondary w-auto opacity-75" id="sailorRemoveBtn">'
        + '<i class="bi bi-dash-square text-danger"></i>'
        + '</button>'
        + '</div>'
    )
});


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

    $('#violationDiv').append(
        '<div class="row">'
        + '<select class="form-select form-select-sm violation" name="violation" style="max-width: 90% !important;">'
        + '<option value="">선택</option>'
        + violation
        + '<option value="etc">직접입력</option>'
        + '</select>'
        + '<button type="button" class="btn btn-sm btn-outline-secondary w-auto opacity-75" id="violationRemoveBtn">'
        + '<i class="bi bi-dash-square text-danger"></i>'
        + '</button>'
        + '</div>'
    )
});


$(document).on('click', '#sailorRemoveBtn', function (e){
    e.preventDefault();
    $(this).parent().remove();
    let deleteKey = $(this).parent().children("input[name='sailorKey']").val();
    $("#cdsEditForm").append('<input type="hidden" name="sailorDeleteKeyList" value="' + deleteKey + '">');
});

$(document).on('click', '#violationRemoveBtn', function (e){
    e.preventDefault()
    $(this).parent().remove();
    let deleteKey = $(this).parent().children("input[name='violationKey']").val();
    $("#cdsEditForm").append('<input type="hidden" name="violationDeleteKeyList" value="' + deleteKey + '">');
});

$(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', '#fisheryType', function (){
    if ($(this).val() == 'etc') {
        $(this).after(
            '<div class="col-auto">'
            + '<input type="text" class="form-control" name="fisheryTypeEtc">'
            + '</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();
    }
});

$(document).on('click', '#cdsDownExcel', function (){
    exportExcel('불법조업 불법어선 단속현황', 'cdsTable');
});

function getCrackdownStatusHistoryDetail(versionNo, cdsKey){
    $.ajax({
        url: '/faStatistics/crackdownStatus/crackdownStatusHistoryDetail',
        data: {
            versionNo : versionNo,
            cdsKey : cdsKey
        },
        type: 'GET',
        dataType:"html",
        success: function(html){
            $("#historyDetailDiv").empty().append(html);
        },
        error:function(){

        }
    });
}

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

        }
    });
}

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

        }
    });
}

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").datetimepicker({
                format:'Y-m-d H:i',
                lang:'kr'
            });
            $("#birthdate").datepicker({
                format: "yyyy-mm-dd",
                language: "ko"
            });
            $("#paymentPaymentDt").datetimepicker({
                format:'Y-m-d H:i',
                lang:'kr'
            });
            $("#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").datetimepicker({
                format:'Y-m-d H:i',
                lang:'kr'
            });
            $("#fieldIvsgtReleaseDt").datetimepicker({
                format:'Y-m-d H:i',
                lang:'kr'
            });
            $("#pressurizedStartDt").datetimepicker({
                format:'Y-m-d H:i',
                lang:'kr'
            });
            $("#pressurizedEndDt").datetimepicker({
                format:'Y-m-d H:i',
                lang:'kr'
            });
        },
        error:function(){

        }
    });
}

function saveCrackdownStatus(saveYn){
    $('input[name="fieldIvsgtTimeTaken"]').val(dateTimeCalc($("#fieldIvsgtNapoDt").val(), $("#fieldIvsgtReleaseDt").val()));
    $('input[name="pressurizedTimeTaken"]').val(dateTimeCalc($("#pressurizedStartDt").val(), $("#pressurizedEndDt").val()));

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

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

            sailorList.push(
                {
                    sailorKey: $("#cdsEditForm").find('input[name="captinSailorKey"]').val() != '' && $("#cdsEditForm").find('input[name="captinSailorKey"]').val() != 'false' ? Number($("#cdsEditForm").find('input[name="captinSailorKey"]').val()) : null,
                    position: 'POS001',
                    sailorNameKr: $("#cdsEditForm").find('input[name="sailorNameKr"]').val() != '' ? $("#cdsEditForm").find('input[name="sailorNameKr"]').val() : null,
                    isRestriction: $("#cdsEditForm").find('select[name="captin"]').val() != '' ? $("#cdsEditForm").find('select[name="captin"]').val() : null,
                    birthdate: $("#cdsEditForm").find('input[name="birthdate"]').val() != '' ? $("#cdsEditForm").find('input[name="birthdate"]').val() : null
                },
                {
                    sailorKey: $("#cdsEditForm").find('input[name="mateSailorKey"]').val() != '' && $("#cdsEditForm").find('input[name="mateSailorKey"]').val() != 'false' ? Number($("#cdsEditForm").find('input[name="mateSailorKey"]').val()) : null,
                    position: 'POS002',
                    sailorNameKr: null,
                    isRestriction: $("#cdsEditForm").find('select[name="mate"]').val()  != '' ? $("#cdsEditForm").find('select[name="mate"]').val() : null
                },
                {
                    sailorKey: $("#cdsEditForm").find('input[name="wardenSailorKey"]').val() != '' && $("#cdsEditForm").find('input[name="wardenSailorKey"]').val() != 'false' ? Number($("#cdsEditForm").find('input[name="wardenSailorKey"]').val()) : null,
                    position: 'POS003',
                    sailorNameKr: null,
                    isRestriction: $("#cdsEditForm").find('select[name="warden"]').val()  != '' ? $("#cdsEditForm").find('select[name="warden"]').val() : null
                }
            );

            $("select[name='sailor']").each(function (){
                sailorList.push({
                    sailorKey: $(this).parent().parent().find('input[name="sailorKey"]').val() != undefined ? Number($(this).parent().parent().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].sailorKey != 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);
                }
                if (sailorList[i].birthdate != null) {
                    formData.append(`sailorList[${i}].birthdate`, sailorList[i].birthdate);
                }
            }

            $(".violation").each(function (){
                violationList.push({
                    violationKey: $(this).parent().find('input[name="violationKey"]').val() != undefined ? Number($(this).parent().find('input[name="violationKey"]').val()) : null,
                    fbKey: $("#cdsEditForm").find('input[name="fbKey"]').val() != undefined ? Number($("#cdsEditForm").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/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(!$('#cdsEditForm').find($('input[name="boatNameKr"]').val())) {
        alert('선명을 입력해주세요.');
        $('input[name="boatNameKr"]').focus();
        return false;
    }

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

    return flag;
}
