$(document).on('click', '#ivsgtAddBtn', function () {
    getIvsgtEditModal(null, $("input[name='ivsgtType']").val());
});

$(document).on('click', '#ivsgtEditBtn', function () {
    $("#ivsgtViewModal").modal('hide');
    getIvsgtEditModal(Number($("#ivsgtViewBody").find("[name='ivsgtKey']").val()));
});


$(document).on('click', '#contentInfoAddBtn', function (){
    $("#contentInfoDiv").append("<input type='text' class='form-control' name='contentInfos'>")
});

$(document).on('click', '#saveIvsgtBtn', function (){
    saveBoardInvestigation('N')
});

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

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

$(document).on('click', '.ivsgtTab', function (){
    location.href = "/ivsgt/"+ $(this).data("ivsgt-type");
});

$(document).on('click', '#relatedReportSearchBtn', function (){
    let contentTitle = $("#ivsgtEditBody").find("[name='searchTitle']").val();
    let ivsgtType = $("#ivsgtEditBody").find("[name='ivsgtType']").val();
    getSearchViewModal(ivsgtType, contentTitle)
});

$(document).on('click', '#completeBtn', function (){
    const checkbox = document.getElementsByClassName('reportChk');

    Array.from(checkbox).forEach(function(element) {
        if (element.checked) {
            $('#relatedReportSearchDiv').append(
                '<input type="hidden" name="relatedReportsKeyList" value="0">'
                + '<input type="hidden" name="childIvsgtKeyList" value="' + element.value + '">'
                + '<div class="col-auto"><input class="border-0" type="text" name="relatedReportsText" value="' + element.name + '" readonly>'
                + '<button class="btn btn-sm btn-primary col-auto cancel-btn" >X</button></div>'
            )
        }
    });
});

$(document).on('click', '.cancel-btn', function (){
    $(this).parent().remove();
    let deleteKey = $(this).parent().children("input[name='relatedReportsKeyList']").val();
    $("#ivsgtEditForm").append('<input type="hidden" name="deleteKeyList" value="' + deleteKey + '">');
});


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


function getIvsgtViewModal(ivsgtKey){
    $.ajax({
        url: '/ivsgt/ivsgtViewModal',
        data: {ivsgtKey: ivsgtKey},
        type: 'GET',
        dataType:"html",
        success: function(html){
            $("#ivsgtViewBody").empty().append(html)
            $("#ivsgtViewModal").modal('show');
        },
        error:function(){

        }
    });
}

function getIvsgtEditModal(ivsgtKey, ivsgtType){
    $.ajax({
        url: '/ivsgt/ivsgtEditModal',
        data: {
            ivsgtKey: ivsgtKey,
            ivsgtType: ivsgtType
        },
        type: 'GET',
        dataType:"html",
        success: function(html){
            $("#ivsgtViewBody").empty();
            $("#ivsgtEditModalContent").empty().append(html)
            $("#ivsgtEditModal").modal('show');
            $("[name='contentInfo']").summernote({
                lang:'ko-KR',
                height: 120,
                disableDragAndDrop: true,
                toolbar: [
                    ['style', ['style']],
                    ['font', ['bold', 'underline', 'clear']],
                    ['color', ['color']],
                    ['para', ['ul', 'ol', 'paragraph']],
                    ['table', ['table']]
                ]
            });
            $("[name='contentMain']").summernote({
                lang:'ko-KR',
                height: 120,
                disableDragAndDrop: true,
                toolbar: [
                    ['style', ['style']],
                    ['font', ['bold', 'underline', 'clear']],
                    ['color', ['color']],
                    ['para', ['ul', 'ol', 'paragraph']],
                    ['table', ['table']]
                ]
            });
            setUploadDiv();
        },
        error:function(){

        }
    });
}

function getSearchViewModal(ivsgtType, contentTitle){
    $.ajax({
        url: '/ivsgt/searchViewModal',
        data: {
            contentTitle: contentTitle,
            ivsgtType: ivsgtType
        },
        type: 'GET',
        dataType:"html",
        success: function(html){
            $("#searchViewBody").empty().append(html)
            $("#searchViewModal").modal('show');
        },
        error:function(){

        }
    });
}

function saveBoardInvestigation(contentState){
    if(contentCheck()){
        if(confirm("저장하시겠습니까?")){
            $("#contentStatus").val(contentState);
            contentFade("in");
            const formData = new FormData($("#ivsgtEditForm")[0]);
            for(const file of files) {
                if(!file.isDelete)
                    formData.append('uploadFiles', file, file.name);
            }
            $(".text-decoration-line-through").each(function (idx, el){
                formData.append('fileSeq', $(el).attr("data-fileseq"));
            })
            $.ajax({
                type : 'POST',
                data : formData,
                url : "/ivsgt/saveBoardInvestigation",
                processData: false,
                contentType: false,
                success : function(result) {
                    alert("저장되었습니다.");
                    contentFade("out");
                    $("#ivsgtEditModal").modal('hide');
                    getIvsgtViewModal(result);
                },
                error : function(xhr, status) {
                    alert("저장에 실패하였습니다.")
                    contentFade("out");
                }
            })
        }
    }
}

function contentCheck(){
    let flag = true;
    if(!$("#contentTitle").val()){
        alert("제목을 입력해주세요.")
        flag = false;
    }
    else if(!$("#arrestCd").val()){
        alert("검거유형1을 선택해주세요.")
        flag = false;
    }
    else if(!$("#arrestCd2").val()){
        alert("검거유형2를 선택해주세요.")
        flag = false;
    }
    else if(!$("#relatedReport").is(':checked') && $("input[name='ivsgtType']").val() != "arrest") {
        if ($('input[name="relatedReportsText"]').length < 1) {
            alert("연관보고서를 확인해 주세요.")
            flag = false;
        }
    }

    flag = fileCheck(flag, files);
    return flag;
}