var menuVal = 'rcpmonitoringconsultingmanage'

var Consulting = {
    searchData: {},

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

    curSearchOpr: '',

    logTypeVal: '',
    talkSeqVal: '',

    pageSize: 10,

    init: function() {
        this.setOprMngCode();
        this.setCurrentDate();
        this.fncConsultingList();
        this.setSearchData();
    },

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

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

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

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

    setSearchData: function() {
        this.setSceneSelectBox();
        this.setEndTypeSelectBox();
        this.setEndReasonSelectBox();
    },

    //시나리오 Select Box
    setSceneSelectBox: function() {
        var param = {
            oprMngCode: $('#oprMngCode').val(),
            oprMngCodeList: Consulting.oprMngCodeList
        }

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

                sceneHtml += '<option value="">전체</option>';

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

                for(var i=0; i<data.length; i++){
                    sceneHtml += '<option value="' + data[i].seq + '">' + data[i].scenarioName + '</option>';
                }

                $('#scenarioSeq').html(sceneHtml);

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

    //종료구분 Select Box
    setEndTypeSelectBox: function() {
        var arr = $('#oprMngCode').val().split('_');

        var param = {
            oprMngCode: $('#oprMngCode').val(),
            custCode: arr[0],
            custCodeList: Consulting.custCodeList,
            oprMngCodeUpper: arr[0] + '_RCP_' + $('#oprMngCode').find(':selected').data('sg-upper'),
            oprMngCodeUpperList: Consulting.oprMngCodeUpperList,
            majorCode: 'CALL_END_CONVERSION'
        }

        $.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 = '';

                html += '<option value="">전체</option>';

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

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

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

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

    //종료상황 Select Box
    setEndReasonSelectBox: function() {
        var arr = $('#oprMngCode').val().split('_');

        var param = {
            oprMngCode: $('#oprMngCode').val(),
            custCode: arr[0],
            custCodeList: Consulting.custCodeList,
            oprMngCodeUpper: arr[0] + '_RCP_' + $('#oprMngCode').find(':selected').data('sg-upper'),
            oprMngCodeUpperList: Consulting.oprMngCodeUpperList,
            majorCode: 'CALL_END_REASON'
        }

        $.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 endReasonHtml = '';

                endReasonHtml += '<option value="">전체</option>';

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

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

                $('#callEndReason').html(endReasonHtml);

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

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

        var param = {
            oprMngCode: $('#oprMngCode').val(),
            custCode: arr[0],
            custCodeList: Consulting.custCodeList,
            oprMngCodeUpper: arr[0] + '_RCP_' + $('#oprMngCode').find(':selected').data('sg-upper'),
            oprMngCodeUpperList: Consulting.oprMngCodeUpperList,
            majorCode: 'BOOKMARK_ERR_CODE'
        }

        $.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 bookmarkErrHtml = '<option value="">--선택해주세요--</option>';

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

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

                $('#bookmarkErr').html(bookmarkErrHtml);

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

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

        var param = {
            oprMngCode: $('#oprMngCode').val(),
            custCode: arr[0],
            custCodeList: Consulting.custCodeList,
            oprMngCodeUpper: arr[0] + '_RCP_' + $('#oprMngCode').find(':selected').data('sg-upper'),
            oprMngCodeUpperList: Consulting.oprMngCodeUpperList,
            majorCode: 'MEASURE_TYPE'
        }

        $.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>';

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

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

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

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

    setBookmarkModal: function(obj) {
        multiModalUi();

        $('#bookmarkText').text($(obj).data('text'));

        this.setBookmarkErrCd();

        $('#addOprMngCode').val($(obj).data('opr'));
        Consulting.logTypeVal = $(obj).data('logType');
        $('#tokenVal').val($(obj).data('token'));
        Consulting.talkSeqVal = $(obj).data('talkSeq');
    },

    setRemoveBookmarkModal: function(obj) {
        $('#measureInfo').val('');

        multiModalUi();

        $('#removeBookmarkText').val($(obj).data('text'));

        this.setMeasureTypeCd();

        $('#removeOprMngCode').val($(obj).data('opr'));
        $('#seqVal').val($(obj).data('seq'));
        Consulting.logTypeVal = $(obj).data('logType');
        $('#tokenVal').val($(obj).data('token'));
        Consulting.talkSeqVal = $(obj).data('talkSeq');
    },

    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 + ' 00:00';
        var toDate = year + '-' + month + '-' + date + ' 23:59';

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

        // 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 + ' 00:00';
        toDate = todayYear + '-' + todayMonth + '-' + todayDate + ' 23:59';

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

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

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

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

        $("#testTb1").dataTable({
            "ajax": {
                url: "/admin/rcp/statistics/monitoring/consulting/list.do",
                contentType: "application/json; charset=utf-8",
                type: "POST",
                dataType: "JSON",
                async: false,
                data : function(d) {
                    var dataFrom = $('#dataFrom').val();
                    var dataTo = $('#dataTo').val();

                    var initDateFrom;
                    var initDateTo;

                    if (dataFrom != '' && dataTo != '') {
                        initDateFrom = dataFrom;
                        initDateTo = dataTo;
                    }

                    var param = {
                        oprMngCode: $('#oprMngCode').val(),
                        oprMngCodeList: Consulting.oprMngCodeList,
                        scenarioSeq: $('#scenarioSeq').val(),
                        callInitDateFrom: initDateFrom,
                        callInitDateTo: initDateTo,
                        callEndConversion: $('#callEndConversion').val(),
                        callEndReason: $('#callEndReason').val(),
                        telNo: $('#telNo').val(),
                        dnisNo: $('#dnisNo').val(),
                        page: $('#testTb1').DataTable().page.info().page,
                        pageSize: Consulting.pageSize
                    }

                    Consulting.searchData = {
                        oprMngCode: $('#oprMngCode').val(),
                        oprMngCodeList: Consulting.oprMngCodeList,
                        scenarioSeq: $('#scenarioSeq').val(),
                        callInitDateFrom: initDateFrom,
                        callInitDateTo: initDateTo,
                        callEndConversion: $('#callEndConversion').val(),
                        callEndReason: $('#callEndReason').val(),
                        telNo: $('#telNo').val(),
                        dnisNo: $('#dnisNo').val()
                    }

                    return JSON.stringify(param);
                },
                dataFilter: function (data) {
                    var jsons = jQuery.parseJSON(data);
                    var json = {};
                    // json.recordsTotal = jsons.getTotal;
                    json.recordsFiltered = jsons.getTotal;
                    json.data = jsons.getList.slice(0,Consulting.pageSize);
                    return JSON.stringify(json);
                }
            },
            createdRow: function (row, data, dataIndex, full) {
                $(row).attr('class', "modalLoad");
                $(row).attr('rel', "viewConversationContent");
                $(row).attr('data-token', data.token);
                $(row).attr('data-opr', data.oprMngCode);
                if (data.callInitDate != null && data.callInitDate != '' && data.callInitDate != 'undefined') {
                    $(row).attr('data-date', data.callInitDate.substring(0, 10));
                }
                $(row).attr('data-origin-tel-no', data.originTelNo);
                $(row).attr('data-tel-no', data.telNo);
                $(row).attr('data-dnis-no', data.dnisNo);
                $(row).children('td:nth-child(3)').html('<p class="max-cell-tit" data="' + data.scenarioName + '">' + data.scenarioName + '</p>');
            },
            columns: [
                {data: "rownum"},
                {data: "oprMngCodeName"},
                {data: "scenarioName"},
                {data: "callTime"},
                {data: "callInitDate"},
                {data: "callEndName"},
                {data: "telNo"},
                {data: "dnisNo"},
                {data: "userTalkCnt"},
                {data: "botTalkCnt"}
            ],
            columnDefs: [
                {
                    targets: 0,
                    orderable: false
                },
                {
                    targets: 1,
                    orderable: false
                },
                {
                    targets: 2,
                    orderable: false
                },
                {
                    targets: 3,
                    orderable: false
                },
                {
                    targets: 4,
                    orderable: false
                },
                {
                    targets: 5,
                    orderable: false
                },
                {
                    targets: 6,
                    orderable: false
                },
                {
                    targets: 7,
                    orderable: false
                },
                {
                    targets: 8,
                    orderable: false
                },
                {
                    visible: false,
                    targets: 9,
                    orderable: false
                }
            ],
            "autoWidth": false,
            "paging": true,
            "pagingType": "simple_numbers",
            "info": false,
            "filter": false,
            "lengthChange": true,
            "dom": 'rt<"bottom"fip><"clear">',
            "destroy": true,
            "serverSide": true,
            "aaSorting": [],
            "drawCallback": function () {
                modalUi();
                Consulting.curSearchOpr = $('#oprMngCode').val();
            }
        });
    },

    // 관리자(봇) 채팅 append
    appendAdminMsg: function(obj) {
        var chkRecFileBool = true;

        // const regExp1 = /https?:\/\/[\w\-\.]+[:|0-9/_a-zA-Z]+.wav/;
        const regExp1 = /recordfile\/[0-9]{8}\/[:|0-9\/_a-zA-Z]+.wav/;
        const filePathValidation = regExp1.test(obj.recFilePath);

        if($.utils.isBlank(obj.recFilePath) || !filePathValidation) {
            chkRecFileBool = false;
        }

        var chkCnt = 0;

        var html = '';

        chkCnt = parseInt(obj.COUNT);

        html += '<div class="monitering-msg admin">'
            +       '<div class="msg-img">'
            +           '<img src="/lib/assets/images/img-bot.png" alt="">'
            +       '</div>'
            +       '<div class="msg-desc gray2">'
            +           '<p>' + obj.CHAT_TEXT + '</p>'
            +       '</div>'
            +       '<span class="time-side-btn" id="fnc' + obj.TYPE + obj.TALK_SEQ + '">'

        if (chkRecFileBool) {
            html += "<a href='#' class='minIco listeningIco' title='녹취 듣기' data-opr='" + obj.oprMngCode + "' data-file-path='" + obj.recFilePath + "'>녹취 듣기</a>"
                + "<a href='#' class='minIco downloaderIco' title='녹취 다운로드' data-opr='" + obj.oprMngCode + "' data-file-path='" + obj.recFilePath + "'>녹취 다운로드</a>"
        }

        if (chkCnt > 0) {
            html += "<a href='#' class='minIco removeIco multiModalLoad' title='대화 책갈피 제거' rel='removeBookmark' data-opr='" + obj.oprMngCode + "' data-seq='" + obj.SEQ + "' data-text='" + obj.CHAT_TEXT + "' data-log-type='" + obj.TYPE + "' data-token='" + obj.TOKEN + "' data-talk-seq='" + obj.TALK_SEQ + "'>대화 책갈피 제거</a>"
        }
        else {
            html += "<a href='#' class='minIco addedIco multiModalLoad' title='대화 책갈피 추가' rel='addedBookmark' data-opr='" + obj.oprMngCode + "' data-text='" + obj.CHAT_TEXT + "' data-log-type='" + obj.TYPE + "' data-token='" + obj.TOKEN + "' data-talk-seq='" + obj.TALK_SEQ + "'>대화 책갈피 추가</a>"
        }

        html +=       '</span>'
            +    '</div>'

        $("#detailTalk").append(html);
    },

    // 사용자 채팅 append
    appendUserMsg: function(obj) {
        var chkRecFileBool = true;

        // const regExp1 = /https?:\/\/[\w\-\.]+[:|0-9/_a-zA-Z]+.wav/;
        const regExp1 = /recordfile\/[0-9]{8}\/[:|0-9\/_a-zA-Z]+.wav/;
        const filePathValidation = regExp1.test(obj.recFilePath);

        if($.utils.isBlank(obj.recFilePath) || !filePathValidation) {
            chkRecFileBool = false;
        }

        var chkCnt = 0;

        var html = '';

        chkCnt = parseInt(obj.COUNT);

        html += '<div class="monitering-msg user">'
            +       '<div class="msg-desc">'
            +           '<p>' + obj.CHAT_TEXT + '</p>'
            +       '</div>'
            +       '<div class="msg-img">'
            +           '<img src="/lib/assets/images/img-user.png" alt="">'
            +       '</div>'
            +       '<span class="time-side-btn" id="fnc' + obj.TYPE + obj.TALK_SEQ + '">'

        if (chkRecFileBool) {
            html += "<a href='#' class='minIco listeningIco' title='녹취 듣기' data-opr='" + obj.oprMngCode + "' data-file-path='" + obj.recFilePath + "'>녹취 듣기</a>"
                + "<a href='#' class='minIco downloaderIco' title='녹취 다운로드' data-opr='" + obj.oprMngCode + "' data-file-path='" + obj.recFilePath + "'>녹취 다운로드</a>"
        }

        if (chkCnt > 0) {
            html += "<a href='#' class='minIco removeIco multiModalLoad' title='대화 책갈피 제거' rel='removeBookmark' data-opr='" + obj.oprMngCode + "' data-seq='" + obj.SEQ + "' data-text='" + obj.CHAT_TEXT + "' data-log-type='" + obj.TYPE + "' data-token='" + obj.TOKEN + "' data-talk-seq='" + obj.TALK_SEQ + "'>대화 책갈피 제거</a>"
        }
        else {
            html += "<a href='#' class='minIco addedIco multiModalLoad' title='대화 책갈피 추가' rel='addedBookmark' data-opr='" + obj.oprMngCode + "' data-text='" + obj.CHAT_TEXT + "' data-log-type='" + obj.TYPE + "' data-token='" + obj.TOKEN + "' data-talk-seq='" + obj.TALK_SEQ + "'>대화 책갈피 추가</a>"
        }

        html +=       '</span>'
            +    '</div>'

        $("#detailTalk").append(html);
    },

    addBookmark: function(obj) {
        if (obj.bookmarkErrCode == null || obj.bookmarkErrCode == '') {
            $.utils.warning('책갈피 유형을 선택해주세요.');
            return;
        }

        var param = {
            logType: obj.logType,
            token: obj.token,
            talkSeq: obj.talkSeq,
            talkText: obj.talkText,
            bookmarkErrCode: obj.bookmarkErrCode,
            menuVal: menuVal,
            oprMngCode: obj.oprMngCode.split('_')[2]
        }

        $.ajax({
            type: "POST",
            async: false,
            datatype: "JSON",
            contentType : "application/json; charset=utf-8",
            url: "/admin/rcp/statistics/monitoring/conversationMark/insert.do",
            data: JSON.stringify(param),
            success: (function(data) {
                if (data == 1) {
                    $.utils.success('저장되었습니다.');
                }

                $('#addedBookmark').fadeOut(250);
                removeDimMulti();
                // $('#addBookmarkBtn').off('click');
                $('#addedBookmark').attr('class', 'modal multi');
                var isVisible = $('#addedBookmark').is(':visible');
                var modalLength = $('.modal.multi:visible').length;

                if (isVisible) {
                    if (modalLength > 1) {
                        $('#addedBookmark').fadeOut(250);
                    } else {
                        $('.dim-multi').fadeOut(250);
                    }
                }

                Consulting.resetAddIcon(obj);
            })
        });
    },

    resetAddIcon: function(obj) {
        var param = {
            logType: obj.logType,
            token: obj.token,
            talkSeq: obj.talkSeq
        }

        $.ajax({
            type: "POST",
            async: false,
            datatype: "JSON",
            contentType : "application/json; charset=utf-8",
            url: "/admin/rcp/statistics/monitoring/conversationMark/checkbookmark.do",
            data: JSON.stringify(param),
            success: (function(data) {
                var logType = Consulting.logTypeVal;
                var talkSeq = Consulting.talkSeqVal;
                var fncLtTs = 'fnc';

                if (logType != null && logType != '' && talkSeq != null && talkSeq != '') {
                    fncLtTs += logType;
                    fncLtTs += talkSeq;
                    var $fncLtTs = $('#' + fncLtTs);

                    $fncLtTs.find('.addedIco').attr('rel', 'removeBookmark');
                    $fncLtTs.find('.addedIco').attr('data-seq', data.SEQ);
                    $fncLtTs.find('.addedIco').addClass('removeIco');
                    $fncLtTs.find('.addedIco').removeClass('addedIco');
                }
            })
        });
    },

    removeBookmark: function(obj) {
        if (obj.measureType == null || obj.measureType == '') {
            $.utils.warning('조치 유형을 선택해주세요.');
            return;
        }

        if (obj.measureInfo == null || obj.measureInfo == '') {
            $.utils.warning('조치 내용을 입력해주세요.');
            return;
        }

        var param = {
            measureType: obj.measureType,
            seq: obj.seq,
            menuVal: menuVal,
            oprMngCode: obj.oprMngCode.split('_')[2],
            measureInfo: obj.measureInfo
        }

        $.ajax({
            type: "POST",
            async: false,
            datatype: "JSON",
            contentType : "application/json; charset=utf-8",
            url: "/admin/rcp/statistics/monitoring/conversationMark/update.do",
            data: JSON.stringify(param),
            success: (function(data) {
                if (data == 1) {
                    $.utils.success('삭제되었습니다.');
                }

                $('#removeBookmark').fadeOut(250);
                removeDimMulti();
                // $('#removeBookmarkBtn').off('click');
                $('#removeBookmark').attr('class', 'modal multi');
                var isVisible = $('#removeBookmark').is(':visible');
                var modalLength = $('.modal.multi:visible').length;

                if (isVisible) {
                    if (modalLength > 1) {
                        $('#removeBookmark').fadeOut(250);
                    } else {
                        $('.dim-multi').fadeOut(250);
                    }
                }

                Consulting.resetRemoveIcon(obj);
            })
        });
    },

    resetRemoveIcon: function(obj) {
        var param = {
            logType: obj.logType,
            token: obj.token,
            talkSeq: obj.talkSeq
        }

        $.ajax({
            type: "POST",
            async: false,
            datatype: "JSON",
            contentType : "application/json; charset=utf-8",
            url: "/admin/rcp/statistics/monitoring/conversationMark/checkbookmark.do",
            data: JSON.stringify(param),
            success: (function(data) {
                var logType = Consulting.logTypeVal;
                var talkSeq = Consulting.talkSeqVal;
                var fncLtTs = 'fnc';

                if (logType != null && logType != '' && talkSeq != null && talkSeq != '') {
                    fncLtTs += logType;
                    fncLtTs += talkSeq;
                    var $fncLtTs = $('#' + fncLtTs);

                    $fncLtTs.find('.removeIco').attr('rel', 'addedBookmark');
                    $fncLtTs.find('.removeIco').addClass('addedIco');
                    $fncLtTs.find('.removeIco').removeClass('removeIco');
                }
            })
        });
    },

    getUserCallCnt: function(telNo, oprMngCode, callInitDate) {
        var param = {
            telNo: telNo,
            oprMngCode: oprMngCode,
            callInitDateFrom: callInitDate,
            callInitDateTo: callInitDate
        }

        $.ajax({
            type: "POST",
            async: false,
            datatype: "JSON",
            contentType : "application/json; charset=utf-8",
            url: "/admin/rcp/statistics/monitoring/consulting/userCallCnt.do",
            data: JSON.stringify(param),
            success: (function(data) {
                $('#userCallCnt').html(data + '건');
            })
        });
    },

    chkListCnt: function() {
        var cnt = 0;

        $.ajax({
            type: "POST",
            async: false,
            datatype: "JSON",
            contentType : "application/json; charset=utf-8",
            url: "/admin/rcp/statistics/monitoring/consulting/chklistcnt.do",
            data: JSON.stringify(Consulting.searchData),
            success: (function(data) {
                cnt = data;
            })
        });

        return cnt;
    },

    excelDownload: function() {
        if (Consulting.chkListCnt() > 1000000) {
            $.utils.warning('엑셀 다운로드는 백만 건 이하로 가능합니다.');
        } else {
            var titleList = ['No', '시나리오 그룹', '시나리오', '통화시간', '통화일자', '종료구분', '발신번호', '수신번호', '고객 발화 횟수', '봇 발화 횟수'];

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

            formData.append("monitoringConsultingVO.callInitDateFrom", Consulting.searchData.callInitDateFrom);
            formData.append("monitoringConsultingVO.callInitDateTo", Consulting.searchData.callInitDateTo);
            formData.append("monitoringConsultingVO.oprMngCode", Consulting.searchData.oprMngCode);
            formData.append("monitoringConsultingVO.oprMngCodeList", Consulting.searchData.oprMngCodeList);
            formData.append("monitoringConsultingVO.callEndConversion", Consulting.searchData.callEndConversion);
            formData.append("monitoringConsultingVO.callEndReason", Consulting.searchData.callEndReason);
            formData.append("monitoringConsultingVO.telNo", Consulting.searchData.telNo);
            formData.append("monitoringConsultingVO.dnisNo", Consulting.searchData.dnisNo);
            formData.append("monitoringConsultingVO.scenarioSeq", Consulting.searchData.scenarioSeq);

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

            req.open("POST", '/admin/rcp/statistics/monitoring/consulting/exceldownload.do', true);
            req.responseType = "arraybuffer";
            req.onload = function() {
                const arrayBuffer = req.response;
                if (arrayBuffer) {
                    var blob = new Blob([arrayBuffer], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
                    var link=document.createElement('a');
                    link.href=window.URL.createObjectURL(blob);
                    link.download="응대이력.xlsx";
                    link.click();
                }
            };
            req.send(formData);
        }
    },

    fncInputEnterKey: function(event) {
        let key = event.key || event.keyCode;

        if (key === 'Enter' || key === 13) {
            Consulting.fncConsultingList();
        }
    }

}

$(document).ready(function () {
    // Consulting.init();
    //
    // $('#oprMngCode').on('change', function() {
    //     Consulting.setSearchData();
    // });
    //
    // $('#addBookmarkBtn').on('click', function() {
    //     var param = {
    //         oprMngCode: $('#addOprMngCode').val(),
    //         logType: Consulting.logTypeVal,
    //         token: $('#tokenVal').val(),
    //         talkSeq: Consulting.talkSeqVal,
    //         talkText: $('#bookmarkText').text(),
    //         bookmarkErrCode: $('#bookmarkErr').val()
    //     }
    //
    //     Consulting.addBookmark(param);
    // });
    //
    // $('#removeBookmarkBtn').on('click', function() {
    //     var param = {
    //         oprMngCode: $('#removeOprMngCode').val(),
    //         measureType: $('#measureType').val(),
    //         seq: $('#seqVal').val(),
    //         measureInfo: $('#measureInfo').val()
    //     }
    //
    //     Consulting.removeBookmark(param);
    // });
    //
    // let telNo = document.getElementById('telNo');
    // telNo.addEventListener('keyup', event => Consulting.fncInputEnterKey(event));
    //
    // let dnisNo = document.getElementById('dnisNo');
    // dnisNo.addEventListener('keyup', event => Consulting.fncInputEnterKey(event));
});

$(document).on("click", ".addedIco", function() {
    Consulting.setBookmarkModal(this);
});

$(document).on("click", ".removeIco", function() {
    Consulting.setRemoveBookmarkModal(this);
});

$(document).on("click", ".stopBtnIco", function() {
    var audio = $(".audio-box audio")[0];
    audio.pause();

    $(this).removeClass('stopBtnIco');
    $(this).addClass('listeningIco');
});

$(document).on("click", ".listeningIco", function() {
    var varThis = this;
    var audio = $(".audio-box audio")[0];

    $('a.stopBtnIco').each(function(index,item){
        $(this).removeClass('stopBtnIco');
        $(this).addClass('listeningIco');
    });

    $(this).removeClass('listeningIco');
    $(this).addClass('stopBtnIco');

    var param = {
        fileName: $(this).data("file-path"),
        menuVal: menuVal,
        oprMngCode: $(this).data("opr").split('_')[2]
    }

    $.ajax({
        type: "POST",
        async: false,
        datatype: "JSON",
        contentType : "application/json; charset=utf-8",
        url: "/admin/rcp/statistics/monitoring/consulting/play.do",
        data: JSON.stringify(param),
        success: (function(data) {
            if (audio.src == data) {
                audio.play();
            }
            else {
                audio.pause();
                audio.src = data;
                audio.play();
            }
        })
    });

    audio.onended = function() {
        $(varThis).removeClass('stopBtnIco');
        $(varThis).addClass('listeningIco');
    };
});

$(document).on("click", ".downloaderIco", function() {
    const req = new XMLHttpRequest();
    const formData = new FormData();

    formData.append("fileName", $(this).data("file-path"));
    formData.append("menuVal", menuVal);
    formData.append("oprMngCode", $(this).data("opr").split('_')[2]);

    req.open("POST", '/admin/rcp/statistics/monitoring/consulting/downloadRecordFile.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="녹취파일.wav";
            link.click();
        }
    };
    req.send(formData);
});

$(document).on("dblclick", "tr.modalLoad", function() {
    $("#detailTalk").html('');

    if ($(this).data('origin-tel-no') == 'undefined' || $(this).data('origin-tel-no') == '' || $(this).data('origin-tel-no') == null) {
        $('#userPhoneNumber').html($(this).data('tel-no'));
    }
    else {
        $('#userPhoneNumber').html($(this).data('origin-tel-no'));
    }

    $('#botPhoneNumber').html($(this).data('dnis-no'));

    var param = {
        token: $(this).data('token')
    }

    $.ajax({
        type: "POST",
        async: false,
        datatype: "JSON",
        contentType : "application/json; charset=utf-8",
        url: "/admin/rcp/statistics/monitoring/consulting/recordCallList.do",
        data: JSON.stringify(param),
        success: (function(data) {
            if(data.length > 0) {
                for(var i in data) {
                    var item = data[i];
                    if(item.TYPE == "B") {
                        Consulting.appendAdminMsg(item);
                    } else {
                        Consulting.appendUserMsg(item);
                    }
                }
            }

            modalUi();
            multiModalUi();
        })
    });

    Consulting.getUserCallCnt($(this).data('origin-tel-no').replace(/-/gi, ""), $(this).data('opr'), $(this).data('date'));
});

function multiModalUi() {
    $('.multiModalLoad').on('click', function () {
        var $self = $(this);
        var $thisrel = $self.attr('rel');
        var $target = $('#' + $thisrel);

        // open and focusin
        $target.attr('tabindex', '0').fadeIn(250).focus();
        $target.css({ display: 'table' });
        $target.attr('class', 'modal multi open');
        // create sizing
        var layerHeight = $target.outerHeight();
        var layerWidth = $target.outerWidth();
        $target.css({
            marginLeft: -layerWidth / 2,
            marginTop: -layerHeight / 2
        });

        // create background
        createDimMulti();

        // close and focusout
        $target.find(".close").on('click', function (e) {
            e.preventDefault();
            $target.fadeOut(250);
            removeDimMulti();
            $(this).off('click');
            $target.attr('class', 'modal multi');
            var isVisible = $target.is(':visible');
            var modalLength = $('.modal.multi:visible').length;

            if (isVisible) {
                if (modalLength > 1) {
                    $target.fadeOut(250);
                } else {
                    $('.dim-multi').fadeOut(250);
                }
            }
        });
    });
}
function createDimMulti() {
    if (!$('.dim-multi').length) {
        $('body').append('<div class="dim-multi"></div>');
    }
    $('.dim-multi').fadeIn(250);
    $('body').css({
        overflow: 'hidden'
    }).bind('touchmove', function (e) {
        e.preventDefault();
    });
}
function removeDimMulti() {
    $('.dim-multi').fadeOut(250);
    $('body').css({
        overflow: 'inherit'
    }).unbind('touchmove');
}

function fncConsultingExcelDown(){
    const req = new XMLHttpRequest();
    const formData = new FormData();

    req.open("POST", '/admin/rcp/statistics/monitoring/consulting/download.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="excel_consulting.xls";
            link.click();
        }
    };
    req.send(formData);
}
