$(function(){
    $("#consignmentStartDate").datepicker({
        format: "yyyy-mm-dd",
        language: "ko"
    });
    $("#consignmentEndDate").datepicker({
        format: "yyyy-mm-dd",
        language: "ko"
    });
    $("#returnDate").datepicker({
        format: "yyyy-mm-dd",
        language: "ko"
    });
    $("#confiscationDate").datepicker({
        format: "yyyy-mm-dd",
        language: "ko"
    });
    $("#boatDisposalDate").datepicker({
        format: "yyyy-mm-dd",
        language: "ko"
    });
});
$(document).on('click', '#processResultAddBtn', function () {
    getProcessResultAddModal(null);
});

$(document).on('click', '#processResultEditBtn', function () {
    $("#processResultViewModal").modal('hide');
    getProcessResultEditModal(Number($("#processResultViewBody").find("[name='prKey']").val()));
});

$(document).on('click', '#saveProcessResultBtn', function (){
    saveProcessResult('N')
});

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

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

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

$(document).on('click', '#processResult-tab', function (){
    getProcessResultViewModal($('#processResultEditForm').find('input[name="prKey"]').val());
});

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

$(document).on('change', 'select[name="caseNum"]', function (){
    $('input[name="boatNameKr"]').val('');
    $('input[name="prKey"]').val('');
    $('input[name="cdsKey"]').val($('select[name="caseNum"] option:selected').val());

    const formdata = new FormData($('#processResultEditForm')[0]);

    $.ajax({
        type: 'POST',
        data: formdata,
        url: "/faStatistics/processResult/getProcessResult",
        processData: false,
        contentType: false,
        success: function(result) {
            $('input[name="boatNameKr"]').val(result.fishingBoat.boatNameKr);
            $('input[name="prKey"]').val(result.prKey);
            $('input[name="sentencingCourt"]').val(result.sentencingCourt);
            $('input[name="sentencingDetail"]').val(result.sentencingDetail);
            $('select[name="executionDetail"]').val(result.executionDetail).prop('selected', true);
            $('input[name="returnDt"]').val(result.returnDt);
            $('input[name="consignmentStartDt"]').val(result.consignmentStartDt);
            $('input[name="consignmentEndDt"]').val(result.consignmentEndDt);
            $('input[name="confiscationDt"]').val(result.confiscationDt);
            $('input[name="boatDisposalDt"]').val(result.boatDisposalDt);
            $('input[name="boatDisposalDt"]').val(result.boatDisposalDt);
        },
        error: function(xhr, status) {

        }
    });
});

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

$(document).on('click', '#processResultDownExcel', function (){
    exportExcel('불법조업 불법어선 처리현황', 'prTable');
});

function getProcessResultHistoryDetail(versionNo, prKey, cdsKey, fbKey){
    $.ajax({
        url: '/faStatistics/processResult/processResultHistoryDetail',
        data: {
            versionNo : versionNo,
            prKey: prKey,
            cdsKey : cdsKey,
            fbKey : fbKey
        },
        type: 'GET',
        dataType:"html",
        success: function(html){
            $("#historyDetailDiv").empty().append(html);
        },
        error:function(){

        }
    });
}

function getProcessResultViewModal(prKey){
    $.ajax({
        url: '/faStatistics/processResult/processResultViewModal',
        data: {prKey: prKey},
        type: 'GET',
        dataType:"html",
        success: function(html){
            $("#processResultEditModalContent").empty();
            $("#processResultViewBody").empty().append(html)
            $("#processResultViewModal").modal('show');
        },
        error:function(){

        }
    });
}

function getProcessResultHistoryViewModal(prKey, cdsKey, fbKey){
    $.ajax({
        url: '/faStatistics/processResult/processResultHistoryViewModal',
        data: {
            prKey: prKey,
            cdsKey : cdsKey,
            fbKey : fbKey
        },
        type: 'GET',
        dataType:"html",
        success: function(html){
            $("#processResultViewBody").empty().append(html)
            $("#processResultViewModal").modal('show');
        },
        error:function(){

        }
    });
}

function getProcessResultAddModal(){
    $.ajax({
        url: '/faStatistics/processResult/processResultAddModal',
        type: 'GET',
        dataType:"html",
        success: function(html){
            $("#processResultViewBody").empty();
            $("#processResultAddModalContent").empty().append(html);
            $("#processResultAddModal").modal('show');

            $("#consignmentStartDt").datepicker({
                format: "yyyy-mm-dd",
                language: "ko"
            });
            $("#consignmentEndDt").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"
            });
        },
        error:function(){

        }
    });
}

function getProcessResultEditModal(prKey){
    $.ajax({
        url: '/faStatistics/processResult/processResultEditModal',
        data: {
            prKey: prKey
        },
        type: 'GET',
        dataType:"html",
        success: function(html){
            $("#processResultViewBody").empty();
            $("#processResultEditModalContent").empty().append(html);
            $("#processResultEditModal").modal('show');

            $("#consignmentStartDt").datepicker({
                format: "yyyy-mm-dd",
                language: "ko"
            });
            $("#consignmentEndDt").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"
            });
        },
        error:function(){

        }
    });
}

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

    if(contentCheck()){
        if(confirm("저장하시겠습니까?")){
            $("#saveYn").val(saveYn);
            contentFade("in");
            const formData = new FormData($("#processResultEditForm")[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: $("#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/processResult/saveProcessResult",
                processData: false,
                contentType: false,
                success : function(result) {
                    alert("저장되었습니다.");
                    contentFade("out");
                    $("#processResultEditModal").modal('hide');
                    $("#processResultAddModal").modal('hide');
                },
                error : function(xhr, status) {
                    alert("저장에 실패하였습니다.")
                    contentFade("out");
                }
            })
        }
    }
}

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