var menuVal = 'rcpmonitoringoutscenariomanage'

var Outscenario = {
    searchData: {},

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

    curSearchOpr: '',

    logTypeVal: '',
    talkSeqVal: '',
    pageSize: 10,

    init: function() {
        this.setOprMngCode();
        this.setCurrentDate();
        this.setScenarioNameList();
        this.getOutscenarioList();
    },

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

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

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

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

        var html = '';

        html += '<div class="chk_box scenarioChkBox">'
            +       '<input type="checkbox" name="all" id="chk" value="all" 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 scenarioChkBox">'
                        +       '<input type="checkbox" name="checkbox" id="chk' + i + '" value="' + data[i].seq + '">'
                        +       '<label for="chk' + i + '">' + data[i].scenarioName + '</label>'
                        +   '</div>'

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

            })
        });

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

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

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

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

        $("#testTb1").dataTable({
            "ajax": {
                url: "/admin/rcp/statistics/monitoring/outscenario/outscenariolist.do",
                contentType: "application/json; charset=utf-8",
                type: "POST",
                dataType: "JSON",
                async: false,
                data : function(d) {
                    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 param = {
                        oprMngCode: $('#oprMngCode').val(),
                        oprMngCodeList: Outscenario.oprMngCodeList,
                        callInitDateFrom: $('#dataFrom').val(),
                        callInitDateTo: $('#dataTo').val(),
                        scenarioIdList: valueArr,
                        allScenarioIdList: Outscenario.allScenarioIdList,
                        chkScenarioAll: chkScenarioAllCd,
                        page: $('#testTb1').DataTable().page.info().page,
                        pageSize: Outscenario.pageSize
                    }

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

                    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,Outscenario.pageSize);
                    return JSON.stringify(json);
                }
            },
            createdRow: function (row, data, dataIndex, full) {
                $(row).attr('class', "modalLoad");
                $(row).attr('rel', "talkHistoryDetails");
                // $(row).attr('data-token-list', data.tokenList);
                $(row).attr('data-scenario-seq', data.scenarioSeq);
                $(row).attr('data-node-code', data.nodeCode);
                $(row).attr('data-opr', data.oprMngCode);

                $(row).children('td:nth-child(2)').html(data.scenarioName + ' (' + data.scenarioCnt + '건)');
                $(row).children('td:nth-child(3)').html(data.nodeName + ' (' + data.nodeType + ')' + ' (' + data.nodeCnt + '건)');

                var nodePercent = (parseFloat(data.nodeCnt)/parseFloat(data.scenarioCnt) * 100).toFixed(1);

                $(row).children('td:nth-child(4)').html(nodePercent + '%');
            },
            columns: [
                {data: "oprMngCodeName"},
                {data: null},
                {data: null},
                {data: null}
            ],
            columnDefs: [
                {
                    targets: 0,
                    orderable: false
                },
                {
                    targets: 1,
                    orderable: false
                },
                {
                    targets: 2,
                    orderable: false
                },
                {
                    targets: 3,
                    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();
                Outscenario.curSearchOpr = $('#oprMngCode').val();
            }
        });
    },

    chkListCnt: function() {
        var cnt = 0;

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

        return cnt;
    },

    excelDownload: function() {
        if (Outscenario.chkListCnt() > 1000000) {
            $.utils.warning('엑셀 다운로드는 백만 건 이하로 가능합니다.');
        } else {
            var titleList = ['시나리오 그룹', '시나리오 명 (건수)', '이탈 구간 노드 코드 (노드 형태) (건수)', '이탈 노드 차지 비율'];

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

            formData.append("monitoringOutscenarioVO.oprMngCode", Outscenario.searchData.oprMngCode);
            formData.append("monitoringOutscenarioVO.oprMngCodeList", Outscenario.searchData.oprMngCodeList);
            formData.append("monitoringOutscenarioVO.callInitDateFrom", Outscenario.searchData.callInitDateFrom);
            formData.append("monitoringOutscenarioVO.callInitDateTo", Outscenario.searchData.callInitDateTo);
            formData.append("monitoringOutscenarioVO.scenarioIdList", Outscenario.searchData.scenarioIdList);
            formData.append("monitoringOutscenarioVO.allScenarioIdList", Outscenario.searchData.allScenarioIdList);
            formData.append("monitoringOutscenarioVO.chkScenarioAll", Outscenario.searchData.chkScenarioAll);

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

            req.open("POST", '/admin/rcp/statistics/monitoring/outscenario/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);
        }
    },

    getTokenList: function(oprMngCode, scenarioSeq, nodeCode) {
        var result = [];

        var param = {
            oprMngCode: oprMngCode,
            scenarioSeq: scenarioSeq,
            nodeCode: nodeCode,
            callInitDateFrom: Outscenario.searchData.callInitDateFrom,
            callInitDateTo: Outscenario.searchData.callInitDateTo
        }

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

        return result;
    },

    setModal: function(obj) {
        $('#detailTalk').html('');

        $("#moveScenario").attr("href", "/admin/rcp/conversation/scenario/manage.do?scenarioSeq="+$(obj).data('scenario-seq'));

        // var tokenListVal = $(obj).data('token-list').split(',');
        var tokenListVal = Outscenario.getTokenList($(obj).data('opr'), $(obj).data('scenario-seq'), $(obj).data('node-code'));

        var param = {
            tokenList: tokenListVal
        }

        var html = '';

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

                if (data.length > 0) {
                    for (var i=0; i<data.length; i++) {
                        html += '<tr class="detailTalk" data-token="' + data[i].token + '">'
                            +       '<td>' + data[i].rownum + '</td>'
                            +       '<td>' + data[i].telNo.substr(0, 3) + '-' + data[i].telNo.substr(3, 4).replaceAll(data[i].telNo.substr(3, 4), '****') + '-' + data[i].telNo.substr(7, 4) + '</td>'
                            +       '<td>' + data[i].dnisNo + '</td>'
                            +       '<td>' + data[i].callTime + '</td>'
                            +       '<td>' + data[i].callInitDate + '</td>'
                            +   '</tr>'
                    }

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

                    $("#testTb2").dataTable({
                        "autoWidth": false,
                        "paging": true,
                        "pagingType": "full_numbers",
                        "ordering": true,
                        "info": false,
                        "filter": false,
                        "lengthChange": true,
                        "dom": 'rt<"bottom"fip><"clear">',
                    });

                    $("#testTb2").dataTable();
                }
            })
        });
    },

    // 관리자(봇) 채팅 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);
    },

    setBookmarkModal: function(obj) {
        multiModalUi();

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

        this.setBookmarkErrCd();

        $('#addOprMngCode').val($(obj).data('opr'));
        Outscenario.logTypeVal = $(obj).data('logType');
        $('#tokenVal').val($(obj).data('token'));
        Outscenario.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'));
        Outscenario.logTypeVal = $(obj).data('logType');
        $('#tokenVal').val($(obj).data('token'));
        Outscenario.talkSeqVal = $(obj).data('talkSeq');
    },

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

        var param = {
            oprMngCode: $('#oprMngCode').val(),
            custCode: arr[0],
            custCodeList: Outscenario.custCodeList,
            oprMngCodeUpper: arr[0] + '_RCP_' + $('#oprMngCode').find(':selected').data('sg-upper'),
            oprMngCodeUpperList: Outscenario.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: Outscenario.custCodeList,
            oprMngCodeUpper: arr[0] + '_RCP_' + $('#oprMngCode').find(':selected').data('sg-upper'),
            oprMngCodeUpperList: Outscenario.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');
            })
        });
    },

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

                Outscenario.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 = Outscenario.logTypeVal;
                var talkSeq = Outscenario.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);
                    }
                }

                Outscenario.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 = Outscenario.logTypeVal;
                var talkSeq = Outscenario.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');
                }
            })
        });
    }

}

$(document).ready(function () {
    Outscenario.init();

    $('#oprMngCode').on('change', function() {
        Outscenario.setScenarioNameList();

        // Outscenario.resetMoreOpenBtn(0);
    });

    $('#addBookmarkBtn').on('click', function() {
        var param = {
            oprMngCode: $('#addOprMngCode').val(),
            logType: Outscenario.logTypeVal,
            token: $('#tokenVal').val(),
            talkSeq: Outscenario.talkSeqVal,
            talkText: $('#bookmarkText').text(),
            bookmarkErrCode: $('#bookmarkErr').val()
        }

        Outscenario.addBookmark(param);
    });

    $('#removeBookmarkBtn').on('click', function() {
        var param = {
            oprMngCode: $('#removeOprMngCode').val(),
            measureType: $('#measureType').val(),
            seq: $('#seqVal').val(),
            measureInfo: $('#measureInfo').val()
        }

        Outscenario.removeBookmark(param);
    });
});

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

$(document).on("click", ".removeIco", function() {
    Outscenario.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("click", ".scenarioChkBox", function() {
    if ($(this).find('input').attr('name') == 'all') {
        $("input:checkbox[name='checkbox']").prop("checked", false);

        if ($('#chk').is(':checked')) {
            Outscenario.resetMoreOpenBtn($("input:checkbox[name=checkbox]").length);
        }
        else {
            Outscenario.resetMoreOpenBtn(0);
        }
    }
    else {
        Outscenario.fncScenarioChk();
    }
});

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

    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") {
                        Outscenario.appendAdminMsg(item);
                    } else {
                        Outscenario.appendUserMsg(item);
                    }
                }
            }

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

$(document).on("dblclick", "tr.modalLoad", function() {
    Outscenario.setModal(this);
});

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');
}
