var menuVal = 'rcpmonitoringconversationMarkmanage'

var Bookmark = {
    searchData: {},

    logTypeVal: '',
    talkSeqVal: '',

    pageSize: 10,

    init: function() {
        this.setCurrentDate();
        this.fncConversationMarkList();
        this.setBookmarkErrCodeSelectBox();
        this.setMeasureTypeCodeSelectBox();
    },

    setCurrentDate: function() {
        var today = new Date();
        var year = today.getFullYear(); // 년도
        var month = today.getMonth() + 1;  // 월
        var date = today.getDate();  // 날짜
        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();  // 날짜

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

    setBookmarkErrCodeSelectBox: function() {
        var param = {
            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 html = '<option value="">전체</option>';

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

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

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

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

    setMeasureTypeCodeSelectBox: function() {
        var param = {
            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>';

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

                html += '<option value="incomplete">미조치</option>';

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

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

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

    checkBookmark: function(obj) {
        var chkCnt = 0;

        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) {
                chkCnt = data.CNT;
            })
        });

        return chkCnt;
    },

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

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

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

        $("#testTb1").dataTable({
            "ajax": {
                url: "/admin/rcp/statistics/monitoring/conversationMark/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 = {
                        callInitDateFrom: initDateFrom,
                        callInitDateTo: initDateTo,
                        bookmarkErrCode: $('#bookmarkErrCode').val(),
                        measureType: $('#measureTypeCode').val(),
                        talkText: $('#talkText').val(),
                        page: $('#testTb1').DataTable().page.info().page,
                        pageSize: Bookmark.pageSize
                    }

                    Bookmark.searchData = {
                        callInitDateFrom: initDateFrom,
                        callInitDateTo: initDateTo,
                        bookmarkErrCode: $('#bookmarkErrCode').val(),
                        measureType: $('#measureTypeCode').val(),
                        talkText: $('#talkText').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,Bookmark.pageSize);
                    return JSON.stringify(json);
                }
            },
            createdRow: function (row, data, dataIndex, full) {
                $(row).attr('class', "modalLoad");
                $(row).attr('rel', "viewConversationContent");
                if (data.callInitDate != null && data.callInitDate != '' && data.callInitDate != 'undefined') {
                    $(row).attr('data-date', data.callInitDate.substring(0, 10));
                }
                $(row).attr('data-token', data.token);
                $(row).attr('data-talk-seq', data.talkSeq);
                $(row).attr('data-log-type', data.logType);

                $(row).children('td:nth-child(2)').html(data.callInitDate);
                $(row).children('td:nth-child(6)').html(data.registDate);

                var chkCnt = Bookmark.checkBookmark(data);

                var html = "";
                html += '<div class="time-side-btn">'
                    +     "<a href='#' rel='addedIntentExam' class='minIco addedIco-sq modalLoad' title='인텐트 예문 추가' data-text='" + data.talkText + "'>인텐트 예문 추가</a>"
                if (chkCnt > 0) {
                    html += "<a href='#' class='minIco removeIco multiModalLoad' title='대화 책갈피 제거' rel='removeBookmark' data-opr='" + data.oprMngCode + "' data-seq='" + data.seq + "' data-text='" + data.talkText + "' data-log-type='" + data.logType + "' data-token='" + data.token + "' data-talk-seq='" + data.talkSeq + "'>대화 책갈피 제거</a>"
                }
                else {
                    html += "<a href='#' class='minIco addedIco multiModalLoad' title='대화 책갈피 추가' rel='addedBookmark' data-opr='" + data.oprMngCode + "' data-text='" + data.talkText + "' data-log-type='" + data.logType + "' data-token='" + data.token + "' data-talk-seq='" + data.talkSeq + "'>대화 책갈피 추가</a>"
                }
                html +=   '</div>'

                $(row).children('td:nth-child(7)').html(html);
            },
            columns: [
                {data: "rownum"},
                {data: null},
                {data: "bookmarkErrCodeName"},
                {data: "measureTypeName"},
                {data: "talkText"},
                {data: null},
                {data: null}
            ],
            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
                }
            ],
            "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();
                multiModalUi();
            }
        });
    },

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

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

                Bookmark.fncConversationMarkList();
            })
        });
    },

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

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

                Bookmark.fncConversationMarkList();
            })
        });
    },

    // 관리자(봇) 채팅 append
    appendAdminMsg: function(obj, subParam) {
        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>'

            if (subParam.token == obj.TOKEN && subParam.talkSeq == obj.TALK_SEQ && subParam.logType == obj.TYPE) {
                html +=       '<div class="msg-desc" style="background-color:#ffdebb">'
            }
            else {
                // if (chkCnt > 0) {
                //     html +=       '<div class="msg-desc" style="background-color:#bfefff">'
                // }
                // else {
                //     html +=       '<div class="msg-desc gray2">'
                // }

                html +=       '<div class="msg-desc gray2">'
            }

        html +=           '<p style="color:black;">' + 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, subParam) {
        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">'

            if (subParam.token == obj.TOKEN && subParam.talkSeq == obj.TALK_SEQ && subParam.logType == obj.TYPE) {
                html +=       '<div class="msg-desc" style="background-color:#ffdebb">'
            }
            else {
                // if (chkCnt > 0) {
                //     html +=       '<div class="msg-desc" style="background-color:#bfefff">'
                // }
                // else {
                //     html +=       '<div class="msg-desc gray2">'
                // }

                html +=       '<div class="msg-desc gray2">'
            }

        html +=           '<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);
    },

    setBookmarkErrCd: function() {
        var param = {
            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 param = {
            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'));
        Bookmark.logTypeVal = $(obj).data('logType');
        $('#tokenVal').val($(obj).data('token'));
        Bookmark.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'));
        Bookmark.logTypeVal = $(obj).data('logType');
        $('#tokenVal').val($(obj).data('token'));
        Bookmark.talkSeqVal = $(obj).data('talkSeq');
    },

    chkListCnt: function() {
        var cnt = 0;

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

        return cnt;
    },

    excelDownload: function() {
        if (Bookmark.chkListCnt() > 1000000) {
            $.utils.warning('엑셀 다운로드는 백만 건 이하로 가능합니다.');
        } else {
            var titleList = ['No', '통화일자', '오류유형', '조치유형', '대화내용'];

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

            formData.append("monitoringConversationMarkVO.callInitDateFrom", Bookmark.searchData.callInitDateFrom);
            formData.append("monitoringConversationMarkVO.callInitDateTo", Bookmark.searchData.callInitDateTo);
            formData.append("monitoringConversationMarkVO.bookmarkErrCode", Bookmark.searchData.bookmarkErrCode);
            formData.append("monitoringConversationMarkVO.measureType", Bookmark.searchData.measureType);
            formData.append("monitoringConversationMarkVO.talkText", Bookmark.searchData.talkText);

            for (let i = 0; i < titleList.length; i++) {
                formData.append("titleList[" + i + "]", titleList[i]);
            }

            formData.append("menuVal", menuVal);
            formData.append("oprMngCode", $('#mainOpr').val());

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

}

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

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

        Bookmark.addBookmark(param);
    });

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

        Bookmark.removeBookmark(param);
    });

    $('.datetimepicker').datetimepicker();

    let talkText = document.getElementById('talkText');
    talkText.addEventListener('keyup', event => Bookmark.fncInputEnterKey(event));
});

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

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

$(document).on("click", ".addedIco-sq", function() {
    AddIntentExample.init($(this).data('text'));
});

$(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() {
    var today = new Date();
    var year = today.getFullYear();
    var month = today.getMonth() -5;
    var date = today.getDate();

    var sixMonthAgo = new Date(year, month, date);

    if ($(this).data('date') != null && $(this).data('date') != '' && $(this).data('date') != 'undefined') {
        var dataDate = new Date($(this).data('date'));
    } else {
        var dataDate = null;
    }

    if (dataDate == 'undefined' || dataDate == null || dataDate == '' || dataDate < sixMonthAgo) {
        $("#viewConversationContent").hide();
        removeDim();
        $.utils.warning('대화 내용은 6개월 이내만 조회할 수 있습니다.');
        return;
    }

    $("#detailTalk").html('');

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

    var subParam = {
        token: $(this).data('token'),
        talkSeq: $(this).data('talk-seq'),
        logType: $(this).data('log-type')
    }

    $.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") {
                        Bookmark.appendAdminMsg(item, subParam);
                    } else {
                        Bookmark.appendUserMsg(item, subParam);
                    }
                }
            }

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

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