var menuVal = 'rcpstatisticscallinfomanage'

var StatisticsCallInfo = {
    dataList: [],

    oprMngCodeList: [],

    curSearchOpr: '',

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

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

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

        var html = '';

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

        $.ajax({
            type: "POST",
            async: false,
            datatype: "JSON",
            contentType : "application/json; charset=utf-8",
            url: "/admin/rcp/statistics/call/list.do",
            data: JSON.stringify(param),
            success: (function(data) {
                StatisticsCallInfo.dataList = [];
                StatisticsCallInfo.curSearchOpr = $('#oprMngCode').val();

                if (data.length > 0) {
                    var totalTot = 0;

                    var totalIngUserReq = 0;
                    var totalIngScenario = 0;
                    var totalIngSilentFb = 0;
                    var totalIngSpeakFb = 0;
                    var totalIngTot = 0;

                    var totalEndUserReq = 0;
                    var totalEndScenario = 0;
                    var totalEndSilentFb = 0;
                    var totalEndSpeakFb = 0;
                    var totalEndInitEnd = 0;
                    var totalEndUserEnd = 0;
                    var totalEndSystem = 0;
                    var totalEndTot = 0;

                    var totalAveTalkCnt = 0;


                    var aveTot = 0;

                    var aveIngUserReq = 0;
                    var aveIngScenario = 0;
                    var aveIngSilentFb = 0;
                    var aveIngSpeakFb = 0;
                    var aveIngTot = 0;

                    var aveEndUserReq = 0;
                    var aveEndScenario = 0;
                    var aveEndSilentFb = 0;
                    var aveEndSpeakFb = 0;
                    var aveEndInitEnd = 0;
                    var aveEndUserEnd = 0;
                    var aveEndSystem = 0;
                    var aveEndTot = 0;

                    var aveAveTalkCnt = 0;

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

                        totalTot += parseFloat(data[i].totCnt);

                        totalIngUserReq += parseFloat(data[i].ingUserReq);
                        totalIngScenario += parseFloat(data[i].ingScenario);
                        totalIngSilentFb += parseFloat(data[i].ingSilentFb);
                        totalIngSpeakFb += parseFloat(data[i].ingSpeakFb);
                        totalIngTot += parseFloat(data[i].ingTot);

                        totalEndUserReq += parseFloat(data[i].endUserReq);
                        totalEndScenario += parseFloat(data[i].endScenario);
                        totalEndSilentFb += parseFloat(data[i].endSilentFb);
                        totalEndSpeakFb += parseFloat(data[i].endSpeakFb);
                        totalEndInitEnd += parseFloat(data[i].endInitEnd);
                        totalEndUserEnd += parseFloat(data[i].endUserEnd);
                        totalEndSystem += parseFloat(data[i].endSystem);
                        totalEndTot += parseFloat(data[i].endTot);

                        totalAveTalkCnt += parseFloat(data[i].aveTalkCnt);

                        html += '<tr>'
                            +   '<td>' + data[i].callInitDate + '</td>'
                            +   '<td>' + data[i].totCnt + '</td>'
                            +   '<td class="tableMoreDataA cdtableMoreDataA">' + data[i].ingUserReq + '</td>'
                            +   '<td class="tableMoreDataA cdtableMoreDataA">' + data[i].ingScenario + '</td>'
                            +   '<td class="tableMoreDataA cdtableMoreDataA">' + data[i].ingSilentFb + '</td>'
                            +   '<td class="tableMoreDataA cdtableMoreDataA">' + data[i].ingSpeakFb + '</td>'
                            +   '<td>' + data[i].ingTot + '</td>'

                            +   '<td class="tableMoreDataB cdtableMoreDataB">' + data[i].endUserReq + '</td>'
                            +   '<td class="tableMoreDataB cdtableMoreDataB">' + data[i].endScenario + '</td>'
                            +   '<td class="tableMoreDataB cdtableMoreDataB">' + data[i].endSilentFb + '</td>'
                            +   '<td class="tableMoreDataB cdtableMoreDataB">' + data[i].endSpeakFb + '</td>'
                            +   '<td class="tableMoreDataB cdtableMoreDataB">' + data[i].endInitEnd + '</td>'
                            +   '<td class="tableMoreDataB cdtableMoreDataB">' + data[i].endUserEnd + '</td>'
                            +   '<td class="tableMoreDataB cdtableMoreDataB">' + data[i].endSystem + '</td>'
                            +   '<td>' + data[i].endTot + '</td>'
                            +   '<td>' + data[i].aveTalkCnt + '</td>'
                            +   '</tr>'

                    }

                    if (data.length < 10) {
                        html += '<tr style="height: calc(100vh - 530px - ' + (31+data.length)*data.length + 'px);"><td colSpan="12" style="background-color: rgb(250 250 250); width: 100%;"></td></tr>'
                    }

                    aveTot = totalTot / data.length;

                    aveIngUserReq = totalIngUserReq / data.length;
                    aveIngScenario = totalIngScenario / data.length;
                    aveIngSilentFb = totalIngSilentFb / data.length;
                    aveIngSpeakFb = totalIngSpeakFb / data.length;
                    aveIngTot = totalIngTot / data.length;

                    aveEndUserReq = totalEndUserReq / data.length;
                    aveEndScenario = totalEndScenario / data.length;
                    aveEndSilentFb = totalEndSilentFb / data.length;
                    aveEndSpeakFb = totalEndSpeakFb / data.length;
                    aveEndInitEnd = totalEndInitEnd / data.length;
                    aveEndUserEnd = totalEndUserEnd / data.length;
                    aveEndSystem = totalEndSystem / data.length;
                    aveEndTot = totalEndTot / data.length;

                    aveAveTalkCnt = totalAveTalkCnt / data.length;

                    $('#totalTot').html(totalTot);
                    $('#totalIngUserReq').html(totalIngUserReq);
                    $('#totalIngScenario').html(totalIngScenario);
                    $('#totalIngSilentFb').html(totalIngSilentFb);
                    $('#totalIngSpeakFb').html(totalIngSpeakFb);
                    $('#totalIngTot').html(totalIngTot);
                    $('#totalEndUserReq').html(totalEndUserReq);
                    $('#totalEndScenario').html(totalEndScenario);
                    $('#totalEndSilentFb').html(totalEndSilentFb);
                    $('#totalEndSpeakFb').html(totalEndSpeakFb);
                    $('#totalEndInitEnd').html(totalEndInitEnd);
                    $('#totalEndUserEnd').html(totalEndUserEnd);
                    $('#totalEndSystem').html(totalEndSystem);
                    $('#totalEndTot').html(totalEndTot);
                    $('#totalAveTalkCnt').html(totalAveTalkCnt.toFixed(1));

                    $('#aveTot').html(aveTot.toFixed(1));
                    $('#aveIngUserReq').html(aveIngUserReq.toFixed(1));
                    $('#aveIngScenario').html(aveIngScenario.toFixed(1));
                    $('#aveIngSilentFb').html(aveIngSilentFb.toFixed(1));
                    $('#aveIngSpeakFb').html(aveIngSpeakFb.toFixed(1));
                    $('#aveIngTot').html(aveIngTot.toFixed(1));
                    $('#aveEndUserReq').html(aveEndUserReq.toFixed(1));
                    $('#aveEndScenario').html(aveEndScenario.toFixed(1));
                    $('#aveEndSilentFb').html(aveEndSilentFb.toFixed(1));
                    $('#aveEndSpeakFb').html(aveEndSpeakFb.toFixed(1));
                    $('#aveEndInitEnd').html(aveEndInitEnd.toFixed(1));
                    $('#aveEndUserEnd').html(aveEndUserEnd.toFixed(1));
                    $('#aveEndSystem').html(aveEndSystem.toFixed(1));
                    $('#aveEndTot').html(aveEndTot.toFixed(1));
                    $('#aveAveTalkCnt').html(aveAveTalkCnt.toFixed(1));
                }
                else {
                    html += '<tr class="odd">'
                        +       '<td colSpan="12" class="dataTables_empty">No data available in table</td>'
                        +   '</tr>'
                        +   '<tr style="height: calc(100vh - 530px);"><td colSpan="12" style="background-color: rgb(250 250 250); width: 100%;"></td></tr>'

                    $('#totalTot').html(0);
                    $('#totalIngUserReq').html(0);
                    $('#totalIngScenario').html(0);
                    $('#totalIngSilentFb').html(0);
                    $('#totalIngSpeakFb').html(0);
                    $('#totalIngTot').html(0);
                    $('#totalEndUserReq').html(0);
                    $('#totalEndScenario').html(0);
                    $('#totalEndSilentFb').html(0);
                    $('#totalEndSpeakFb').html(0);
                    $('#totalEndInitEnd').html(0);
                    $('#totalEndUserEnd').html(0);
                    $('#totalEndSystem').html(0);
                    $('#totalEndTot').html(0);
                    $('#totalAveTalkCnt').html(0);

                    $('#aveTot').html(0);
                    $('#aveIngUserReq').html(0);
                    $('#aveIngScenario').html(0);
                    $('#aveIngSilentFb').html(0);
                    $('#aveIngSpeakFb').html(0);
                    $('#aveIngTot').html(0);
                    $('#aveEndUserReq').html(0);
                    $('#aveEndScenario').html(0);
                    $('#aveEndSilentFb').html(0);
                    $('#aveEndSpeakFb').html(0);
                    $('#aveEndInitEnd').html(0);
                    $('#aveEndUserEnd').html(0);
                    $('#aveEndSystem').html(0);
                    $('#aveEndTot').html(0);
                    $('#aveAveTalkCnt').html(0);
                }

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

                $('.tlBtn').each(function(index,item){
                    if ($(this).hasClass("active") === false) {
                        $('.cd'+$(this).data('code')).hide();
                    }
                });
            })
        });
    },

    setGrid: function() {
        $('.tableMoreDataB').css('display', 'none')
        $('.tableMoreViewA').css('display', 'none')
        $('.tableMoreViewA').parent('th').addClass('active');
        const defaultColsapnVal = ''



        $('.tableMoreViewA').on('click', function () {
            const colspanValue = $(this).parent('th').attr('colspan');

            $('.tableMoreViewB').show()
            $('.tableMoreDataB').hide()
            $(this).hide();
            if (colspanValue == defaultColsapnVal) {
                $(this).parent('th').attr('colspan', '5');
                $('.tableMoreDataA').show()
                $('.tableMoreViewB').parents('th').attr('colspan', defaultColsapnVal)
                $(this).parent('th').addClass('active');
                $('.tableMoreViewB').parent('th').removeClass('active');
            }
            if (colspanValue == '5') {
                $(this).parent('th').attr('colspan', defaultColsapnVal);
                $('.tableMoreDataA').hide()
                $('.tableMoreViewB').parents('th').attr('colspan', '8')

            }
        })

        $('.tableMoreViewB').on('click', function () {
            const colspanValue = $(this).parent('th').attr('colspan');

            $('.tableMoreViewA').show()
            $('.tableMoreDataA').hide()

            $(this).hide();


            if (colspanValue == defaultColsapnVal) {
                $(this).parent('th').attr('colspan', '8');
                $('.tableMoreDataB').show()
                $('.tableMoreViewA').parents('th').attr('colspan', defaultColsapnVal)
                $(this).parent('th').addClass('active');
                $('.tableMoreViewA').parent('th').removeClass('active');
            }
            if (colspanValue == '8') {
                $(this).parent('th').attr('colspan', defaultColsapnVal);
                $('.tableMoreDataB').hide();
                $('.tableMoreViewA').parents('th').attr('colspan', '5')

            }
        })
    },

    excelDownload: function() {
        var titleList = ['통화일자', '전체 콜', '호전환 사용자 요청', '호전환 시나리오 흐름', '호전환 묵음 폴백', '호전환 발화 폴백', '호전환 소계', '호종료 사용자 요청', '호종료 시나리오 흐름', '호종료 묵음 폴백', '호종료 발화 폴백', '호종료 인입 후 끊음', '호종료 고객 끊음', '호종료 시스템', '호종료 소계', '평균 발화 건수'];

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

        if (StatisticsCallInfo.dataList.length > 0) {
            for (let i=0; i<StatisticsCallInfo.dataList.length; i++) {
                formData.append("statisticsCallInfoExcelVOList["+i+"].callInitDate", StatisticsCallInfo.dataList[i].callInitDate);
                formData.append("statisticsCallInfoExcelVOList["+i+"].totCnt", StatisticsCallInfo.dataList[i].totCnt);
                formData.append("statisticsCallInfoExcelVOList["+i+"].ingUserReq", StatisticsCallInfo.dataList[i].ingUserReq);
                formData.append("statisticsCallInfoExcelVOList["+i+"].ingScenario", StatisticsCallInfo.dataList[i].ingScenario);
                formData.append("statisticsCallInfoExcelVOList["+i+"].ingSilentFb", StatisticsCallInfo.dataList[i].ingSilentFb);
                formData.append("statisticsCallInfoExcelVOList["+i+"].ingSpeakFb", StatisticsCallInfo.dataList[i].ingSpeakFb);
                formData.append("statisticsCallInfoExcelVOList["+i+"].ingTot", StatisticsCallInfo.dataList[i].ingTot);
                formData.append("statisticsCallInfoExcelVOList["+i+"].endUserReq", StatisticsCallInfo.dataList[i].endUserReq);
                formData.append("statisticsCallInfoExcelVOList["+i+"].endScenario", StatisticsCallInfo.dataList[i].endScenario);
                formData.append("statisticsCallInfoExcelVOList["+i+"].endSilentFb", StatisticsCallInfo.dataList[i].endSilentFb);
                formData.append("statisticsCallInfoExcelVOList["+i+"].endSpeakFb", StatisticsCallInfo.dataList[i].endSpeakFb);
                formData.append("statisticsCallInfoExcelVOList["+i+"].endInitEnd", StatisticsCallInfo.dataList[i].endInitEnd);
                formData.append("statisticsCallInfoExcelVOList["+i+"].endUserEnd", StatisticsCallInfo.dataList[i].endUserEnd);
                formData.append("statisticsCallInfoExcelVOList["+i+"].endSystem", StatisticsCallInfo.dataList[i].endSystem);
                formData.append("statisticsCallInfoExcelVOList["+i+"].endTot", StatisticsCallInfo.dataList[i].endTot);
                formData.append("statisticsCallInfoExcelVOList["+i+"].aveTalkCnt", StatisticsCallInfo.dataList[i].aveTalkCnt);
            }
        }
        else {
            formData.append("statisticsCallInfoExcelVOList[0].callInitDate", '');
            formData.append("statisticsCallInfoExcelVOList[0].totCnt", '');
            formData.append("statisticsCallInfoExcelVOList[0].ingUserReq", '');
            formData.append("statisticsCallInfoExcelVOList[0].ingScenario", '');
            formData.append("statisticsCallInfoExcelVOList[0].ingSilentFb", '');
            formData.append("statisticsCallInfoExcelVOList[0].ingSpeakFb", '');
            formData.append("statisticsCallInfoExcelVOList[0].ingTot", '');
            formData.append("statisticsCallInfoExcelVOList[0].endUserReq", '');
            formData.append("statisticsCallInfoExcelVOList[0].endScenario", '');
            formData.append("statisticsCallInfoExcelVOList[0].endSilentFb", '');
            formData.append("statisticsCallInfoExcelVOList[0].endSpeakFb", '');
            formData.append("statisticsCallInfoExcelVOList[0].endInitEnd", '');
            formData.append("statisticsCallInfoExcelVOList[0].endUserEnd", '');
            formData.append("statisticsCallInfoExcelVOList[0].endSystem", '');
            formData.append("statisticsCallInfoExcelVOList[0].endTot", '');
            formData.append("statisticsCallInfoExcelVOList[0].aveTalkCnt", '');
        }

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

        req.open("POST", '/admin/rcp/statistics/call/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 () {
    StatisticsCallInfo.setOprMngCode();
    StatisticsCallInfo.setCurrentDate();
    StatisticsCallInfo.setGrid();
    StatisticsCallInfo.getStatisticsCallInfo();
});
