var menuVal = 'rcpstatisticsintentdaymanage'

var StatisticsIntentDay = {
    dataList: [],

    oprMngCodeList: [],

    curSearchOpr: '',

    setOprMngCode: function() {
        $.ajax({
            type: "GET",
            async: false,
            datatype: "JSON",
            contentType : "application/json; charset=utf-8",
            url: "/adm/menu/oprmng",
            data: {menuval: 'rcpstatisticsintentdaymanage'},
            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[i].serviceGroupName + '</option>';

                    StatisticsIntentDay.oprMngCodeList.push(data[i].custCode + '_RCP_' + data[i].serviceGroup);
                }

                $('#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);
    },

    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;
    },

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

        var html = '';

        var param = {
            oprMngCode: $('#oprMngCode').val(),
            oprMngCodeList: StatisticsIntentDay.oprMngCodeList,
            callInitDateFrom: $('#dataFrom').val(),
            callInitDateTo: $('#dataTo').val()
        }

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

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

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

                        html += '<tr rel="viewTableGroup" class="modalLoad" ondblclick="javascript:StatisticsIntentDay.GoIntentAnalysisPage(\'' + data[i].oprMngCode + '\', \'' + data[i].callInitDate + '\', \'' + data[i].callInitDate + '\')">'
                            +       '<td>' + data[i].oprMngCodeName + '</td>'
                            +       '<td>' + data[i].callInitDate + '</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][2]);
                            totalSucc += parseFloat(data[i][3]);
                            totalFail += parseFloat(data[i][4]);
                            totalSuccPer += parseFloat(replaceSymbol(data[i][5] + ''));
                            totalIntentPer += parseFloat(replaceSymbol(data[i][6] + ''));

                            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(2)', api.table().footer()).html(totalTot);
                        $('tr:eq(0) th:eq(3)', api.table().footer()).html(totalSucc);
                        $('tr:eq(0) th:eq(4)', api.table().footer()).html(totalFail);

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

                    }

                });


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

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

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

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

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

        if (StatisticsIntentDay.dataList.length > 0) {
            for (let i=0; i<StatisticsIntentDay.dataList.length; i++) {
                formData.append("intentAnalysisDayList["+i+"].oprMngCodeName", StatisticsIntentDay.dataList[i].oprMngCodeName);
                formData.append("intentAnalysisDayList["+i+"].callInitDate", StatisticsIntentDay.dataList[i].callInitDate);
                formData.append("intentAnalysisDayList["+i+"].totCnt", StatisticsIntentDay.dataList[i].totCnt);
                formData.append("intentAnalysisDayList["+i+"].succCnt", StatisticsIntentDay.dataList[i].succCnt);
                formData.append("intentAnalysisDayList["+i+"].failCnt", StatisticsIntentDay.dataList[i].failCnt);
                formData.append("intentAnalysisDayList["+i+"].succPer", StatisticsIntentDay.dataList[i].succPer + '%');
                formData.append("intentAnalysisDayList["+i+"].avgIntentPer", StatisticsIntentDay.dataList[i].avgIntentPer + '%');
            }
        }
        else {
            formData.append("intentAnalysisDayList[0].oprMngCodeName", '');
            formData.append("intentAnalysisDayList[0].callInitDate", '');
            formData.append("intentAnalysisDayList[0].totCnt", '');
            formData.append("intentAnalysisDayList[0].succCnt", '');
            formData.append("intentAnalysisDayList[0].failCnt", '');
            formData.append("intentAnalysisDayList[0].succPer", '');
            formData.append("intentAnalysisDayList[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 (StatisticsIntentDay.curSearchOpr == '') {
                formData.append("oprMngCode", $('#oprMngCode').val().split('_')[2]);
            }
            else {
                formData.append("oprMngCode", StatisticsIntentDay.curSearchOpr.split('_')[2]);
            }
        }

        req.open("POST", '/admin/rcp/statistics/intent/day/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 () {
    StatisticsIntentDay.setOprMngCode();
    StatisticsIntentDay.setCurrentDate();
    StatisticsIntentDay.getStatisticsIntentDay();
});
