var AddIntentExample = {
    examples: [],

    custCodeList: [],
    oprMngCodeUpperList: [],

    removeExampleSeq: '',

    init: function(exampleText) {
        this.setOprMngCode();

        $('#popIntentGroupCode').html('<option value="">--시나리오 그룹을 선택해주세요--</option>');

        $('#popIntentGroupCode').niceSelect('update');

        $('#popIntent').html('<option value="">--분류를 선택해주세요--</option>');

        $('#popIntent').niceSelect('update');

        $('#addIntentExampleText').val(exampleText);

        $('#popIntentExample').html('');
    },

    setOprMngCode: function() {
        $.ajax({
            type: "GET",
            async: false,
            datatype: "JSON",
            contentType : "application/json; charset=utf-8",
            url: "/adm/menu/oprmng",
            data: {menuval: menuVal},
            success: (function(data) {
                var html = '<option value="">--선택해주세요--</option>';

                $('#popOprMngCode').html('');

                for(var i=0; i<data.length; i++){
                    html += '<option value="' + data[i].custCode + '_RCP_' + data[i].serviceGroup + '" data-sg-upper="' + data[i].serviceGroupUpper + '">' + data[i].serviceGroupName + '</option>';

                    AddIntentExample.oprMngCodeUpperList.push(data[i].custCode + '_RCP_' + data[i].serviceGroupUpper);
                }

                $('#popOprMngCode').html(html);

                $('#popOprMngCode').niceSelect('update');
            })
        });
    },

    setIntentGroupCd: function() {
        var arr = $('#popOprMngCode').val().split('_');

        var param = {
            oprMngCode: $('#popOprMngCode').val(),
            custCode: arr[0],
            custCodeList: AddIntentExample.custCodeList,
            oprMngCodeUpper: arr[0] + '_RCP_' + $('#popOprMngCode').find(':selected').data('sg-upper'),
            oprMngCodeUpperList: AddIntentExample.oprMngCodeUpperList,
            majorCode: 'INTENT_GROUP'
        }

        $.ajax({
            type: "POST",
            async: false,
            datatype: "JSON",
            contentType : "application/json; charset=utf-8",
            url: "/admin/rcp/statistics/monitoring/consulting/commonCodeSelectList.do",
            data: JSON.stringify(param),
            success: (function(data) {
                var html = '<option value="">선택</option>';

                $('#popIntentGroupCode').html('');

                for(var i=0; i<data.length; i++){
                    html += '<option value="' + data[i].minorCode + '">' + data[i].description + '</option>';
                }

                $('#popIntentGroupCode').html(html);

                $('#popIntentGroupCode').niceSelect('update');
            })
        });
    },

    setIntentNameSelectBox: function() {
        if ($('#popIntentGroupCode').val() == '') {
            $('#popIntent').html('<option value="">--분류를 선택해주세요--</option>');

            $('#popIntent').niceSelect('update');
        }
        else {
            var param = {
                oprMngCode: $('#popOprMngCode').val(),
                intentGroupCode: $('#popIntentGroupCode').val()
            }

            $.ajax({
                type: "POST",
                async: false,
                datatype: "JSON",
                contentType : "application/json; charset=utf-8",
                url: "/admin/rcp/statistics/monitoring/intentAnalysis/intentnamelist.do",
                data: JSON.stringify(param),
                success: (function(data) {
                    var html = '';

                    for(var i=0; i<data.length; i++){
                        html += '<option value="' + data[i].seq + '">' + data[i].intentName + '</option>';
                    }

                    $('#popIntent').html(html);

                    $('#popIntent').niceSelect('update');
                })
            });

            AddIntentExample.renderIntentExample();
        }
    },

    searchExample: function(dList) {
        var html = '';

        for (var i=0; i<dList.length; i++) {
            html += '<li>'
                +       dList[i].exampleText
                +       '<a href="#" class="minIco removeIco removeExmaple" data-seq="' + dList[i].seq + '">삭제</a>'
                +   '</li>'
        }

        $('#popIntentExample').html(html);
    },

    renderIntentExample: function() {
        if ($('#popIntent').val() != null && $('#popIntent').val() != '') {
            $.ajax({
                url: '/admin/rcp/conversation/intent/examples.do',
                data: {intentSeq: $('#popIntent').val()},
                success: function(d) {
                    AddIntentExample.examples = d.list;

                    if ($('#addIntentExampleText').val() != '') {
                        AddIntentExample.fncExampleKeyup($('#addIntentExampleText'));
                    }
                    else {
                        var html = '';

                        for (var i=0; i<d.list.length; i++) {
                            html += '<li>'
                                +       d.list[i].exampleText
                                +       '<a href="#" class="minIco removeIco removeExmaple" data-seq="' + d.list[i].seq + '">삭제</a>'
                                +   '</li>'
                        }

                        $('#popIntentExample').html(html);
                    }
                }
            });
        }
        else {
            $('#popIntentExample').html('');
        }
    },

    removeIntentExample: function() {
        var param = {
            serviceGroup: $('#popOprMngCode').val().split('_')[2],
            seq: AddIntentExample.removeExampleSeq,
            saveType : 'D',
            menuVal: menuVal
        }

        $.ajax({
            url: '/admin/rcp/conversation/intent/insertExample.do',
            type: "POST",
            data: JSON.stringify(param),
            contentType: "application/json",
            success: function(d) {
                if(d.result) {
                    AddIntentExample.renderIntentExample();
                }
            }
        });

        AddIntentExample.checkRemove = false;
    },

    addIntentExample: function() {
        if ($('#popIntent').val() == '') {
            $.utils.warning('인텐트를 선택해주세요.');
            return false;
        }
        
        var exampleIpt = $('#addIntentExampleText');

        if(exampleIpt.isNotBlank()) {
            var v = exampleIpt.val();
            // 중복 예문 체크
            var cnt = AddIntentExample.examples.filter(function(e) {
                return e.exampleText == v;
            }).length;
            if(cnt > 0) {
                $.utils.warning('중복된 예문입니다.');
                return false;
            }

            AddIntentExample.examples = [];
            AddIntentExample.examples.push({seq: '', exampleText: v});

            var param = {
                seq: $('#popIntent').val(),
                intentSeq: $('#popIntent').val(),
                custCode: $('#popOprMngCode').val().split('_')[0],
                serviceGroup: $('#popOprMngCode').val().split('_')[2],
                intentName: $("#popIntent option:checked").text(),
                category: $('#popIntentGroupCode').val(),
                exampleList: AddIntentExample.examples,
                saveType : 'I',
                menuVal: menuVal
            };

            $.ajax({
                url: '/admin/rcp/conversation/intent/insertExample.do',
                type: "POST",
                data: JSON.stringify(param),
                contentType: "application/json",
                success: function(d) {
                    if(d.result) {
                        $.utils.success('저장되었습니다.');
                        $('#addIntentExampleText').val('');
                        AddIntentExample.renderIntentExample();
                    } else {
                        $.utils.error(d.message);
                    }
                }
            });
        }
    },

    fncExampleKeyup: function(obj) {
        if(AddIntentExample.examples.length < 1) {
            return false;
        }
        var v = $(obj).val();

        var result = AddIntentExample.examples.filter(function(o) {
            return (o.exampleText.indexOf(v) > -1);
        });

        AddIntentExample.searchExample(result);
    },

    fncInputEnterKey: function(event) {
        let key = event.key || event.keyCode;

        if (key === 'Enter' || key === 13) {
            AddIntentExample.addIntentExample();
        }
    }

}


$(document).ready(function () {
    $("input[id=addIntentExampleText]").keyup(function() {
        AddIntentExample.fncExampleKeyup(this);
    });

    let addIntentExampleText = document.getElementById('addIntentExampleText');
    addIntentExampleText.addEventListener('keyup', event => AddIntentExample.fncInputEnterKey(event));
});

$(document).on("change", "#popOprMngCode", function() {
    if ($('#popOprMngCode').val() != '') {
        AddIntentExample.setIntentGroupCd();
        AddIntentExample.setIntentNameSelectBox();
    }
    else {
        $('#popIntentGroupCode').html('<option value="">--시나리오 그룹을 선택해주세요--</option>');

        $('#popIntentGroupCode').niceSelect('update');

        $('#popIntent').html('<option value="">--분류를 선택해주세요--</option>');

        $('#popIntent').niceSelect('update');
    }

    AddIntentExample.renderIntentExample();
});

$(document).on("change", "#popIntentGroupCode", function() {
    if ($('#popIntentGroupCode').val() != '') {
        AddIntentExample.setIntentNameSelectBox();
    }
    else {
        $('#popIntent').html('<option value="">--분류를 선택해주세요--</option>');

        $('#popIntent').niceSelect('update');
    }
});

$(document).on("change", "#popIntent", function() {
    if ($('#popIntent').val() != '') {
        AddIntentExample.renderIntentExample();
    }
    else {
        $('#popIntent').html('<option value="">--분류를 선택해주세요--</option>');

        $('#popIntent').niceSelect('update');
    }
});

$(document).on("click", ".removeExmaple", function() {
    AddIntentExample.removeExampleSeq = $(this).data('seq');

    $.utils.confirm('삭제하시겠습니까?', AddIntentExample.removeIntentExample);
});

$(document).on("click", "#addIntentExampleBtn", function() {
    AddIntentExample.addIntentExample();
});
