var menuVal = 'rcpstatisticsscenariodaymanage'

var StatisticsScenarioDay = {
    dataList: [],

    oprMngCodeList: [],

    curSearchOpr: '',

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

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

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

        var html = '';

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

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

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

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

                        html += '<tr rel="viewTableGroup" class="modalLoad">'
                            +       '<td>' + data[i].oprMngCodeName + '</td>'
                            +       '<td>' + data[i].callInitDate + '</td>'
                            +       '<td>' + data[i].useCnt + '</td>'
                            +       '<td>' + data[i].succCnt + '</td>'
                            +       '<td>' + data[i].failCnt + '</td>'
                            +       '<td>' + data[i].succPer + '%</td>'
                            +       '<td>' + data[i].failPer + '%</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 totalUse = 0;
                        var totalSucc = 0;
                        var totalFail = 0;
                        var totalSuccPer = 0;
                        var totalFailPer = 0;

                        var avgUse = 0;
                        var avgSucc = 0;
                        var avgFail = 0;
                        var avgSuccPer = 0;
                        var avgFailPer = 0;

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

                            avgUse = totalUse / data.length;
                            avgSucc = totalSucc / data.length;
                            avgFail = totalFail / data.length;
                            avgSuccPer = totalSuccPer / data.length;
                            avgFailPer = totalFailPer / 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(totalUse);
                        $('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(avgUse.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(avgFailPer.toFixed(1) + '%');

                    }

                });


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

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

    excelDownload: function() {
        var titleList = ['시나리오 그룹', '통화일자', '이용 건수', '완료 건수', '이탈 건수', '완료율', '이탈율'];

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

        if (StatisticsScenarioDay.dataList.length > 0) {
            for (let i=0; i<StatisticsScenarioDay.dataList.length; i++) {
                formData.append("statisticsScenarioDayVoList["+i+"].oprMngCodeName", StatisticsScenarioDay.dataList[i].oprMngCodeName);
                formData.append("statisticsScenarioDayVoList["+i+"].callInitDate", StatisticsScenarioDay.dataList[i].callInitDate);
                formData.append("statisticsScenarioDayVoList["+i+"].useCnt", StatisticsScenarioDay.dataList[i].useCnt);
                formData.append("statisticsScenarioDayVoList["+i+"].succCnt", StatisticsScenarioDay.dataList[i].succCnt);
                formData.append("statisticsScenarioDayVoList["+i+"].failCnt", StatisticsScenarioDay.dataList[i].failCnt);
                formData.append("statisticsScenarioDayVoList["+i+"].succPer", StatisticsScenarioDay.dataList[i].succPer + '%');
                formData.append("statisticsScenarioDayVoList["+i+"].failPer", StatisticsScenarioDay.dataList[i].failPer + '%');
            }
        }
        else {
            formData.append("statisticsScenarioDayVoList[0].oprMngCodeName", '');
            formData.append("statisticsScenarioDayVoList[0].callInitDate", '');
            formData.append("statisticsScenarioDayVoList[0].useCnt", '');
            formData.append("statisticsScenarioDayVoList[0].succCnt", '');
            formData.append("statisticsScenarioDayVoList[0].failCnt", '');
            formData.append("statisticsScenarioDayVoList[0].succPer", '');
            formData.append("statisticsScenarioDayVoList[0].failPer", '');
        }

        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 (StatisticsScenarioDay.curSearchOpr == '') {
                formData.append("oprMngCode", $('#oprMngCode').val().split('_')[2]);
            }
            else {
                formData.append("oprMngCode", StatisticsScenarioDay.curSearchOpr.split('_')[2]);
            }
        }

        req.open("POST", '/admin/rcp/statistics/scenario/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 () {
    StatisticsScenarioDay.setOprMngCode();
    StatisticsScenarioDay.setCurrentDate();
    StatisticsScenarioDay.getStatisticsScenarioDay();
});
