var menuVal = 'rcpstatisticsintentitemmanage'

var StatisticsIntentItem = {
    dataList: [],

    oprMngCodeList: [],
    oprMngCodeUpperList: [],
    custCodeList: [],
    allIntentIdList: [],

    curSearchOpr: '',

    setOprMngCode: function() {
        $.ajax({
            type: "GET",
            async: false,
            datatype: "JSON",
            contentType : "application/json; charset=utf-8",
            url: "/adm/menu/oprmng",
            data: {menuval: 'rcpstatisticsintentitemmanage'},
            success: (function(data) {
                var html = '';

                if (data.length > 1) {
                    html += '<option value="all">전체</option>';
                }

                $('#oprMngCode').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>';

                    StatisticsIntentItem.oprMngCodeList.push(data[i].custCode + '_RCP_' + data[i].serviceGroup);
                    StatisticsIntentItem.oprMngCodeUpperList.push(data[i].custCode + '_RCP_' + data[i].serviceGroupUpper);
                    StatisticsIntentItem.custCodeList.push(data[i].custCode);
                }

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

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

    setCurrentDate: function() {
        var today = new Date();
        var year = today.getFullYear(); // 년도
        var month = today.getMonth() + 1;  // 월
        var date = today.getDate();  // 날짜

        // $('#dataFrom').val(year + '-' + month + '-' + date + ' 00:00');
        // $('#dataTo').val(year + '-' + month + '-' + date + ' 23:59');

        var fromDate = year + '-' + month + '-' + date;
        var toDate = year + '-' + month + '-' + date;

        $('.datetimepicker_from').datetimepicker().data('DateTimePicker').format('YYYY-MM-DD');
        $('.datetimepicker_to').datetimepicker().data('DateTimePicker').format('YYYY-MM-DD');

        // date Set
        $('.datetimepicker_from').datetimepicker().data('DateTimePicker').date(fromDate);
        $('.datetimepicker_to').datetimepicker().data('DateTimePicker').date(toDate);
    },

    setWeekDate: function() {
        var today = new Date();
        var todayYear = today.getFullYear(); // 년도
        var todayMonth = today.getMonth() + 1;  // 월
        var todayDate = today.getDate();  // 날짜

        var week = new Date(todayYear, todayMonth - 1, todayDate - 6);
        var weekYear = week.getFullYear(); // 년도
        var weekMonth = week.getMonth() + 1;  // 월
        var weekDate = week.getDate();  // 날짜

        // $('#dataFrom').val(weekYear + '-' + weekMonth + '-' + weekDate + ' 00:00');
        // $('#dataTo').val(todayYear + '-' + todayMonth + '-' + todayDate + ' 23:59');

        fromDate = weekYear + '-' + weekMonth + '-' + weekDate;
        toDate = todayYear + '-' + todayMonth + '-' + todayDate;

        $('.datetimepicker_from').datetimepicker().data('DateTimePicker').format('YYYY-MM-DD');
        $('.datetimepicker_to').datetimepicker().data('DateTimePicker').format('YYYY-MM-DD');

        // date Set
        $('.datetimepicker_from').datetimepicker().data('DateTimePicker').date(fromDate);
        $('.datetimepicker_to').datetimepicker().data('DateTimePicker').date(toDate);
    },

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

        var param = {
            oprMngCode: $('#oprMngCode').val(),
            custCode: arr[0],
            custCodeList: StatisticsIntentItem.custCodeList,
            oprMngCodeUpper: arr[0] + '_RCP_' + $('#oprMngCode').find(':selected').data('sg-upper'),
            oprMngCodeUpperList: StatisticsIntentItem.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>';

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

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

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

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

    setIntentNameCheckBox: function() {
        var param = {
            oprMngCode: $('#oprMngCode').val(),
            oprMngCodeList: StatisticsIntentItem.oprMngCodeList,
            intentGroupCode: $('#intentGroupCode').val(),
            serviceGroup: $('#oprMngCode').val().split('_')[2]
        }

        var html = '';

        html += '<div class="chk_box">'
            +       '<input type="checkbox" name="all" id="chk" value="" checked>'
            +       '<label for="chk">전체</label>'
            +   '</div>'
            +   '<div class="chk_box">'
            +       '<input type="checkbox" name="checkbox" id="chkFail" value="00000">'
            +       '<label for="chkFail" style="color:red;">인텐트 분류 실패</label>'
            +   '</div>'

        $.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) {
                StatisticsIntentItem.allIntentIdList = [];

                for (var i=0; i<data.length; i++) {
                    html += '<div class="chk_box">'
                        +       '<input type="checkbox" name="checkbox" id="chk' + i + '" value="' + data[i].ifMappingId + '">'
                        +       '<label for="chk' + i + '">' + data[i].intentName + '</label>'
                        +   '</div>'

                    StatisticsIntentItem.allIntentIdList.push(data[i].ifMappingId);
                }

            })
        });

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

        StatisticsIntentItem.resetMoreOpenBtn($("input:checkbox[name=checkbox]").length);
    },

    fncIntentChk: function() {
        var cnt = 0;
        var html = '';

        if ($("input:checkbox[name=checkbox]:checked").length > 0) {
            $("input:checkbox[name='all']").prop("checked", false);
        }

        this.resetMoreOpenBtn($("input:checkbox[name=checkbox]:checked").length);
    },

    resetMoreOpenBtn: function(cnt) {
        var html = '<b>+</b> ' + cnt + '개'

        $('.moreOpenBtn').html(html);
    },

    chkDate31: function() {
        const dateA = new Date($('#dataTo').val().substring(0,10));
        const dateB = new Date($('#dataFrom').val().substring(0,10));
        const diffMSec = dateA.getTime() - dateB.getTime();
        const diffDate = diffMSec / (24 * 60 * 60 * 1000);
        return diffDate;
    },

    getStatisticsIntentItem: function() {
        if (StatisticsIntentItem.chkDate31() > 31) {
            $.utils.warning('31일 이내로 조회 가능합니다.');
            return;
        }

        var chkIntentAllCd = '';

        var valueArr = new Array();

        var list = $("input[name='checkbox']:checked");

        if ($('#chk').is(':checked')) {
            chkIntentAllCd = 'Y';
        }

        for (var i=0; i<list.length; i++) {
            valueArr.push(list[i].defaultValue);
        }

        var html = '';

        var param = {
            oprMngCode: $('#oprMngCode').val(),
            oprMngCodeList: StatisticsIntentItem.oprMngCodeList,
            callInitDateFrom: $('#dataFrom').val(),
            callInitDateTo: $('#dataTo').val(),
            intentIdList: valueArr,
            allIntentIdList: StatisticsIntentItem.allIntentIdList,
            chkIntentAll: chkIntentAllCd
        }

        $.ajax({
            type: "POST",
            async: false,
            datatype: "JSON",
            contentType : "application/json; charset=utf-8",
            url: "/admin/rcp/statistics/intent/item/list.do",
            data: JSON.stringify(param),
            success: (function(data) {
                $('#testTb1').DataTable().destroy();

                StatisticsIntentItem.dataList = [];
                StatisticsIntentItem.curSearchOpr = $('#oprMngCode').val();

                if (data.length > 0) {
                    for (var i = 0; i < data.length; i++) {
                        StatisticsIntentItem.dataList.push(data[i]);

                        html += '<tr rel="viewTableGroup" class="modalLoad" ondblclick="javascript:StatisticsIntentItem.GoIntentAnalysisPage(\'' + data[i].oprMngCode + '\', \'' + $('#dataFrom').val() + '\', \'' + $('#dataTo').val() + '\', \'' + data[i].intentId + '\')">'
                            +       '<td>' + data[i].oprMngCodeName + '</td>'
                            +       '<td>' + data[i].intentGroup + '</td>'
                            +       '<td'

                            if (data[i].intentId == '00000') {
                                html += ' style="color:red;"'
                            }

                        html +=       '>' + data[i].intentName + '</td>'
                            +       '<td>' + data[i].totCnt + '</td>'
                            +       '<td>' + data[i].succCnt + '</td>'
                            +       '<td>' + data[i].failCnt + '</td>'
                            +       '<td>' + data[i].succPer + '%</td>'
                            +       '<td>' + data[i].avgIntentPer + '%</td>'
                            +    '</tr>'

                    }
                }

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

                $("#testTb1").dataTable({
                    "autoWidth": true,
                    "paging": false,
                    "pagingType": "full_numbers",
                    "ordering": true,
                    "order": [],
                    "info": false,
                    "filter": false,
                    "lengthChange": true,
                    "dom": 'rt<"bottom"fip><"clear">',
                    "scrollY": "calc(100vh - 440px)",

                    "footerCallback": function (row, data, start, end, display) {
                        var api = this.api();

                        var replaceSymbol = function (i) {
                            var value = i.replace('%', '');
                            return value;
                        };

                        //Do whatever you want. Example:
                        var totalTot = 0;
                        var totalSucc = 0;
                        var totalFail = 0;
                        var totalSuccPer = 0;
                        var totalIntentPer = 0;

                        var avgTot = 0;
                        var avgSucc = 0;
                        var avgFail = 0;
                        var avgSuccPer = 0;
                        var avgIntentPer = 0;

                        for (var i=0; i<data.length; i++) {
                            totalTot += parseFloat(data[i][3]);
                            totalSucc += parseFloat(data[i][4]);
                            totalFail += parseFloat(data[i][5]);
                            totalSuccPer += parseFloat(replaceSymbol(data[i][6] + ''));
                            totalIntentPer += parseFloat(replaceSymbol(data[i][7] + ''));

                            avgTot = totalTot / data.length;
                            avgSucc = totalSucc / data.length;
                            avgFail = totalFail / data.length;
                            avgSuccPer = totalSuccPer / data.length;
                            avgIntentPer = totalIntentPer / data.length;
                        }

                        // $(api.column(2).footer()).html(totalTot);
                        // $(api.column(3).footer()).html(totalSucc);
                        // $(api.column(4).footer()).html(totalFail);

                        $('tr:eq(0) th:eq(3)', api.table().footer()).html(totalTot);
                        $('tr:eq(0) th:eq(4)', api.table().footer()).html(totalSucc);
                        $('tr:eq(0) th:eq(5)', api.table().footer()).html(totalFail);

                        $('tr:eq(1) th:eq(3)', api.table().footer()).html(avgTot.toFixed(1));
                        $('tr:eq(1) th:eq(4)', api.table().footer()).html(avgSucc.toFixed(1));
                        $('tr:eq(1) th:eq(5)', api.table().footer()).html(avgFail.toFixed(1));
                        $('tr:eq(1) th:eq(6)', api.table().footer()).html(avgSuccPer.toFixed(1) + '%');
                        $('tr:eq(1) th:eq(7)', api.table().footer()).html(avgIntentPer.toFixed(1) + '%');

                    }

                });


                $("#testTb1").dataTable();

                $(".dataTables_scrollHeadInner").css("box-sizing", "");
            })
        });
    },

    GoIntentAnalysisPage: function(oprMngCode, callInitDateFrom, callInitDateTo, intentId) {
        location.href = "/admin/rcp/statistics/monitoring/intentAnalysis/manage.do?oprMngCode="+oprMngCode+"&callInitDateFrom="+callInitDateFrom+" 00:00&callInitDateTo="+callInitDateTo+" 23:59&intentId="+intentId;
    },

    excelDownload: function() {
        var titleList = ['시나리오 그룹', '분류', '인텐트 명', '인텐트 분류 전체 건수', '인텐트 분류 성공 건수', '인텐트 분류 실패 건수', '인텐트 분류 성공률', '평균 의도추론율'];

        const req = new XMLHttpRequest();
        const formData = new FormData();

        if (StatisticsIntentItem.dataList.length > 0) {
            for (let i=0; i<StatisticsIntentItem.dataList.length; i++) {
                formData.append("intentAnalysisItemList["+i+"].oprMngCodeName", StatisticsIntentItem.dataList[i].oprMngCodeName);
                formData.append("intentAnalysisItemList["+i+"].intentGroup", StatisticsIntentItem.dataList[i].intentGroup);
                formData.append("intentAnalysisItemList["+i+"].intentName", StatisticsIntentItem.dataList[i].intentName);
                formData.append("intentAnalysisItemList["+i+"].totCnt", StatisticsIntentItem.dataList[i].totCnt);
                formData.append("intentAnalysisItemList["+i+"].succCnt", StatisticsIntentItem.dataList[i].succCnt);
                formData.append("intentAnalysisItemList["+i+"].failCnt", StatisticsIntentItem.dataList[i].failCnt);
                formData.append("intentAnalysisItemList["+i+"].succPer", StatisticsIntentItem.dataList[i].succPer + '%');
                formData.append("intentAnalysisItemList["+i+"].avgIntentPer", StatisticsIntentItem.dataList[i].avgIntentPer + '%');
            }
        }
        else {
            formData.append("intentAnalysisItemList[0].oprMngCodeName", '');
            formData.append("intentAnalysisItemList[0].intentGroup", '');
            formData.append("intentAnalysisItemList[0].intentName", '');
            formData.append("intentAnalysisItemList[0].totCnt", '');
            formData.append("intentAnalysisItemList[0].succCnt", '');
            formData.append("intentAnalysisItemList[0].failCnt", '');
            formData.append("intentAnalysisItemList[0].succPer", '');
            formData.append("intentAnalysisItemList[0].avgIntentPer", '');
        }

        for (let i=0; i<titleList.length; i++) {
            formData.append("titleList["+i+"]", titleList[i]);
        }

        formData.append("menuVal", menuVal);

        if ($('#oprMngCode').val() == 'all') {
            formData.append("oprMngCode", $('#mainOpr').val());
        }
        else {
            if (StatisticsIntentItem.curSearchOpr == '') {
                formData.append("oprMngCode", $('#oprMngCode').val().split('_')[2]);
            }
            else {
                formData.append("oprMngCode", StatisticsIntentItem.curSearchOpr.split('_')[2]);
            }
        }

        req.open("POST", '/admin/rcp/statistics/intent/item/exceldownload.do', true);
        req.responseType = "arraybuffer";
        req.onload = function() {
            const arrayBuffer = req.response;
            if (arrayBuffer) {
                var blob = new Blob([arrayBuffer], { type: "application/octetstream" });
                var link=document.createElement('a');
                link.href=window.URL.createObjectURL(blob);
                link.download="항목별_인텐트_통계.xls";
                link.click();
            }
        };
        req.send(formData);
    }

}

$(document).ready(function () {
    StatisticsIntentItem.setOprMngCode();
    StatisticsIntentItem.setIntentGroupCd();
    StatisticsIntentItem.setCurrentDate();
    StatisticsIntentItem.setIntentNameCheckBox();
    StatisticsIntentItem.getStatisticsIntentItem();

    $('#oprMngCode').on('change', function() {
        StatisticsIntentItem.setIntentGroupCd();
        StatisticsIntentItem.setIntentNameCheckBox();

        // StatisticsIntentItem.resetMoreOpenBtn(0);
    });

    $('#intentGroupCode').on('change', function() {
        StatisticsIntentItem.setIntentNameCheckBox();

        // StatisticsIntentItem.resetMoreOpenBtn(0);
    });
});

$(document).on("click", ".chk_box", function() {
    if ($(this).find('input').attr('name') == 'all') {
        $("input:checkbox[name='checkbox']").prop("checked", false);

        if ($('#chk').is(':checked')) {
            StatisticsIntentItem.resetMoreOpenBtn($("input:checkbox[name=checkbox]").length);
        }
        else {
            StatisticsIntentItem.resetMoreOpenBtn(0);
        }
    }
    else {
        StatisticsIntentItem.fncIntentChk();
    }
});
