var menuVal = 'rcpstatisticsscenarioitemmanage'

var StatisticsScenarioItem = {
    dataList: [],

    oprMngCodeList: [],
    allScenarioIdList: [],

    curSearchOpr: '',

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

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

    setScenarioNameCheckBox: function() {
        var param = {
            oprMngCode: $('#oprMngCode').val(),
            oprMngCodeList: StatisticsScenarioItem.oprMngCodeList
        }

        var html = '';

        html += '<div class="chk_box">'
            +       '<input type="checkbox" name="all" id="chk" value="" checked>'
            +       '<label for="chk">전체</label>'
            +   '</div>'

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

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

                    StatisticsScenarioItem.allScenarioIdList.push(data[i].seq);
                }

            })
        });

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

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

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

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

        var chkScenarioAllCd = '';

        var valueArr = new Array();

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

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

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

        var html = '';

        var param = {
            oprMngCode: $('#oprMngCode').val(),
            oprMngCodeList: StatisticsScenarioItem.oprMngCodeList,
            callInitDateFrom: $('#dataFrom').val(),
            callInitDateTo: $('#dataTo').val(),
            scenarioIdList: valueArr,
            allScenarioIdList: StatisticsScenarioItem.allScenarioIdList,
            chkScenarioAll: chkScenarioAllCd
        }

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

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

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

                        html += '<tr rel="viewTableGroup" class="modalLoad">'
                            +       '<td>' + data[i].oprMngCodeName + '</td>'
                            +       '<td>' + data[i].scenarioName + '</td>'
                            +       '<td>' + data[i].useCnt + '</td>'
                            +       '<td>' + data[i].succCnt + '</td>'
                            +       '<td>' + data[i].failCnt + '</td>'
                            +       '<td>' + data[i].usePer + '%</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 totalUsePer = 0;
                        var totalSuccPer = 0;
                        var totalFailPer = 0;

                        var avgUse = 0;
                        var avgSucc = 0;
                        var avgFail = 0;
                        var avgUsePer = 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]);
                            totalUsePer += parseFloat(replaceSymbol(data[i][5] + ''));
                            totalSuccPer += parseFloat(replaceSymbol(data[i][6] + ''));
                            totalFailPer += parseFloat(replaceSymbol(data[i][7] + ''));

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

                    }

                });


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

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

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

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

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

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

    $('#oprMngCode').on('change', function() {
        StatisticsScenarioItem.setScenarioNameCheckBox();

        // StatisticsScenarioItem.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')) {
            StatisticsScenarioItem.resetMoreOpenBtn($("input:checkbox[name=checkbox]").length);
        }
        else {
            StatisticsScenarioItem.resetMoreOpenBtn(0);
        }
    }
    else {
        StatisticsScenarioItem.fncScenarioChk();
    }
});
