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


$(document).on('click', '#icaAddBtn', function () {
    getIcaEditModal(null);
});

$(document).on('click', '#icaEditBtn', function () {
    $("#icaViewModal").modal('hide');
    getIcaEditModal(Number($("#icaViewBody").find("[name='icaKey']").val()));
});


$(document).on('click', '#saveIcaBtn', function (){
    saveInternationalCrimeArrest('N')
});

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

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

$(document).on('change', 'select[name="organ"]', function (){
    departmentDynamicOption('select[name="department"]', $(this).val());
});

$(document).on('change', '#crimeType', function (){
    dynamicOption('#violationType', $(this).val());
});

$(document).on('change', '#searchCrimeType', function (){
    dynamicOption('#searchViolationType', $(this).val(), '위반유형');
});


$(document).on('change', '#crimeForm', function (){
    $('#crimeFormDiv').next().remove();
    if ($(this).val() != 'CMF001') {
        $('#crimeFormDiv').after('<button type="button" class="col-sm-1 btn btn-sm btn-primary" id="spiAddBtn">+</button>');
    } else {
        $.each($('.dynamic').children("input[name='spiKey']"), function (idx, item){
            let deleteKey = item.value;
            $("#icaEditForm").append('<input type="hidden" name="deleteSpiKeyList" value="' + deleteKey + '">');
        });
        $("#spiDiv").children('.dynamic').remove();
    }
});

$(document).on('click', '#spiAddBtn', function (){

    let sex = '';
    commonCode.SEX.forEach(function (item){
        sex += '<option value="'+ item.itemCd +'">' + item.itemValue +'</option>';
    });

    let age = '';
    commonCode.AGE.forEach(function (item){
        age += '<option value="'+ item.itemCd +'">' + item.itemValue +'</option>';
    })

    let country = '';
    commonCode.NNY.forEach(function (item){
        country += '<option value="'+ item.itemCd +'">' + item.itemValue +'</option>';
    })

    $("#spiDiv").append(
        '<div class="row dynamic spi-list">'
        + '<label class="col-sm-1 col-form-label col-form-label-sm text-center">성별</label>'
        + '<div class="col-sm-2" id="sexFormDiv">'
        + '<select class="form-select form-select-sm" name="sex">'
        + sex
        + '</select>'
        + '</div>'
        + '<label class="col-sm-1 col-form-label col-form-label-sm text-center">나이</label>'
        + '<div class="col-sm-2" id="ageFormDiv">'
        + '<select class="form-select form-select-sm" name="age">'
        + age
        + '</select>'
        + '</div>'
        + '<label class="col-sm-1 col-form-label col-form-label-sm text-center">국적</label>'
        + '<div class="col-sm-2" id="countryFormDiv">'
        + '<select class="form-select form-select-sm country" name="country">'
        + country
        + '<option value="etc">기타</option>'
        + '</select>'
        + '</div>'
        + '<button type="button" class="col-sm-1 btn btn-sm btn-primary" id="spiCancelBtn">-</button>'
        + '</div>'
    );
});

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

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

$(document).on('click', '.spiCancelBtn', function (){
    let deleteKey = $(this).parent().children("input[name='spiKey']").val();
    $("#icaEditForm").append('<input type="hidden" name="deleteSpiKeyList" value="' + deleteKey + '">');
   $(this).parent().remove();
});

$(document).on('change', '#crimeType', function (){
    $('#smugglingAmountDiv').children().remove();
    $('#crimeNameDiv').children().remove();
    $('#arrestAreaDiv').remove();

    let smugglingAmount = '';
    commonCode.SG.forEach(function (item){
        smugglingAmount += '<option value="'+ item.itemCd +'">' + item.itemValue +'</option>';
    })

    if ($(this).val() == 'CTH2') {
        makeArrestAreaDiv('장소');
        $('#smugglingAmountDiv').append(
            '<label class="col-sm-2 col-form-label col-form-label-sm text-center">밀수입출 품목</label>'
            + '<div class="col-sm-2">'
            + '<select class="form-select form-select-sm" name="smuggledGoods" id="smugglingAmount">'
            + '<option>선택</option>'
            + smugglingAmount
            + '<option value="etc">기타</option>'
            + '</select>'
            + '</div>'
            + '<label class="col-sm-2 col-form-label col-form-label-sm text-center">밀수가액</label>'
            + '<div class="col-sm-2">'
            + '<input class="form-control form-control-sm" type="number" min="0" name="smugglingAmount">'
            + '</div>'
            + '<label class="col-sm-2 col-form-label col-form-label-sm text-center">단속 인원(경찰관)</label>'
            + '<div class="col-sm-2">'
            + '<input class="form-control form-control-sm" type="number" min="0" name="caseNum">'
            + '</div>'
        );
    } else {
        $("#crimeNameDiv").append(
            '<label class="col-sm-2 col-form-label col-form-label-sm text-center">죄명</label>'
            + '<div class="col-sm-10 input-daterange">'
            + '<input type="text" class="form-control form-control-sm" name="crimeName">'
            + '</div>'
        );
    }
});

$(document).on('change', '#violationType', function (){
    $('#spiInfoDiv').remove();
    $('#arrestAreaDiv').remove();
    $('#meansDiv').remove();
    $('.entryVisa').remove();
    $('#violationAmountDiv').remove();

    if ($(this).val() == 'CTH101') {
        makeSpiInfoDiv('피의자 정보');
        makeArrestAreaDiv('지역');
        makeSeaAreaDiv('밀입국');
        makeMeansDiv('밀입국');
        makePurposeDiv('밀입국');
        makeDestinationDiv('밀입국 출발지(국가)');
    }

    if ($(this).val() == 'CTH102') {
        makeSpiInfoDiv('피의자 정보');
        makeArrestAreaDiv('지역');
        makeSeaAreaDiv('도외이탈');
        makeMeansDiv('도외이탈');
        makePurposeDiv('도외이탈');
    }

    if ($(this).val() == 'CTH103') {
        makeSpiInfoDiv('피의자 정보');
        makeArrestAreaDiv('지역');
        makeSeaAreaDiv('밀출국');
        makeMeansDiv('밀출국');
        makePurposeDiv('밀출국');
        makeDestinationDiv('밀출국 행선지(도착예정지)');
    }

    if ($(this).val() == 'CTH104') {
        makeSpiInfoDiv('피의자 정보');
        makeArrestAreaDiv('지역');
        makeSeaAreaDiv('밀항');
        makeMeansDiv('밀항');
        makePurposeDiv('밀항');
        makeDestinationDiv('밀항 행선지(도착예정지)');
    }

    if ($(this).val() == 'CTH105') {
        makeSpiInfoDiv('불법체류 및 취업');
        makeEntryVisaDiv();
    }

    if ($(this).val() == 'CTH401') {
        makeViolationAmountDiv();
    }

    if ($(this).val() == 'CTH201' || $(this).val() == 'CTH202' || $(this).val() == 'CTH203' || $(this).val() == 'CTH204') {
        makeArrestAreaDiv('장소');
    }
});

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

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

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

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

function makeEntryVisaDiv() {
    $('#spiWrapper').prepend(
        '<label class="col-sm-2 col-form-label col-form-label-sm text-center entryVisa">입국비자</label>'
        + '<div class="col-sm-2 entryVisa">'
        + '<input type="text" class="form-control form-control-sm" name="entryVisa">'
        + '</div>'
    );
}

function makeSpiInfoDiv(name) {
    $('#spiParentDiv').after(
        '<div class="mb-3 row" id="spiInfoDiv">'
        + '<label class="col-sm-2 col-form-label col-form-label-sm text-center">' + name + '</label>'
        + '<div class="col-sm-10">'
        + '<div class="row" id="spiWrapper">'
        + '<label class="col-sm-2 col-form-label col-form-label-sm text-center">체류 자격</label>'
        + '<div class="col-sm-2">'
        + '<input type="text" class="form-control form-control-sm" name="stayQualification">'
        + '</div>'
        + '<label class="col-sm-2 col-form-label col-form-label-sm text-center">체류기간 만료일</label>'
        + '<div class="col-sm-2 input-daterange" id="stayQualificationDiv">'
        + '<input type="text" class="form-control form-control-sm" name="stayPeriodExpiredDt" id="stayPeriodExpiredDt" readonly>'
        + '</div>'
        + '</div>'
        + '</div>'
        + '</div>'
    );
    $("#stayQualificationDiv").datepicker({
        format: "yyyy-mm-dd",
        language: "ko"
    });
}

function makeSeaAreaDiv(name) {

    let seaArea = '';
    commonCode.SAA.forEach(function (item){
        seaArea += '<option value="'+ item.itemCd +'">' + item.itemValue +'</option>';
    })

    $('#arrestAreaDiv').append(
        '<label class="col-sm-2 col-form-label col-form-label-sm text-center">' + name + '시도 해역(해안)</label>'
        + '<div class="col-sm-3">'
        + '<select class="form-select form-select-sm" name="seaArea">'
        + '<option>선택</option>'
        + seaArea
        + '</select>'
        + '</div>'
    );
}

function makeArrestAreaDiv(name) {

    let arrestArea = '';
    commonCode.SAA.forEach(function (item){
        arrestArea += '<option value="'+ item.itemCd +'">' + item.itemValue +'</option>';
    })

    $('#spiParentDiv').after(
        '<div class="mb-3 row" id="arrestAreaDiv">'
        + '<label class="col-sm-2 col-form-label col-form-label-sm text-center">검거' + name + '</label>'
        + '<div class="col-sm-2">'
        + '<input type="text" class="form-control form-control-sm" name="arrestArea">'
        + '</div>'
        + '</div>'
    );
}

function makeMeansDiv(name, code) {
    let means = '';
    if (code == 'CTH101') {
        commonCode.MS1.forEach(function (item){
            means += '<option value="'+ item.itemCd +'">' + item.itemValue +'</option>';
        })
    } else {
        commonCode.MS2.forEach(function (item){
            means += '<option value="'+ item.itemCd +'">' + item.itemValue +'</option>';
        })
    }

    $('#spiParentDiv').after(
        '<div class="mb-3 row" id="meansDiv">'
        + '<label class="col-sm-2 col-form-label col-form-label-sm text-center">' + name + ' 수단(방법)</label>'
        + '<div class="col-sm-2">'
        + '<select class="form-select form-select-sm" name="means" id="means">'
        + '<option>선택</option>'
        + means
        + '<option value="etc">기타</option>'
        + '</select>'
        + '</div>'
        + '</div>'
    );
}

function makePurposeDiv(name) {

    let purpose = "";
    commonCode.PPS.forEach(function (item){
        purpose += '<option value="'+ item.itemCd +'">' + item.itemValue +'</option>';
    })

    $('#meansDiv').append(
        '<label class="col-sm-2 col-form-label col-form-label-sm text-center">' + name + ' 목적(사유)</label>'
        + '<div class="col-sm-2">'
        + '<select class="form-select form-select-sm" name="purpose" id="purpose">'
        + '<option>선택</option>'
        + purpose
        + '<option value="etc">기타</option>'
        + '</select>'
        + '</div>'
    );
}

function makeDestinationDiv(name) {
    $('#meansDiv').append(
        '<label class="col-sm-2 col-form-label col-form-label-sm text-center">' + name + '</label>'
        + '<div class="col-sm-2">'
        + '<input type="text" class="form-control form-control-sm" name="destination">'
        + '</div>'
    );
}

function makeViolationAmountDiv() {
    $('#spiParentDiv').after(
        '<div class="mb-3 row" id="violationAmountDiv">'
        + '<label class="col-sm-2 col-form-label col-form-label-sm text-center">표시위반 금액(만원)</label>'
        + '<div class="col-sm-2">'
        + '<input type="number" min="0" class="form-control form-control-sm" name="violationAmount">'
        + '</div>'
        + '</div>'
    );
}

function getIcaViewModal(icaKey){
    $.ajax({
        url: '/faStatistics/internationalCrimeArrest/internationalCrimeArrestViewModal',
        data: {icaKey: icaKey},
        type: 'GET',
        dataType:"html",
        success: function(html){
            $("#icaViewBody").empty().append(html)
            $("#icaViewModal").modal('show');
        },
        error:function(){

        }
    });
}

function getIcaEditModal(icaKey){
    $.ajax({
        url: '/faStatistics/internationalCrimeArrest/internationalCrimeArrestEditModal',
        data: {
            icaKey: icaKey
        },
        type: 'GET',
        dataType:"html",
        success: function(html){
            $("#icaViewBody").empty();
            $("#icaEditModalContent").empty().append(html);
            $("#icaEditModal").modal('show');
            $("#crimeAwarenessDtDiv").datepicker({
                format: "yyyy-mm-dd",
                language: "ko"
            });
            $("#caseSentDtDiv").datepicker({
                format: "yyyy-mm-dd",
                language: "ko"
            });
            $("[name='caseOverview']").summernote({
                lang:'ko-KR',
                height: 120,
                disableDragAndDrop: true,
                toolbar: [
                    ['style', ['style']],
                    ['font', ['bold', 'underline', 'clear']],
                    ['color', ['color']],
                    ['para', ['ul', 'ol', 'paragraph']],
                    ['table', ['table']]
                ]
            });
        },
        error:function(){

        }
    });
}

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

            let spiList = [];

            $(".spi-list").each(function (){
                spiList.push({
                    spiKey: $(this).find('input[name="spiKey"]').val() != undefined ? Number($(this).find('input[name="spiKey"]').val()) : null,
                    sex: $(this).find('select[name="sex"]').val(),
                    age: $(this).find('select[name="age"]').val(),
                    country: $(this).find('select[name="country"]').val(),
                    stayQualification: $(this).find('input[name="stayQualification"]').val() != undefined ? $(this).find('input[name="stayQualification"]').val() : null,
                    stayPeriodExpiredDt: $(this).find('input[name="stayPeriodExpiredDt"]').val() != undefined ? $(this).find('input[name="stayPeriodExpiredDt"]').val() : null,
                    countryEtc: $(this).find('input[name="countryEtc"]').val() != undefined ? $(this).find('input[name="countryEtc"]').val() : null
                });
            });

            for (let i=0; i < spiList.length; i++) {
                if (spiList[i].spiKey != null) {
                    formData.append(`suspectPersonInfoList[${i}].spiKey`, spiList[i].spiKey);
                }
                formData.append(`suspectPersonInfoList[${i}].sex`, spiList[i].sex);
                formData.append(`suspectPersonInfoList[${i}].age`, spiList[i].age);
                formData.append(`suspectPersonInfoList[${i}].country`, spiList[i].country);
                if (spiList[i].stayQualification != null) {
                    formData.append(`suspectPersonInfoList[${i}].stayQualification`, spiList[i].stayQualification);
                }
                if (spiList[i].stayPeriodExpiredDt != null) {
                    formData.append(`suspectPersonInfoList[${i}].stayPeriodExpiredDt`, spiList[i].stayPeriodExpiredDt);
                }
                if (spiList[i].countryEtc != null) {
                    formData.append(`suspectPersonInfoList[${i}].countryEtc`, spiList[i].countryEtc);
                }
            }

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

function contentCheck(){
    let flag = true;

    return flag;
}

$(document).on('click', '#icaExcelDownBtn', function (){
    const formData = $("#icaSearchForm").serialize();
    location.href = '/faStatistics/internationalCrimeArrest/ExcelDown?'+formData;
});
