var seconds = 0;
var keyBoardArr = ["0","1","2","3","4","5","6","7","8","9","*","#"]
var ivrList = [] //ivr列表
var siteList = [] //坐席列表
var consultingState = false //是否咨询状态
var selectedIndex = '1' //1 坐席 2 技能 3ivr4外线5满意度
var otherBoardType = '0' // 1转接2咨询3三方4二次拨号
var basic_camera_stream = null //检测流
var localStream = null //本地流
var audioTimer = null // 语音计时器
var setParam = {}
var restTimer = null
var restTimes = 0
var messageTimer = null
var transMode = '2'
var i18nArray = []
var nowStatusText = '离线'
var i18nInputArray = []
var changeArray = []
var ivrObj = {}
var videoStatus = -1
var desensitization = 0 //0 不脱敏 1脱敏
var callin_channel = '' // 来电方式  TRANS转接来电  CONSULT 咨询来电 THREE_WAY三方来电   空为正常来电
var msgEvent = {}
var callee_number = ''
let seatABoxUserList = [];//通话用户
let seatBoxEnlargeParams = {};//坐席助手放大位置参数
let seatABoxUserHistory = {};//通话历史
let seatABoxQualityCheckHistory = {};//质检历史
let activeUserCallUuid = '';//选中的通话唯一id
let defaultUserCallUuid = '';//通话中随机唯一id
let sendFillInFormTimer = null;
let assistantEnablePermission = {};
let textTargetKeys = {
    1: "中文",
    2: "English",
    3: "日本語",
    4: "한국어",
}
let audioTargetKeys = {
    1: "中文",
    2: "English",
    3: "日本語",
    4: "한국어",
}
let asrCustomUuid = '';
let asrMyUuid = '';
var note = [
    {class: 'sitetype',type: 'div', txt: '',id: 'sitetype'},
    {class: 'notes',type: 'div', txt: '',id: 'notes'},
    {class: 'setBox',type: 'div', txt: '',id: 'setBox'},
    {class: 'tipsShow',type: 'div', txt: '',id: 'tipsShow'},
    {class: 'basic_monitor_popup',type: 'div', txt: '',id: 'detectionBox'},
    {class: 'vritual_popup',type: 'div', txt: '',id: 'vritual_popup'},
    {class: 'setting_popup',type: 'div', txt: '',id: 'setting_popup'},
    {class: 'main_center_wrap',type: 'div', txt: '',id: 'main_center_wrap'},
    {class: 'seatAssistantBox',type: 'div', txt: '',id: 'seatAssistantBox'},
    {class: 'knowledgeModal',type: 'div', txt: '',id: 'knowledgeModal'},
]
var noteChild = [
    {class: 'statusFont',type: 'div', txt: `${i18ntc('离线')}`,id: 'note'},
    {class: '',type: 'div', txt: '|',id: ''},
    {class: 'time',type: 'div', txt: '--:--:--',id: 'time'},
    {class: 'tips',type: 'div', txt: '<span class="i18n">通话结束后进入</span><span id="overCall" style="margin-left:3px;"></span>',id: 'tips'},
    {class: 'choseStatus',type: 'div', txt: '<div value="free" class="i18n">空闲</div><div value="busy" class="i18n">忙碌</div><div value="rest" id="restBtn" class="i18n">小休</div><div value="offline" id="offlineBtn" class="i18n">离线</div>',id: 'choseStatus'},
]
var inputArr = [
    {class: 'numberKeyBoard',type: 'div', txt: '',id: 'numberKeyBoard'},
    {class: 'inputBox',type: 'div', txt: '',id: 'inputBox'},
    {class: 'showDiv',type: 'div', txt: '',id: 'showDiv'},
    {class: 'showMore',type: 'div', txt: '',id: 'showMore'},
]
var btnkeys = [
    {class: 'btns',type: 'div', txt: '保持',id: 'hold'},
    {class: 'btns',type: 'div', txt: '接听',id: 'pickup'},
    {class: 'btns',type: 'div', txt: '取回',id: 'holdCancel'},
    {class: 'btns',type: 'div', txt: '静音',id: 'mute'},
    {class: 'btns',type: 'div', txt: '取消静音',id: 'muteCancel'},
    {class: 'btns',type: 'div', txt: '转接',id: 'trans'},
    {class: 'btns',type: 'div', txt: '转接',id: 'transfer'},
    {class: 'btns',type: 'div', txt: '取消转接',id: 'transferCancel'},
    {class: 'btns',type: 'div', txt: '咨询',id: 'consulting'},
    {class: 'btns',type: 'div', txt: '取消咨询',id: 'consultingCancel'},
    {class: 'btns',type: 'div', txt: '三方通话',id: 'threeCall'},
    {class: 'btns',type: 'div', txt: '转视频',id: 'toVideo'},
    {class: 'btns',type: 'div', txt: '满意度',id: 'satisfaction'},
    {class: 'btns',type: 'div', txt: '挂断',id: 'hangup'},
    {class: 'btns',type: 'div', txt: '按键',id: 'dtmf'},
    {class: 'btns',type: 'div', txt: '更多',id: 'more'},
    // {class: 'btns',type: 'div', txt: '复位',id: 'reset'},
    // {class: 'btns',type: 'div', txt: '设备检测',id: 'detection'},
    {class: 'btns',type: 'div', txt: '设置',id: 'set'},
    {class: 'btns',type: 'div', txt: '坐席助手',id: 'seatAssistant'}
]
var colors = ['#CACACA','#2ED8AD','#EA1A00','#F9C22E','#627DFF','#02830F'] //离线 空闲 忙碌 振铃 通话  灰绿红黄蓝 整理
msgEvent.event_cmdres = function event_cmdres(msg){
    let backMsg = JSON.parse(msg)
    if (backMsg.code == '5103'){
        toastMessage(backMsg.msg)
    }
    switch(backMsg.msg_type){
        case 'change_status':
            if (backMsg.agent_status){
                if(['PLAY_RECORD'].includes(backMsg.sub_agent_status)){
                    document.getElementById('note').innerHTML = bgText(backMsg.sub_agent_status)
                } else {
                    document.getElementById('note').innerHTML = bgText(backMsg.agent_status)
                    if (backMsg.agent_status == 'OFFLINE'){
                        isCheckIn = false
                        hideDomTree()
                        document.getElementById('note').innerHTML = i18ntc('离线')
                        document.getElementById('more').style.display = 'none'
                        document.getElementById('inputNum').disabled = true
                        document.getElementById('keyModel').style.display = 'none'
                        document.getElementById('sitetype').style.visibility = 'hidden'
                        if (restTimer){
                            clearTimeout(restTimer)
                            restTimer = null
                        }
                        if (audioTimer){
                            cleanTime('1')
                        }
                    }
                }
                if(['FREE','BUSY','REST'].includes(backMsg.agent_status) && backMsg.action){
                    toastMessage(backMsg.msg)
                }
                if(['FREE','BUSY','ARRANGE','REST'].includes(backMsg.agent_status)){
                    hideDomTree()
                    document.getElementById('play_calling').pause()
                    document.getElementById('play_calling').currentTime = 0;
                    if (window.stopRecordingPlay){
                        stopRecordingPlay()
                    }
                    if (backMsg.agent_status != 'REST'){
                        if (restTimer){
                            clearTimeout(restTimer)
                            restTimer = null
                        }
                    }
                    if (['ARRANGE','REST'].includes(backMsg.agent_status)){
                        if (!audioTimer){
                            audioTimer = setInterval(updateTime, 1000)
                        } else {
                            cleanTime('2')
                            audioTimer = setInterval(updateTime, 1000)
                        }
                        if (backMsg.agent_status == 'REST'){
                            if (localStorage.getItem('restTimes')){
                                restTimes = Number(localStorage.getItem('restTimes'))
                            }
                            restTimer = setTimeout(()=>{
                                document.getElementById('timeOut').style.display = 'flex'
                                localStorage.removeItem('restTimes')
                            },restTimes * 60000)
                        }
                    } else {
                        if (audioTimer){
                            cleanTime('1')
                        }
                    }
                    if(virtua){
                        stopVirtua()
                    }
                    if (vague){
                        stopBlurBackground()
                    }
                }
                if (backMsg.agent_status == 'CALLING' || backMsg.agent_status == 'RINGING'){
                    if (restTimer){
                        clearTimeout(restTimer)
                        restTimer = null
                    }
                    if (!audioTimer){
                        audioTimer = setInterval(updateTime, 1000)
                    } else {
                        if (!backMsg.sub_agent_status && backMsg.agent_status != backMsg.last_agent_status){
                            cleanTime('3')
                            audioTimer = setInterval(updateTime, 1000)
                        }
                    }
                    //质检功能 直接return
                    if (['EAVESDROP','FORCE_CALL','WHISPER','CONSULT','THREE_WAY'].includes(backMsg.reason)&& ['RINGING','CALLING'].includes(backMsg.agent_status)){
                            if ('RINGING' == backMsg.agent_status){
                                if (setParam.agentAnswerMode == '1'){
                                    document.getElementById('pickup').style.display = 'block'
                                    if (window.openWindow){
                                        window.openWindow(callingPhone)
                                    }
                                }
                                document.getElementById('hangup').style.display = 'block'
                            } else if('CALLING' == backMsg.agent_status){
                                document.getElementById('showDiv').style.display = 'block'
                                switch(backMsg.reason){
                                    case 'EAVESDROP':
                                        document.getElementById('showDiv').innerHTML = `<span class="i18n">${i18ntc('监听')}：</span>` + cutPhone(backMsg.in_call_numbers[0]) + '<span class="i18n">和</span>' + cutPhone(backMsg.in_call_numbers[1])
                                    break;
                                    case 'WHISPER':
                                        document.getElementById('showDiv').innerHTML = `<span class="i18n">${i18ntc('耳语')}：</span>` + cutPhone(backMsg.in_call_numbers[0]) + '<span class="i18n">和</span>' + cutPhone(backMsg.in_call_numbers[1])
                                    break;
                                    case 'FORCE_CALL':
                                        document.getElementById('showDiv').innerHTML = `<span class="i18n">${i18ntc('强插')}：</span>` + cutPhone(backMsg.in_call_numbers[0]) + '<span class="i18n">和</span>' + cutPhone(backMsg.in_call_numbers[1])
                                    break;
                                    case 'CONSULT':
                                        document.getElementById('showDiv').innerHTML = `<span class="i18n">${i18ntc('咨询')}：</span>` + cutPhone(backMsg.in_call_numbers[0]) + '<span class="i18n">和</span>' + cutPhone(backMsg.in_call_numbers[1])
                                        if (window.goPage){
                                            let param = backMsg
                                            param.uuid = nowUuid
                                            param.client_uuid = nowClientUuid
                                            param.type = 2  //呼入1  呼出2
                                            param.phonenum = callingPhone
                                            param.companyCustomFromId = setParam.companyCustomFromId;
                                            window.goPage(param)
                                        }
                                        break;
                                    case 'THREE_WAY':
                                        document.getElementById('showDiv').innerHTML = `<span class="i18n">${i18ntc('三方通话')}：</span>` + cutPhone(backMsg.in_call_numbers[0]) + '<span class="i18n">和</span>' + cutPhone(cutPhone(backMsg.in_call_numbers[1]))
                                        if (window.goPage){
                                            let param = backMsg
                                            param.uuid = nowUuid
                                            param.client_uuid = nowClientUuid
                                            param.type = 2  //呼入1  呼出2
                                            param.phonenum = callingPhone
                                            param.companyCustomFromId = setParam.companyCustomFromId;
                                            window.goPage(param)
                                        }
                                    break;
                                }

                                document.getElementById('pickup').style.display = 'none'
                                document.getElementById('hangup').style.display = 'block'
                                if (window.hideWindow){
                                    window.hideWindow()
                                }
                            }
                        return
                    }
                    //语音
                    if (!hasVideo){
                        switch(backMsg.agent_status){
                            case 'RINGING':
                                document.getElementById('hangup').style.display = 'block'
                                document.getElementById('inputNum').disabled = true
                                if (setParam.agentAnswerMode == 1 && callType == 'callin'){
                                    document.getElementById('pickup').style.display = 'block'
                                    if (window.openWindow){
                                        window.openWindow(callingPhone)
                                    }
                                    document.getElementById('play_calling').play().catch(function(error) {
                                        // 忽略错误
                                        setLog(error)
                                    });
                                }
                                if (callType == 'callout'){
                                    document.getElementById('dtmf').style.display = 'block'
                                }
                                break;
                            case 'CALLING':
                                if (callType=='callin'){
                                    document.getElementById('play_calling').pause()
                                    document.getElementById('play_calling').currentTime = 0;
                                    if ((!backMsg.reason || callin_channel == 'TRANS' || backMsg.reason == '坐席进入通话中') && backMsg.agent_status != backMsg.last_agent_status){
                                        document.getElementById('dtmf').style.display = 'block'
                                        document.getElementById('hangup').style.display = 'block'
                                        document.getElementById('mute').style.display = 'block'
                                        document.getElementById('hold').style.display = 'block'
                                        document.getElementById('threeCall').style.display = 'block'
                                        document.getElementById('consulting').style.display = 'block'
                                        document.getElementById('transfer').style.display = 'block'
                                        document.getElementById('dtmf').style.display = 'block'
                                        document.getElementById('satisfaction').style.display = 'block'
                                        document.getElementById('toVideo').style.display = 'block'
                                        document.getElementById('pickup').style.display = 'none'
                                        if (window.hideWindow){
                                            window.hideWindow()
                                        }
                                    }
                                    if (backMsg.agent_status == 'CALLING' &&  backMsg.last_agent_status == 'RINGING'){
                                        if (window.goPage){
                                            let param = backMsg
                                            param.uuid = nowUuid
                                            param.client_uuid = nowClientUuid
                                            param.type = callType=='callin'?1:2  //呼入1  呼出2
                                            param.phonenum = callingPhone
                                            param.display_number = callee_number
                                            param.companyCustomFromId = setParam.companyCustomFromId;
                                            window.goPage(param)
                                        }
                                        callin_channel = ''
                                    }
                                }
                            break;
                        }
                    } else {
                        switch(backMsg.agent_status){
                            case 'RINGING':
                                document.getElementById('inputNum').disabled = true
                                if (setParam.agentAnswerMode == 1 && callType == 'callin'){
                                    document.getElementById('await').style.display = 'flex'
                                }
                            break;
                            case 'CALLING':
                                if (callType=='callin'){
                                    if (backMsg.last_agent_status == 'RINGING'){
                                        document.getElementById('await').style.display = 'none'
                                        document.getElementById('calloutWait').style.display = 'none'
                                        $('.center_btns_wrap .can_click').show();
                                        $('.center_btns_wrap .forbid_click').hide();
                                        $('#closeMic').hide()
                                        $('#closeVideo').hide()
                                    }
                                }
                            break;
                        }
                    }
                }
            }
            if (backMsg.action){
                switch(backMsg.action){
                    case 'MAKE_BUSY_AFTER_CALL_STOP':
                        document.getElementById('overCall').innerHTML =  '●' + i18ntc('忙碌')
                        document.getElementById('overCall').style.color = '#EA1A00'
                        document.getElementById('tips').style.display = 'block'
                        break
                    case 'MAKE_FREE_AFTER_CALL_STOP':
                        document.getElementById('overCall').innerHTML = '●' + i18ntc('空闲')
                        document.getElementById('overCall').style.color = '#2ED8AD'
                        document.getElementById('tips').style.display = 'block'
                        break
                    case 'MAKE_REST_AFTER_CALL_STOP':
                        document.getElementById('overCall').innerHTML = '●' + i18ntc('小休')
                        document.getElementById('overCall').style.color = '#FF6011'
                        document.getElementById('tips').style.display = 'block'
                        break
                    case 'MAKE_REST':
                        if (restTimer && backMsg.code == '1'){
                            cleanTime(2)
                            audioTimer = setInterval(updateTime, 1000)
                            clearTimeout(restTimer)
                            restTimer = null
                            restTimer = setTimeout(()=>{
                                document.getElementById('timeOut').style.display = 'flex'
                                localStorage.removeItem('restTimes')
                            },restTimes * 60000)
                        }
                }
            }
            if (backMsg.agent_status == 'BUSY' && backMsg.code == '1'){
                toastMessage(i18ntc(backMsg.msg))
            }
        break
        case 'connect':
            if (backMsg.code == '0'){
                getStatus()
                getSet()
            }
        break
        case 'callback':
            try{
                setAsrCustomUuid(backMsg.peer_uuid);
            }catch(res){}

            if (backMsg.phase == 'START_CALL' && ['CALL','PREVIEW_OUT_CALL'].includes(backMsg.action)){
                callingPhone = backMsg.callee_number
                if (hasVideo && videoStatus == 0){
                    callBackAudio()
                    document.getElementById('main_center_wrap').style.display = 'none'
                    toastMessage(i18ntc('对方语音接通'))
                }
                if (!hasVideo){
                    document.getElementById('dtmf').style.display = 'block'
                    document.getElementById('hangup').style.display = 'block'
                    document.getElementById('mute').style.display = 'block'
                    document.getElementById('hold').style.display = 'block'
                    document.getElementById('threeCall').style.display = 'block'
                    document.getElementById('consulting').style.display = 'block'
                    document.getElementById('transfer').style.display = 'block'
                    document.getElementById('dtmf').style.display = 'block'
                    document.getElementById('satisfaction').style.display = 'block'
                    document.getElementById('toVideo').style.display = 'block'
                    document.getElementById('pickup').style.display = 'none'
                    if (window.hideWindow){
                        window.hideWindow()
                    }
                    if (window.goPage){
                        let param = backMsg
                        param.uuid = nowUuid
                        param.type = callType=='callin'?1:2  //呼入1  呼出2
                        param.phonenum = callingPhone
                        param.companyCustomFromId = setParam.companyCustomFromId;
                        window.goPage(param)
                    }
                    callin_channel = ''
                } else {
                    document.getElementById('await').style.display = 'none'
                    document.getElementById('calloutWait').style.display = 'none'
                    $('.center_btns_wrap .can_click').show();
                    $('.center_btns_wrap .forbid_click').hide();
                    $('#closeMic').hide()
                    $('#closeVideo').hide()
                }
            }
            if (backMsg.phase == 'END_CALL' && backMsg.action == 'TRANS' ){
                if (hasVideo){
                    document.getElementById('calloutWait').style.display = 'none'
                } else {
                    document.getElementById('mute').style.display = 'block'
                    document.getElementById('showDiv').style.display = 'none'
                    document.getElementById('hold').style.display = 'block'
                    document.getElementById('threeCall').style.display = 'block'
                    document.getElementById('consulting').style.display = 'block'
                    document.getElementById('transfer').style.display = 'block'
                    document.getElementById('transferCancel').style.display = 'none'
                    document.getElementById('satisfaction').style.display = 'block'
                    document.getElementById('toVideo').style.display = 'block'
                }
            }
            if (backMsg.phase == 'END_CALL' && backMsg.action == 'CONSULT'){
                if (nowStatus=='CALLING'){
                    if (hasVideo){
                        document.getElementById('calloutWait').style.display = 'none'
                    } else {
                        document.getElementById('showDiv').style.display = 'none'
                        document.getElementById('mute').style.display = 'block'
                        document.getElementById('hold').style.display = 'block'
                        document.getElementById('threeCall').style.display = 'block'
                        document.getElementById('consulting').style.display = 'block'
                        document.getElementById('transfer').style.display = 'block'
                        document.getElementById('consultingCancel').style.display = 'none'
                        document.getElementById('trans').style.display = 'none'
                        document.getElementById('satisfaction').style.display = 'block'
                        document.getElementById('toVideo').style.display = 'block'
                    }
                }
            } else if (backMsg.phase == 'START_CALL' && backMsg.action == 'CONSULT'){
                document.getElementById('waitText').innerHTML = i18ntc('咨询通话')
                document.getElementById('trans').style.display = 'block'
            }
            // 0: 坐席发起音视频切换请求<br />1: 坐席发起音视频切换请求, 对方接通情况<br />2: 音视频切换应答(坐席视频外呼, 对方接通情况; 手机侧切换音视频 )
            if (backMsg.action == 'CHANGE_MEDIA' && backMsg.change_media_flag == '1'){
                if (backMsg.last_video == '0' && backMsg.video == '0'){
                    changeMedia('audio')
                    callBackAudio()
                    toastMessage(i18ntc('对方拒绝视频通话'))
                } else if (backMsg.last_video == '0' && backMsg.video == '3'){
                    $('#calloutWait').hide()
                    $('.center_btns_wrap .can_click').show();
                    $('.center_btns_wrap .forbid_click').hide();
                    $('#closeMic').hide()
                    $('#closeVideo').hide()
                }
            }
            if (backMsg.action == 'CHANGE_MEDIA' && backMsg.change_media_flag == '2'){
                videoStatus = backMsg.video
                if (backMsg.video == '3'){
                    document.getElementById('mute').style.display = 'none'
                    document.getElementById('hold').style.display = 'none'
                    document.getElementById('threeCall').style.display = 'none'
                    document.getElementById('consulting').style.display = 'none'
                    document.getElementById('transfer').style.display = 'none'
                    document.getElementById('dtmf').style.display = 'none'
                    document.getElementById('satisfaction').style.display = 'none'
                    document.getElementById('toVideo').style.display = 'none'
                    document.getElementById('pickup').style.display = 'none'
                    document.getElementById('hangup').style.display = 'none'
                    document.getElementById('main_center_wrap').style.display = 'block'
                    dragDom($('#main_center_wrap'))
                    if (window.hideWindow){
                        window.hideWindow()
                    }
                } else {
                    document.getElementById('mute').style.display = 'block'
                    document.getElementById('hold').style.display = 'block'
                    document.getElementById('threeCall').style.display = 'block'
                    document.getElementById('consulting').style.display = 'block'
                    document.getElementById('transfer').style.display = 'block'
                    document.getElementById('dtmf').style.display = 'block'
                    document.getElementById('satisfaction').style.display = 'block'
                    document.getElementById('toVideo').style.display = 'block'
                    document.getElementById('hangup').style.display = 'block'
                    document.getElementById('main_center_wrap').style.display = 'none'
                    toastMessage(i18ntc('对方已切换语音通话'))
                }
            }
            if (backMsg.action == 'CALL' && !backMsg.success){
                toastMessage(backMsg.msg)
            }
            //录音相关
            if (backMsg.action == 'PLAY_RECORD'){
                if (backMsg.success && window.startRecording){
                    startRecording()
                }
            }
            // 咨询转转接
            if (backMsg.action == 'CONSULT_TO_TRANS'){
                document.getElementById('mute').style.display = 'block'
                document.getElementById('showDiv').style.display = 'none'
                document.getElementById('hold').style.display = 'block'
                document.getElementById('threeCall').style.display = 'block'
                document.getElementById('consulting').style.display = 'block'
                document.getElementById('transfer').style.display = 'block'
                document.getElementById('transferCancel').style.display = 'none'
                document.getElementById('satisfaction').style.display = 'block'
                document.getElementById('toVideo').style.display = 'block'
                callingPhone = backMsg.in_call_numbers[0]
                if (window.goPage){
                    let param = backMsg
                    param.uuid = nowUuid
                    param.type = 1
                    param.phonenum = callingPhone
                    param.companyCustomFromId = setParam.companyCustomFromId;
                    window.goPage(param)
                }
            }
        break
        case 'hangup':
            if (backMsg.code == '0'){
                hideDomTree()
                if (window.stopRecordingPlay){
                    stopRecordingPlay()
                }
                handleSeatABoxHangUp();
            } else {
                toastMessage(backMsg.msg)
            }
        break
        case 'agent_hangup':
            handleSeatABoxHangUp();
        break
        case 'change_media':
            if (backMsg.code == '0'){
                if (backMsg.video == '3'){
                    document.getElementById('mute').style.display = 'none'
                    document.getElementById('hold').style.display = 'none'
                    document.getElementById('threeCall').style.display = 'none'
                    document.getElementById('consulting').style.display = 'none'
                    document.getElementById('transfer').style.display = 'none'
                    document.getElementById('dtmf').style.display = 'none'
                    document.getElementById('satisfaction').style.display = 'none'
                    document.getElementById('toVideo').style.display = 'none'
                    document.getElementById('pickup').style.display = 'none'
                    document.getElementById('hangup').style.display = 'none'
                    document.getElementById('main_center_wrap').style.display = 'block'
                    dragDom($('#main_center_wrap'))
                    if (window.hideWindow){
                        window.hideWindow()
                    }
                } else {
                    document.getElementById('mute').style.display = 'block'
                    document.getElementById('hold').style.display = 'block'
                    document.getElementById('threeCall').style.display = 'block'
                    document.getElementById('consulting').style.display = 'block'
                    document.getElementById('transfer').style.display = 'block'
                    document.getElementById('dtmf').style.display = 'block'
                    document.getElementById('satisfaction').style.display = 'block'
                    document.getElementById('toVideo').style.display = 'block'
                    document.getElementById('hangup').style.display = 'block'
                    document.getElementById('main_center_wrap').style.display = 'none'
                }
            }
        break
        case 'callin':
            try{
                setAsrMyUuid(backMsg.uuid);
                setAsrCustomUuid(backMsg.client_uuid);
            }catch(res){}
            callee_number = backMsg.callee_number
            document.getElementById('screen_left_id').innerHTML = backMsg.caller_number
            document.getElementById('small_win_left_id').innerHTML = agent_id
            document.getElementById('caller').innerHTML = backMsg.caller_number
            document.getElementById('inputNum').value = isDesensitization(backMsg.caller_number)
            callin_channel = backMsg.callin_channel
            callee_number = backMsg.callee_number
            if (backMsg.video != 0){
                if (setParam && setParam.videoCallAnswerMode == '1'){
                    document.getElementById('main_center_wrap').style.display = 'none'
                    hasVideo = false
                } else {
                    hasVideo = true
                    if (setParam && setParam.videoCallTurnOffCamera == '1'){
                        hasVideo = false
                        document.getElementById('closeVideo').style.display = 'block'
                        document.getElementById('openVideo').style.display = 'none'
                    }
                    document.getElementById('main_center_wrap').style.display = 'block'
                    dragDom($('#main_center_wrap'))
                }
            } else {
                hasVideo = false
            }
        break
        case 'get_status':
            if (backMsg.code == '0' && backMsg.status != 'OFFLINE'){
                if (!isCheckIn){
                    if (['FREE','BUSY','REST'].includes(backMsg.status)){
                        signIn(backMsg.status)
                    } else {
                        signIn('BUSY')
                    }
                }
            } else if (backMsg.code == '0' && backMsg.status == 'OFFLINE'){
                hideDomTree()
                document.getElementById('note').innerHTML = i18ntc('离线')
                if (audioTimer){
                    cleanTime('1')
                }
                isCheckIn = false
            }
        break
        case 'checkin':
            if (backMsg.code == '0'){
                isCheckIn = true
                if (backMsg.service_mode == '1'){
                    //客服
                    document.getElementById('sitetypeImg').setAttribute('src',resourceUrl + "/images/strip/customer.png")
                    document.getElementById('sitetypeNow').innerHTML = i18ntc('客服型')
                } else if (backMsg.service_mode == '2'){
                    //外呼
                    document.getElementById('sitetypeImg').setAttribute('src',resourceUrl + "/images/strip/bound.png")
                    document.getElementById('sitetypeNow').innerHTML = i18ntc('外呼型')
                }
                document.getElementById('more').style.display = 'block'
                document.getElementById('inputNum').disabled = false
                document.getElementById('sitetype').style.visibility = 'visible'
            } else if (backMsg.code == '1004'){
                toastMessage(backMsg.msg)
                document.getElementById('extBox').style.display = 'flex'
            } else {
                toastMessage(backMsg.msg)
            }
        break
        case 'checkout':
            if (backMsg.code == '0'){
                isCheckIn = false
                hideDomTree()
                document.getElementById('note').innerHTML = i18ntc('离线')
                document.getElementById('more').style.display = 'none'
                document.getElementById('inputNum').disabled = true
                document.getElementById('keyModel').style.display = 'none'
                document.getElementById('sitetype').style.visibility = 'hidden'
            } else {
                toastMessage(backMsg.msg)
            }
            if (audioTimer){
                cleanTime('1')
            }
        break
        case 'kick_off':
            if (backMsg.code == '0'){
                hideDomTree()
                document.getElementById('note').innerHTML = i18ntc('离线')
                document.getElementById('inputNum').disabled = true
                document.getElementById('keyModel').style.display = 'none'
                document.getElementById('sitetype').style.visibility = 'hidden'
                document.getElementById('play_calling').pause()
                document.getElementById('play_calling').currentTime = 0;
                toastMessage(backMsg.msg)
                if (audioTimer){
                    cleanTime('1')
                }
            }
        break;
        case 'call':
            try{
                setAsrMyUuid(backMsg.uuid);
            }catch(res){}
            if (backMsg.code == '0'){
                if (window.callSuccess){
                    window.callSuccess()
                }
            } else if (backMsg.code == '1'){
                toastMessage(backMsg.msg)
                document.getElementById('main_center_wrap').style.display = 'none'
            } else {
                document.getElementById('main_center_wrap').style.display = 'none'
            }
        break
        case 'consult':
            if (backMsg.code == '0'){
                if (backMsg.msg.includes('发起咨询成功')){
                    if(hasVideo){
                        document.getElementById('calloutWait').style.display = 'flex'
                        document.getElementById('calloutText').innerHTML = document.getElementById('callPhone').value
                        document.getElementById('waitText').innerHTML = i18ntc('咨询呼叫')
                    } else {
                        document.getElementById('mute').style.display = 'none'
                        document.getElementById('hold').style.display = 'none'
                        document.getElementById('threeCall').style.display = 'none'
                        document.getElementById('consulting').style.display = 'none'
                        document.getElementById('transfer').style.display = 'none'
                        document.getElementById('toVideo').style.display = 'none'
                        document.getElementById('showDiv').style.display = 'block'
                        document.getElementById('showDiv').innerHTML =  i18ntc('咨询呼叫') + '：' + document.getElementById('callPhone').value
                        document.getElementById('consultingCancel').style.display = 'block'
                        document.getElementById('satisfaction').style.display = 'none'
                    }
                } else if (backMsg.msg.includes('取消咨询成功')){
                    if (hasVideo){
                        document.getElementById('calloutWait').style.display = 'none'
                    } else {
                        document.getElementById('showDiv').style.display = 'none'
                        document.getElementById('mute').style.display = 'block'
                        document.getElementById('hold').style.display = 'block'
                        document.getElementById('threeCall').style.display = 'block'
                        document.getElementById('consulting').style.display = 'block'
                        document.getElementById('transfer').style.display = 'block'
                        document.getElementById('consultingCancel').style.display = 'none'
                        document.getElementById('satisfaction').style.display = 'block'
                        document.getElementById('toVideo').style.display = 'block'
                        document.getElementById('trans').style.display = 'none'
                    }
                }
            } else {
                toastMessage(backMsg.msg)
            }
        break
        case 'trans':
            if (backMsg.code == '0'){
                if (backMsg.msg.includes('发起咨询转成功')){
                    if (hasVideo){
                        document.getElementById('calloutWait').style.display = 'flex'
                        document.getElementById('calloutText').innerHTML = document.getElementById('callPhone').value
                        document.getElementById('waitText').innerHTML = i18ntc('转接呼叫')
                    } else {
                        document.getElementById('showDiv').style.display = 'block'
                        document.getElementById('showDiv').innerHTML = i18ntc('转接呼叫') + '：' + document.getElementById('callPhone').value
                        document.getElementById('mute').style.display = 'none'
                        document.getElementById('hold').style.display = 'none'
                        document.getElementById('threeCall').style.display = 'none'
                        document.getElementById('consulting').style.display = 'none'
                        document.getElementById('transfer').style.display = 'none'
                        document.getElementById('transferCancel').style.display = 'block'
                        document.getElementById('satisfaction').style.display = 'none'
                        document.getElementById('toVideo').style.display = 'none'
                    }
                } else if (backMsg.msg.includes('咨询转取消成功')){
                    if (hasVideo){
                        document.getElementById('calloutWait').style.display = 'none'
                    } else {
                        document.getElementById('mute').style.display = 'block'
                        document.getElementById('showDiv').style.display = 'none'
                        document.getElementById('hold').style.display = 'block'
                        document.getElementById('threeCall').style.display = 'block'
                        document.getElementById('consulting').style.display = 'block'
                        document.getElementById('transfer').style.display = 'block'
                        document.getElementById('transferCancel').style.display = 'none'
                        document.getElementById('satisfaction').style.display = 'block'
                        document.getElementById('toVideo').style.display = 'block'
                    }
                }
            } else {
                toastMessage(backMsg.msg)
            }
        break
        case 'three_way':
            if (backMsg.code == '0'){
                document.getElementById('showDiv').style.display = 'block'
                if (backMsg.in_call_numbers){
                    document.getElementById('showDiv').innerHTML = i18ntc('三方通话') + '：' + cutPhone(backMsg.in_call_numbers[0]) + '和' + cutPhone(backMsg.in_call_numbers[1])
                }
                document.getElementById('mute').style.display = 'none'
                document.getElementById('hold').style.display = 'none'
                document.getElementById('threeCall').style.display = 'none'
                document.getElementById('consulting').style.display = 'none'
                document.getElementById('transfer').style.display = 'none'
                document.getElementById('satisfaction').style.display = 'none'
                document.getElementById('toVideo').style.display = 'none'
                document.getElementById('dtmf').style.display = 'none'
            } else {
                toastMessage(backMsg.msg)
            }
        break
        case 'hold':
            if (backMsg.code == '0'){
                if (backMsg.hold == '1'){
                    //当前保持
                    document.getElementById('hold').style.display = 'none'
                    document.getElementById('holdCancel').style.display = 'block'
                } else {
                    document.getElementById('holdCancel').style.display = 'none'
                    document.getElementById('hold').style.display = 'block'
                }
            } else {
                toastMessage(backMsg.msg)
            }
        break
        case 'mute':
            if (backMsg.code == '0'){
                if (backMsg.mute == '1'){
                    //当前保持
                    document.getElementById('mute').style.display = 'none'
                    document.getElementById('muteCancel').style.display = 'block'
                } else {
                    document.getElementById('mute').style.display = 'block'
                    document.getElementById('muteCancel').style.display = 'none'
                }
            } else {
                toastMessage(backMsg.msg)
            }
        break
        case 'video':
            if (backMsg.code == '0'){
                if (backMsg.video == '1'){
                    //当前保持
                    document.getElementById('openVideo').style.display = 'none'
                    document.getElementById('closeVideo').style.display = 'block'
                } else {
                    document.getElementById('closeVideo').style.display = 'block'
                    document.getElementById('openVideo').style.display = 'none'
                }
            } else {
                toastMessage(backMsg.msg)
            }
        break
        case 'toggle_service_mode':
            if (backMsg.code == '0'){
                if (backMsg.service_mode == '1'){
                    //客服
                    document.getElementById('sitetypeImg').setAttribute('src',resourceUrl + "/images/strip/customer.png")
                    document.getElementById('sitetypeNow').innerHTML = i18ntc('客服型')
                    toastMessage(i18ntc('已切换至客服型，处于空闲状态将分配人工服务组的话务'))
                } else {
                    //外呼
                    document.getElementById('sitetypeImg').setAttribute('src',resourceUrl + "/images/strip/bound.png")
                    document.getElementById('sitetypeNow').innerHTML = i18ntc('外呼型')
                    toastMessage(i18ntc('已切换至外呼型，处于空闲状态将分配外呼任务的话务'))
                }
            } else {
                toastMessage(backMsg.msg)
            }
        break
        case 'asr_online':
            if (backMsg.code == '0'){
                if(asrMyUuid || asrCustomUuid) {
                    if(backMsg.type == 'quality_check') {
                        let data = backMsg.src_text ? JSON.parse(backMsg.src_text) : {};
                        getQualityCheck(data);
                        if(!seatABoxQualityCheckHistory[defaultUserCallUuid]) {
                            seatABoxQualityCheckHistory[defaultUserCallUuid] = {
                                qualityCheckObj: data,
                            };
                        }else{
                            seatABoxQualityCheckHistory[defaultUserCallUuid].qualityCheckObj = data;
                        }
                    }else{
                        if(!defaultUserCallUuid) {
                            setSeatAssistantBoxPannelRightEmptyFun();
                            defaultUserCallUuid = generateUUID();
                        }
                        // 删除首个不合理符号
                        let symbolList = [",",".","?","!",";",":","，","。","？","！","；","：",];
                        let src_text = backMsg.src_text;
                        if(src_text) {
                            let firstTxt = src_text.substring(0,1);
                            if (symbolList.includes(firstTxt)) {
                                src_text = src_text.substring(1);
                            }
                        }
                        backMsg.src_text = src_text;
            
                        let trans_text = backMsg.trans_text;
                        if(trans_text) {
                            let firstTxt = trans_text.substring(0,1);
                            if (symbolList.includes(firstTxt)) {
                                trans_text = trans_text.substring(1);
                            }
                        }
                        backMsg.trans_text = trans_text;
                    //去掉译文双引号
                        //   let trans_text = backMsg.trans_text;
                        //   if(trans_text.substring(0,1) == '"') {
                        //     trans_text = trans_text.substring(1);
                        //   }
                        //   if(trans_text.substring(trans_text.length-1) == '"') {
                        //     trans_text = trans_text.substring(0, trans_text.length-1);
                        //   }
                        //   backMsg.trans_text = trans_text;
                        handleSeatABoxUserList(backMsg);
                        if (backMsg.type == 'client' && backMsg.src_text){
                            let content = backMsg.src_text;
                            if(content) {
                                getTextExtraction(content)
                                getKnowhistorySearch(content)
                            }
                        }
                        if(!seatABoxQualityCheckHistory[defaultUserCallUuid]) {
                            seatABoxQualityCheckHistory[defaultUserCallUuid] = {};
                        }
                        if(asrMyUuid) {
                            seatABoxQualityCheckHistory[defaultUserCallUuid].asrMyUuid = asrMyUuid;
                        }
                        if(asrCustomUuid) {
                            seatABoxQualityCheckHistory[defaultUserCallUuid].asrCustomUuid = asrCustomUuid;
                        }
                    }
                }
            }
        break
    }
}
function createDom(){
    let domArr = [...note,...inputArr,...btnkeys]
    let noteChildArr = [...noteChild]
    for (let i=0;i<domArr.length;i++){
        let dom = document.createElement(domArr[i].type)
        dom.id = domArr[i].id
        dom.setAttribute('class',domArr[i].class)
        // dom.innerHTML = domArr[i].txt
        document.getElementById('strip').appendChild(dom)
    }
    for (let j=0;j<noteChildArr.length;j++){
        let dom = document.createElement(noteChildArr[j].type)
        dom.id = noteChildArr[j].id
        dom.setAttribute('class',noteChildArr[j].class)
        dom.innerHTML = noteChildArr[j].txt
        document.getElementById('notes').appendChild(dom)
    }
    for (let i=0;i<btnkeys.length;i++){
        var img = document.createElement('img')
        var span = document.createElement('span')
        // span.innerHTML = btnkeys[i].txt
        span.innerHTML = btnkeys[i].txt
        // span.setAttribute('class','i18n')
        span.setAttribute('class','i18nFromOritxt')
        span.setAttribute('data-oritxt',btnkeys[i].txt)
        img.src = `${resourceUrl}/images/strip/${btnkeys[i].id}.png`
        document.getElementById(btnkeys[i].id).appendChild(img)
        document.getElementById(btnkeys[i].id).appendChild(span)
    }
    createdSitetype()
    createdKeyBoard()
    createdInputBox()
    createdSetBox()
    createdDetectionBox()
    createdVideoBox()
    createdMore()
    createdSure()
    createdReset()
    createdRest()
    createdSignout()
    createdExt()
    createdTips()
    createdTimeOut()
    createdSeatAssistantBox()
    createKnowledgeModal()
    createdChangeWorkOrder()
    addListenNotes()
    // handleOpenVideoCall();
    setTimeout(() => {
        setLang()
    }, 1000)
}

function handleOpenVideoCall() {
    if (!videoCall){
        if(document.getElementById('toVideo')) {
            document.getElementById('toVideo').style.visibility = 'hidden'
            document.getElementById('toVideo').style.width = '0px'
        }
        const startCallElement = document.getElementById('startCall');
        if (startCallElement.children.length >= 3) {
            // 设置第二个和第三个div的display为none
            if(startCallElement.children[1]) {
                startCallElement.children[1].style.visibility = 'hidden';
                startCallElement.children[1].style.width = '0px'
            }
            if(startCallElement.children[2]) {
                startCallElement.children[2].style.visibility = 'hidden';
                startCallElement.children[2].style.width = '0px'
            }
        }
    }
}

// 创建更多
function createdMore(){
    let str = ''
    str+= `<span id="reset" class="i18n">复位</span>`
    str+= '<span id="detection" class="i18n">设备检测</span>'
    document.getElementById('showMore').innerHTML = str
}
function createdSitetype(){
    let str = ''
    str+= `
    <div class='topCall' id='topCall'><img src="${resourceUrl}/images/strip/customer.png " alt="" id="sitetypeImg"><span id="sitetypeNow" class="i18n">外呼型</span><img src="${resourceUrl}/images/strip/down.png " alt="" id="sitetypeArrow"></div>
    <div class="customerDiv" id='customerDiv'>
        <div class="customerClass" id='toggleMode1'><img src="${resourceUrl}/images/strip/bound.png " alt="" id="sitetypeImg"><span class="i18n">外呼型</span><img src="${resourceUrl}/images/strip/gth.png" id='sitetypetips1'></div>
        <div class="customerClass" style="border-top:1px solid #efefef" id='toggleMode2'><img src="${resourceUrl}/images/strip/customer.png " alt="" id="sitetypeImg"><span class="i18n">客服型</span><img src="${resourceUrl}/images/strip/gth.png" id='sitetypetips2'></div>
        <div class="sitetypetipsText" id='sitetypetipsText1'><span class="i18n">外呼型</span><span class="i18n">外呼模式，将分配预测外呼的任务号码；</span><span class="i18n">所有的呼入来电，包含IVR服务、人工服务的来电都不会分配给外呼模式。</span></div>
        <div class="sitetypetipsText" id='sitetypetipsText2'><span class="i18n">客服型</span><span class="i18n">将分配呼入的来电，包含IVR服务、人工服务的来电；</span><span class="i18n">所有的预测外呼的任务号码都不会分配给客服模式。</span></div>
        </div>
    `
    document.getElementById('sitetype').innerHTML = str
}
// 创建输入键盘
function createdKeyBoard(){
    let str = ''
    str += `<img src="${resourceUrl}/images/strip/keyboard.png " alt="" class="stripPng">`
    str += `<input id="inputNum" value="" autocomplete="off" class="inputNum i18nInput" placeholder="${i18ntc('请输入')}" disabled>`
    str += '<div id="keyModel">'
    str += `<div class="moadlTop"><div class="moadlTopLeft" id='moadlTopLeft'><img alt="" id='closeMoadl' src="${resourceUrl}/images/strip/closeMoadl.png" /></div><div class="moadlTopRight"><img alt="" id='openModal' src="${resourceUrl}/images/strip/openModal.png" /><img alt="" id='closekeyModel' src="${resourceUrl}/images/close.png" /></div></div>`
    str += '<div class="numberHistoryDiv" id="numberHistoryDiv"><span class="i18n">最近通话</span><div id="numberHistory"></div></div><div id="board"><span>1</span><span>2</span><span>3</span><span>4</span><span>5</span><span>6</span><span>7</span><span>8</span><span>9</span><span>*</span><span>0</span><span>#</span><div id="startCall"><div value="1"><img alt="" class="operation_item_img" src='+ resourceUrl +'/images/icons/phone.png value="1"/><span value="1" class="i18n">语音</span></div><div value="2"><img alt="" class="operation_item_img" value="2" src=' + resourceUrl + '/images/icons/video.png /><span value="2">480P</span></div><div value="3"><img alt="" class="operation_item_img" value="3" src='+ resourceUrl + '/images/icons/video.png /><span value="3">720P</span></div></div></div></div>'
    document.getElementById('numberKeyBoard').innerHTML = str
}
// 创建转接、咨询、会议、二次拨号框
function createdInputBox(){
    let str = ''
    str += '<div id="closeInputBox" style="background:url(' + resourceUrl + '/images/close.png)"></div>'
    str += `<div class="boxInputTitle" id="boxInputTitle" ><span id="callText" class="i18n">呼叫类型：</span><select id="callType"  class="boxInput" value="">
                <option class="i18n" value="1">呼叫坐席</option>
                <option class="i18n" value="4">外线号码</option>
                <option class="i18n" value="2" id="queue">人工服务</option>
                <option class="i18n" value="3" id="toivr">IVR服务</option>
            </select></div>`
    str += '<div class="boxInputTitle"><span id="siteText" class="i18n">坐席搜索：</span><input id="callPhone"  class="boxInput" value="" autocomplete="off"></div>'
    str += '<div id="otherBoard"><span>1</span><span>2</span><span>3</span><span>4</span><span>5</span><span>6</span><span>7</span><span>8</span><span>9</span><span>*</span><span>0</span><span>#</span></div></div>'
    str += '<div id="ivrlist">'

    str += '</div>'
    str += '<div id="siteTree">'
    str += '</div>'
    str += '<div id="otherCall"><img  src ="' + resourceUrl + '/images/call.png" id="otherCallImg"><span id="otherCallText" class="i18n">语音</span></div>'
    document.getElementById('inputBox').innerHTML = str
}
// 创建检测弹窗
function createdDetectionBox(){
    let str = ''
    let vristr = ''
    let videostr = ''
    str = `<!-- 基础检测弹窗 -->
        <div class="basic_monitor_wrap">
            <div class="basic_monitor_close i18n" onclick="basic_monitor_hide()">跳过检测</div>
            <!-- 1 -->
            <div class="basic_one_wrap">
                <div class="basic_monitor_header i18n">设备连接</div>
                <div class="normal_form_header_line"></div>
                <div class="basic_one_title i18n">设备检测前请确认设备连接了摄像头、麦克风、扬声器和网络</div>
                <div class="basic_one_center">
                    <div class="basic_one_center_item">
                        <img alt="" class="basic_one_center_item_icon" src="${resourceUrl}/images/monitor/camera_1.png" />
                        <img alt="" class="basic_one_center_item_check basic_one_camera" src="${resourceUrl}/images/monitor/check.png" />
                    </div>
                    <div class="basic_one_center_item">
                        <img alt="" class="basic_one_center_item_icon" src="${resourceUrl}/images/monitor/mic_1.png" />
                        <img alt="" class="basic_one_center_item_check basic_one_microphone" src="${resourceUrl}/images/monitor/check.png" />
                    </div>
                    <div class="basic_one_center_item">
                        <img alt="" class="basic_one_center_item_icon" src="${resourceUrl}/images/monitor/speaker_1.png" />
                        <img alt="" class="basic_one_center_item_check basic_one_speaker" src="${resourceUrl}/images/monitor/check.png" />
                    </div>
                    <div class="basic_one_center_item">
                        <img alt="" class="basic_one_center_item_icon" src="${resourceUrl}/images/monitor/net_1.png" />
                        <img alt="" class="basic_one_center_item_check basic_one_network" src="${resourceUrl}/images/monitor/check.png" />
                    </div>
                </div>
                <div class="basic_one_footer_tip i18n">设备及网络连接成功，请开始设备检测</div>
                <div class="basic_one_footer">
                    <div onclick="start_basic_monitor()" class="basic_one_footer_btn i18n">开始检测</div>
                </div>
            </div>
            <div class="basic_progress_header_wrap" style="display: none;">
                <div class="basic_progress_header_item basic_camera_icon active">
                    <img alt="" class="basic_progress_header_item_icon" src="${resourceUrl}/images/monitor/camera_2.png" />
                    <div class="basic_progress_header_item_txt">CAMERA</div>
                </div>
                <div class="basic_progress_header_item_line basic_camera_line"></div>
                <div class="basic_progress_header_item basic_microphone_icon">
                    <img alt="" class="basic_progress_header_item_icon" src="${resourceUrl}/images/monitor/mic_4.png" />
                    <div class="basic_progress_header_item_txt">MICROPHONE</div>
                </div>
                <div class="basic_progress_header_item_line basic_microphone_line"></div>
                <div class="basic_progress_header_item basic_speaker_icon">
                    <img alt="" class="basic_progress_header_item_icon" src="${resourceUrl}/images/monitor/speaker_4.png" />
                    <div class="basic_progress_header_item_txt">SPEAKER</div>
                </div>
                <div class="basic_progress_header_item_line basic_speaker_line"></div>
                <div class="basic_progress_header_item basic_network_icon">
                    <img alt="" class="basic_progress_header_item_icon" src="${resourceUrl}/images/monitor/net_4.png" />
                    <div class="basic_progress_header_item_txt">NETWORK</div>
                </div>
            </div>

            <!-- 2 -->
            <div class="basic_two_wrap" style="display: none;">
                <div class="basic_two_center">
                    <div class="basic_two_select_wrap">
                        <div class="basic_selecct_row_title i18n">摄像头选择</div>
                        <div class="basic_normal_select_item">
                            <div class="basic_normal_select_input_wrap">
                                <div class="basic_normal_select_container">
                                    
                                    <input class="basic_normal_select_input" id="basic_camera_select_wrap" type="text" readonly="readonly" onfocus="this.nextSibling.nextSibling.style.display='block';"
                                        onblur="var t=this;setTimeout(()=>{t.nextSibling.nextSibling.style.display='none';},150);" placeholder="" />
                                    <ul class="basic_camera_select">
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="basic_two_camera_wrap">
                        <div class="basic_two_video_wrap"></div>
                    </div>
                    <div class="basic_two_center_tip i18n">是否可以看清楚自己？</div>
                </div>
                <div class="basic_two_footer">
                    <div onclick="camera_available_click(false)" class="basic_two_footer_btn i18n">看不到</div>
                    <div onclick="camera_available_click(true)" class="basic_two_footer_btn basic_two_confirm_btn i18n">看的到</div>
                </div>
            </div>

            <!-- 3 -->
            <div class="basic_three_wrap" style="display: none;">
                <div class="basic_three_center">
                    <div class="basic_three_select_wrap">
                        <div class="basic_selecct_row_title i18n">麦克风选择</div>
                        <div class="basic_normal_select_item">
                            <div class="basic_normal_select_input_wrap">
                                <div class="basic_normal_select_container">
                                    <input class="basic_normal_select_input" id="basic_microphone_select_wrap" type="text" readonly="readonly" onfocus="this.nextSibling.nextSibling.style.display='block';"
                                        onblur="var t=this;setTimeout(()=>{t.nextSibling.nextSibling.style.display='none';},150);" placeholder="" />
                                    <ul class="basic_microphone_select">
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="basic_three_microphone_wrap">
                        <div class="basic_three_video_wrap">
                            <div class="basic_three_audio_dom" style="display: none;"></div>
                            <div class="basic_three_video_tip i18n">对着麦克风说哈喽试试~</div>
                            <div class="basic_three_video_icon_wrap">
                                <img alt="" class="basic_three_video_icon" src="${resourceUrl}/images/icons/volume_img_sprites.png" />
                            </div>
                        </div>
                    </div>
                    <div class="basic_three_center_tip i18n">是否可以看到音量图标跳动？</div>
                </div>
                <div class="basic_three_footer">
                    <div onclick="microphone_available_click(false)" class="basic_three_footer_btn i18n">看不到</div>
                    <div onclick="microphone_available_click(true)" class="basic_three_footer_btn basic_three_confirm_btn i18n">看的到</div>
                </div>
            </div>

            <!-- 4 -->
            <div class="basic_four_wrap" style="display: none;">
                <div class="basic_four_center">
                    <div class="basic_four_select_wrap">
                        <div class="basic_selecct_row_title i18n">扬声器选择</div>
                        <div class="basic_normal_select_item">
                            <div class="basic_normal_select_input_wrap">
                                <div class="basic_normal_select_container">
                                    
                                    <input class="basic_normal_select_input" id="basic_speaker_select_wrap" type="text" readonly="readonly" onfocus="this.nextSibling.nextSibling.style.display='block';"
                                        onblur="var t=this;setTimeout(()=>{t.nextSibling.nextSibling.style.display='none';},150);" placeholder="" />
                                    <ul class="basic_speaker_select">
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="basic_four_speaker_wrap">
                        <div class="basic_four_audio_wrap">
                            <div class="basic_four_audio_tip i18n">请调高设备音量，点击播放下面的音频试试~</div>
                            <audio id="basic_four_audio" controlsList="nodownload nofullscreen noremoteplayback noplaybackrate" src="${resourceUrl}/audio/piano_music.wav" controls></audio>
                        </div>
                    </div>
                    <div class="basic_four_center_tip i18n">是否可以听到声音？</div>
                </div>
                <div class="basic_four_footer">
                    <div onclick="speaker_available_click(false)" class="basic_four_footer_btn i18n">听不到</div>
                    <div onclick="speaker_available_click(true)" class="basic_four_footer_btn basic_four_confirm_btn i18n">听的到</div>
                </div>
            </div>

            <!-- 5 -->
            <div class="basic_five_wrap" style="display: none;">
                <div class="basic_five_center">
                    <div class="basic_five_item">
                        <div class="basic_five_item_tilte i18n">操作系统</div>
                        <div class="basic_five_item_txt check_system"></div>
                    </div>
                    <div class="basic_five_item">
                        <div class="basic_five_item_tilte i18n">浏览器</div>
                        <div class="basic_five_item_txt check_browser"></div>
                    </div>
                    <div class="basic_five_item">
                        <div class="basic_five_item_tilte i18n">是否支持WEBRTC</div>
                        <div class="basic_five_item_txt check_trtc"></div>
                    </div>
                    <div class="basic_five_item">
                        <div class="basic_five_item_tilte i18n">是否支持屏幕分享</div>
                        <div class="basic_five_item_txt check_share_screen"></div>
                    </div>
                    <div class="basic_five_item">
                        <div class="basic_five_item_tilte i18n">网络延时</div>
                        <div class="basic_five_item_txt check_network_delay"></div>
                    </div>
                    <div class="basic_five_item">
                        <div class="basic_five_item_tilte i18n">上行网络质量</div>
                        <div class="basic_five_item_txt check_downlink"></div>
                    </div>
                    <div class="basic_five_item">
                        <div class="basic_five_item_tilte i18n">下行网络质量</div>
                        <div class="basic_five_item_txt check_downlink"></div>
                    </div>
                </div>
                <div class="basic_five_btn_wrap">
                    <div class="basic_five_btn"><span class="i18n">剩余检测时间</span>(<span class="remaining_detection_time">7</span>)s</div>
                    <div onclick="view_check_report()" class="basic_five_btn_next i18n">查看检测报告</div>
                </div>
            </div>

            <!-- 6 -->
            <div class="basic_six_wrap" style="display: none;">
                <div class="basic_six_header">
                    <div class="basic_six_header_txt i18n">检测报告</div>
                </div>
                <div class="basic_six_center">
                    <div class="basic_six_item">
                        <div class="basic_six_item_left">
                            <img alt="" class="basic_six_item_icon" src="${resourceUrl}/images/monitor/camera_1.png" />
                            <div class="basic_six_item_title basic_six_camera"></div>
                        </div>
                        <div class="basic_six_item_status basic_six_camera_status"></div>
                    </div>
                    <div class="basic_six_item">
                        <div class="basic_six_item_left">
                            <img alt="" class="basic_six_item_icon" src="${resourceUrl}/images/monitor/mic_1.png" />
                            <div class="basic_six_item_title basic_six_microphone"></div>
                        </div>
                        <div class="basic_six_item_status basic_six_microphone_status"></div>
                    </div>
                    <div class="basic_six_item">
                        <div class="basic_six_item_left">
                            <img alt="" class="basic_six_item_icon" src="${resourceUrl}/images/monitor/speaker_1.png" />
                            <div class="basic_six_item_title basic_six_speaker"></div>
                        </div>
                        <div class="basic_six_item_status basic_six_speaker_status"></div>
                    </div>
                    <div class="basic_six_item">
                        <div class="basic_six_item_left">
                            <img alt="" class="basic_six_item_icon" src="${resourceUrl}/images/monitor/net_1.png" />
                            <div class="basic_six_item_title i18n">网络延迟</div>
                        </div>
                        <div class="basic_six_item_status basic_six_net"></div>
                    </div>
                    <div class="basic_six_item">
                        <div class="basic_six_item_left">
                            <img alt="" class="basic_six_item_icon" src="${resourceUrl}/images/monitor/net_1.png" />
                            <div class="basic_six_item_title i18n">上行网络质量</div>
                        </div>
                        <div class="basic_six_item_status basic_six_downlink"></div>
                    </div>
                    <div class="basic_six_item">
                        <div class="basic_six_item_left">
                            <img alt="" class="basic_six_item_icon" src="${resourceUrl}/images/monitor/net_1.png" />
                            <div class="basic_six_item_title i18n">下行网络质量</div>
                        </div>
                        <div class="basic_six_item_status basic_six_downlink"></div>
                    </div>
                </div>
                <div class="basic_six_footer">
                    <div onclick="reset_check()" class="basic_six_footer_btn i18n">重新检测</div>
                    <div onclick="finish_check()" class="basic_six_footer_btn basic_six_footer_btn_finish i18n">完成检测</div>
                </div>
            </div>
    </div>
    `
    vristr = `
    <!-- 虚拟背景弹窗 -->
        <div class="vritual_body">
            <div onclick="vritual_close_fun()" class="normal_pop_close_wrap">
                <img alt="" class="normal_pop_close_img" src="${resourceUrl}/images/icons/close_btn.png" />
            </div>
            <div class="normal_pop_header_wrap">
                虚拟背景
            </div>
            <div class="normal_pop_header_line"></div>
            <div class="blur_row_wrap">
                <div class="blur_row_title">模糊背景</div>
                <div class="vritual_switch_wrap">
                    <div class="layui-form" >
                        <input type="checkbox" name="vritual_blur_switch" id="vagueCheck"/>
                    </div>
                </div>
            </div>
            <div class="vritual_row_wrap">
                <div class="vritual_row_title">虚拟背景</div>
                <div class="vritual_switch_wrap">
                    <div class="layui-form" >
                        <input type="checkbox" id="vritualCheck"/>
                    </div>
                </div>
            </div>
            <div class="vritual_small_row_wrap">
                <img alt="" class="vritual_small_row_wrap_img" src="${resourceUrl}/images/vritual/ayers-rock.jpg" />
                <img alt="" class="vritual_small_row_wrap_img" src="${resourceUrl}/images/vritual/banner.png" />
                <img alt="" class="vritual_small_row_wrap_img" src="${resourceUrl}/images/vritual/beach.jpg" />
                <img alt="" class="vritual_small_row_wrap_img" src="${resourceUrl}/images/vritual/Blue_mountains.jpg" />
                <img alt="" class="vritual_small_row_wrap_img" src="${resourceUrl}/images/vritual/Christ.jpg" />
                <img alt="" class="vritual_small_row_wrap_img" src="${resourceUrl}/images/vritual/Colosseum.jpg" />
                <img alt="" class="vritual_small_row_wrap_img" src="${resourceUrl}/images/vritual/desert.jpg" />
                <img alt="" class="vritual_small_row_wrap_img" src="${resourceUrl}/images/vritual/easter-island.jpg" />
                <img alt="" class="vritual_small_row_wrap_img" src="${resourceUrl}/images/vritual/eiffel-tower.jpg" />
                <img alt="" class="vritual_small_row_wrap_img" src="${resourceUrl}/images/vritual/mohu.jpg" />
                <img alt="" class="vritual_small_row_wrap_img" src="${resourceUrl}/images/vritual/venice.jpg" />
                <div style="position:relative" id="uploadImg">
                    <img alt="" class="vritual_small_row_wrap_img" src="${resourceUrl}/images/vritual/upload.png" />
                    <input type="file" style="position:absolute;left:0;top:0;width:100%;height:100%;z-index:9;opacity:0" id="upload" disabled='true' onchange="uploadHandler(this)"></input>
                </div>
            </div>
        </div>`
    videostr = `
    <!-- 设置弹窗 -->
        <div class="setting_body">
            <div onclick="setting_close_fun()" class="normal_pop_close_wrap">
                <img alt="" class="normal_pop_close_img" src="${resourceUrl}/images/icons/close_btn.png" />
            </div>
            <div class="normal_pop_header_wrap">
                设备
            </div>
            <div class="normal_pop_header_line"></div>
            <div class="set_row_wrap" style="padding-top: 16px;">
                <div class="set_row_title">摄像头</div>
                <div class="normal_select_item" style="width: 100%;">
                    <div class="normal_select_input_wrap" style="margin-right: 0;">
                        <div class="normal_select_container">
                            <img alt="" class="show_select_img" src="${resourceUrl}/images/icons/show_select.png" />
                            <input class="normal_select_input" id="camera_select_wrap" type="text" readonly="readonly" onfocus="this.nextSibling.nextSibling.style.display='block';"
                                onblur="var t=this;setTimeout(()=>{t.nextSibling.nextSibling.style.display='none';},150);" placeholder="" />
                            <ul class="normal_select_wrap camera_select_ul">
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
            <div class="set_row_wrap">
                <div class="set_row_title">麦克风</div>
                <div class="normal_select_item" style="width: 100%;">
                    <div class="normal_select_input_wrap" style="margin-right: 0;">
                        <div class="normal_select_container">
                            <img alt="" class="show_select_img" src="${resourceUrl}/images/icons/show_select.png" />
                            <input class="normal_select_input" id="record_select_wrap" type="text" readonly="readonly" onfocus="this.nextSibling.nextSibling.style.display='block';"
                                onblur="var t=this;setTimeout(()=>{t.nextSibling.nextSibling.style.display='none';},150);" placeholder="" />
                            <ul class="normal_select_wrap record_select_ul">
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
            <div class="set_small_row_wrap" style="padding-bottom: 8px;">
                <div class="set_row_title"></div>
                <div class="set_row_container">
                    <div class="mic_sprites_wrap">
                        <img alt="" class="mic_sprites" src="${resourceUrl}/images/icons/mic_sprites.png" alt="">
                    </div>
                    <div class="volume_wrap">
                        <img alt="" class="volume_img" src="${resourceUrl}/images/icons/volume_img_sprites.png" alt="">
                    </div>
                </div>
            </div>
            <div class="set_row_wrap">
                <div class="set_row_title">扬声器</div>
                <div class="normal_select_item" style="width: 100%;">
                    <div class="normal_select_input_wrap" style="margin-right: 0;">
                        <div class="normal_select_container">
                            <img alt="" class="show_select_img" src="${resourceUrl}/images/icons/show_select.png" />
                            <input class="normal_select_input" id="playout_select_wrap" type="text" readonly="readonly" onfocus="this.nextSibling.nextSibling.style.display='block';"
                                onblur="var t=this;setTimeout(()=>{t.nextSibling.nextSibling.style.display='none';},150);" placeholder="" />
                            <ul class="normal_select_wrap playout_select_ul">
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
            <div class="set_small_row_wrap" style="padding-bottom: 8px;">
                <div class="set_row_title"></div>
                <div class="set_row_container">
                    <img class="voice_img" src="${resourceUrl}/images/icons/voice.png" alt="">
                    <div class="voice_wrap">
                        <div id="voice_range"></div>
                    </div>
                </div>
            </div>
        </div>`
    document.getElementById('detectionBox').innerHTML = str
    document.getElementById('vritual_popup').innerHTML = vristr
    document.getElementById('setting_popup').innerHTML = videostr
}
// 创建设置弹窗
function createdSetBox(){
    let str = ''
    str +='<div class="setBoxItme">'
    str += '<div id="closeBtn" style="background: url(' + resourceUrl + '/images/close.png)"></div>'
    str += '<span id="setTitle" class="i18n">设置</span>'
    str += '<span class="smallTitle i18n">应答方式</span>'
    str += '<div class="radioItems"><div><input type="radio" class="choseRadio"  onclick="changeSet(this)" name="agentAnswerMode" value="1" ><span class="radioTextClass i18n">手动应答</span></div><div class="marginLeft"><input type="radio" class="choseRadio"  onclick="changeSet(this)" name="agentAnswerMode" value="2"><span class="radioTextClass i18n">自动应答</span></div></div>'
    str += '<div class="requestTypeClass"><div><span class="smallTitle i18n" style="display:none !important">语音来电应答方式</span>'
    str += '<div class="radioItems" style="display:none !important"><div><input type="radio" class="choseRadio"  onclick="changeSet(this)" name="voiceCallAnswerMode" value="1"><span class="radioTextClass i18n">语音应答</span></div></div></div>'
    str += '<div><span class="smallTitle i18n">视频来电应答方式</span>'
    str += '<div class="radioItems"><div><input type="radio" class="choseRadio"  onclick="changeSet(this)" name="videoCallAnswerMode" value="1"><span class="radioTextClass i18n">语音应答</span></div><div class="marginLeft"><input type="radio" class="choseRadio"  onclick="changeSet(this)" name="videoCallAnswerMode" value="2"><span class="radioTextClass i18n">视频应答</span></div></div></div></div>'
    str += '<span class="smallTitle i18n">手机接听（离线坐席）</span>'
    str += `<div class="radioItems"><div><input type="radio" class="choseRadio"  onclick="changeSet(this)" name="offlineAgent" value="0"><span class="radioTextClass i18n">关闭</span></div><div class="marginLeft"><input type="radio" class="choseRadio"  onclick="changeSet(this)" name="offlineAgent" value="1"><span class="radioTextClass i18n">开启</span></div><input id="onlinePhone" type="number" autocomplete="off" class="marginLeft i18nInput" placeholder="${i18ntc('请输入')}"></div>`
    str += '<span class="smallTitle"><span class="i18n">分机注册方式</span><span class="smallTitleTips i18n">注：需重新签入后才能生效</span></span>'
    str += '<div class="radioItems"><div><input type="radio" class="choseRadio"  onclick="changeSet(this)" name="extRegMode" value="1"><span class="radioTextClass">WebRtc</span></div><div class="marginLeft"><input type="radio" class="choseRadio"  onclick="changeSet(this)" name="extRegMode" value="2"><span class="radioTextClass i18n">其他第三方话机</span></div></div>'
    str += '<span class="smallTitle i18n">签入后默认服务模式</span>'
    str += '<div class="radioItems"><div><input type="radio" class="choseRadio"  onclick="changeSet(this)" name="serviceMode" value="1"><span class="radioTextClass i18n">客服型</span></div><div class="marginLeft"><input type="radio" class="choseRadio"  onclick="changeSet(this)" name="serviceMode" value="2"><span class="radioTextClass i18n">外呼型</span></div></div>'
    str += '<div class="workOrderTemplateWrap" id="workOrderTemplateWrap" ></div>'
    str += '<span class="bottomTips bottomTips2 i18n">说明：</span>'
    str += '<span class="bottomTips i18n">客服型：即使坐席空闲，预测外呼任务不分配话务给客服型坐席；</span>'
    str += '<span class="bottomTips i18n">外呼型：即使坐席空闲，呼入的话务通过人工服务、IVR服务等方式都无法分配到外呼型坐席，坐席呼叫坐席可正常呼叫；</span>'
    str += '<div class="setbtns"><button id="setCancel" class="i18n">取消</button><button id="submit" class="i18n">确定</button></div>'
    str +='</div>'
    document.getElementById('setBox').innerHTML = str
}
//创建视频
function createdVideoBox(){
    let str = ''
    str +=`
    <!-- 通话 -->
    <div class="call_wrap">
        <!-- 呼出等待框 -->
        <div class="call_out_wait_wrap" style="display: none;" id="calloutWait">
            <div class="call_out_user_name" id="calloutText"></div>
            <div class="call_out_wait_txt" id="waitText">正在等待对方接受邀请</div>
        </div>
        <!-- 呼入等待框 -->
        <div class="call_in_wait_wrap" style="display: none;" id="await">
            <div class="call_in_user_name" id="caller"></div>
            <div class="call_in_wait_txt">正在等待接受邀请</div>
            <!-- 呼入接听按钮 -->
            <div class="answer_btns_wrap">
                <!-- 语音接听按钮 -->
                <div class="accept_audio_button" onclick="btn_audio_accept()">
                    <img src="${resourceUrl}/images/monitor/accept_audio_button.png" alt="接听">
                </div>
                <!-- 视频接听按钮 -->
                <div class="accept_video_button" onclick="btn_video_accept()">
                    <img src="${resourceUrl}/images/monitor/accept_video_button.png" alt="接听">
                </div>
            </div>
        </div>
        <div class="screen_header_wrap">
            <div class="screen_header_center">
                <img alt="" class="network_img network_good" src="${resourceUrl}/images/icons/network_good.png" />
                <img style="display: none;" alt="" class="network_img network_medium" src="${resourceUrl}/images/icons/network_medium.png" />
                <img style="display: none;" alt="" class="network_img network_poor" src="${resourceUrl}/images/icons/network_poor.png" />
                <div class="screen_center_title">通话中</div>
                <div class="screen_center_line">|</div>
                <div class="screen_center_time" id="screen_center_time">00:00:00</div>
            </div>
        </div>
        <!-- 主屏画面 -->
        <div class="big_screen_wrap">
            <div class="screen_left_name">
                <img alt="" class="screen_left_icon" src="${resourceUrl}/images/icons/open_micro_icon.png" />
                <div class="screen_left_nick"></div>
                <div class="screen_left_line">|</div>
                <div class="screen_left_id" id="screen_left_id"></div>
            </div>
            <div class="videoClick video_div" id="miniVideo">
                <video id="remoteVideo" autoplay="autoplay" style="width:100%;height:100%"></video>
            </div>
        </div>
        <!-- 窗口1 -->
        <div class="small_win_1">
            <div class="small_win_header_wrap">
                <div class="small_win_header_left">
                    <img alt="" class="small_win_left_icon" src="${resourceUrl}/images/icons/open_micro_icon.png" />
                    <div class="small_win_left_nick">我</div>
                    <div class="small_win_left_line">|</div>
                    <div class="small_win_left_id" id="small_win_left_id"></div>
                </div>
                <div class="small_win_header_right">
                </div>
            </div>
            <div class="videoClick video_width" id="video">
                <video id="localVideo" autoplay="autoplay" muted="muted" width="160" height="120" style="width:100%;height:100%"></video>
                <canvas id="backgroundImg" width="160" height="120" class="mask" style="display:none;"></canvas>
            </div>
        </div>
        <!-- 窗口2 -->
        <div class="small_win_2" style="display: none;">
            <div class="small_win_header_wrap">
                <div class="small_win_header_left">
                    <img alt="" class="small_win_left_icon" src="${resourceUrl}/images/icons/open_micro_icon.png" />
                    <div class="small_win_left_nick"></div>
                    <div class="small_win_left_line">|</div>
                    <div class="small_win_left_id"></div>
                </div>
                <div class="small_win_header_right">
                </div>
            </div>
            <div class="videoClick video_width" id="miniSecondVideo"></div>
        </div>
    </div>
    <!-- 按钮 -->
    <div class="center_btns_wrap">
        <!-- 静音 -->
        <div class="audio_mute_wrap can_click" id="openMic">
            <div onclick="change_micro(1)" class="operation_item audio_mute">
                <img alt="" class="operation_item_img" src="${resourceUrl}/images/icons/open_micro.png" />
                <div class="operation_item_txt">静音</div>
            </div>
        </div>
        <div class="audio_mute_wrap can_click" id="closeMic">
            <div onclick="change_micro(0)" class="operation_item audio_mute">
                <img alt="" class="operation_item_img" src="${resourceUrl}/images/icons/close_micro.png" />
                <div class="operation_item_txt">取消静音</div>
            </div>
        </div>
        <div class="audio_mute_wrap forbid_click">
            <div class="operation_item">
                <img alt="" class="operation_item_img" src="${resourceUrl}/images/icons/open_micro_forbid.png" />
                <div class="operation_item_txt">静音</div>
            </div>
        </div>
        <!-- 视频 -->
        <div class="video_mute_wrap can_click" id="openVideo">
            <div onclick="change_video_local(1)" class="operation_item video_mute">
                <img alt="" class="operation_item_img" src="${resourceUrl}/images/icons/open_video.png" />
                <div class="operation_item_txt">关视频</div>
            </div>
        </div>
        <div class="video_mute_wrap can_click" id="closeVideo">
            <div onclick="change_video_local(0)" class="operation_item video_mute">
                <img alt="" class="operation_item_img" src="${resourceUrl}/images/icons/close_video.png" />
                <div class="operation_item_txt">开视频</div>
            </div>
        </div>
        <div class="video_mute_wrap forbid_click">
            <div class="operation_item">
                <img alt="" class="operation_item_img" src="${resourceUrl}/images/icons/open_video_forbid.png" />
                <div class="operation_item_txt">关视频</div>
            </div>
        </div>
        <!-- 转语音 -->
        <div class="turn_audio_wrap can_click">
            <div onclick="switch_audio_mode()" class="operation_item turn_audio">
                <img alt="" class="operation_item_img" src="${resourceUrl}/images/icons/switch_voice.png" />
                <div class="operation_item_txt">转语音</div>
            </div>
        </div>
        <div class="turn_audio_wrap forbid_click">
            <div class="operation_item">
                <img alt="" class="operation_item_img" src="${resourceUrl}/images/icons/switch_voice_forbid.png" />
                <div class="operation_item_txt">转语音</div>
            </div>
        </div>
        <!-- 按键 -->
        <div class="keyboard_wrap can_click" id="dtmfVideo">
            <div class="operation_item keyboard_btn">
                <img alt="" class="operation_item_img" src="${resourceUrl}/images/icons/keyboard.png" />
                <div class="operation_item_txt">按键</div>
            </div>
        </div>
        <div class="keyboard_wrap forbid_click">
            <div class="operation_item">
                <img alt="" class="operation_item_img" src="${resourceUrl}/images/icons/keyboard_forbid.png" />
                <div class="operation_item_txt">按键</div>
            </div>
        </div>
        <!-- 共享 -->
        <div class="start_screen_wrap can_click" id="share_screen">
            <div onclick="screen_publish()" class="operation_item start_screen">
                <img alt="" class="operation_item_img" src="${resourceUrl}/images/icons/start_screen.png" />
                <div class="operation_item_txt">共享</div>
            </div>
        </div>
        <div class="start_screen_wrap forbid_click">
            <div class="operation_item">
                <img alt="" class="operation_item_img" src="${resourceUrl}/images/icons/start_screen_forbid.png" />
                <div class="operation_item_txt">共享</div>
            </div>
        </div>
        <div class="stop_screen_wrap" id="stop_screen">
            <div class="operation_item">
                <img alt="" onclick="screen_stop_publish()" class="operation_item_img" src="${resourceUrl}/images/icons/stop_screen.png" />
                <div class="operation_item_txt">停止共享</div>
            </div>
        </div>
        <!-- 挂断 -->
        <div class="hang_up_btn_wrap">
            <div class="operation_item hang_up_btn">
                <img alt="" onclick="hangUp()" class="operation_hang_up_img" src="${resourceUrl}/images/icons/hang_up.png" />
            </div>
        </div>
        <!-- 拍照 -->
        <div class="capture_select_wrap can_click">
            <div onclick="screen_capture_select()" class="operation_item capture_select">
                <img alt="" class="operation_item_img" src="${resourceUrl}/images/icons/camera.png" />
                <div class="operation_item_txt">拍照</div>
            </div>
        </div>
        <div class="capture_select_wrap forbid_click">
            <div class="operation_item">
                <img alt="" class="operation_item_img forbid_click" src="${resourceUrl}/images/icons/camera_forbid.png" />
                <div class="operation_item_txt">拍照</div>
            </div>
        </div>
        <!-- 录制 -->
        <div class="start_record_select_wrap can_click" id="start_record_select_wrap">
            <div class="operation_item start_record_select" onclick="record_select_fun()">
                <img alt=""  class="operation_item_img" src="${resourceUrl}/images/icons/record_video.png" />
                <div class="operation_item_txt">录制</div>
            </div>
        </div>
        <div class="start_record_select_wrap forbid_click">
            <div class="operation_item">
                <img alt="" class="operation_item_img" src="${resourceUrl}/images/icons/record_video_forbid.png" />
                <div class="operation_item_txt">录制</div>
            </div>
        </div>
        <div class="stop_record_select_wrap">
            <div onclick="stop_all_recording()" class="operation_item stop_record_select">
                <img alt="" class="operation_item_img" src="${resourceUrl}/images/icons/recording.png" />
                <div class="operation_item_txt">停止录制</div>
            </div>
        </div>
        <!-- 设备 -->
        <div onclick="setting_show_fun()" class="equipment_btn_wrap can_click">
            <div class="operation_item ">
                <img alt="" class="operation_item_img" src="${resourceUrl}/images/icons/equipment.png" />
                <div class="operation_item_txt">设备</div>
            </div>
        </div>
        <div class="equipment_btn_wrap forbid_click">
            <div class="operation_item ">
                <img alt="" class="operation_item_img" src="${resourceUrl}/images/icons/equipment_forbid.png" />
                <div class="operation_item_txt">设备</div>
            </div>
        </div>
    </div>`
    document.getElementById('main_center_wrap').innerHTML = str
}
//创建二次确认框
function createdSure(){
    let div = document.createElement('div')
    div.id = 'sureBoxNote'
    let str = ''
    str += `
            <div class="hangupDiv"><img src="${resourceUrl}/images/strip/gth.png">
            <span class="hangupText i18n">${i18ntc('挂断将结束本次通话')}</span></div>
            <div class='hangupBtns'>
            <span id="hangupCancel" class='i18n'>${i18ntc('取消')}</span>
            <span id="hangupSure" class='i18n'>${i18ntc('确定')}</span>
            </div>
            `
    document.getElementById('strip').appendChild(div)
    document.getElementById('sureBoxNote').innerHTML = str
}
//创建小休
function createdRest(){
    let div = document.createElement('div')
    div.id = 'restBox'
    let str = ''
    str += `
            <div class="tipsBoxClass">
                <span class="hangupTitle i18n">${i18ntc('设置小休时长')}</span>
                <div class="restNumClass">
                    <input id="restNum" value="" autocomplete="off">
                    <span class="i18n">${i18ntc('分钟')}</span>
                </div>
                <span class="hangupText""><img src="${resourceUrl}/images/strip/gth.png"><span class="i18n">到达小休时长时，系统会提示坐席小休时长已到达最大时长，但坐席扔处于小休状态。</span></span>
                <div class='hangupBtns'>
                    <span id="restSure" class="hangupSure i18n">${i18ntc('确定')}</span>
                    <span id="restCancel" class="hangupCancel i18n">${i18ntc('取消')}</span>
                </div>
            </div>
            `
    document.body.appendChild(div);
    document.getElementById('restBox').innerHTML = str
}
function createdSignout(){
    let div = document.createElement('div')
    div.id = 'signoutBox'
    let str = ''
    str += `
            <div class="tipsBoxClass">
                <span class="hangupTitle i18n">${i18ntc('签出确认')}</span>
                <span class="hangupText i18n">${i18ntc('签出将结束通话，确定签出？')}</span>
                <div class='hangupBtns'>
                    <span id="signOutSure" class="hangupSure i18n">${i18ntc('确定')}</span>
                    <span id="signOutCancel" class="hangupCancel i18n">${i18ntc('取消')}</span>
                </div>
            </div>
            `
    document.body.appendChild(div);
    document.getElementById('signoutBox').innerHTML = str
}
//创建分机绑定框
function createdExt(){
    let div = document.createElement('div')
    div.id = 'extBox'
    let str = ''
    str += `
            <div class="tipsBoxClass">
                <span class="hangupTitle i18n">绑定分机号</span>
                <div class="restNumClass">
                    <input id="extNum" value="" autocomplete="off" class="i18nInput" placeholder="${i18ntc('请输入')}" style="width:160px">
                </div>
                <span class="hangupText i18n">请输入已创建的分机号码且未被其他人绑定</span>
                <div class='hangupBtns'>
                    <span id="extSure" class="hangupSure i18n">确定</span>
                    <span id="extCancel" class="hangupCancel i18n">取消</span>
                </div>
            </div>
            `
    document.body.appendChild(div);
    document.getElementById('extBox').innerHTML = str
}
//tips
function createdTips(){
    let div = document.createElement('div')
    div.id = 'messageBox'
    let str = ''
    str += `<div><img src="${resourceUrl}/images/strip/gth.png"><span class="messageBoxText" id="messageBoxText"></span></div>`
    document.getElementById('tipsShow').appendChild(div);
    document.getElementById('messageBox').innerHTML = str
}
//创建小休时间到
function createdTimeOut(){
    let div = document.createElement('div')
    div.id = 'timeOut'
    let str = ''
    str += `
            <div class="tipsBoxClass">
                <span class="hangupTitle i18n">${i18ntc('小休时间结束提示')}</span>
                <span class="hangupText i18n">${i18ntc('小休时长已到达最大时长，是否要变更状态')}</span>
                <div class='hangupBtns'>
                    <span id="outBusy" class="hangupSure i18n"  style="background:#EA1A00">${i18ntc('忙碌')}</span>
                    <span id="outFree" class="hangupSure i18n" style="background:#2ED8AD">${i18ntc('空闲')}</span>
                    <span id="outCancel" class="hangupCancel i18n">${i18ntc('取消')}</span>
                </div>
            </div>
            `
    document.body.appendChild(div);
    document.getElementById('timeOut').innerHTML = str
}
//创建二次确认框
function createdReset(){
    let div = document.createElement('div')
    div.id = 'resetBox'
    let str = ''
    str += `
            <div class="tipsBoxClass">
                <span class="hangupTitle i18n">确定复位</span>
                <span class="hangupText i18n">强复位将会强制签出并重新签入。如若处于通话，通话将被挂断，确定执行强复位？</span>
                <div class='hangupBtns'>
                <span id="resetSure" class="i18n">确定</span>
                <span id="resetCancel" class="i18n">取消</span>
                </div>
            </div>
            `
    document.body.appendChild(div);
    document.getElementById('resetBox').innerHTML = str
}
function hideDomTree(){
    videoStatus = -1
    document.getElementById('muteCancel').style.display = 'none'
    document.getElementById('holdCancel').style.display = 'none'
    document.getElementById('transferCancel').style.display = 'none'
    document.getElementById('consultingCancel').style.display = 'none'
    document.getElementById('share_screen').style.display = 'block'
    document.getElementById('stop_screen').style.display = 'none'
    document.getElementById('mute').style.display = 'none'
    document.getElementById('transfer').style.display = 'none'
    document.getElementById('consulting').style.display = 'none'
    document.getElementById('threeCall').style.display = 'none'
    document.getElementById('satisfaction').style.display = 'none'
    document.getElementById('hangup').style.display = 'none'
    document.getElementById('dtmf').style.display = 'none'
    document.getElementById('pickup').style.display = 'none'
    document.getElementById('toVideo').style.display = 'none'
    document.getElementById('hold').style.display = 'none'
    document.getElementById('main_center_wrap').style.display = 'none'
    document.getElementById('inputBox').style.display = 'none'
    document.getElementById('calloutWait').style.display = 'none'
    document.getElementById('await').style.display = 'none'
    document.getElementById('showDiv').style.display = 'none'
    document.getElementById('trans').style.display = 'none'
    document.getElementById('inputNum').disabled = false
    $('.center_btns_wrap .can_click').hide();
    $('.center_btns_wrap .forbid_click').show();
    if (window.hideWindow){
        window.hideWindow()
    }
}
function formatTime(seconds) {
    var hours = Math.floor(seconds / 3600);
    var minutes = Math.floor((seconds % 3600) / 60);
    var secs = seconds % 60;
    var formattedTime = hours.toString().padStart(2, '0') + ':' + minutes.toString().padStart(2, '0') + ':' + secs.toString().padStart(2, '0');
    return formattedTime;
  }
function updateTime() {
    seconds++;
    var formattedTime = formatTime(seconds);
    document.getElementById('time').innerHTML = formattedTime
    document.getElementById('screen_center_time').innerHTML = formattedTime
}
function cleanTime(type){
    seconds = 0
    if (audioTimer){
        clearInterval(audioTimer)
        audioTimer = null
    }
    if (type == '1'){
        document.getElementById('time').innerHTML = '--:--:--'
    } else if (type == '2'){
        document.getElementById('time').innerHTML = '00:00:00'
    } else {
        document.getElementById('time').innerHTML = '00:00:00'
        return
    }
    document.getElementById('tips').style.display = 'none'
}
function addListenNotes(){
    const listenConfig = {attributes: true,childList:true,subtree:true}
    const callbackDom = function(mutationsList,observer){
        for (let mutation of mutationsList){
            if (mutation.type == 'childList'){
                document.getElementById('notes').style.backgroundColor = bgColor(i18ntc(mutation.target.innerHTML));
            }
        }
    }
    const observer = new MutationObserver(callbackDom)
    observer.observe(document.getElementById('notes'),listenConfig)
//按钮方法
document.getElementById('hold').addEventListener("click", function() {
    // 在按钮点击时执行的代码
    hold('1')
});
document.getElementById('holdCancel').addEventListener("click", function() {
    // 在按钮点击时执行的代码
    hold('0')
});
document.getElementById('mute').addEventListener("click", function() {
    // 在按钮点击时执行的代码
    localMute('1').then(res =>{
        if (res == 'mute'){
            //当前保持
            document.getElementById('mute').style.display = 'none'
            document.getElementById('muteCancel').style.display = 'block'
        } else if (res == 'unmute'){
            document.getElementById('mute').style.display = 'block'
            document.getElementById('muteCancel').style.display = 'none'
        }
    })
});
document.getElementById('muteCancel').addEventListener("click", function() {
    // 在按钮点击时执行的代码
    localMute('0').then(res =>{
        if (res == 'mute'){
            //当前保持
            document.getElementById('mute').style.display = 'none'
            document.getElementById('muteCancel').style.display = 'block'
        } else if (res == 'unmute'){
            document.getElementById('mute').style.display = 'block'
            document.getElementById('muteCancel').style.display = 'none'
        }
    })
});
document.getElementById('satisfaction').addEventListener("click", function() {
    if(callingPhone){
        if (callingPhone.indexOf("_")>-1){
            toastMessage(i18ntc('内线通话无法转接满意度'))
            return
        }
    }
    transferCall('','5')
});
//挂断
document.getElementById('hangup').addEventListener("click", function(e) {
    e.stopPropagation();
    document.getElementById('sureBoxNote').style.left = e.clientX - document.getElementById('sitetype').getBoundingClientRect().x  + 50+ 'px'
    document.getElementById('sureBoxNote').style.top = document.getElementById('note').getBoundingClientRect().y + 35 + 'px'
    document.getElementById('sureBoxNote').style.display = 'block'
})
document.getElementById('hangupCancel').addEventListener("click", function(e) {
    document.getElementById('sureBoxNote').style.display = 'none'
})
document.getElementById('hangupSure').addEventListener("click", function(e) {
    hangUp()
    document.getElementById('sureBoxNote').style.display = 'none'
})
document.getElementById('note').addEventListener("click", function(e) {
    // 在按钮点击时执行的代码
    e.stopPropagation();
    if (document.getElementById('note').getAttribute('class') == 'statusFont'){
        document.getElementById('note').setAttribute("class","statusFontbottom");
        document.getElementById('choseStatus').style.display = 'flex'
        if (document.getElementById('note').innerHTML == i18ntc('离线')){
            document.getElementById('offlineBtn').style.display = 'none'
            document.getElementById('restBtn').style.display = 'none'
        } else {
            document.getElementById('offlineBtn').style.display = 'flex'
            document.getElementById('restBtn').style.display = 'flex'
        }
    } else {
        document.getElementById('note').setAttribute("class","statusFont");
        document.getElementById('choseStatus').style.display = 'none'
    }
});
document.getElementById('set').addEventListener("click", function() {
    document.getElementById('setBox').style.display = 'flex'
    getSet()
})
document.getElementById('seatAssistant').addEventListener("click", function() {
    let seatAssistantBoxPannel = document.getElementById('seatAssistantBoxPannel');
    if(seatAssistantBoxPannel.style.display == 'block') {
        document.getElementById('seatAssistantBoxPannel').style.display = 'none';
    }else{
        document.getElementById('seatAssistantBoxPannel').style.display = 'block';
        autoContentToBottom();
    }
    getSet()
    // let myRollScreenSwitch = document.getElementById('myRollScreenSwitch');
    // if(localStorage.getItem("myRollScreenSwitch") == "true") {
    //     myRollScreenSwitch.checked = true;
    // }else{
    //     myRollScreenSwitch.checked = false;
    // }
})
document.getElementById('inputNum').addEventListener("click", function() {
    // 在按钮点击时执行的代码
    document.getElementById('keyModel').style.display = 'flex'
    document.getElementById('numberHistory').style.display = 'block'
    if (desensitization == 1){
        document.getElementById('numberHistoryDiv').style.display = 'none'
        document.getElementById('keyModel').style.width = '292px'
        document.getElementById('openModal').style.visibility = 'hidden'
        document.getElementById('closeMoadl').style.visibility = 'hidden'
    }
    if (localStorage.getItem(agent_id + 'numberHistory')){
        let numberList = JSON.parse(localStorage.getItem(agent_id + 'numberHistory'))
        let str = ''
        for (let i=0;i<numberList.length;i++){
            str += '<span>'
            str += numberList[i].replace(/\s/g, "")
            str += '</span>'
        }
        document.getElementById('numberHistory').innerHTML = str
    }
});
document.getElementById('closekeyModel').addEventListener("click", function() {
    // 在按钮点击时执行的代码
    document.getElementById('keyModel').style.display = 'none'
});
document.getElementById('closeMoadl').addEventListener("click", function() {
    // 在按钮点击时执行的代码
    document.getElementById('closeMoadl').style.display = 'none'
    document.getElementById('openModal').style.visibility = 'visible'
    document.getElementById('moadlTopLeft').style.display = 'none'
    document.getElementById('numberHistoryDiv').style.display = 'none'
    document.getElementById('keyModel').style.width = '292px'
});
document.getElementById('openModal').addEventListener("click", function() {
    // 在按钮点击时执行的代码
    document.getElementById('openModal').style.visibility = 'hidden'
    document.getElementById('closeMoadl').style.display = 'block'
    document.getElementById('moadlTopLeft').style.display = 'flex'
    document.getElementById('numberHistoryDiv').style.display = 'flex'
    document.getElementById('keyModel').style.width = '465px'
});
// enter事件
document.getElementById('inputNum').addEventListener("keyup", function(e) {
    if (!document.getElementById('inputNum').value){
        return
    }
    if (e.keyCode == 13){
        setNumberHistory()
        call_out(Number(setParam.enterKeyCallMode))
    }
});
function call_out(val){
    switch (val){
        case 1:
            callOut(document.getElementById('inputNum').value).then(res =>{
                if (res == 'OFFLINE'){
                    toastMessage(i18ntc('外呼失败，话务条未签入'))
                } else if (res == 'CALLING' || res == 'RINGING'){
                    toastMessage(i18ntc('外呼失败，坐席处于通话状态'))
                }
            })
            document.getElementById('screen_left_id').innerHTML = document.getElementById('inputNum').value
            document.getElementById('small_win_left_id').innerHTML = agent_id
        break;
        case 2:
            document.getElementById('main_center_wrap').style.display = 'block'
            document.getElementById('calloutWait').style.display = 'flex'
            document.getElementById('calloutText').innerHTML = document.getElementById('inputNum').value
            document.getElementById('waitText').innerHTML = i18ntc('正在等待对方接受邀请')
            document.getElementById('screen_left_id').innerHTML = document.getElementById('inputNum').value
            document.getElementById('small_win_left_id').innerHTML = agent_id
            dragDom($('#main_center_wrap'))
            callOut(document.getElementById('inputNum').value,3,3,'480')
        break;
        case 3:
            document.getElementById('main_center_wrap').style.display = 'block'
            document.getElementById('calloutWait').style.display = 'flex'
            document.getElementById('calloutText').innerHTML = document.getElementById('inputNum').value
            document.getElementById('waitText').innerHTML = i18ntc('正在等待对方接受邀请')
            document.getElementById('screen_left_id').innerHTML = document.getElementById('inputNum').value
            document.getElementById('small_win_left_id').innerHTML = agent_id
            dragDom($('#main_center_wrap'))
            callOut(document.getElementById('inputNum').value,3,3,'720')
        break;
    }
    document.getElementById('keyModel').style.display = 'none'
}
document.getElementById('board').addEventListener("click", function(e) {
    // 在按钮点击时执行的代码
    if (keyBoardArr.includes(e.target.innerHTML)){
        document.getElementById('inputNum').value += e.target.innerHTML
    }
});
document.getElementById('numberHistory').addEventListener("click", function(e) {
    // 在按钮点击时执行的代码
    if (e.target.tagName === 'SPAN'){
        document.getElementById('inputNum').value = e.target.innerHTML
    }
});
document.getElementById('startCall').addEventListener("click", function(e) {
    // 在按钮点击时执行的代码
    if (!document.getElementById('inputNum').value){
        toastMessage(i18ntc('请输入外呼号码'))
        return
    }
    setNumberHistory()
    call_out(Number(e.target.attributes[0].value))
});
document.getElementById('choseStatus').addEventListener("click", function(e) {
    // 在按钮点击时执行的代码
    switch (e.target.attributes[0].value){
        case 'free':
            isCheckIn?nowStatus=='CALLING'||nowStatus=='RINGING'?changeStatus('MAKE_FREE_AFTER_CALL_STOP'):changeStatus('MAKE_FREE'):signIn('FREE')
        break;
        case 'busy':
            isCheckIn?nowStatus=='CALLING'||nowStatus=='RINGING'?changeStatus('MAKE_BUSY_AFTER_CALL_STOP'):changeStatus('MAKE_BUSY'):signIn('BUSY')
        break;
        case 'rest':
            document.getElementById('restBox').style.display = 'flex'
        break;
        case 'offline':
            nowStatus=='CALLING'||nowStatus=='RINGING'?document.getElementById('signoutBox').style.display = 'flex':signOut()
        break;
    }
    document.getElementById('choseStatus').style.display = 'none'
    document.getElementById('note').setAttribute("class","statusFont");
});
//转接
document.getElementById('transfer').addEventListener("click", function(e) {
    getIvrList()
    getagents()
    if (consultingState){
        transferCall(document.getElementById('callPhone').value,3)
    } else {
        otherBoardType = '1'
        document.getElementById('inputBox').style.display = 'flex'
        document.getElementById('inputBox').style.left = e.clientX - document.getElementById('sitetype').getBoundingClientRect().x + 'px'
        document.getElementById('inputBox').style.top = e.clientY + document.getElementById('note').getBoundingClientRect().y + 30 + 'px'
        document.getElementById('callText').innerHTML = i18ntc('转接类型') + '：'
        document.getElementById('inputBox').classList.remove('dtmfBox')
        document.getElementById('otherCallImg').style.display = 'block'
        document.getElementById('siteText').style.display = 'block'
        document.getElementById('otherCallText').innerHTML = i18ntc('语音')
        document.getElementById('queue').style.display = 'block'
        document.getElementById('toivr').style.display = 'block'
        document.getElementById('siteTree').style.display = 'block'
        document.getElementById('otherBoard').style.display = 'none'
        document.getElementById('otherCall').style.display = 'flex'
        document.getElementById('boxInputTitle').style.display = 'flex'
        document.getElementById('callPhone').value = ''
        document.getElementById("callType")[0].selected = true;
        document.getElementById('callPhone').setAttribute('placeholder','')
        selectedIndex = '1'
        changeSite()
    }
})
//咨询中转
document.getElementById('trans').addEventListener("click", function(e) {
    transfer()
})
//转接视频
// document.getElementById('transferVideo').addEventListener("click", function(e) {
//     getIvrList()
//     getagents()
//     if (consultingState){
//         transferCall(document.getElementById('callPhone').value,3)
//     } else {
//         otherBoardType = '1'
//         document.getElementById('inputBox').style.display = 'flex'
//         document.getElementById('inputBox').style.left = document.getElementById('main_center_wrap').getBoundingClientRect().x - 465 +  'px'
//         document.getElementById('inputBox').style.top = document.getElementById('main_center_wrap').getBoundingClientRect().y  + 'px'
//         document.getElementById('callText').innerHTML = i18ntc('转接类型') + '：'
//         document.getElementById('inputBox').classList.remove('dtmfBox')
//         document.getElementById('otherCallImg').style.display = 'block'
//         document.getElementById('siteText').style.display = 'block'
//         document.getElementById('otherCallText').innerHTML = i18ntc('语音')
//         document.getElementById('queue').style.display = 'block'
//         document.getElementById('toivr').style.display = 'block'
//         document.getElementById('siteTree').style.display = 'block'
//         document.getElementById('otherBoard').style.display = 'none'
//         document.getElementById('otherCall').style.display = 'flex'
//         document.getElementById('boxInputTitle').style.display = 'flex'
//         document.getElementById('callPhone').value = ''
//         document.getElementById("callType")[0].selected = true;
//         document.getElementById('callPhone').setAttribute('placeholder','')
//         selectedIndex = '1'
//         changeSite()
//     }
// })
//转接取消
document.getElementById('transferCancel').addEventListener("click", function(e) {
    transferCall('','','3')
})
document.getElementById('callPhone').addEventListener("input", function(e) {
    if (selectedIndex == 1 || selectedIndex == 2){
        getagents(document.getElementById('callPhone').value)
    } else if (selectedIndex == 3){
        getIvrList(document.getElementById('callPhone').value)
    }
})
// 小休逻辑
document.getElementById('restSure').addEventListener("click", function(e) {
    restTimes = Number(document.getElementById('restNum').value)
    nowStatus=='CALLING'||nowStatus=='RINGING'?changeStatus('MAKE_REST_AFTER_CALL_STOP'):changeStatus('MAKE_REST')
    document.getElementById('restBox').style.display = 'none'
    localStorage.setItem('restTimes',restTimes)
})
document.getElementById('restCancel').addEventListener("click", function(e) {
    document.getElementById('restBox').style.display = 'none'
})
// 签出
document.getElementById('signOutSure').addEventListener("click", function(e) {
    signOut()
    document.getElementById('signoutBox').style.display = 'none'
})
document.getElementById('signOutCancel').addEventListener("click", function(e) {
    document.getElementById('signoutBox').style.display = 'none'
})
//分机逻辑
document.getElementById('extSure').addEventListener("click", function(e) {
    ext_id = Number(document.getElementById('extNum').value)
    signIn()
    document.getElementById('extBox').style.display = 'none'
})
document.getElementById('extCancel').addEventListener("click", function(e) {
    document.getElementById('extBox').style.display = 'none'
})
document.getElementById('outCancel').addEventListener("click", function(e) {
    document.getElementById('timeOut').style.display = 'none'
})
document.getElementById('outFree').addEventListener("click", function(e) {
    changeStatus('MAKE_FREE')
    document.getElementById('timeOut').style.display = 'none'
})
document.getElementById('outBusy').addEventListener("click", function(e) {
    changeStatus('MAKE_BUSY')
    document.getElementById('timeOut').style.display = 'none'
})
//休息时间
document.getElementById('restNum').addEventListener("input", function(e) {
    if (e.target.value){
        if (![0,1,2,3,4,5,6,7,8,9].includes(Number(e.target.value.slice(-1)))){
            document.getElementById('restNum').value = document.getElementById('restNum').value.slice(0,-1)
        }
    }
})
//分机
document.getElementById('extNum').addEventListener("input", function(e) {
    if (e.target.value){
        if (![0,1,2,3,4,5,6,7,8,9].includes(Number(e.target.value.slice(-1)))){
            document.getElementById('extNum').value = document.getElementById('extNum').value.slice(0,-1)
        }
    }
})
//复位
document.getElementById('reset').addEventListener("click", function(e) {
    document.getElementById('resetBox').style.display = 'flex'
    document.getElementById('showMore').style.display = 'none'
})
document.getElementById('resetCancel').addEventListener("click", function(e) {
    document.getElementById('resetBox').style.display = 'none'
})
document.getElementById('resetSure').addEventListener("click", function(e) {
    reset()
    document.getElementById('resetBox').style.display = 'none'
})
//咨询
document.getElementById('consulting').addEventListener("click", function(e) {
    getagents()
    otherBoardType = '2'
    document.getElementById('inputBox').style.display = 'flex'
    document.getElementById('inputBox').classList.remove('dtmfBox')
    document.getElementById('otherCallImg').style.display = 'block'
    document.getElementById('siteText').style.display = 'block'
    document.getElementById('otherCallText').innerHTML = i18ntc('语音')
    document.getElementById('inputBox').style.left = e.clientX - document.getElementById('sitetype').getBoundingClientRect().x + 'px'
    document.getElementById('inputBox').style.top = e.clientY + document.getElementById('note').getBoundingClientRect().y + 30 + 'px'
    document.getElementById('callText').innerHTML = i18ntc('咨询类型') + '：'
    document.getElementById('queue').style.display = 'none'
    document.getElementById('toivr').style.display = 'none'
    document.getElementById('siteTree').style.display = 'block'
    document.getElementById('otherBoard').style.display = 'none'
    document.getElementById('otherCall').style.display = 'flex'
    document.getElementById('boxInputTitle').style.display = 'flex'
    document.getElementById('callPhone').value = ''
    document.getElementById("callType")[0].selected = true;
    document.getElementById('callPhone').setAttribute('placeholder','')
    selectedIndex = '1'
    changeSite()
})
//咨询视频
// document.getElementById('consultingVideo').addEventListener("click", function(e) {
//     getagents()
//     otherBoardType = '2'
//     document.getElementById('inputBox').style.display = 'flex'
//     document.getElementById('inputBox').classList.remove('dtmfBox')
//     document.getElementById('otherCallImg').style.display = 'block'
//     document.getElementById('siteText').style.display = 'block'
//     document.getElementById('otherCallText').innerHTML = i18ntc('语音')
//     document.getElementById('inputBox').style.left = document.getElementById('main_center_wrap').getBoundingClientRect().x - 465 +  'px'
//     document.getElementById('inputBox').style.top = document.getElementById('main_center_wrap').getBoundingClientRect().y + 'px'
//     document.getElementById('callText').innerHTML = i18ntc('咨询类型') + '：'
//     document.getElementById('queue').style.display = 'none'
//     document.getElementById('toivr').style.display = 'none'
//     document.getElementById('siteTree').style.display = 'block'
//     document.getElementById('otherBoard').style.display = 'none'
//     document.getElementById('otherCall').style.display = 'flex'
//     document.getElementById('boxInputTitle').style.display = 'flex'
//     document.getElementById('callPhone').value = ''
//     document.getElementById("callType")[0].selected = true;
//     document.getElementById('callPhone').setAttribute('placeholder','')
//     selectedIndex = '1'
//     changeSite()
// })
//取消咨询
document.getElementById('consultingCancel').addEventListener("click", function(e) {
    consultingCall('','','2')
})
//转视频
document.getElementById('toVideo').addEventListener("click", function(e) {
    document.getElementById('calloutWait').style.display = 'flex'
    changeMedia('video')
})
//更多
document.getElementById('more').addEventListener("click", function(e) {
    e.stopPropagation();
    if (document.getElementById('showMore').style.display == 'flex'){
        document.getElementById('showMore').style.display = 'none'
    } else {
        document.getElementById('showMore').style.display = 'flex'
        document.getElementById('showMore').style.left = e.clientX + 'px'
        document.getElementById('showMore').style.top = e.clientY + 'px'
    }

})
//三方
document.getElementById('threeCall').addEventListener("click", function(e) {
    getagents()
    otherBoardType = '3'
    document.getElementById('inputBox').style.display = 'flex'
    document.getElementById('inputBox').classList.remove('dtmfBox')
    document.getElementById('otherCallImg').style.display = 'block'
    document.getElementById('siteText').style.display = 'block'
    document.getElementById('otherCallText').innerHTML = i18ntc('语音')
    document.getElementById('inputBox').style.left = e.clientX - document.getElementById('sitetype').getBoundingClientRect().x + 'px'
    document.getElementById('inputBox').style.top = e.clientY + document.getElementById('note').getBoundingClientRect().y + 30 + 'px'
    document.getElementById('callText').innerHTML = i18ntc('呼叫类型') + ':'
    document.getElementById('queue').style.display = 'none'
    document.getElementById('toivr').style.display = 'none'
    document.getElementById('siteTree').style.display = 'block'
    document.getElementById('otherBoard').style.display = 'none'
    document.getElementById('otherCall').style.display = 'flex'
    document.getElementById('boxInputTitle').style.display = 'flex'
    document.getElementById('callPhone').value = ''
    document.getElementById("callType")[0].selected = true;
    document.getElementById('callPhone').setAttribute('placeholder','')
    selectedIndex = '1'
    changeSite()
})
// //三方视频
// document.getElementById('threeCallVideo').addEventListener("click", function(e) {
//     getagents()
//     otherBoardType = '3'
//     document.getElementById('inputBox').style.display = 'flex'
//     document.getElementById('inputBox').classList.remove('dtmfBox')
//     document.getElementById('otherCallImg').style.display = 'block'
//     document.getElementById('siteText').style.display = 'block'
//     document.getElementById('otherCallText').innerHTML = i18ntc('语音')
//     document.getElementById('inputBox').style.left = document.getElementById('main_center_wrap').getBoundingClientRect().x - 465 +  'px'
//     document.getElementById('inputBox').style.top = document.getElementById('main_center_wrap').getBoundingClientRect().y + 'px'
//     document.getElementById('callText').innerHTML = i18ntc('呼叫类型') + ':'
//     document.getElementById('queue').style.display = 'none'
//     document.getElementById('toivr').style.display = 'none'
//     document.getElementById('siteTree').style.display = 'block'
//     document.getElementById('otherBoard').style.display = 'none'
//     document.getElementById('otherCall').style.display = 'flex'
//     document.getElementById('boxInputTitle').style.display = 'flex'
//     document.getElementById('callPhone').value = ''
//     document.getElementById("callType")[0].selected = true;
//     document.getElementById('callPhone').setAttribute('placeholder','')
//     selectedIndex = '1'
//     changeSite()
// })
//二次拨号
document.getElementById('dtmf').addEventListener("click", function(e) {
    otherBoardType = '4'
    document.getElementById('inputBox').style.display = 'flex'
    document.getElementById('otherCallImg').style.display = 'none'
    document.getElementById('siteText').style.display = 'none'
    document.getElementById('otherCallText').innerHTML = i18ntc('发送')
    document.getElementById('inputBox').classList.add('dtmfBox')
    document.getElementById('inputBox').style.left = e.clientX + 'px'
    document.getElementById('inputBox').style.top = e.clientY  + 'px'
    document.getElementById('boxInputTitle').style.display = 'none'
    document.getElementById('otherBoard').style.display = 'flex'
    document.getElementById('siteTree').style.display = 'none'
    document.getElementById('queue').style.display = 'none'
    document.getElementById('toivr').style.display = 'none'
    document.getElementById('callPhone').value = ''
    document.getElementById('callPhone').setAttribute('placeholder','')
    document.getElementById('ivrlist').style.display = 'none'
})
//案件视频
document.getElementById('dtmfVideo').addEventListener("click", function(e) {
    otherBoardType = '4'
    document.getElementById('inputBox').style.display = 'flex'
    document.getElementById('inputBox').style.left = document.getElementById('main_center_wrap').getBoundingClientRect().x - 465 +  'px'
    document.getElementById('inputBox').style.top = document.getElementById('main_center_wrap').getBoundingClientRect().y + 'px'
    document.getElementById('siteText').innerHTML = i18ntc('呼叫号码') + '：'
    document.getElementById('boxInputTitle').style.display = 'none'
    document.getElementById('otherBoard').style.display = 'flex'
    document.getElementById('siteTree').style.display = 'none'
    document.getElementById('queue').style.display = 'none'
    document.getElementById('toivr').style.display = 'none'
    document.getElementById('callPhone').value = ''
    document.getElementById('callPhone').setAttribute('placeholder','')
    document.getElementById('ivrlist').style.display = 'none'
})
document.getElementById('closeInputBox').addEventListener("click", function(e) {
    document.getElementById('inputBox').style.display = 'none'
})
document.getElementById('pickup').addEventListener("click", function(e) {
    if(document.getElementById('play_calling')) {
        try{
            document.getElementById('play_calling').pause()
        }catch(err){}
    }
    pickUp()
    document.getElementById('pickup').style.display = 'none'
    if (window.hideWindow){
        window.hideWindow()
    }
})
document.getElementById('siteTree').addEventListener("click", function(e) {
    if (selectedIndex == '1'){
        if (e.target.getAttribute('value') == 'more'){
            getAgentMoreList(e.target.getAttribute('dataValue'),e.target.getAttribute('pageValue'))
            document.getElementById(e.target.getAttribute('dataValue') + '_more').remove()
        } else {
            // 技能组 直接给ID
            if (e.target.getAttribute('nodeValue') == null){
                // 父节点
                if (document.getElementById(e.target.getAttribute('value')).style.display == 'flex'){
                    document.getElementById('img_' + e.target.getAttribute('value')).setAttribute('src',resourceUrl + "/images/strip/right.png")
                    document.getElementById(e.target.getAttribute('value')).style.display = 'none'
                } else {
                    document.getElementById('img_' + e.target.getAttribute('value')).setAttribute('src',resourceUrl + "/images/strip/down.png")
                    document.getElementById(e.target.getAttribute('value')).style.display = 'flex'
                }
            } else {
                // 子节点
                document.getElementById('callPhone').value = e.target.getAttribute('nodeValue')
            }
        }
    } else if (selectedIndex == '2'){
        ivrObj = {
            ivrId: e.target.getAttribute('value'),
            ivrName: e.target.innerHTML
        }
        document.getElementById('callPhone').value = e.target.innerHTML
    }
})
document.getElementById('otherBoard').addEventListener("click", function(e) {
    if (keyBoardArr.includes(e.target.innerHTML)){
        document.getElementById('callPhone').value += e.target.innerHTML
    }
})
document.getElementById('otherCall').addEventListener("click", function(e) {
    let otherNumber = document.getElementById('callPhone').value
    if (selectedIndex == '3' || selectedIndex == '2'){
        otherNumber = ivrObj.ivrId
    }
    if(selectedIndex == '1' && otherBoardType != '4'){
        otherNumber = company_code + '_' + otherNumber
    }
    switch (otherBoardType){
        case "1":
            if (hasVideo){
                transferCall(otherNumber,selectedIndex,transMode,'1',3,3)
            } else {
                transferCall(otherNumber,selectedIndex,transMode)
            }
        break
        case "2":
            if(hasVideo){
                selectedIndex == '4'?consultingCall(otherNumber,'1','1',3,3):consultingCall(otherNumber,'0','1',3,3)
            } else {
                selectedIndex == '4'?consultingCall(otherNumber,'1'):consultingCall(otherNumber,'0')
            }
        break
        case "3":
            if (hasVideo){
                selectedIndex == '4'?multiCall(otherNumber,'1','1',3,3):multiCall(otherNumber,'0','1',3,3)
            } else {
                selectedIndex == '4'?multiCall(otherNumber,'1'):multiCall(otherNumber,'0')
            }
        break
        case "4":
            dtmfCall(otherNumber)
            document.getElementById('callPhone').value = ''
        break
    }
    if (otherBoardType != 4){
        document.getElementById('inputBox').style.display = 'none'
    }
})
document.getElementById('callType').addEventListener("change", function(e) {
    selectedIndex = document.getElementById('callType')[this.selectedIndex].value
    document.getElementById('callPhone').value = ''
    switch(selectedIndex){
        case "1":
          changeSite()
          document.getElementById('callPhone').setAttribute('placeholder','')
        break
        case "4":
          document.getElementById('otherBoard').style.display = 'flex'
          document.getElementById('siteTree').style.display = 'none'
          document.getElementById('ivrlist').style.display = 'none'
          document.getElementById('siteText').innerHTML = i18ntc('呼叫号码') + '：'
          document.getElementById('callPhone').setAttribute('placeholder',i18ntc('请输入'))
        break
        case "2":
        // 技能组
          document.getElementById('otherBoard').style.display = 'none'
          document.getElementById('siteTree').style.display = 'block'
          document.getElementById('ivrlist').style.display = 'none'
          document.getElementById('siteText').innerHTML = i18ntc('转人工服务') + '：'
          document.getElementById('callPhone').setAttribute('placeholder','')
          for (let i=0;i<document.getElementsByClassName('agentInfoClass').length;i++){
              document.getElementsByClassName('agentInfoClass')[i].style.display = 'none'
          }
          for (let i=0;i<document.getElementsByClassName('getMore').length;i++){
              document.getElementsByClassName('getMore')[i].style.display = 'none'
          }
          $('.siteItems').addClass('choseSkill')
        break
        case "3":
          document.getElementById('otherBoard').style.display = 'none'
          document.getElementById('siteTree').style.display = 'none'
          document.getElementById('ivrlist').style.display = 'flex'
          document.getElementById('siteText').innerHTML = i18ntc('IVR搜索') + '：'
          document.getElementById('callPhone').setAttribute('placeholder',i18ntc('请输入'))
        break
    }
})
document.getElementById('closeBtn').addEventListener("click", function(e) {
    document.getElementById('setBox').style.display = 'none'
    getSet()
})
document.getElementById('setCancel').addEventListener("click", function(e) {
    document.getElementById('setBox').style.display = 'none'
    getSet()
})
document.getElementById('submit').addEventListener("click", function(e) {
    updateSet()
    document.getElementById('setBox').style.display = 'none'
    getSet()
    handleInitPopWork();
})
document.getElementById('detection').addEventListener("click", function(e) {
    document.getElementById('detectionBox').style.display = 'flex'
    document.getElementById('showMore').style.display = 'none'
    $('.basic_one_wrap').show().siblings().hide()
    $('.basic_monitor_close').show()
})
document.getElementById('toggleMode1').addEventListener("click", function(e) {
    toggleServiceMode(2)
})
document.getElementById('toggleMode2').addEventListener("click", function(e) {
    toggleServiceMode(1)
})
document.getElementById('topCall').addEventListener("click", function(e) {
    e.stopPropagation();
    if (document.getElementById('customerDiv').style.display != 'flex'){
        document.getElementById('customerDiv').style.display = 'flex'
        document.getElementById('sitetypeArrow').style.transform = 'rotate(180deg)'
    } else {
        document.getElementById('customerDiv').style.display = 'none'
        document.getElementById('sitetypeArrow').style.transform = 'rotate(0)'
    }
})
// document.getElementById('customerDiv').addEventListener("mouseleave", function(e) {
//     document.getElementById('customerDiv').style.display = 'none'
//     document.getElementById('sitetypeArrow').style.transform = 'rotate(0)'
// })
document.getElementById('sitetypetips1').addEventListener("mouseover", function(e) {
    document.getElementById('sitetypetipsText1').style.display = 'flex'
})
document.getElementById('sitetypetips2').addEventListener("mouseover", function(e) {
    document.getElementById('sitetypetipsText2').style.display = 'flex'
})
document.getElementById('sitetypetips1').addEventListener("mouseout", function(e) {
    document.getElementById('sitetypetipsText1').style.display = 'none'
})
document.getElementById('sitetypetips2').addEventListener("mouseout", function(e) {
    document.getElementById('sitetypetipsText2').style.display = 'none'
})
    // 摄像头选择框点击
    $('.basic_camera_select').on('click', 'li',  function() {
        let is_active = $(this).children('.label').hasClass('active');
        if(!is_active) {
            let label = $(this).children('.label').text();
            basic_monitor_obj.camera_name = label;
            $(this).parent().siblings('input').val(label);
            //赋值option
            let option = $(this).children('.label').attr('option');
            basic_monitor_obj.camera_id = option;
            $(this).parent().siblings('input').attr('option', option);
            // active
            $(this).children('.label').addClass('active');
            $(this).siblings().children('.label').removeClass('active');
            // 切换相机
            create_camera_stream();
        }
    });
    // 麦克风选择框点击
    $('.basic_microphone_select').on('click', 'li',  function() {
        let is_active = $(this).children('.label').hasClass('active');
        if(!is_active) {
            let label = $(this).children('.label').text();
            basic_monitor_obj.microphone_name = label;
            $(this).parent().siblings('input').val(label);
            //赋值option
            let option = $(this).children('.label').attr('option');
            basic_monitor_obj.microphone_id = option;
            $(this).parent().siblings('input').attr('option', option);
            // active
            $(this).children('.label').addClass('active');
            $(this).siblings().children('.label').removeClass('active');
            // 切换麦克风
            create_microphone_stream();
        }
    });
    // 扬声器选择框点击
    $('.basic_speaker_select').on('click', 'li',  function() {
        let is_active = $(this).children('.label').hasClass('active');
        if(!is_active) {
            let label = $(this).children('.label').text();
            basic_monitor_obj.speaker_name = label;
            $(this).parent().siblings('input').val(label);
            //赋值option
            let option = $(this).children('.label').attr('option');
            basic_monitor_obj.speaker_id = option;
            $(this).parent().siblings('input').attr('option', option);
            // active
            $(this).children('.label').addClass('active');
            $(this).siblings().children('.label').removeClass('active');
            // 切换扬声器
            set_audio_id(option);
        }
    });
    $('.camera_select_ul').on('click','li',function(e){
        $('#camera_select_wrap').val(e.target.innerHTML)
        if (e.target.getAttribute('option') != basic_monitor_obj.camera_id){
            swithc_cameras(e.target.getAttribute('option'))
            basic_monitor_obj.camera_id = e.target.getAttribute('option')
        }
    })
    $('.record_select_ul').on('click','li',function(e){
        $('#record_select_wrap').val(e.target.innerHTML)
        if (e.target.getAttribute('option') != basic_monitor_obj.microphone_id){
            swithc_mic(e.target.getAttribute('option'))
            basic_monitor_obj.microphone_id = e.target.getAttribute('option')
        }
    })
    $('.playout_select_ul').on('click','li',function(e){
        $('#playout_select_wrap').val(e.target.innerHTML)
        if (e.target.getAttribute('option') != basic_monitor_obj.speaker_id){
            swithc_speaker(e.target.getAttribute('option'))
            basic_monitor_obj.speaker_id = e.target.getAttribute('option')
        }
    })
    // 坐席助手
    document.getElementById('seatAssistantBoxNarrowBtn').addEventListener("click", function(e) {
        let seatAssistantBoxPannel = document.getElementById("seatAssistantBoxPannel");
        seatAssistantBoxPannel.style.display = "none";
    });
    document.getElementById('seatAssistantBoxRestoreBtn').addEventListener("click", function(e) {
        let seatAssistantBoxEnlargeBtn = document.getElementById("seatAssistantBoxEnlargeBtn");
        seatAssistantBoxEnlargeBtn.style.display = "block";
        let seatAssistantBoxRestoreBtn = document.getElementById("seatAssistantBoxRestoreBtn");
        seatAssistantBoxRestoreBtn.style.display = "none";
        let seatAssistantBoxPannel = document.getElementById("seatAssistantBoxPannel");
        seatAssistantBoxPannel.style.position = "absolute";
        seatAssistantBoxPannel.style.width = seatBoxEnlargeParams.width + 'px';
        seatAssistantBoxPannel.style.height = seatBoxEnlargeParams.height + 'px';
        seatAssistantBoxPannel.style.top = seatBoxEnlargeParams.top + 'px';
        seatAssistantBoxPannel.style.left = seatBoxEnlargeParams.left + 'px';
        handleSeatABoxUserArrow();
    });
    document.getElementById('seatAssistantBoxEnlargeBtn').addEventListener("click", function(e) {
        let seatAssistantBoxEnlargeBtn = document.getElementById("seatAssistantBoxEnlargeBtn");
        seatAssistantBoxEnlargeBtn.style.display = "none";
        let seatAssistantBoxRestoreBtn = document.getElementById("seatAssistantBoxRestoreBtn");
        seatAssistantBoxRestoreBtn.style.display = "block";
        let seatAssistantBoxPannel = document.getElementById("seatAssistantBoxPannel");
        seatBoxEnlargeParams = {
            width: seatAssistantBoxPannel.offsetWidth,
            height: seatAssistantBoxPannel.offsetHeight,
            top: seatAssistantBoxPannel.offsetTop,
            left: seatAssistantBoxPannel.offsetLeft,
        }
        handleSeatAssistantBoxEnlarge();
    });
    document.getElementById('seatAssistantBoxCloseBtn').addEventListener("click", function(e) {
        let seatAssistantBoxPannel = document.getElementById("seatAssistantBoxPannel");
        seatAssistantBoxPannel.style.display = "none";
        handleCloseSeatAssistantBox();
    });
    //客户 文本翻译目标语言
    document.getElementById('seatABoxCustomTargetLanguage').addEventListener("click", function(e) {
        let targetCustomLanguageSelectWrap = document.getElementById('targetCustomLanguageSelectWrap');
        if(targetCustomLanguageSelectWrap.style.display == 'none' || !targetCustomLanguageSelectWrap.style.display) {
            document.getElementById('targetCustomLanguageSelectWrap').style.display = "block";
        }else{
            hideTargetCustomLanguageSelectWrap()
        }
    });
    document.getElementById('targetCustomLanguageSelectWrap').addEventListener("click", function(e) {
        if (e.target.classList.contains('targetLanguageSelectItem')) {
            let dataValue = e.target.getAttribute('data-value');
            let textContent = e.target.textContent.trim();
            document.getElementById('seatABoxCustomTargetLanguage').innerHTML = textContent;
            setParam.customAsrTranslateType = Number(dataValue);
            updateSet()
            hideTargetLanguageSelectWrap()
        }
    });
    //my 文本翻译目标语言
    document.getElementById('seatABoxTargetLanguage').addEventListener("click", function(e) {
        let targetLanguageSelectWrap = document.getElementById('targetLanguageSelectWrap');
        if(targetLanguageSelectWrap.style.display == 'none' || !targetLanguageSelectWrap.style.display) {
            document.getElementById('targetLanguageSelectWrap').style.display = "block";
        }else{
            hideTargetLanguageSelectWrap()
        }
    });
    document.getElementById('targetLanguageSelectWrap').addEventListener("click", function(e) {
        if (e.target.classList.contains('targetLanguageSelectItem')) {
            let dataValue = e.target.getAttribute('data-value');
            let textContent = e.target.textContent.trim();
            document.getElementById('seatABoxTargetLanguage').innerHTML = textContent;
            setParam.asrTranslateType = Number(dataValue);
            updateSet()
            hideTargetLanguageSelectWrap()
        }
    });

    $('body').on('click', function(e){
        if($(e.target).attr('id') != 'seatABoxCustomTargetLanguage') {
            hideTargetCustomLanguageSelectWrap()
        }
        if($(e.target).attr('id') != 'seatABoxCustomSendLanguage') {
            hideSendCustomLanguageSelectWrap()
        }
        if($(e.target).attr('id') != 'seatABoxTargetLanguage') {
            hideTargetLanguageSelectWrap()
        }
        if($(e.target).attr('id') != 'seatABoxSendLanguage') {
            hideSendLanguageSelectWrap()
        }
    })
    function hideTargetCustomLanguageSelectWrap() {
        document.getElementById('targetCustomLanguageSelectWrap').style.display = "none";
    }
    function hideTargetLanguageSelectWrap() {
        document.getElementById('targetLanguageSelectWrap').style.display = "none";
    }
    //客户 发送翻译语言
    document.getElementById('seatABoxCustomSendLanguage').addEventListener("click", function(e) {
        let sendCustomLanguageSelectWrap = document.getElementById('sendCustomLanguageSelectWrap');
        if(sendCustomLanguageSelectWrap.style.display == 'none' || !sendCustomLanguageSelectWrap.style.display) {
            document.getElementById('sendCustomLanguageSelectWrap').style.display = "block";
        }else{
            hideSendCustomLanguageSelectWrap()
        }
    });
    document.getElementById('sendCustomLanguageSelectWrap').addEventListener("click", function(e) {
        if (e.target.classList.contains('targetLanguageSelectItem')) {
            let dataValue = e.target.getAttribute('data-value');
            // let textContent = e.target.textContent.trim();
            // document.getElementById('seatABoxCustomSendLanguage').innerHTML = textContent;
            hideSendCustomLanguageSelectWrap()
            updateVoiceTranslateSwitch({
                uuid: asrCustomUuid,
                translate_type: 1,
                trans_lang_id: Number(dataValue),
            });
        }
    });

    function hideSendCustomLanguageSelectWrap() {
        document.getElementById('sendCustomLanguageSelectWrap').style.display = "none";
    }
    //my 发送翻译语言
    document.getElementById('seatABoxSendLanguage').addEventListener("click", function(e) {
        let sendLanguageSelectWrap = document.getElementById('sendLanguageSelectWrap');
        if(sendLanguageSelectWrap.style.display == 'none' || !sendLanguageSelectWrap.style.display) {
            document.getElementById('sendLanguageSelectWrap').style.display = "block";
        }else{
            hideSendLanguageSelectWrap()
        }
    });
    document.getElementById('sendLanguageSelectWrap').addEventListener("click", function(e) {
        if (e.target.classList.contains('targetLanguageSelectItem')) {
            let dataValue = e.target.getAttribute('data-value');
            // let textContent = e.target.textContent.trim();
            // document.getElementById('seatABoxSendLanguage').innerHTML = textContent;
            hideSendLanguageSelectWrap()
            updateVoiceTranslateSwitch({
                uuid: asrMyUuid,
                translate_type: 1,
                trans_lang_id: Number(dataValue),
            });
        }
    });

    function hideSendLanguageSelectWrap() {
        document.getElementById('sendLanguageSelectWrap').style.display = "none";
    }

    let seatABoxDropUp = document.getElementById('seatABoxDropUp');
    let seatABoxDropDown = document.getElementById('seatABoxDropDown');
    let seatABoxNeckList = document.querySelectorAll('.seatABoxNeck');
    // height: calc(100% - 56px - 65px);
    seatABoxDropUp.addEventListener('click', function() {
        seatABoxDropUp.style.display = 'none';
        seatABoxDropDown.style.display = 'block';

        seatABoxNeckList.forEach(function(element) {
            element.style.display = 'none';
        });
        handleSeatABoxSearch();
    });
    seatABoxDropDown.addEventListener('click', function() {
        seatABoxDropDown.style.display = 'none';
        seatABoxDropUp.style.display = 'block';
        seatABoxNeckList.forEach(function(element) {
            element.style.display = 'flex';
        });
        handleSeatABoxSearch();
    });

    // search
    let seatABoxSearchWrap = document.getElementById('seatABoxSearchWrap');
    let searchToggle = document.getElementById('seatABoxSearchIconWrap');
    let searchBox = document.getElementById('seatABoxSearchInput');
    let searchSubmit = document.getElementById('seatABoxSearchSubmit');
    searchToggle.addEventListener('click', function() {
        searchBox.classList.toggle('active');
        seatABoxSearchWrap.style.width = "auto";
        if (searchBox.classList.contains('active')) {
            searchSubmit.style.display = 'inline-block';
        } else {
            seatABoxSearchWrap.style.width = "36px";
            searchSubmit.style.display = 'none';
        }
    });
    // 回车滚动
    searchBox.addEventListener('keydown', function(e) {
        if(e.keyCode == 13) {
            searchRollScreen()
        }
    });
    // 搜索滚动
    searchSubmit.addEventListener('click', function(e) {
        searchRollScreen()
    });
    function searchRollScreen() {
        let text = seatABoxSearchInput.value;
        seatABoxSearchInput.value = "";
        let user_default_uuid = activeUserCallUuid;
        if(user_default_uuid) {
            let userCallLoglist = seatABoxUserHistory[user_default_uuid];
            let rollId = '';
            userCallLoglist.map(item => {
                if(item.src_text && item.src_text.indexOf(text) > -1) {
                    rollId = item.rollId;
                }
                if(!rollId) {
                    if(item.target_text && item.target_text.indexOf(text) > -1) {
                        rollId = item.rollId;
                    }
                }
            });
            if(rollId) {
                let offsetTop = document.getElementById(rollId).offsetTop;
                setTimeout(() => {
                    seatABoxContent.scrollTop = offsetTop;
                }, 100);
            }
        }
    }

    $("#seatABoxUserWrap").on('click', '.seatABoxUserItem', function(e) {
       // 历史聊天用户点击
        let seatABoxUserItems = document.querySelectorAll('#seatABoxUserWrap .seatABoxUserItem');
        seatABoxUserItems.forEach(item => {
            seatABoxUserItems.forEach(el => {
                el.classList.remove('active');
            });
        });
        $(this).addClass('active');
        let user_default_uuid = $(this).data("calluuid");
        activeUserCallUuid = user_default_uuid;
        let userCallLoglist = seatABoxUserHistory[user_default_uuid] || [];
        $('#seatABoxContent').empty();
        userCallLoglist.map(item => {
            updateCallLog(item);
            contentToBottom()
        });
        updateUserQualityCheckHistory(activeUserCallUuid)
        // handleInitPopWork();
    });

    // 初始化显示滑动箭头
    handleSeatABoxUserRightArrow();

    let seatABoxUserRightArrowBtn = document.getElementById('seatABoxUserRightArrowBtn');
    seatABoxUserRightArrowBtn.addEventListener('click', function() {
        let seatABoxUserLeftArrowBtnWrap = document.getElementById('seatABoxUserLeftArrowBtnWrap');
        seatABoxUserLeftArrowBtnWrap.style.display = "flex";
        let seatABoxUserWrap = document.getElementById('seatABoxUserWrap');
        let scrollLeft = seatABoxUserWrap.scrollLeft;
        let clientWidth = seatABoxUserWrap.clientWidth;
        seatABoxUserWrap.scrollLeft = scrollLeft + clientWidth;

        // 是否滚动到最右边
        handleSeatABoxUserToRight();

    });
    let seatABoxUserLeftArrowBtn = document.getElementById('seatABoxUserLeftArrowBtn');
    seatABoxUserLeftArrowBtn.addEventListener('click', function() {
        let seatABoxUserWrap = document.getElementById('seatABoxUserWrap');
        let scrollLeft = seatABoxUserWrap.scrollLeft;
        let clientWidth = seatABoxUserWrap.clientWidth;
        let left = scrollLeft - clientWidth;
        seatABoxUserWrap.scrollLeft = left > 0 ? left : 0;
        handleSeatABoxUserLeftArrow()
        handleSeatABoxUserRightArrow()
    });

    //客户 文本翻译
    let myCustomTranslateSwitch = document.getElementById('myCustomTranslateSwitch');
    myCustomTranslateSwitch.addEventListener('change', function() {
        if(!assistantEnablePermission['2']) {
            document.getElementById('myCustomTranslateSwitch').checked = false;
            return;
        }
        if (myCustomTranslateSwitch.checked) {
            let seatABoxCustomTargetLanguage = document.getElementById("seatABoxCustomTargetLanguage").innerHTML;
            Object.keys(textTargetKeys).map(item => {
                let language = textTargetKeys[item];
                if(language == seatABoxCustomTargetLanguage) {
                    setParam.customAsrTranslateType = Number(item);
                }
            });
            updateSet()
        } else {
            setParam.customAsrTranslateType = 0;
            updateSet()
        }
    });
    //客户 语音翻译
    let myCustomAudioTranslateSwitch = document.getElementById('myCustomAudioTranslateSwitch');
    myCustomAudioTranslateSwitch.addEventListener('change', function() {
        if(!assistantEnablePermission['3']) {
            document.getElementById('myCustomAudioTranslateSwitch').checked = false;
            return;
        }
        let trans_lang_id = 0;
        let seatABoxCustomTargetLanguage = document.getElementById("seatABoxCustomSendLanguage").innerHTML;
        Object.keys(audioTargetKeys).map(item => {
            let language = audioTargetKeys[item];
            if(language == seatABoxCustomTargetLanguage) {
                trans_lang_id = Number(item);
            }
        });
        if (myCustomAudioTranslateSwitch.checked) {
            myCustomAudioTranslateSwitch.checked = false;
            updateVoiceTranslateSwitch({
                uuid: asrCustomUuid,
                translate_type: 1,
                trans_lang_id: trans_lang_id,
            });
        } else {
            myCustomAudioTranslateSwitch.checked = true;
            updateVoiceTranslateSwitch({
                uuid: asrCustomUuid,
                translate_type: 0,
                trans_lang_id: trans_lang_id,
            });
        }
    });

    //my 文本翻译
    let myTranslateSwitch = document.getElementById('myTranslateSwitch');
    myTranslateSwitch.addEventListener('change', function() {
        if(!assistantEnablePermission['2']) {
            document.getElementById('myTranslateSwitch').checked = false;
            return;
        }
        if (myTranslateSwitch.checked) {
            let seatABoxTargetLanguage = document.getElementById("seatABoxTargetLanguage").innerHTML;
            Object.keys(textTargetKeys).map(item => {
                let language = textTargetKeys[item];
                if(language == seatABoxTargetLanguage) {
                    setParam.asrTranslateType = Number(item);
                }
            });
            updateSet()
        } else {
            setParam.asrTranslateType = 0;
            updateSet()
        }
    });

    //my 语音翻译
    let myAudioTranslateSwitch = document.getElementById('myAudioTranslateSwitch');
    myAudioTranslateSwitch.addEventListener('change', function() {
        if(!assistantEnablePermission['3']) {
            document.getElementById('myAudioTranslateSwitch').checked = false;
            return;
        }
        let trans_lang_id = 0;
        let seatABoxCustomTargetLanguage = document.getElementById("seatABoxSendLanguage").innerHTML;
        Object.keys(audioTargetKeys).map(item => {
            let language = audioTargetKeys[item];
            if(language == seatABoxCustomTargetLanguage) {
                trans_lang_id = Number(item);
            }
        });
        if (myAudioTranslateSwitch.checked) {
            myAudioTranslateSwitch.checked = false;
            updateVoiceTranslateSwitch({
                uuid: asrMyUuid,
                translate_type: 1,
                trans_lang_id: trans_lang_id,
            });
        } else {
            myAudioTranslateSwitch.checked = true;
            updateVoiceTranslateSwitch({
                uuid: asrMyUuid,
                translate_type: 0,
                trans_lang_id: trans_lang_id,
            });
        }
    });

    // 自动滚屏
    // let myRollScreenSwitch = document.getElementById('myRollScreenSwitch');
    // myRollScreenSwitch.addEventListener('change', function() {
    //     if (myRollScreenSwitch.checked) {
    //         localStorage.setItem("myRollScreenSwitch", true)
    //     } else {
    //         localStorage.setItem("myRollScreenSwitch", false)
    //     }
    // });

    // 复制
    $("#seatABoxContent").on('click', '.seatABoxContentCopyImgBtn', function(e) {
        let srcText = e.target.getAttribute('data-src_text');
        handleCopyText(srcText);

    });

    // 图片按钮翻译
    $("#seatABoxContent").on('click', '.seatABoxContentTranslateImgBtn', function(e) {
        let src_text = e.target.getAttribute('data-src_text');
        let src_lang_id = e.target.getAttribute('data-src_lang_id');
        let parentDom = $(this).parent().siblings('.seatABoxContentTxtWrap');

        translateText(parentDom, {
            src_text: src_text,
            src_lang_id: src_lang_id,
            trans_lang_id: setParam.asrTranslateType,
        });
    });

    //点击按钮翻译
    $("#seatABoxContent").on('click', '.seatABoxContentTraRetryTxt', function(e) {
        seatABoxContentTraBtnTraFun(e)
    });
    //点击翻译失败按钮翻译
    $("#seatABoxContent").on('click', '.seatABoxContentTraErrorTxt', function(e) {
        seatABoxContentTraBtnTraFun(e)
    });

    // 右侧收起展开
    let seatABoxPullUp = document.getElementById('seatABoxPullUp');
    let seatABoxPullDown = document.getElementById('seatABoxPullDown');
    let seatAssistantBoxPannelRight = document.querySelectorAll('.seatAssistantBoxPannelRight');
    let seatAssistantBoxPannel = document.getElementById('seatAssistantBoxPannel');
    seatABoxPullUp.addEventListener('click', function() {
        seatABoxPullUp.style.display = 'none';
        seatABoxPullDown.style.display = 'block';
        seatAssistantBoxPannelRight.forEach(function(element) {
            element.style.display = 'none';
        });
        showAiDetectionTimeWrap();
        showKnowledgeRecommentWrap();
    });
    seatABoxPullDown.addEventListener('click', function() {
        seatABoxPullDown.style.display = 'none';
        seatABoxPullUp.style.display = 'block';
        seatAssistantBoxPannelRight.forEach(function(element) {
            element.style.display = 'flex';
        });
        hideKnowledgeRecommentWrap();
        hideAiDetectionTimeWrap();
    });

    // tab点击
    $(".aiRecognitionTabsWrap .aiRecognitionTabItem").click(function () {
        let type = $(this).attr('data-type');
        $(this).addClass('active').siblings().removeClass('active');
        $('.aiRecognitionTabsContent .aiRecognitionTab').hide();
        if(type == '1') {
            $(".aiRecognitionTabOneWrap").show();
        }else if(type == '2') {
            $(".aiRecognitionTabTwoWrap").show();
        }else if(type == '3') {
            $(".aiRecognitionTabThreeWrap").show();
        }
    })

    function seatABoxContentTraBtnTraFun(e) {
        let src_text = e.target.getAttribute('data-src_text');
        let src_lang_id = e.target.getAttribute('data-src_lang_id');
        let parentDom = $(e.target).parent().parent();
        translateText(parentDom, {
            src_text: src_text,
            src_lang_id: src_lang_id,
            trans_lang_id: setParam.asrTranslateType,
        });
    }

    let resizableDiv = document.getElementById('seatAssistantBoxPannel');
    const resizeObserver = new ResizeObserver(entries => {
        for (let entry of entries) {
            const { width, height } = entry.contentRect;
            handleSeatABoxUserArrow();
            handleSeatABoxSearch();
        }
    });
    if(resizableDiv) {
        resizeObserver.observe(resizableDiv);
    }

    document.getElementById('changeWorkOrderSure').addEventListener("click", function(e) {
        let changeWorkOrderSure = document.getElementById('changeWorkOrderSure');
        setParam[changeWorkOrderSure.getAttribute('data-name')] = changeWorkOrderSure.getAttribute('data-value')
        document.getElementById('changeWorkOrderBox').style.display = 'none';
    })
    document.getElementById('changeWorkOrderCancel').addEventListener("click", function(e) {
        document.getElementById('changeWorkOrderBox').style.display = 'none';
        var radioButtons = document.querySelectorAll('input[name="companyCustomFromId"]');
        radioButtons.forEach(function(radioButton) {
            if (radioButton.value == setParam.companyCustomFromId) {
                radioButton.checked = true;
            }else{
                radioButton.checked = false;
            }
        });
    })
}
//状态背景色
function bgColor(val){
    switch (val){
        case i18ntc('离线'):
        return '#CACACA'
        case i18ntc('空闲'):
        return '#2ED8AD'
        case i18ntc('忙碌'):
        return '#EA1A00'
        case i18ntc('小休'):
        return '#FF6011'
        case i18ntc('事后处理'):
        return '#E0194F'
        case i18ntc('振铃'):
        return '#F9C22E'
        case i18ntc('通话'):
        return '#627DFF'
        case i18ntc('整理'):
        return '#02830F'
      }
}
function bgText(val){
    switch (val){
        case 'OFFLINE':
            nowStatusText = '离线'
        return i18ntc('离线')
        case 'FREE':
            nowStatusText = '空闲'
        return i18ntc('空闲')
        case 'BUSY':
            nowStatusText = '忙碌'
        return i18ntc('忙碌')
        case 'REST':
            nowStatusText = '小休'
        return i18ntc('小休')
        case 'ARRANGE':
            nowStatusText = '事后处理'
        return i18ntc('事后处理')
        case 'RINGING':
            nowStatusText = '振铃'
        return i18ntc('振铃')
        case 'CALLING':
            nowStatusText = '通话'
        return i18ntc('通话')
        case 'PLAY_RECORD':
            nowStatusText = '整理'
        return i18ntc('整理')
        default:
            nowStatusText = '离线'
        return i18ntc('离线')
      }
}
function switch_audio_mode(){
    changeMedia('audio')
}
// 获取设置记录
async function getSet(){
    await getToken({
        company_code,
        agent_pwd,
        agent_id: company_code + '_' + agent_id,
        msg_type: "get_token",
        os: system,
        req_id: generateUUID(),
    })
    ajax({
        type: 'GET',
        url: dominUrl + 'cloudcc-client-server/openapi/get-agent-info',
        data: {company_code,agent_id: company_code+'_'+agent_id},
        success: function (res) {
            let result = JSON.parse(res)
            setParam = result.data
            handleSeatAssistantSetting();
            if (setParam.agentAnswerMode == '2'){
                $('.requestTypeClass').css('display','flex')
            } else {
                $('.requestTypeClass').hide()
            }
            for (key in setParam){
                if (key == 'phoneNumber'){
                    document.getElementById('onlinePhone').value = setParam[key]
                } else if (key == 'callNoteAbilities'){
                    if (setParam[key]){
                        let obj = JSON.parse(setParam[key])
                        for (keyItem in obj){
                            switch (keyItem){
                                case "change_media":
                                    if (obj[keyItem]  == false || obj[keyItem] == 'false'){
                                        document.getElementById('toVideo').style.width = '0px'
                                        document.getElementById('toVideo').style.visibility = 'hidden'
                                    }
                                    break;
                                case "consult":
                                    if (obj[keyItem]  == false || obj[keyItem] == 'false'){
                                        document.getElementById('consulting').style.width = '0px'
                                        document.getElementById('consulting').style.visibility = 'hidden'
                                    }
                                    break;
                                case "hold":
                                    if (obj[keyItem]  == false || obj[keyItem] == 'false'){
                                        document.getElementById('hold').style.width = '0px'
                                        document.getElementById('hold').style.visibility = 'hidden'
                                    }
                                    break;
                                case "mute":
                                    if (obj[keyItem]  == false || obj[keyItem] == 'false'){
                                        document.getElementById('mute').style.width = '0px'
                                        document.getElementById('mute').style.visibility = 'hidden'
                                    }
                                    break;
                                case "trans":
                                    if (obj[keyItem]  == false || obj[keyItem] == 'false'){
                                        document.getElementById('trans').style.width = '0px'
                                        document.getElementById('transfer').style.width = '0px'
                                        document.getElementById('trans').style.visibility = 'hidden'
                                        document.getElementById('transfer').style.visibility = 'hidden'
                                    }
                                    break;
                                case "csat":
                                    if (obj[keyItem]  == false || obj[keyItem] == 'false'){
                                        document.getElementById('satisfaction').style.width = '0px'
                                        document.getElementById('satisfaction').style.visibility = 'hidden'
                                    }
                                    break;
                                case "three_way":
                                    if (obj[keyItem]  == false || obj[keyItem] == 'false'){
                                        document.getElementById('threeCall').style.width = '0px'
                                        document.getElementById('threeCall').style.visibility = 'hidden'
                                    }
                                    break;
                            }
                        }
                    }
                } else {
                    for (let i=0;i<document.getElementsByName(key).length;i++){
                        if (document.getElementsByName(key)[i].value == setParam[key]){
                            document.getElementsByName(key)[i].checked = true
                            if (key == 'offlineAgent'){
                                if (setParam[key] == '0'){
                                    document.getElementById('onlinePhone').style.display = 'none'
                                } else {
                                    document.getElementById('onlinePhone').style.display = 'block'
                                }
                            }
                        }
                    }
                }
            }
        }, error: function(err){
        }
    })
    getFromByAgentId();
}
async function updateSet(){
    await getToken({
        company_code,
        agent_pwd,
        agent_id: company_code + '_' + agent_id,
        msg_type: "get_token",
        os: system,
        req_id: generateUUID(),
    })
    setParam.phoneNumber = document.getElementById('onlinePhone').value
    ajax({
        type: 'POST',
        url: dominUrl + 'cloudcc-client-server/openapi/update-agent-info',
        data: setParam,
        success: function (res) {
            let result = JSON.parse(res)
            if (result.code == 0){
                getSet()
            } else {
                toastMessage(result.msg)
            }
        }, error: function(err){
        }
    })
}
function changeSet(val){
    setParam[val.getAttribute('name')] = val.getAttribute('value')
    if (val.getAttribute('name') == 'offlineAgent'){
        if (val.getAttribute('value') == '0'){
            document.getElementById('onlinePhone').style.display = 'none'
        } else {
            document.getElementById('onlinePhone').style.display = 'block'
        }
    }
    if (val.getAttribute('name') == 'agentAnswerMode'){
        if (val.getAttribute('value') == '2'){
           $('.requestTypeClass').css('display','flex')
        } else {
            $('.requestTypeClass').hide()
        }
    }
}
//获取IVRlist
async function getIvrList(service_name){
    await getToken({
        company_code,
        agent_pwd,
        agent_id: company_code + '_' + agent_id,
        msg_type: "get_token",
        os: system,
        req_id: generateUUID(),
    })
    ajax({
        type: 'GET',
        url: dominUrl + 'cloudcc-client-server/openapi/get-ivr-service-list',
        data: {company_code,service_name:service_name||''},
        success: function (res) {
            let result = JSON.parse(res)
            ivrList = result.data
            let str = ''
            for (let i=0;i<ivrList.length;i++){
                str += `<span onclick="inputIvr('${ivrList[i].ivr_service_id}','${ivrList[i].ivr_service_name}')">${ivrList[i].ivr_service_name}</span>`
            }
            document.getElementById('ivrlist').innerHTML = str
        }, error: function(err){
        }
    })
}
//获取坐席
async function getagents(keyword){
    await getToken({
        company_code,
        agent_pwd,
        agent_id: company_code + '_' + agent_id,
        msg_type: "get_token",
        os: system,
        req_id: generateUUID(),
    })
    ajax({
        type: 'POST',
        url: dominUrl + 'cloudcc-client-server/openapi/get-agent-list',
        data: {company_code,page_size: '5',page_no: '1',agent_id: company_code+'_'+agent_id,skill_id:'',keyword: keyword || ''},
        success: function (res) {
            let result = JSON.parse(res)
            siteList = result.data
            let str = ''
            for (let i=0;i<siteList.length;i++){
                if (siteList[i].agents.list.length > 0){
                    str += `<div class="siteItems">
                    <div class='arrows'><img src=${resourceUrl}/images/strip/down.png id="img_${siteList[i].skill_id}">
                    <span value="${siteList[i].skill_id}">${siteList[i].skill_name}</span></div>
                    <div id="${siteList[i].skill_id}" class="agentInfo" style="display: flex;">`
                    for (let j=0;j < siteList[i].agents.list.length;j++){
                        str += `<div class='agentInfoClass'><span nodeValue="${siteList[i].agents.list[j].agent_id}">${siteList[i].agents.list[j].agent_name}</span><span nodeValue="${siteList[i].agents.list[j].agent_id}">${siteList[i].agents.list[j].agent_id}</span><span nodeValue="${siteList[i].agents.list[j].agent_id}" style="color: ${bgColor(bgText(siteList[i].agents.list[j].agent_status))};">${bgText(siteList[i].agents.list[j].agent_status)}</span></div>`
                    }
                    if (siteList[i].agents.total_page > 1){
                        str += `<span class="getMore" value="more" dataValue="${siteList[i].skill_id}" pageValue="1" id="${siteList[i].skill_id}_more">${i18ntc('加载更多')}</span>`
                    }
                    str += '</div></div>'
                }
            }
            document.getElementById('siteTree').innerHTML = str
        }, error: function(err){
        }
    })
}
//更多坐席
async function getAgentMoreList(val,page_no){
    await getToken({
        company_code,
        agent_pwd,
        agent_id: company_code + '_' + agent_id,
        msg_type: "get_token",
        os: system,
        req_id: generateUUID(),
    })
    ajax({
        type: 'POST',
        url: dominUrl + 'cloudcc-client-server/openapi/get-agent-list',
        data: {company_code,page_size: '5',page_no: Number(page_no) + 1,agent_id: company_code+'_'+agent_id,skill_id:val},
        success: function (res) {
            let result = JSON.parse(res)
            if (result.data[0].agents.list.length > 0){
                let str = ''
                for (let j=0;j < result.data[0].agents.list.length;j++){
                    str += `<div class='agentInfoClass'><span nodeValue="${result.data[0].agents.list[j].agent_id}">${result.data[0].agents.list[j].agent_name}</span><span nodeValue="${result.data[0].agents.list[j].agent_id}">${result.data[0].agents.list[j].agent_id}</span><span nodeValue="${result.data[0].agents.list[j].agent_id}" style="color: ${bgColor(bgText(result.data[0].agents.list[j].agent_status))};">${bgText(result.data[0].agents.list[j].agent_status)}</span></div>`
                }
                let dom = document.createElement('div')
                if (result.data[0].agents.total_page - 1 > Number(page_no)){
                    str += `<span class="getMore" value="more" dataValue="${result.data[0].skill_id}" pageValue="${Number(page_no) + 1}" id="${result.data[0].skill_id}_more">加载更多</span>`
                }
                dom.innerHTML = str
                document.getElementById(result.data[0].skill_id).appendChild(dom)
            }
        },
        error: function(err){
            if (typeof(ccs5Application) != 'undefined'&& ccs5Application.on_ajax_fail){
                ccs5Application.on_ajax_fail(JSON.stringify(err))
            }
        }
    })
}
// 获取状态颜色
function getStatusColor(val){
    switch (val){
        case '1' || 1:
        return '#2ED8AD'
        case '2' || 2:
        return '#EA1A00'
        case '100' || 100:
        return '#CACACA'
    }
}
function inputIvr(ivrId,ivrName){
    ivrObj = {
        ivrId,ivrName
    }
    document.getElementById('callPhone').value = ivrName
}
// 选择坐席选项
function changeSite(){
    document.getElementById('otherBoard').style.display = 'none'
    document.getElementById('siteTree').style.display = 'block'
    document.getElementById('siteText').innerHTML = i18ntc('坐席搜索') + '：'
    document.getElementById('ivrlist').style.display = 'none'
    $('.siteItems').removeClass('choseSkill')
    for (let i=0;i<document.getElementsByClassName('agentInfoClass').length;i++){
        document.getElementsByClassName('agentInfoClass')[i].style.display = 'flex'
    }
    for (let i=0;i<document.getElementsByClassName('getMore').length;i++){
        document.getElementsByClassName('getMore')[i].style.display = 'block'
    }
    document.getElementById('callPhone').dispatchEvent(new InputEvent("input"))
}

// 基础监测js
var basic_monitor_obj = {
    current_click_step: 0, //当前正看到的步骤
    current_step: 0, // 当前已经检测的步骤
    camera: false, // 摄像头是否看得见
    camera_id: '', // 摄像头ID
    camera_name: '', // 摄像头名称
    microphone: false, // 麦克风是否看得见
    microphone_id: '', // 麦克风ID
    microphone_name: '', // 麦克风名称
    speaker: false, // 扬声器是否听得见
    speaker_id: '', // 扬声器ID
    speaker_name: '', // 扬声器名称
    network_delay: '未知', // 网络延迟
}
var basic_camera_stream = null;
var basic_microphone_stream = null;
var basic_microphone_volume_timer = null;
var detection_time_countdown_timer = null; //检测时间倒计时
var is_check_finish = false; //是否已经检测完成

$(document).ready(function() {
    is_check_expire();
    init_basic_select();
});

// 6小时弹窗检测
function is_check_expire() {
    let basic_check_time = localStorage.getItem('basic_check_time');
    if(!basic_check_time){
        localStorage.setItem('basic_check_time', Date.now());
        basic_monitor_show();
    }
}

// 清空检测时间
function remove_basic_check_time() {
    localStorage.removeItem('basic_check_time');
}

// 检测弹窗显示
function basic_monitor_show() {
    start_check_dom();
    $('.basic_monitor_popup').css('display','flex')
}

// 开始检测相关dom显示
function start_check_dom() {
    $('.basic_monitor_close').show();
    $('.basic_progress_header_wrap').hide();
    $('.basic_one_wrap').show();
    $('.basic_two_wrap').hide();
    $('.basic_three_wrap').hide();
    $('.basic_four_wrap').hide();
    $('.basic_five_wrap').hide();
    $('.basic_six_wrap').hide();
    start_check_init_data();
}

function start_check_init_data() {
    basic_monitor_obj = {
        current_click_step: 0, //当前正看到的步骤
        current_step: 0, // 当前已经检测的步骤
        camera: false, // 摄像头是否看得见
        camera_id: '', // 摄像头ID
        camera_name: '', // 摄像头名称
        microphone: false, // 麦克风是否看得见
        microphone_id: '', // 麦克风ID
        microphone_name: '', // 麦克风名称
        speaker: false, // 扬声器是否听得见
        speaker_id: '', // 扬声器ID
        speaker_name: '', // 扬声器名称
        network_delay: '未知', // 网络延迟
    }
    // 首个检测页面
    update_start_check_page();
}

// 开始检测页面更新
function update_start_check_page() {
    getCameras().then(devices => {
        if(devices.length > 0) {
            $('.basic_one_camera').attr('src', resourceUrl + '/images/monitor/check.png');
        }else{
            $('.basic_one_camera').attr('src', resourceUrl + '/images/monitor/error.png');
        }
    });
    getRecordingDevices().then(devices => {
        if(devices.length > 0) {
            $('.basic_one_microphone').attr('src', resourceUrl + '/images/monitor/check.png');
        }else{
            $('.basic_one_microphone').attr('src', resourceUrl +  '/images/monitor/error.png');
        }
    });
    getPlayoutDevices().then(devices => {
        if(devices.length > 0) {
            $('.basic_one_speaker').attr('src', resourceUrl + '/images/monitor/check.png');
        }else{
            $('.basic_one_speaker').attr('src', resourceUrl + '/images/monitor/error.png');
        }
    });
    if(navigator.onLine) {
        $('.basic_one_network').attr('src', resourceUrl + '/images/monitor/check.png');
    }else{
        $('.basic_one_network').attr('src', resourceUrl + '/images/monitor/error.png');
    }
}

function basic_monitor_hide() {
    stop_basic_camera_stream();
    stop_basic_microphone_stream();
    $('.basic_monitor_popup').hide();
}
/**
 * @desc 获取摄像头
 */
 function getCamera() {
    let Dom = $('.camera_select_ul');
    Dom.empty();
    // 相机选择框点击事件
    $('.camera_select_ul').on('click', 'li',  function() {
        let label = $(this).children('.label').text();
        $(this).parent().siblings('input').val(label);
        //赋值option
        let option = $(this).children('.label').attr('option');
        $(this).parent().siblings('input').attr('option', option);
        // 切换相机
        changeCamera();
        // active
        $(this).children('.label').addClass('active');
        $(this).siblings().children('.label').removeClass('active');
    });
    client && client.getCameras(devices => {
        if(devices && devices.length > 0) {
            if(!set_params.cameraId){
                let _deviceId = devices[0]._deviceId;
                let _label = devices[0]._label;
                // 默认选中第一项
                set_params.cameraId = _deviceId;
                $('#camera_select_wrap').val(_label);
                $('#camera_select_wrap').attr('option', _deviceId);
            }
            for(let i = 0; i < devices.length; i++) {
                let _deviceId = devices[i]._deviceId;
                let _label = devices[i]._label;
                if(_deviceId && _label) {
                    let option = `<li><div class="label" option="${_deviceId}">${_label}</div></li>`;
                    if(set_params.cameraId == _deviceId) {
                        // 选中的
                        option = `<li><div class="label active" option="${_deviceId}">${_label}</div></li>`;
                    }
                    Dom.append(option);
                }
            }
        }
    });
}
function init_basic_select() {
    // 摄像头选择框点击
    $('.basic_camera_select').on('click', 'li',  function() {
        let is_active = $(this).children('.label').hasClass('active');
        if(!is_active) {
            let label = $(this).children('.label').text();
            basic_monitor_obj.camera_name = label;
            $(this).parent().siblings('input').val(label);
            //赋值option
            let option = $(this).children('.label').attr('option');
            basic_monitor_obj.camera_id = option;
            $(this).parent().siblings('input').attr('option', option);
            // active
            $(this).children('.label').addClass('active');
            $(this).siblings().children('.label').removeClass('active');
            // 切换相机
            create_camera_stream();
        }
    });
    // 麦克风选择框点击
    $('.basic_microphone_select').on('click', 'li',  function() {
        let is_active = $(this).children('.label').hasClass('active');
        if(!is_active) {
            let label = $(this).children('.label').text();
            basic_monitor_obj.microphone_name = label;
            $(this).parent().siblings('input').val(label);
            //赋值option
            let option = $(this).children('.label').attr('option');
            basic_monitor_obj.microphone_id = option;
            $(this).parent().siblings('input').attr('option', option);
            // active
            $(this).children('.label').addClass('active');
            $(this).siblings().children('.label').removeClass('active');
            // 切换麦克风
            create_microphone_stream();
        }
    });
    // 扬声器选择框点击
    $('.basic_speaker_select').on('click', 'li',  function() {
        let is_active = $(this).children('.label').hasClass('active');
        if(!is_active) {
            let label = $(this).children('.label').text();
            basic_monitor_obj.speaker_name = label;
            $(this).parent().siblings('input').val(label);
            //赋值option
            let option = $(this).children('.label').attr('option');
            basic_monitor_obj.speaker_id = option;
            $(this).parent().siblings('input').attr('option', option);
            // active
            $(this).children('.label').addClass('active');
            $(this).siblings().children('.label').removeClass('active');
            // 切换扬声器
            set_audio_id(option);
        }
    });

    $('.basic_camera_icon').on('click', function() {
        let has_active = $(this).hasClass('active') || $(this).hasClass('error');
        if(has_active){
            camera_icon_click();
        }
    });

    $('.basic_microphone_icon').on('click', function() {
        let has_active = $(this).hasClass('active') || $(this).hasClass('error');
        if(has_active){
            microphone_icon_click();
        }
    });

    $('.basic_speaker_icon').on('click', function() {
        let has_active = $(this).hasClass('active') || $(this).hasClass('error');
        if(has_active){
            speaker_icon_click();
        }
    });

    $('.basic_network_icon').on('click', function() {
        let has_active = $(this).hasClass('active') || $(this).hasClass('error');
        if(has_active){
            network_icon_click();
        }
    });
}

// 初始化相机选择框
function get_cameras_select() {
    getCameras().then(devices => {
        if(devices && devices.length > 0) {
            if(!basic_monitor_obj.camera_id || !basic_monitor_obj.camera_name){
                let _deviceId = devices[0].deviceId;
                let _label = devices[0].label;
                // 默认选中第一项
                basic_monitor_obj.camera = true;
                basic_monitor_obj.camera_id = _deviceId;
                basic_monitor_obj.camera_name = _label;
                $('#basic_camera_select_wrap').val(_label);
                $('#basic_camera_select_wrap').attr('option', _deviceId);
            }
            let Dom = $('.basic_camera_select');
            Dom.empty();
            for(let i = 0; i < devices.length; i++) {
                let _deviceId = devices[i].deviceId;
                let _label = devices[i].label;
                if(_deviceId && _label) {
                    let option = `<li><div class="label" option="${_deviceId}">${_label}</div></li>`;
                    if(basic_monitor_obj.camera_id == _deviceId) {
                        // 选中的
                        option = `<li><div class="label active" option="${_deviceId}">${_label}</div></li>`;
                    }
                    Dom.append(option);
                }
            }
        }
    });
}

// 初始化麦克风选择框
function get_microphone_select() {
    getRecordingDevices().then(devices => {
        if(devices && devices.length > 0) {
            if(!basic_monitor_obj.microphone_id || !basic_monitor_obj.microphone_name){
                let _deviceId = devices[0].deviceId;
                let _label = devices[0].label;
                // 默认选中第一项
                basic_monitor_obj.microphone = true;
                basic_monitor_obj.microphone_id = _deviceId;
                basic_monitor_obj.microphone_name = _label;
                $('#basic_microphone_select_wrap').val(_label);
                $('#basic_microphone_select_wrap').attr('option', _deviceId);
            }
            let Dom = $('.basic_microphone_select');
            Dom.empty();
            for(let i = 0; i < devices.length; i++) {
                let _deviceId = devices[i].deviceId;
                let _label = devices[i].label;
                if(_deviceId && _label) {
                    let option = `<li><div class="label" option="${_deviceId}">${_label}</div></li>`;
                    if(basic_monitor_obj.microphone_id == _deviceId) {
                        // 选中的
                        option = `<li><div class="label active" option="${_deviceId}">${_label}</div></li>`;
                    }
                    Dom.append(option);
                }
            }
        }
    });
}

/**
 * @desc 获取扬声器
 */
function get_basic_speaker() {
    getPlayoutDevices().then(devices => {
        if(devices && devices.length > 0) {
            if(!basic_monitor_obj.speaker_id || !basic_monitor_obj.speaker_name){
                let _deviceId = devices[0].deviceId;
                let _label = devices[0].label;
                // 默认选中第一项
                basic_monitor_obj.speaker = true;
                basic_monitor_obj.speaker_id = _deviceId;
                basic_monitor_obj.speaker_name = _label;
                set_audio_id(_deviceId);
                $('#basic_speaker_select_wrap').val(_label);
                $('#basic_speaker_select_wrap').attr('option', _deviceId);
            }
            let Dom = $('.basic_speaker_select');
            Dom.empty();
            for(let i = 0; i < devices.length; i++) {
                let _deviceId = devices[i].deviceId;
                let _label = devices[i].label;
                if(_deviceId && _label) {
                    let option = `<li><div class="label" option="${_deviceId}">${_label}</div></li>`;
                    if(basic_monitor_obj.speaker_id == _deviceId) {
                        // 选中的
                        option = `<li><div class="label active" option="${_deviceId}">${_label}</div></li>`;
                    }
                    Dom.append(option);
                }
            }
        }
    });
}

function set_audio_id(audio_id) {
    let basic_four_audio = document.getElementById('basic_four_audio');
    basic_four_audio.setSinkId(audio_id);
}

// 开始检测
function start_basic_monitor() {
    $('.basic_camera_icon .basic_progress_header_item_icon').attr('src', resourceUrl + '/images/monitor/camera_2.png');
    $('.basic_microphone_icon .basic_progress_header_item_icon').attr('src', resourceUrl + '/images/monitor/mic_4.png');
    $('.basic_speaker_icon .basic_progress_header_item_icon').attr('src', resourceUrl + '/images/monitor/speaker_4.png');
    $('.basic_network_icon .basic_progress_header_item_icon').attr('src', resourceUrl + '/images/monitor/net_4.png');

    $('.basic_progress_header_wrap').children('.basic_progress_header_item_line').removeClass('active');
    $('.basic_progress_header_wrap').children('.basic_progress_header_item').removeClass('active').removeClass('error');

    $('.basic_camera_icon').addClass('active');

    basic_monitor_obj.current_step = 1;
    basic_monitor_obj.current_click_step = 1;

    camera_icon_click();
    get_cameras_select();
}

// 摄像头可用点击
function camera_available_click(use) {
    let step = 2;
    stop_basic_camera_stream();
    // 页面显示
    basic_monitor_obj.camera = use;
    if(!use) {
        $('.basic_camera_icon .basic_progress_header_item_icon').attr('src', resourceUrl + '/images/monitor/camera_3.png');
        $('.basic_camera_icon').removeClass('active').addClass('error');
    }else{
        $('.basic_camera_icon .basic_progress_header_item_icon').attr('src', resourceUrl + '/images/monitor/camera_2.png');
        $('.basic_camera_icon').removeClass('error').addClass('active');
    }
    // 切换检测过的步骤
    if(basic_monitor_obj.current_step < step) {
        $('.basic_microphone_icon .basic_progress_header_item_icon').attr('src', resourceUrl + '/images/monitor/mic_2.png');
        $('.basic_microphone_icon').addClass('active');
        $('.basic_progress_header_wrap .basic_camera_line').addClass('active');
        basic_monitor_obj.current_step = 2;
        basic_monitor_obj.current_click_step = 2;
    }
    // 下一步
    microphone_icon_click();
    get_microphone_select();
}

// 麦克风可用点击
function microphone_available_click(use) {
    let step = 3;
    stop_basic_microphone_stream();
    basic_monitor_obj.microphone = use;
    if(!use) {
        $('.basic_microphone_icon .basic_progress_header_item_icon').attr('src', resourceUrl + '/images/monitor/mic_3.png');
        $('.basic_microphone_icon').removeClass('active').addClass('error');
    }else{
        $('.basic_microphone_icon .basic_progress_header_item_icon').attr('src', resourceUrl + '/images/monitor/mic_2.png');
        $('.basic_microphone_icon').removeClass('error').addClass('active');
    }
    if(basic_monitor_obj.current_step < step) {
        $('.basic_speaker_icon .basic_progress_header_item_icon').attr('src', resourceUrl + '/images/monitor/speaker_2.png');
        $('.basic_speaker_icon').addClass('active');
        $('.basic_progress_header_wrap .basic_microphone_line').addClass('active');
        basic_monitor_obj.current_step = 3;
        basic_monitor_obj.current_click_step = 3;
    }
    // 下一步
    speaker_icon_click();
    get_basic_speaker();
}

// 扬声器可用点击
function speaker_available_click(use) {
    let step = 4;
    stop_speaker_audio();
    basic_monitor_obj.speaker = use;
    if(!use) {
        $('.basic_speaker_icon .basic_progress_header_item_icon').attr('src', resourceUrl + '/images/monitor/speaker_3.png');
        $('.basic_speaker_icon').removeClass('active').addClass('error');
    }else{
        $('.basic_speaker_icon .basic_progress_header_item_icon').attr('src', resourceUrl + '/images/monitor/speaker_2.png');
        $('.basic_speaker_icon').removeClass('error').addClass('active');
    }
    if(basic_monitor_obj.current_step < step) {
        $('.basic_network_icon .basic_progress_header_item_icon').attr('src', resourceUrl + '/images/monitor/net_2.png');
        $('.basic_network_icon').addClass('active');
        $('.basic_progress_header_wrap .basic_speaker_line').addClass('active');
        basic_monitor_obj.current_step = 4;
        basic_monitor_obj.current_click_step = 4;
    }
    // 下一步
    network_icon_click();
    basic_network_check();
}

// 摄像头图标点击
function camera_icon_click() {
    $('.basic_progress_header_wrap').show();
    $('.basic_one_wrap').hide();
    $('.basic_two_wrap').show(); //其他弹窗hide
    $('.basic_three_wrap').hide();
    $('.basic_four_wrap').hide();
    $('.basic_five_wrap').hide();
    $('.basic_six_wrap').hide();

    basic_monitor_obj.current_click_step = 1;

    stop_basic_microphone_stream();

    //开启视频流
    create_camera_stream();
}

// 麦克风图标点击
function microphone_icon_click() {
    $('.basic_one_wrap').hide();
    $('.basic_two_wrap').hide();
    $('.basic_three_wrap').show(); //其他弹窗hide
    $('.basic_four_wrap').hide();
    $('.basic_five_wrap').hide();
    $('.basic_six_wrap').hide();

    basic_monitor_obj.current_click_step = 2;

    stop_basic_camera_stream();

    // 开启音频流
    create_microphone_stream();
}

// 扬声器图标点击
function speaker_icon_click() {
    $('.basic_one_wrap').hide();
    $('.basic_two_wrap').hide();
    $('.basic_three_wrap').hide();
    $('.basic_four_wrap').show(); //其他弹窗hide
    $('.basic_five_wrap').hide();
    $('.basic_six_wrap').hide();

    basic_monitor_obj.current_click_step = 3;
}

// 网络图标点击
function network_icon_click() {
    $('.basic_one_wrap').hide();
    $('.basic_two_wrap').hide();
    $('.basic_three_wrap').hide();
    $('.basic_four_wrap').hide();
    $('.basic_five_wrap').show(); //其他弹窗hide
    $('.basic_six_wrap').hide();

    basic_monitor_obj.current_click_step = 4;
    // TODO:检测网络
}
// 创建视频检测流
function create_camera_stream() {
    stop_basic_camera_stream();
    let video_device_id = $('#basic_camera_select_wrap').attr('option') || undefined;
    let audio_device_id = undefined;
    let option = {
        audio: false,
        video: true,
    };
    basic_camera_stream = RTC.createStream(option);
    basic_camera_stream.setVideoEncoderConfiguration({
        resolution: {
            width: 640,
            height: 480
        },
        frameRate: { //帧率
            max: 30,
        },
        bitrate: { //码率
            max: 1000,
        },
        codec: {
            name: 'vp8',
            profile: ''
        }
    });
    basic_camera_stream.init(() => {
        if(!basic_monitor_obj.camera_name) {
            get_cameras_select();
        }
        if(basic_monitor_obj.current_click_step == 1) {
            $('.basic_two_video_wrap').empty();
            $('.basic_two_video_wrap').append('<div id="' + basic_camera_stream.getId() + '" style="width:100%;height:100%;position:relative;" ></div>');
            basic_camera_stream.play(basic_camera_stream.getId());
        }else{
            stop_basic_camera_stream();
        }
    }, err => {
        let message = '获取摄像头失败，请刷新浏览器重试，或更换其他浏览器';
        if (err.name == "NotFoundError" || err.name == "DevicesNotFoundError") {
        // required track is missing
            message = "未检测到可用设备，请重试"
        } else if (err.name == "NotReadableError" || err.name == "TrackStartError") {
            // webcam or mic are already in use
            message = "摄像头被占用，请刷新浏览器重试";
        } else if (err.name == "OverconstrainedError" || err.name == "ConstraintNotSatisfiedError") {
            // constraints can not be satisfied by avb. devices
            message = "未检测到可用设备";
        } else if (err.name == "NotAllowedError" || err.name == "PermissionDeniedError") {
            message = "无法获取摄像头权限";
        } else if (err.name == "TypeError" || err.name == "TypeError") {
            // empty constraints object
            message = "未检测到可用设备";
        } else {
            // other errors
            message = "未检测到可用设备";
        }
        toastMessage(message);
    }, video_device_id, audio_device_id);
}
// 停止视频流
function stop_basic_camera_stream() {
    // 停止采集流
    basic_camera_stream && basic_camera_stream.stop();
    basic_camera_stream && basic_camera_stream.close();
}
function setting_show_fun() {
   $('.setting_popup').css({'display':'flex'});
   init_setting();
}

/**
* @desc 关闭弹窗
*/
function setting_close_fun() {
   $('.setting_popup').hide();
}

/**
* @desc 初始化设备
*/
function init_setting() {
   getCameras().then(devices =>{
    $('.camera_select_ul').empty();
        for(let i = 0; i < devices.length; i++) {
            let _deviceId = devices[i].deviceId;
            let _label = devices[i].label;
            if(_deviceId && _label) {
                let option = `<li><div class="label" option="${_deviceId}">${_label}</div></li>`;
                if(basic_monitor_obj.camera_id == _deviceId) {
                    // 选中的
                    option = `<li><div class="label active" option="${_deviceId}">${_label}</div></li>`;
                    $('#camera_select_wrap').val(_label);
                }
                $('.camera_select_ul').append(option);
            }
        }
        if (!basic_monitor_obj.camera_id && devices.length > 0){
            $('#camera_select_wrap').val(devices[0].label);
        }
   });
   getRecordingDevices().then(devices =>{
    $('.record_select_ul').empty();
        for(let i = 0; i < devices.length; i++) {
            let _deviceId = devices[i].deviceId;
            let _label = devices[i].label;
            if(_deviceId && _label) {
                let option = `<li><div class="label" option="${_deviceId}">${_label}</div></li>`;
                if(basic_monitor_obj.microphone_id == _deviceId) {
                    // 选中的
                    option = `<li><div class="label active" option="${_deviceId}">${_label}</div></li>`;
                    $('#record_select_wrap').val(_label);
                }
                $('.record_select_ul').append(option);
            }
        }
        if (!basic_monitor_obj.microphone_id && devices.length > 0){
            $('#record_select_wrap').val(devices[0].label);
        }
   });
   getPlayoutDevices().then(devices =>{
    $('.playout_select_ul').empty();
    for(let i = 0; i < devices.length; i++) {
        let _deviceId = devices[i].deviceId;
        let _label = devices[i].label;
        if(_deviceId && _label) {
            let option = `<li><div class="label" option="${_deviceId}">${_label}</div></li>`;
            if(basic_monitor_obj.speaker_id == _deviceId) {
                // 选中的
                option = `<li><div class="label active" option="${_deviceId}">${_label}</div></li>`;
                $('#playout_select_wrap').val(_label);
            }
            $('.playout_select_ul').append(option);
        }
    }
    if (!basic_monitor_obj.speaker_id && devices.length > 0){
        $('#playout_select_wrap').val(devices[0].label);
    }
   });
//    init_slider();
}


// 创建音频检测流
function create_microphone_stream() {
    stop_basic_microphone_stream();
    let voice_num = 100;
    let video_device_id = undefined;
    let audio_device_id = $('#basic_microphone_select_wrap').attr('option') || undefined;
    let option = {
        audio: true,
        video: false,
    };
    basic_microphone_stream = RTC.createStream(option);
    basic_microphone_stream.setVideoEncoderConfiguration({
        resolution: {
            width: 640,
            height: 480
        },
        frameRate: { //帧率
            max: 30,
        },
        bitrate: { //码率
            max: 1000,
        },
        codec: {
            name: 'vp8',
            profile: ''
        }
    });
    basic_microphone_stream.init(() => {
        if(!basic_monitor_obj.microphone_name) {
            get_microphone_select();
        }
        if(basic_monitor_obj.current_click_step == 2) {
            $('.basic_three_audio_dom').empty();
            $('.basic_three_audio_dom').append('<div id="' + basic_microphone_stream.getId() + '" style="width:100%;height:100%;position:relative;" ></div>');
            basic_microphone_stream.play(basic_microphone_stream.getId());
            basic_microphone_stream.setEffectsVolume(Number(voice_num).toFixed(0), error => {
                if (!error) {
                    console.log('setEffectsVolume2 success' + voice_num);
                } else {
                    console.log('setEffectsVolume2 fail', error);
                }
            });
            basic_microphone_volume_timer = setInterval(() => {
                let volume = basic_microphone_stream.getAudioLevel();
                if(volume == 0) {
                    $('.basic_three_video_icon').css({
                        top: '-0',
                    });
                }else if(volume < 0.1) {
                    $('.basic_three_video_icon').css({
                        top: '-16px',
                    });
                }else if(volume < 0.2) {
                    $('.basic_three_video_icon').css({
                        top: '-32px',
                    });
                }else if(volume < 0.6) {
                    $('.basic_three_video_icon').css({
                        top: '-48px',
                    });
                }else if(volume > 0.6) {
                    $('.basic_three_video_icon').css({
                        top: '-64px',
                    });
                }
            }, 60);
        }else{
            stop_basic_microphone_stream();
        }
    }, err => {
        let message = '获取麦克风失败，请刷新浏览器重试，或更换其他浏览器';
        if (err.name == "NotFoundError" || err.name == "DevicesNotFoundError") {
        // required track is missing
            message = "未检测到可用设备，请重试"
        } else if (err.name == "NotReadableError" || err.name == "TrackStartError") {
            // webcam or mic are already in use
            message = "摄像头被占用，请刷新浏览器重试";
        } else if (err.name == "OverconstrainedError" || err.name == "ConstraintNotSatisfiedError") {
            // constraints can not be satisfied by avb. devices
            message = "未检测到可用设备";
        } else if (err.name == "NotAllowedError" || err.name == "PermissionDeniedError") {
            message = "无法获取麦克风权限";
        } else if (err.name == "TypeError" || err.name == "TypeError") {
            // empty constraints object
            message = "未检测到可用设备";
        } else {
            // other errors
            message = "未检测到可用设备";
        }
        toastMessage(message);
    }, video_device_id, audio_device_id);
}


// 停止麦克风流
function stop_basic_microphone_stream() {
    // 停止采集流
    basic_microphone_volume_timer && clearInterval(basic_microphone_volume_timer);
    basic_microphone_stream && basic_microphone_stream.stop();
    basic_microphone_stream && basic_microphone_stream.close();
}

//停止扬声器audio播放
function stop_speaker_audio() {
    let basic_four_audio = document.getElementById('basic_four_audio');
    basic_four_audio.pause();
    basic_four_audio.currentTime = 0;
}

// 开始网络检测
function basic_network_check() {
    is_check_finish = false;
    // loading图标
    let check_icon = document.createElement('img');
    check_icon.setAttribute('class', 'check_loading');
    check_icon.setAttribute('src', resourceUrl + '/images/monitor/loading.png');
    $('.basic_five_item .basic_five_item_txt').empty();
    $('.basic_five_item .basic_five_item_txt').append(check_icon);

    // 剩余检测时间
    $('.basic_five_btn').show();
    $('.basic_five_btn_next').hide();
    let detection_time = 10;
    $('.remaining_detection_time').text('10');
    detection_time_countdown_timer && clearTimeout(detection_time_countdown_timer);
    detection_time_countdown(detection_time)
    // 操作系统
    setTimeout(() => {
        $('.check_system').empty();
        $('.check_system').text(system);
    }, 500);
    // 浏览器
    setTimeout(() => {
        $('.check_browser').empty();
        let browser = check_browser();
        $('.check_browser').text(browser);
    }, 1000);
    // 是否支持TRTC
    setTimeout(() => {
        $('.check_trtc').empty();
        let trtc = check_trtc() ? i18ntc('是') : i18ntc('否');
        $('.check_trtc').text(trtc);
    }, 1500);
    // 是否支持屏幕共享
    setTimeout(() => {
        $('.check_share_screen').empty();
        let share_screen = check_share_screen() ? i18ntc('是'): i18ntc('否');
        $('.check_share_screen').text(share_screen);
    }, 2000);
    // 网络延迟
    setTimeout(() => {
        $('.check_network_delay').empty();
        check_network_delay();
    }, 2000);
    // 上下行速率
    setTimeout(() => {
        $('.check_downlink').empty();
        check_downlink();
    }, 2000);

}

function detection_time_countdown(detection_time) {
    // 是否检测完成
    if(is_check_finish) {
        // 查看检测报告按钮
        $('.basic_five_btn').hide();
        $('.basic_five_btn_next').show();
    }else{
        detection_time_countdown_timer = setTimeout(() => {
            detection_time--;
            if(detection_time > 0) {
                $('.remaining_detection_time').text(detection_time);
                detection_time_countdown(detection_time);
            }else{
                $('.remaining_detection_time').text(detection_time);
                // 查看检测报告按钮
                $('.basic_five_btn').hide();
                $('.basic_five_btn_next').show();
            }
        }, 1000);
    }
}

// 判断浏览器版本
function check_browser() {
    let browser = {};
    let ua = navigator.userAgent.toLowerCase();
    let s;
    (s = ua.match(/rv:([\d.]+)\) like gecko/)) ? browser.ie = s[1]: '';
    (s = ua.match(/msie ([\d\.]+)/)) ? browser.ie = s[1] : '';
    (s = ua.match(/edge\/([\d\.]+)/)) ? browser.edge = s[1] : '';
    (s = ua.match(/edg\/([\d\.]+)/)) ? browser.edge = s[1] : '';
    (s = ua.match(/firefox\/([\d\.]+)/)) ? browser.firefox = s[1] : '';
    (s = ua.match(/(?:opera|opr).([\d\.]+)/)) ? browser.opera = s[1] : '';
    (s = ua.match(/chrome\/([\d\.]+)/)) ? browser.chrome = s[1] : '';
    (s = ua.match(/version\/([\d\.]+).*safari/)) ? browser.safari = s[1] : '';
    (s = ua.match(/qqbrowser\/([\d\.]+)/)) ? browser.qqbroser = s[1] : '';
    (s = ua.match(/tencenttraveler\/([\d\.]+)/)) ? browser.qqbroser = s[1] : '';
    (s = ua.match(/ubrowser\/([\d\.]+)/)) ? browser.ubrowser = s[1] : '';
    (s = ua.match(/baidubrowser\/([\d\.]+)/)) ? browser.baidubrowser = s[1] : '';
    (s = ua.match(/metasr\/([\d\.]+)/)) ? browser.metasr = s[1] : '';
    (s = ua.match(/maxthon\/([\d\.]+)/)) ? browser.maxthon = s[1] : '';
    // 根据关系进行判断
    if (browser.ie) return ('IE ' + browser.ie);
    if (browser.edge) return ('EDGE ' + browser.edge);
    if (browser.firefox) return ('Firefox ' + browser.firefox);
    if (browser.qqbroser) return ('QQBrowser ' + browser.qqbroser);
    if (browser.ubrowser) return ('UC ' + browser.ubrowser);
    if (browser.baidubrowser) return ('Baidu ' + browser.baidubrowser);
    if (browser.metasr) return ('Sougou ' + browser.metasr);
    if (browser.maxthon) return ('Maxthon ' + browser.maxthon);
    if (browser.chrome) return ('Chrome ' + browser.chrome);
    if (browser.opera) return ('Opera ' + browser.opera);
    if (browser.safari) return ('Safari ' + browser.safari);
    return 'Unkonwn';
}

// 是否支持trtc
function check_trtc() {
    try {
        let testRTCPeerConnection = window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection || window.RTCIceGatherer;
        if (testRTCPeerConnection) {
          let serverConfig = {
            "iceServers": [{
              urls: [
                "stun:stun.l.google.com:19302"
              ]
            }]
          };
          new RTCPeerConnection(serverConfig);
          return true;
        } else {
            return false
        }
    } catch (error) {
        return false;
    }
}

// 是否支持屏幕分享
function check_share_screen() {
    if(navigator && navigator.mediaDevices && navigator.mediaDevices.getDisplayMedia) {
        return true;
    }else{
        return false;
    }
}

// 网络延迟
function check_network_delay() {
    if(navigator && navigator.onLine) {
        let rtt = navigator.connection && navigator.connection.rtt ? navigator.connection.rtt : 0;
        if(rtt) {
            refresh_network_delay(rtt);
        }else{
            img = document.createElement('IMG');
            try {
                let start = new Date().getTime();
                img.onload = function() {
                    let end = new Date().getTime()
                    let delta = end -start;
                    refresh_network_delay(delta);
                }
                img.onerror = function() {
                    refresh_network_delay(false);
                }
                img.src = resourceUrl + '/images/monitor/check.png?_t=' + new Date().getTime();
            } catch (e) {
                refresh_network_delay(false);
            }
        }
    }else{
        refresh_network_delay(false);
    }
}

// 网络延迟显示
function refresh_network_delay(value) {
    if(value) {
        basic_monitor_obj.network_delay = value + 'ms';
        $('.check_network_delay').text(value + 'ms');
    }else{
        basic_monitor_obj.network_delay = '未知';
        $('.check_network_delay').text('未知');
    }
}

// 上下行速率
function check_downlink() {
    if(navigator && navigator.onLine) {
        let downlink = navigator.connection && navigator.connection.downlink ? navigator.connection.downlink : 0;
        if(downlink) {
            is_check_finish = true;
            refresh_downlink(downlink/8);
        }else{
            let fileSize = 0.324;
            let img = document.createElement('img');
            try {
                let start = new Date().getTime();
                img.onload = function (e) {
                    let end = new Date().getTime();
                    let speed = fileSize * 1000 / (end - start);
                    is_check_finish = true;
                    refresh_downlink(speed);
                }
                img.onerror = function() {
                    is_check_finish = true;
                    refresh_downlink(false);
                }
                img.src = 'images/vritual/venice.jpg?_t=' + new Date().getTime();
            } catch ( e ) {
                is_check_finish = true;
                refresh_downlink(false);
            }
        }
    }else{
        is_check_finish = true;
        refresh_downlink(false);
    }
}

// 上下行速率显示
function refresh_downlink(value) {
    if(value) {
        let downlink_txt = i18ntc('未知');
        if(value >= 1) {
            downlink_txt = i18ntc('极佳');
        }else if(value < 1) {
            downlink_txt = i18ntc('一般');
        }else if(value < 0.5) {
            downlink_txt = i18ntc('较差');
        }
        $('.check_downlink').text(downlink_txt);
        basic_monitor_obj.network_downlink = downlink_txt;
    }else{
        $('.check_downlink').text(i18ntc('未知'));
        basic_monitor_obj.network_downlink = i18ntc('未知');
    }
}

//查看检测报告
function view_check_report() {
    update_check_report();
    $('.basic_monitor_close').hide(); // 跳过检测关闭
    $('.basic_progress_header_wrap').hide();
    $('.basic_one_wrap').hide();
    $('.basic_two_wrap').hide();
    $('.basic_three_wrap').hide();
    $('.basic_four_wrap').hide();
    $('.basic_five_wrap').hide();
    $('.basic_six_wrap').show();
}

// 更新检测报告
function update_check_report() {
    let camera_name = basic_monitor_obj.camera_name;
    let camera = basic_monitor_obj.camera;
    let microphone_name = basic_monitor_obj.microphone_name;
    let microphone = basic_monitor_obj.microphone;
    let speaker_name = basic_monitor_obj.speaker_name;
    let speaker = basic_monitor_obj.speaker;
    if(camera_name) {
        $('.basic_six_camera').text(camera_name);
        $('.basic_six_camera').removeClass('basic_six_item_title_error');
    }else{
        $('.basic_six_camera').text(i18ntc('未检测到摄像头'));
        $('.basic_six_camera').addClass('basic_six_item_title_error');
    }
    if(camera) {
        $('.basic_six_camera_status').text(i18ntc('正常'));
        $('.basic_six_camera_status').removeClass('basic_six_item_status_error');
    }else{
        $('.basic_six_camera_status').text(i18ntc('异常'));
        $('.basic_six_camera_status').addClass('basic_six_item_status_error');
    }
    if(microphone_name) {
        $('.basic_six_microphone').text(microphone_name);
        $('.basic_six_microphone').removeClass('basic_six_item_title_error');
    }else{
        $('.basic_six_microphone').text(i18ntc('未检测到麦克风'));
        $('.basic_six_microphone').addClass('basic_six_item_title_error');
    }
    if(microphone) {
        $('.basic_six_microphone_status').text(i18ntc('正常'));
        $('.basic_six_microphone_status').removeClass('basic_six_item_status_error');
    }else{
        $('.basic_six_microphone_status').text(i18ntc('异常'));
        $('.basic_six_microphone_status').addClass('basic_six_item_status_error');
    }
    if(speaker_name) {
        $('.basic_six_speaker').text(speaker_name);
        $('.basic_six_speaker').removeClass('basic_six_item_title_error');
    }else{
        $('.basic_six_speaker').text(i18ntc('未检测到扬声器'));
        $('.basic_six_speaker').addClass('basic_six_item_title_error');
    }
    if(speaker) {
        $('.basic_six_speaker_status').text(i18ntc('正常'));
        $('.basic_six_speaker_status').removeClass('basic_six_item_status_error');
    }else{
        $('.basic_six_speaker_status').text(i18ntc('异常'));
        $('.basic_six_speaker_status').addClass('basic_six_item_status_error');
    }
    $('.basic_six_net').text(basic_monitor_obj.network_delay);
    $('.basic_six_downlink').text(basic_monitor_obj.network_downlink);
}

// 重新检测
function reset_check() {
    basic_monitor_show();
}

// 完成检测
function finish_check() {
    basic_monitor_hide();
}
function getRecordingDevices() {
    return new Promise(function (resolve, reject) {
        navigator.mediaDevices.enumerateDevices().then(function (deviceInfos) {
            let datas = [];
            for (let i = 0; i !== deviceInfos.length; ++i) {
                let deviceInfo = deviceInfos[i];
                if (deviceInfo.kind === 'audioinput') {
                    let mediaDeviceInfo = {}
                    mediaDeviceInfo.deviceId = deviceInfo.deviceId;
                    mediaDeviceInfo.kind = 'audioinput';
                    mediaDeviceInfo.label = deviceInfo.label;
                    datas.push(mediaDeviceInfo);
                }
            }
            resolve(datas);
        }).catch(function (error) {
            reject([]);
        });
    })
}
function getPlayoutDevices() {
    return new Promise(function (resolve, reject) {
        navigator.mediaDevices.enumerateDevices().then(function (deviceInfos) {
            let datas = [];
            for (let i = 0; i !== deviceInfos.length; ++i) {
                let deviceInfo = deviceInfos[i];
                if (deviceInfo.kind === 'audiooutput') {
                    let mediaDeviceInfo = {}
                    mediaDeviceInfo.deviceId = deviceInfo.deviceId;
                    mediaDeviceInfo.kind = 'audiooutput';
                    mediaDeviceInfo.label = deviceInfo.label;
                    datas.push(mediaDeviceInfo);
                }
            }
            resolve(datas);
        }).catch(function (error) {
            reject([]);
        });
    })
}

//停止推屏幕
function screen_stop_publish() {
    if(localStreamScreen && localStreamScreen._oStream) {
        change_isScreenShare && change_isScreenShare({
            share: false,
            end: false,
        });
        var localId = '#' + localStreamScreen.getId();
        $(localId).remove();
        if(localStreamScreen && localStreamScreen._oStream) {
            localStreamScreen.close();
        }
        toastMessage("停止推屏")
        let ls_vt = localStream.getVideoTrack();
        if(isFirefox()) {
            localStream.replaceTrack(vt, true);
        }else if(ls_vt) {
            if(ls_vt.label && (ls_vt.label.indexOf('screen') > -1 || ls_vt.label.indexOf('window') > -1) || ls_vt.label.indexOf('web-contents-media-stream') > -1 || picStream) {
                localStream.replaceTrack(vt, true);
            }
        }
        localStreamScreen = null;
        send_end_screen();
        screen_stop_vritual_start();
    }else{
        toastMessage('暂无屏幕推送')
    }
}
/**
 * msg提示框
 */
function tip_msg_fun(str) {
    console.log(str)
}

/**
 * @desc 拖动
 * @tip 拖动元素自身需要有绝对定位
 * @use dragDom(element)
 * @param {*} dragElement
 */
 function dragDom(dragElement) {
    var Moving = false;
    var clickMoveX = 0;
    var clickMoveY = 0;
    var nowMarginX = 0;
    var nowMarginY = 0;
    $(document).mousemove(function(e){
        //窗口拖动
        if(Moving==true){
            var changeX = e.clientX - Number(clickMoveX);
            var changeY = e.clientY - Number(clickMoveY);
            dragElement.css('left',changeX + Number(nowMarginX) + 'px');
            dragElement.css('top',changeY + Number(nowMarginY) + 'px');
        }
    });
    dragElement.mousedown(function(e){
        e.stopPropagation()
        if (e.stopPropagation) {
            e.stopPropagation();
        }else if (window.e) {
            window.e.cancelBubble = true;
        }
        $('body').css('user-select','none');
        clickMoveX =  e.clientX;
        clickMoveY =  e.clientY;
        nowMarginX = dragElement.css('left').slice(0,-2);
        nowMarginY = dragElement.css('top').slice(0,-2);
        Moving = true;
    });
    $('body').mouseup(function(){
        $('body').css('user-select','text')
        Moving = false
    })
}
$("body").on("click", ".small_win_1", function() {
  $('.big_screen_wrap').removeClass('big_screen_wrap').addClass('small_win_1')
  $(this).addClass('big_screen_wrap').removeClass('small_win_1')
});
//截屏
function screen_capture_select() {
    takeSnapshot(document.getElementById('screen_left_id').innerHTML, 'jpeg', true, true)
}
function record_select_fun() {
    startRecording()
    $('#start_record_select_wrap').hide()
    $('.stop_record_select_wrap').show()
}
function stop_all_recording(){
    stopRecording()
    $('#start_record_select_wrap').show()
    $('.stop_record_select_wrap').hide()
}
function switch_audio_mode(){
    changeMedia('audio')
}


function change_video_local(val){
    localHasVideo(val).then(res =>{
        if (res == 'close'){
            //当前保持
            document.getElementById('openVideo').style.display = 'none'
            document.getElementById('closeVideo').style.display = 'block'
        } else if (res =='open'){
            document.getElementById('openVideo').style.display = 'block'
            document.getElementById('closeVideo').style.display = 'none'
        }
    })
}
function change_micro(val){
    localMute(val).then(res =>{
        if (res == 'mute'){
            //当前保持
            document.getElementById('openMic').style.display = 'none'
            document.getElementById('closeMic').style.display = 'block'
        } else if (res == 'unmute'){
            document.getElementById('openMic').style.display = 'block'
            document.getElementById('closeMic').style.display = 'none'
        }
    })
}

function screen_publish(){
    share_screen().then(res =>{
        if (res){
            document.getElementById('share_screen').style.display = 'none'
            document.getElementById('stop_screen').style.display = 'block'
        }
    })
}
function screen_stop_publish(){
    stop_screen().then(res =>{
        if (res){
            document.getElementById('share_screen').style.display = 'block'
            document.getElementById('stop_screen').style.display = 'none'
        }
    })
}
function stop_screen_back(){
    document.getElementById('share_screen').style.display = 'block'
    document.getElementById('stop_screen').style.display = 'none'
}


















// document.onkeydown = function ()
// {
//     if (event.keyCode == 116) {
//         event.keyCode = 0;
//         event.cancelBubble = true;
//         return false;
//     }
// }
// document.oncontextmenu = function () {
//     return false;
// }


function vritual_show_fun(){
    document.getElementById('vritual_popup').style.display = 'flex'
    for(let i=0;i<$('.vritual_small_row_wrap img').length;i++){
        if ($($('.vritual_small_row_wrap img')[i]).attr("src") == backgroundImgUrl){
            $($('.vritual_small_row_wrap img')[i]).addClass('imgBorder')
            $($('.vritual_small_row_wrap img')[i]).siblings().removeClass('imgBorder')
        }
    }
}
function vritual_close_fun(){
    document.getElementById('vritual_popup').style.display = 'none'
}
$(document).on('change', '#vagueCheck', function() {
    if($(this).is(':checked')) {
        startBlurBackground()
    } else {
        stopBlurBackground()
    }
});
$(document).on('change', '#vritualCheck', function() {
    if($(this).is(':checked')) {
        if (backgroundImgUrl){
            startVirtua(backgroundImgUrl)
        }
        $('.vritual_small_row_wrap_img').css({'cursor':'pointer','opacity':'1'})
        $('#upload').attr('disabled',false)
    } else {
        stopVirtua()
        $('.vritual_small_row_wrap_img').css({'cursor':'no-drop','opacity':'0.5'})
        $('#upload').attr('disabled',true)
    }
});
$(document).on('click', '.vritual_small_row_wrap img', function(e) {
    if ($(this).attr('id') != 'uploadImg'){
        if ($('#vritualCheck').is(':checked')){
            $(this).addClass('imgBorder')
            $(this).siblings().removeClass('imgBorder')
            startVirtua($(this).attr("src"))
        }
    } else {

    }
});
function uploadHandler(e){
    var file = e.files[0];
    var imgSrc;
    if (!/image\/\w+/.test(file.type)) {
        alert("请上传图片！");
        return false;
    }
    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function() {
        imgSrc = this.result;
        var div=$(`<img alt="" class="vritual_small_row_wrap_img" style="cursor:pointer;opacity:1" src="${imgSrc}" />`);
        //创建含有内容的div元素
        $(".vritual_small_row_wrap").prepend(div)
    }
}
function setNumberHistory(){
    let newHistory = []
    if (localStorage.getItem(agent_id + 'numberHistory')){
        let oldHistory = JSON.parse(localStorage.getItem(agent_id + 'numberHistory'))
        oldHistory.unshift(document.getElementById('inputNum').value.replace(/\s/g, ""))
        const set = new Set(oldHistory)
        oldHistory = [...set]
        if (oldHistory.length > 10){
            newHistory = oldHistory.slice(0,10)
        } else {
            newHistory = oldHistory
        }
    } else {
        newHistory.unshift(document.getElementById('inputNum').value)
        const set = new Set(newHistory)
        newHistory = [...set]
        if (newHistory.length > 10){
            newHistory = newHistory.slice(0,10)
        }
    }
    localStorage.setItem(agent_id + 'numberHistory',JSON.stringify(newHistory))
}
function btn_video_accept(){
    $('.call_in_wait_wrap').hide()
    pickUp()
}
function btn_audio_accept(){
    hasVideo = false
    document.getElementById('main_center_wrap').style.display = 'none'
    pickUp()
}

$('body').on('click',function(){
    if (document.getElementById('choseStatus') && document.getElementById('choseStatus').style.display != 'none'){
        document.getElementById('note').setAttribute("class","statusFont");
        document.getElementById('choseStatus').style.display = 'none'
    }
    if (document.getElementById('showMore') && document.getElementById('showMore').style.display != 'none'){
        document.getElementById('showMore').style.display = 'none'
    }
    if (document.getElementById('sureBoxNote') && document.getElementById('sureBoxNote').style.display != 'none'){
        document.getElementById('sureBoxNote').style.display = 'none'
    }
    if (document.getElementById('customerDiv') && document.getElementById('customerDiv').style.display != 'none'){
        document.getElementById('customerDiv').style.display = 'none'
        document.getElementById('sitetypeArrow').style.transform = 'rotate(0)'
    }
})

function toastMessage(val){
    if (document.getElementById('messageBox')){
        if (messageTimer){
            clearTimeout(messageTimer)
            messageTimer = null
        }
        document.getElementById('messageBox').style.display = 'block'
        document.getElementById('messageBoxText').innerHTML = i18ntc(val)
        messageTimer = setTimeout(()=>{
            document.getElementById('messageBox').style.display = 'none'
        },3000)
    }
}



// 质检功能 接口  强签 强制示闲/忙
async function forceChangeStatus(action,operated_ext_id,operated_agent_id){
    await getToken({
      company_code,
      agent_pwd,
      agent_id: company_code + '_' + agent_id,
      msg_type: "get_token",
      os: system,
      req_id: generateUUID(),
    })
    let msgObj = {
      req_id: generateUUID(),
      company_code,
      agent_id: company_code + '_' + agent_id,
      os: system,
      action,
      operated_ext_id: company_code + '_' + operated_ext_id,
      operated_agent_id: company_code + '_' + operated_agent_id,
      msg_type: 'change_status',
    }
    return new Promise(function (resolve, reject){
        ajax({
            type: 'POST',
            url: dominUrl + 'cloudcc-client-server/openapi/request',
            data: msgObj,
            success: function (res) {
                let result = JSON.parse(res)
                if (result.code == 0){
                    resolve(true)
                } else {
                    resolve(false)
                }
            }, error: function(err){
                reject(false)
            }
        })
    })
  }
// 获取token
async function getToken(param){
  if (!token){
    await new Promise((resolve) =>{
      ajax({
        type: 'POST',
        url: dominUrl + 'cloudcc-client-server/openapi/get-token',
        data: param,
        success: function (res) {
            let result = JSON.parse(res)
            if (result.code == 0){
              token = result.token
            } else {
              token = null
            }
            resolve()
        }, error: function(err){
        }
      })
    })
  }
}

async function playRecord(file_path,server_id){
    await getToken({
        company_code,
        agent_pwd,
        agent_id: company_code + '_' + agent_id,
        msg_type: "get_token",
        os: system,
        req_id: generateUUID(),
    })
    return new Promise(function (resolve, reject){
      if (!company_code || !agent_id || !ext_id){
          resolve('no_check_in')
      }
      let msgObj = {
          req_id: generateUUID(),
          company_code,
          agent_id: company_code + '_' + agent_id,
          ext_id: company_code + '_' + ext_id,
          os: system,
          file_path,
          msg_type: 'play_record',
          audio: '3',
          video: '0',
          server_id
      }
      callType = 'callout'
      ajax({
            type: 'POST',
            url: dominUrl + 'cloudcc-client-server/openapi/request',
            data: msgObj,
            success: function (res) {
                let result = JSON.parse(res)
                resolve(result)
            }, error: function(err){
                reject(false)
            }
        })
    })
}

function playRecordControl(action,seek_value,server_id){
    //pause:暂停, resume:恢复, replay:重播, seek:指定时间, speed:倍速播放, stop:停止播放, volume:音量
    return new Promise(function (resolve, reject){
        let msgObj = {
            req_id: generateUUID(),
            company_code,
            agent_id: company_code + '_' + agent_id,
            ext_id: company_code + '_' + ext_id,
            os: system,
            uuid: nowUuid,
            msg_type: 'play_record_control',
            seek_value: seek_value || '',
            action,
            server_id
        }
        ajax({
            type: 'POST',
            url: dominUrl + 'cloudcc-client-server/openapi/request',
            data: msgObj,
            success: function(res) {
                let result = JSON.parse(res)
                if (result.code == 0){
                    resolve(true)
                } else {
                    resolve(false)
                }
            }, error: function(err){
                reject(false)
            }
          })
      })
}

function getPerssion(){
    return setParam
}

function backCall(phone){
    callType = 'callout'
    callingPhone = phone
    document.getElementById('inputNum').value = phone
}

function getAgentInfo(){
    let info = {}
    info.system = system
    info.ext_id = ext_id
    info.company_code = company_code
    return info
}

function setTransMode(val){
 transMode = val
}
function setdesensitization(val){
   desensitization = val
}
function setPlatformConfig(val){
    document.getElementById('play_calling') && document.getElementById('play_calling').setAttribute('src',`${resourceUrl}/audio/${val}.wav`)
}
function getStreamError(error){
    toastMessage(i18ntc('未检测到设备,请检测设备或者设备权限后刷新页面重新尝试。'))
}
function setLang(){
    if (window.i18n){
        var elements = document.getElementsByClassName("i18n");
        if (i18nArray.length == 0){
            for (var i = 0; i < elements.length; i++) {
                i18nArray.push(elements[i].innerHTML)
            }
        }
        for (var i = 0; i < i18nArray.length; i++) {
            elements[i].innerHTML = window.i18n.tc(i18nArray[i])
        }
        var inputDom = document.getElementsByClassName("i18nInput");
        if (i18nInputArray.length == 0){
            for (var i = 0; i < inputDom.length; i++) {
                i18nInputArray.push(inputDom[i].getAttribute('placeholder'))
            }
        }
        for (var i = 0; i < i18nInputArray.length; i++) {
            inputDom[i].setAttribute('placeholder',window.i18n.tc(i18nInputArray[i]))
        }
        if (document.getElementById('note')){
            document.getElementById('note').innerHTML = i18ntc(nowStatusText)
        }
        // oritxt
        var elementsOritxt = document.getElementsByClassName("i18nFromOritxt");
        for (var i = 0; i < elementsOritxt.length; i++) {
            let oritxt = elementsOritxt[i].getAttribute("data-oritxt");
            if(oritxt) {
                elementsOritxt[i].innerHTML = i18ntc(oritxt);
            }
        }
    }
    handleSeatABoxSearch();
}

function i18ntc(text){
    if (window.i18n){
        return window.i18n.tc(text)
    } else {
        return text
    }
}

function cutPhone(phone){
  if (phone && phone.indexOf('_') > -1){
    let parts = phone.split('_')
    // 获取 '_' 之后的部分
    let result = parts[1];
    return result
  } else {
    return phone
  }
}

function isDesensitization(str){
    if (desensitization == '0'){
        return str
    } else {
        if (str.length < 5){
            return str
        } else {
            return str.replace(/\b(\w{1,3})\w*\b/g, function(str, p1) {
                return '*'.repeat(str.length - 4) + str.slice(-4);
            });
        }
    }
}

function createExamine(){
    let str = ''
    if (document.getElementById('detectionBox')){
        document.getElementById('detectionBox').style.display = 'flex'
    } else {
        str = `<!-- 基础检测弹窗 -->
        <div class="basic_monitor_wrap">
            <div class="basic_monitor_close i18n" onclick="basic_monitor_hide()">跳过检测</div>
            <!-- 1 -->
            <div class="basic_one_wrap">
                <div class="basic_monitor_header i18n">设备连接</div>
                <div class="normal_form_header_line"></div>
                <div class="basic_one_title i18n">设备检测前请确认设备连接了摄像头、麦克风、扬声器和网络</div>
                <div class="basic_one_center">
                    <div class="basic_one_center_item">
                        <img alt="" class="basic_one_center_item_icon" src="${resourceUrl}/images/monitor/camera_1.png" />
                        <img alt="" class="basic_one_center_item_check basic_one_camera" src="${resourceUrl}/images/monitor/check.png" />
                    </div>
                    <div class="basic_one_center_item">
                        <img alt="" class="basic_one_center_item_icon" src="${resourceUrl}/images/monitor/mic_1.png" />
                        <img alt="" class="basic_one_center_item_check basic_one_microphone" src="${resourceUrl}/images/monitor/check.png" />
                    </div>
                    <div class="basic_one_center_item">
                        <img alt="" class="basic_one_center_item_icon" src="${resourceUrl}/images/monitor/speaker_1.png" />
                        <img alt="" class="basic_one_center_item_check basic_one_speaker" src="${resourceUrl}/images/monitor/check.png" />
                    </div>
                    <div class="basic_one_center_item">
                        <img alt="" class="basic_one_center_item_icon" src="${resourceUrl}/images/monitor/net_1.png" />
                        <img alt="" class="basic_one_center_item_check basic_one_network" src="${resourceUrl}/images/monitor/check.png" />
                    </div>
                </div>
                <div class="basic_one_footer_tip i18n">设备及网络连接成功，请开始设备检测</div>
                <div class="basic_one_footer">
                    <div onclick="start_basic_monitor()" class="basic_one_footer_btn i18n">开始检测</div>
                </div>
            </div>
            <div class="basic_progress_header_wrap" style="display: none;">
                <div class="basic_progress_header_item basic_camera_icon active">
                    <img alt="" class="basic_progress_header_item_icon" src="${resourceUrl}/images/monitor/camera_2.png" />
                    <div class="basic_progress_header_item_txt">CAMERA</div>
                </div>
                <div class="basic_progress_header_item_line basic_camera_line"></div>
                <div class="basic_progress_header_item basic_microphone_icon">
                    <img alt="" class="basic_progress_header_item_icon" src="${resourceUrl}/images/monitor/mic_4.png" />
                    <div class="basic_progress_header_item_txt">MICROPHONE</div>
                </div>
                <div class="basic_progress_header_item_line basic_microphone_line"></div>
                <div class="basic_progress_header_item basic_speaker_icon">
                    <img alt="" class="basic_progress_header_item_icon" src="${resourceUrl}/images/monitor/speaker_4.png" />
                    <div class="basic_progress_header_item_txt">SPEAKER</div>
                </div>
                <div class="basic_progress_header_item_line basic_speaker_line"></div>
                <div class="basic_progress_header_item basic_network_icon">
                    <img alt="" class="basic_progress_header_item_icon" src="${resourceUrl}/images/monitor/net_4.png" />
                    <div class="basic_progress_header_item_txt">NETWORK</div>
                </div>
            </div>

            <!-- 2 -->
            <div class="basic_two_wrap" style="display: none;">
                <div class="basic_two_center">
                    <div class="basic_two_select_wrap">
                        <div class="basic_selecct_row_title i18n">摄像头选择</div>
                        <div class="basic_normal_select_item">
                            <div class="basic_normal_select_input_wrap">
                                <div class="basic_normal_select_container">
                                    
                                    <input class="basic_normal_select_input" id="basic_camera_select_wrap" type="text" readonly="readonly" onfocus="this.nextSibling.nextSibling.style.display='block';"
                                        onblur="var t=this;setTimeout(()=>{t.nextSibling.nextSibling.style.display='none';},150);" placeholder="" />
                                    <ul class="basic_camera_select">
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="basic_two_camera_wrap">
                        <div class="basic_two_video_wrap"></div>
                    </div>
                    <div class="basic_two_center_tip i18n">是否可以看清楚自己？</div>
                </div>
                <div class="basic_two_footer">
                    <div onclick="camera_available_click(false)" class="basic_two_footer_btn i18n">看不到</div>
                    <div onclick="camera_available_click(true)" class="basic_two_footer_btn basic_two_confirm_btn i18n">看的到</div>
                </div>
            </div>

            <!-- 3 -->
            <div class="basic_three_wrap" style="display: none;">
                <div class="basic_three_center">
                    <div class="basic_three_select_wrap">
                        <div class="basic_selecct_row_title i18n">麦克风选择</div>
                        <div class="basic_normal_select_item">
                            <div class="basic_normal_select_input_wrap">
                                <div class="basic_normal_select_container">
                                    
                                    <input class="basic_normal_select_input" id="basic_microphone_select_wrap" type="text" readonly="readonly" onfocus="this.nextSibling.nextSibling.style.display='block';"
                                        onblur="var t=this;setTimeout(()=>{t.nextSibling.nextSibling.style.display='none';},150);" placeholder="" />
                                    <ul class="basic_microphone_select">
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="basic_three_microphone_wrap">
                        <div class="basic_three_video_wrap">
                            <div class="basic_three_audio_dom" style="display: none;"></div>
                            <div class="basic_three_video_tip i18n">对着麦克风说哈喽试试~</div>
                            <div class="basic_three_video_icon_wrap">
                                <img alt="" class="basic_three_video_icon" src="${resourceUrl}/images/icons/volume_img_sprites.png" />
                            </div>
                        </div>
                    </div>
                    <div class="basic_three_center_tip i18n">是否可以看到音量图标跳动？</div>
                </div>
                <div class="basic_three_footer">
                    <div onclick="microphone_available_click(false)" class="basic_three_footer_btn i18n">看不到</div>
                    <div onclick="microphone_available_click(true)" class="basic_three_footer_btn basic_three_confirm_btn i18n">看的到</div>
                </div>
            </div>

            <!-- 4 -->
            <div class="basic_four_wrap" style="display: none;">
                <div class="basic_four_center">
                    <div class="basic_four_select_wrap">
                        <div class="basic_selecct_row_title i18n">扬声器选择</div>
                        <div class="basic_normal_select_item">
                            <div class="basic_normal_select_input_wrap">
                                <div class="basic_normal_select_container">
                                    
                                    <input class="basic_normal_select_input" id="basic_speaker_select_wrap" type="text" readonly="readonly" onfocus="this.nextSibling.nextSibling.style.display='block';"
                                        onblur="var t=this;setTimeout(()=>{t.nextSibling.nextSibling.style.display='none';},150);" placeholder="" />
                                    <ul class="basic_speaker_select">
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="basic_four_speaker_wrap">
                        <div class="basic_four_audio_wrap">
                            <div class="basic_four_audio_tip i18n">请调高设备音量，点击播放下面的音频试试~</div>
                            <audio id="basic_four_audio" controlsList="nodownload nofullscreen noremoteplayback noplaybackrate" src="${resourceUrl}/audio/piano_music.wav" controls></audio>
                        </div>
                    </div>
                    <div class="basic_four_center_tip i18n">是否可以听到声音？</div>
                </div>
                <div class="basic_four_footer">
                    <div onclick="speaker_available_click(false)" class="basic_four_footer_btn i18n">听不到</div>
                    <div onclick="speaker_available_click(true)" class="basic_four_footer_btn basic_four_confirm_btn i18n">听的到</div>
                </div>
            </div>

            <!-- 5 -->
            <div class="basic_five_wrap" style="display: none;">
                <div class="basic_five_center">
                    <div class="basic_five_item">
                        <div class="basic_five_item_tilte i18n">操作系统</div>
                        <div class="basic_five_item_txt check_system"></div>
                    </div>
                    <div class="basic_five_item">
                        <div class="basic_five_item_tilte i18n">浏览器</div>
                        <div class="basic_five_item_txt check_browser"></div>
                    </div>
                    <div class="basic_five_item">
                        <div class="basic_five_item_tilte i18n">是否支持WEBRTC</div>
                        <div class="basic_five_item_txt check_trtc"></div>
                    </div>
                    <div class="basic_five_item">
                        <div class="basic_five_item_tilte i18n">是否支持屏幕分享</div>
                        <div class="basic_five_item_txt check_share_screen"></div>
                    </div>
                    <div class="basic_five_item">
                        <div class="basic_five_item_tilte i18n">网络延时</div>
                        <div class="basic_five_item_txt check_network_delay"></div>
                    </div>
                    <div class="basic_five_item">
                        <div class="basic_five_item_tilte i18n">上行网络质量</div>
                        <div class="basic_five_item_txt check_downlink"></div>
                    </div>
                    <div class="basic_five_item">
                        <div class="basic_five_item_tilte i18n">下行网络质量</div>
                        <div class="basic_five_item_txt check_downlink"></div>
                    </div>
                </div>
                <div class="basic_five_btn_wrap">
                    <div class="basic_five_btn"><span class="i18n">剩余检测时间</span>(<span class="remaining_detection_time">7</span>)s</div>
                    <div onclick="view_check_report()" class="basic_five_btn_next i18n">查看检测报告</div>
                </div>
            </div>

            <!-- 6 -->
            <div class="basic_six_wrap" style="display: none;">
                <div class="basic_six_header">
                    <div class="basic_six_header_txt i18n">检测报告</div>
                </div>
                <div class="basic_six_center">
                    <div class="basic_six_item">
                        <div class="basic_six_item_left">
                            <img alt="" class="basic_six_item_icon" src="${resourceUrl}/images/monitor/camera_1.png" />
                            <div class="basic_six_item_title basic_six_camera"></div>
                        </div>
                        <div class="basic_six_item_status basic_six_camera_status"></div>
                    </div>
                    <div class="basic_six_item">
                        <div class="basic_six_item_left">
                            <img alt="" class="basic_six_item_icon" src="${resourceUrl}/images/monitor/mic_1.png" />
                            <div class="basic_six_item_title basic_six_microphone"></div>
                        </div>
                        <div class="basic_six_item_status basic_six_microphone_status"></div>
                    </div>
                    <div class="basic_six_item">
                        <div class="basic_six_item_left">
                            <img alt="" class="basic_six_item_icon" src="${resourceUrl}/images/monitor/speaker_1.png" />
                            <div class="basic_six_item_title basic_six_speaker"></div>
                        </div>
                        <div class="basic_six_item_status basic_six_speaker_status"></div>
                    </div>
                    <div class="basic_six_item">
                        <div class="basic_six_item_left">
                            <img alt="" class="basic_six_item_icon" src="${resourceUrl}/images/monitor/net_1.png" />
                            <div class="basic_six_item_title i18n">网络延迟</div>
                        </div>
                        <div class="basic_six_item_status basic_six_net"></div>
                    </div>
                    <div class="basic_six_item">
                        <div class="basic_six_item_left">
                            <img alt="" class="basic_six_item_icon" src="${resourceUrl}/images/monitor/net_1.png" />
                            <div class="basic_six_item_title i18n">上行网络质量</div>
                        </div>
                        <div class="basic_six_item_status basic_six_downlink"></div>
                    </div>
                    <div class="basic_six_item">
                        <div class="basic_six_item_left">
                            <img alt="" class="basic_six_item_icon" src="${resourceUrl}/images/monitor/net_1.png" />
                            <div class="basic_six_item_title i18n">下行网络质量</div>
                        </div>
                        <div class="basic_six_item_status basic_six_downlink"></div>
                    </div>
                </div>
                <div class="basic_six_footer">
                    <div onclick="reset_check()" class="basic_six_footer_btn i18n">重新检测</div>
                    <div onclick="finish_check()" class="basic_six_footer_btn basic_six_footer_btn_finish i18n">完成检测</div>
                </div>
            </div>
    </div>
        `
        let dom = document.createElement('div')
        dom.id = 'detectionBox'
        dom.setAttribute('class','basic_monitor_popup')
        // dom.innerHTML = domArr[i].txt
        document.body.appendChild(dom)
        if(document.getElementById('detectionBox')) {
            document.getElementById('detectionBox').innerHTML = str
            document.getElementById('detectionBox').style.display = 'flex'
        }
    }

}
function autoContentToBottom() {
    // if(localStorage.getItem("myRollScreenSwitch") == "true") {
        contentToBottom()
    // }
}
function contentToBottom() {
    let seatABoxContent = document.getElementById("seatABoxContent");
    setTimeout(() => {
        seatABoxContent.scrollTop = seatABoxContent.scrollHeight
    }, 100);
}
function handleSeatABoxUserList(data = {}) {
    // data = {
    //     agent_id: "000003_1009",
    //     code: "0",
    //     company_code: "000003",
    //     msg: "asr调用成功",
    //     msg_type: "asr_online",
    //     os: null,
    //     req_id: "1f328bcb-cd9b-43f5-b44b-f6fe011288df",
    //     src_lang_id: "auto",
    //     src_text: "嗯12",
    //     success: true,
    //     trans_lang_id: "en",
    //     trans_text: "",
    //     ts: 1722414263858,
    //     type: "agent",
    //     user_phone: "15559152388",
    //     uuid: "call-1a25cd88-b53f-4fdf-9a4f-00c0cfa1eeec",
    //      uuid: "B-call-1a25cd88-b53f-4fdf-9a4f-00c0cfa1eeec", //type:"client"
    // }

    let src_text = data.src_text;
    let src_lang_id = data.src_lang_id;
    let trans_text = data.trans_text;
    let trans_lang_id = data.trans_lang_id;
    let type = data.type;
    let agent_id = data.agent_id;
    let user_phone = data.user_phone;
    let user_default_uuid = defaultUserCallUuid;

    // 坐席助手顶部呼叫记录
    let isExit = false;
    seatABoxUserList.map(item => {
        if(item.user_default_uuid == user_default_uuid) {
            isExit = true;
        }
    });
    try{

    if(!isExit) {
        let seatABoxUserItems = document.querySelectorAll('#seatABoxUserWrap .seatABoxUserItem');
        seatABoxUserItems.forEach(el => {
            el.classList.remove('active');
        });
        $('#seatABoxContent').empty();
        seatABoxUserList.push({
            user_phone: user_phone,
            user_default_uuid: user_default_uuid,
        });
        activeUserCallUuid = user_default_uuid;
        handleAddSeatABoxUserName({
            user_phone: user_phone,
            user_default_uuid: user_default_uuid,
            active: true,
        });
        setTimeout(() => {
            let seatABoxUserWrap = document.getElementById('seatABoxUserWrap');
            let scrollWidth = seatABoxUserWrap.scrollWidth;
            seatABoxUserWrap.scrollLeft = scrollWidth;
        }, 500);
        
        if(document.getElementById("seatABoxUserRightArrowWrap")) {
            document.getElementById("seatABoxUserRightArrowWrap").style.display = 'flex';
        }

        // 通话记录
        if(!seatABoxUserHistory[user_default_uuid]) {
            seatABoxUserHistory[user_default_uuid] = [];
        }

        let now = new Date();
        let timeData = {
            type: "time",
            callTime: formatDate(now),
        }
        seatABoxUserHistory[user_default_uuid].push(timeData)
       // let rollId = generateUUID();
        data.rollId = data.req_id;
        data.callTime = formatDate(now);
        seatABoxUserHistory[user_default_uuid].push(data)
        handleUseHistoryCallLog(user_default_uuid);
    }else{
        // 通话记录加一条
        if(!seatABoxUserHistory[user_default_uuid]) {
            seatABoxUserHistory[user_default_uuid] = [];
        }else{
            let currentList = seatABoxUserHistory[user_default_uuid]
            let lastUserObj = currentList[currentList.length - 1];
            let callTime = lastUserObj.callTime;
            let now = new Date();
            try{
                if(now.getTime() - new Date(callTime).getTime() > 10*60*1000) {
                    let timeData = {
                        type: "time",
                        callTime: formatDate(now),
                    }
                    seatABoxUserHistory[user_default_uuid].push(timeData);
                    updateCallLog(timeData);
                }
            }catch(res){}

        }
        let now = new Date();
        // let rollId = generateUUID();
        data.rollId = data.req_id;
        data.callTime = formatDate(now);
        seatABoxUserHistory[user_default_uuid].push(data);
        if(activeUserCallUuid == user_default_uuid) {
            updateCallLog(data);
        }
    }
    setSeatABoxUserHistory();
}catch(res){
    console.log(res)
}
}
function updateCallLog(data) {
    if(data.type == "time") {
        let currentDate = new Date();
        let currentYear = currentDate.getFullYear();
        let currentMonth = currentDate.getMonth(); // 返回的月份是从 0 开始的，所以要加 1
        let currentDay = currentDate.getDate();

        // 解析目标日期
        let targetDate = new Date(data.callTime);
        let targetYear = targetDate.getFullYear();
        let targetMonth = targetDate.getMonth();
        let targetDay = targetDate.getDate();
        let hours = targetDate.getHours().toString().padStart(2, '0');
        let minutes = targetDate.getMinutes().toString().padStart(2, '0');
        let seconds = targetDate.getSeconds().toString().padStart(2, '0');

        let timeTxt = '';
        if(currentYear === targetYear && currentMonth === targetMonth && currentDay === targetDay) { //今天
            let callTime = `${hours}:${minutes}:${seconds}`;
            timeTxt = `<div class="seatABoxContentTime">${callTime}</div>`;
        }else{
            timeTxt = `<div class="seatABoxContentTime">${data.callTime}</div>`;
        }
        $('#seatABoxContent').append(timeTxt);
    }else{
        setChatBodyHtml(data)
    }
}
function setChatBodyHtml(data) {
    if($(`#${data.rollId}`).length > 0){
        // dom已经存在 更新翻译
        if(data.trans_text) {
            $(`#${data.rollId}`).find('.seatABoxContentTraTxt').css('display', 'block');
            $(`#${data.rollId}`).find('.seatABoxContentTraLoadingWrap').css('display', 'none');
            $(`#${data.rollId}`).find('.seatABoxContentTraRetry').css('display', 'none');
            $(`#${data.rollId}`).find('.seatABoxContentTraError').css('display', 'none');
            $(`#${data.rollId}`).find('.seatABoxContentTraTxt').text(data.trans_text);
        }
        return;
    }
    let direction = '';
    let checked = false; //开启文本翻译
    let headerImg = '';
    if(data.type == "agent") {
        direction = 'Right';
        headerImg = 'seatHeader';
        let myTranslateSwitch = document.getElementById('myTranslateSwitch');
        checked = myTranslateSwitch.checked;
    }else{
        direction = 'Left';
        headerImg = 'userHeader';
        let myCustomTranslateSwitch = document.getElementById('myCustomTranslateSwitch');
        checked = myCustomTranslateSwitch.checked;
    }

    let transTxt = '';
    let traRetryBtnTxt = '';
    let traFailBtnTxt = '';
    let traLoadingImg = "";

    let transTxtShow = false;
    let traRetryBtnTxtShow = false;
    let traLoadingImgShow = false;
    let traFailBtnTxtShow = false;

    if(data.trans_text) {
        // 有翻译文本显示翻译文本
        transTxtShow = true;
    }else if(checked){
        // 开启了文本翻译但没有翻译文本显示转圈loading
        traLoadingImgShow = true;
    }else{
        // 没有翻译文本显示点击翻译按钮
        traRetryBtnTxtShow = true;
    }
    transTxt = `<div class="seatABoxContentTraTxt" style="display: ${transTxtShow ? 'block' : 'none'};">${data.trans_text}</div>`;
    traRetryBtnTxt = `<div class="seatABoxContentTraBtn seatABoxContentTraRetry" style="display: ${traRetryBtnTxtShow ? 'block' : 'none'};" ><span class="seatABoxContentTraRetryTxt i18nFromOritxt" data-oritxt="点击翻译" data-src_text="${data.src_text}" data-src_lang_id="${data.src_lang_id}">${i18ntc("点击翻译")}</span></div>`;
    traLoadingImg = `<div class="seatABoxContentTraLoadingWrap" style="display: ${traLoadingImgShow ? 'block' : 'none'};"><img class="loadingImg" src="${resourceUrl}/images/seatAiImages/loading.png" /></div>`;
    traFailBtnTxt = `<div class="seatABoxContentTraBtn seatABoxContentTraError" style="display: ${traFailBtnTxtShow ? 'block' : 'none'};"><span class="seatABoxContentTraErrorTxt i18nFromOritxt" data-oritxt="翻译失败" data-src_text="${data.src_text}" data-src_lang_id="${data.src_lang_id}">${i18ntc("翻译失败")}</span></div>`;
    let tipTxtHtml = `
        <div class="aiTipWrap" >
            <div class="aiTipContent">
                <span class="aiTipTxt i18nFromOritxt" data-oritxt="提示">${i18ntc("提示")}</span>
                <span class="aiTipTxtUnit" >:</span>
                <span class="aiTipTxt i18nFromOritxt" id="aiTipTxtContent" data-oritxt=""></span>
            </div>
        </div>
    `;
    // seatABoxContent${direction}TxtWrap" 加上active就是red顔色
    let htmlTxt = `
    <div id="${data.rollId}" class="seatABoxContentBodyWrap seatABox${direction}Content">
        <div class="seatABoxContentBody">
            <div class="seatABox${direction}ContentBody">
                <img class="seatABoxContentHeaderImg" src="${resourceUrl}/images/seatAiImages/${headerImg}.png"/>
                <div class="seatABoxContentTxtWrap seatABoxContent${direction}TxtWrap">
                    <div class="seatABoxContent${direction}Triangle"></div>
                    <div class="seatABoxContentSrcTxt">${data.src_text}</div>
                    ${transTxt}${traRetryBtnTxt}${traFailBtnTxt}${traLoadingImg}
                </div>
                <div class="seatABoxContentCopyImgWrap">
                    <div class="seatABoxPropWrap">
                        <div class="seatABoxPropTxt i18nFromOritxt" data-oritxt="复制">${i18ntc("复制")}</div>
                        <div class="seatABoxPropTriangle"></div>
                    </div>
                    <img data-src_text="${data.src_text}" class="seatABoxContentCopyImg seatABoxContentCopyImgBtn" src="${resourceUrl}/images/seatAiImages/copy.png"/>
                </div>
                <div class="seatABoxContentTranslateImgWrap">
                    <div class="seatABoxPropWrap">
                        <div class="seatABoxPropTxt i18nFromOritxt" data-oritxt="翻译">${i18ntc("翻译")}</div>
                        <div class="seatABoxPropTriangle"></div>
                    </div>
                    <img data-src_text="${data.src_text}" data-src_lang_id="${data.src_lang_id}" class="seatABoxContentTranslateImg seatABoxContentTranslateImgBtn" src="${resourceUrl}/images/seatAiImages/translate.png"/>
                </div>
            </div>
            ${tipTxtHtml}
        </div>
    </div>`
    $('#seatABoxContent').append(htmlTxt);

    // 转圈判断3s后消失 显示点击翻译按钮
    if(traLoadingImgShow) {
        window[`traLoadingImgShowTime${data.rollId}`] = setTimeout(() => {
            if($(`#${data.rollId}`).find('.seatABoxContentTraLoadingWrap').css('display') == 'block') {
                $(`#${data.rollId}`).find('.seatABoxContentTraLoadingWrap').css('display', 'none');
                $(`#${data.rollId}`).find('.seatABoxContentTraRetry').css('display', 'block');
            }
        }, 3000);
    }

    // 聊天记录进来滚动到底部
    autoContentToBottom();
}
function handleUseHistoryCallLog(user_default_uuid) {
    seatABoxUserHistory[user_default_uuid].map(item => {
        updateCallLog(item);
    })
}
function handleSeatAssistantSetting() {
    let customAsrTranslateType = setParam.customAsrTranslateType;
    if(customAsrTranslateType && customAsrTranslateType != 0) {
        let currentLanguage = textTargetKeys[customAsrTranslateType];
        document.getElementById('seatABoxCustomTargetLanguage').innerHTML = currentLanguage;
        if(assistantEnablePermission['2']) {
            document.getElementById('myCustomTranslateSwitch').checked = true;
        }
    }else{
        document.getElementById('myCustomTranslateSwitch').checked = false;
    }

    let asrTranslateType = setParam.asrTranslateType;
    if(asrTranslateType && asrTranslateType != 0) {
        let currentLanguage = textTargetKeys[asrTranslateType];
        document.getElementById('seatABoxTargetLanguage').innerHTML = currentLanguage;
        if(assistantEnablePermission['2']) {
            document.getElementById('myTranslateSwitch').checked = true;
        }
    }else{
        document.getElementById('myTranslateSwitch').checked = false;
    }
}
//创建坐席助手
function createdSeatAssistantBox(){
    let str = `
     <div id="seatAssistantBoxPannel">
        <div class="seatABoxHeader">
            <div class="seatABoxHeaderLeftWrap">
                <img class="seatABoxHeaderLogoImg" src="${resourceUrl}/images/seatAiImages/seatLogoOn.png" alt="logo"/>
                <div class="seatABoxHeaderTitle i18nFromOritxt" data-oritxt="坐席助手">坐席助手</div>
            </div>
            <div id="seatABoxUserLeftArrowBtnWrap" class="seatABoxUserLeftArrowWrap">
                <img id="seatABoxUserLeftArrowBtn" class="seatABoxUserLeftArrow" src="${resourceUrl}/images/seatAiImages/seatABoxArrow.png" alt="arrow">
            </div>
            <div id="seatABoxUserWrap" class="seatABoxUserWrap">
               
            </div>
            <div id="seatABoxUserRightArrowWrap" class="seatABoxUserRightArrowWrap">
                <img id="seatABoxUserRightArrowBtn" class="seatABoxUserRightArrow" src="${resourceUrl}/images/seatAiImages/seatABoxArrow.png" alt="arrow">
            </div>
            <div class="seatABoxHeaderRightWrap">
                <img id="seatAssistantBoxNarrowBtn" class="seatABoxHeaderNarrowImg" src="${resourceUrl}/images/seatAiImages/narrow.png" alt="smaller"/>
                <img id="seatAssistantBoxRestoreBtn" class="seatABoxHeaderRestoreImg" src="${resourceUrl}/images/seatAiImages/restore.png" alt="restore"/>
                <img id="seatAssistantBoxEnlargeBtn" class="seatABoxHeaderEnlargeImg" src="${resourceUrl}/images/seatAiImages/enlarge.png" alt="bigger"/>
                <img id="seatAssistantBoxCloseBtn" class="seatABoxHeaderCloseImg" src="${resourceUrl}/images/seatAiImages/close.png" alt="close"/>
            </div>
        </div>
        <div class="seatAssistantBoxPannelContentWrap">
            <div class="seatAssistantBoxPannelLeft">
                <div class="seatABoxNeck seatABoxNeck1">
                    <div class="seatABoxNeckNameWrap">
                        <div class="seatABoxNeckName i18nFromOritxt" data-oritxt="客户">客户</div>
                    </div>
                    <div class="seatABoxNeckItemContainer">
                        <div class="seatABoxNeckItemWrap">
                            <div class="seatABoxNeckItem">
                                <div class="seatABoxNeckItemLabel i18nFromOritxt" data-oritxt="文本翻译" style="margin-left: 0px;">文本翻译</div>
                                <label class="switch">
                                    <input type="checkbox" id="myCustomTranslateSwitch" />
                                    <span class="slider round"></span>
                                </label>
                            </div>
                            <div class="seatABoxNeckItem">
                                <div class="seatABoxNeckItemLabel i18nFromOritxt" data-oritxt="翻译目标语言" style="margin-right: 0px;">翻译目标语言</div>
                                <div style="position: relative;">
                                    <div id="seatABoxCustomTargetLanguage" class="seatABoxTargetLanguage"></div>
                                    <div id="targetCustomLanguageSelectWrap" class="targetLanguageSelectWrap">

                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="seatABoxNeckItemWrap">
                            <div class="seatABoxNeckItem">
                                <div class="seatABoxNeckItemLabel i18nFromOritxt" data-oritxt="语音翻译" style="margin-left: 0px;">语音翻译</div>
                                <label class="switch">
                                    <input type="checkbox" id="myCustomAudioTranslateSwitch" />
                                    <span class="slider round"></span>
                                </label>
                            </div>
                            <div class="seatABoxNeckItem">
                                <div class="seatABoxNeckItemLabel i18nFromOritxt" data-oritxt="翻译目标语言" style="margin-right: 0px;">翻译目标语言</div>
                                <div style="position: relative;">
                                    <div id="seatABoxCustomSendLanguage" class="seatABoxTargetLanguage"></div>
                                    <div id="sendCustomLanguageSelectWrap" class="targetLanguageSelectWrap">

                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="seatABoxNeck seatABoxNeck2">
                    <div class="seatABoxNeckNameWrap">
                        <div class="seatABoxNeckName i18nFromOritxt" data-oritxt="我">我</div>
                    </div>
                    <div class="seatABoxNeckItemContainer">
                        <div class="seatABoxNeckItemWrap">
                            <div class="seatABoxNeckItem">
                                <div class="seatABoxNeckItemLabel i18nFromOritxt" data-oritxt="文本翻译" style="margin-left: 0px;">文本翻译</div>
                                <label class="switch">
                                    <input type="checkbox" id="myTranslateSwitch" />
                                    <span class="slider round"></span>
                                </label>
                            </div>
                            <div class="seatABoxNeckItem">
                                <div class="seatABoxNeckItemLabel i18nFromOritxt" data-oritxt="翻译目标语言" style="margin-right: 0px;">翻译目标语言</div>
                                <div style="position: relative;">
                                    <div id="seatABoxTargetLanguage" class="seatABoxTargetLanguage"></div>
                                    <div id="targetLanguageSelectWrap" class="targetLanguageSelectWrap">

                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="seatABoxNeckItemWrap">
                            <div class="seatABoxNeckItem">
                                <div class="seatABoxNeckItemLabel i18nFromOritxt" data-oritxt="语音翻译" style="margin-left: 0px;">语音翻译</div>
                                <label class="switch">
                                    <input type="checkbox" id="myAudioTranslateSwitch" />
                                    <span class="slider round"></span>
                                </label>
                            </div>
                            <div class="seatABoxNeckItem">
                                <div class="seatABoxNeckItemLabel i18nFromOritxt" data-oritxt="翻译目标语言" style="margin-right: 0px;">翻译目标语言</div>
                                <div style="position: relative;">
                                    <div id="seatABoxSendLanguage" class="seatABoxTargetLanguage"></div>
                                    <div id="sendLanguageSelectWrap" class="targetLanguageSelectWrap">

                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="seatABoxDropIconWrap">
                    <img class="seatABoxDropIcon seatABoxDropUp" id="seatABoxDropUp" src="${resourceUrl}/images/seatAiImages/dropUp.png" />
                    <img class="seatABoxDropIcon seatABoxDropDown" id="seatABoxDropDown" src="${resourceUrl}/images/seatAiImages/dropDown.png" />
                </div>
                <div id="seatABoxSearchWrap" class="seatABoxSearchWrap">
                    <div class="seatABoxSearchContent">
                        <div id="seatABoxSearchIconWrap" class="seatABoxSearchIconWrap">
                            <img class="seatABoxSearchIcon" src="${resourceUrl}/images/seatAiImages/search.png"/>
                        </div>
                        <div class="seatABoxSearchInputWrap">
                            <input id="seatABoxSearchInput" class="seatABoxSearchInput i18nInput" type="text" placeholder="${i18ntc('请输入')}" />
                            <button id="seatABoxSearchSubmit" class="seatABoxSearchSubmit i18nFromOritxt" data-oritxt="搜索">搜索</button>
                        </div>
                    </div>
                </div>
                <div id="seatABoxContent" class="seatABoxContent">
                    
                </div>
            </div>
            <div class="seatABoxPullIconWrap" id="seatABoxPullIconWrap">
                <img class="seatABoxPullIcon seatABoxPullUp" id="seatABoxPullUp" src="${resourceUrl}/images/seatAiImages/PullUp.png" />
                <img class="seatABoxPullIcon seatABoxPullDown" id="seatABoxPullDown" src="${resourceUrl}/images/seatAiImages/PullDown.png" />
            </div>
            <div class="seatAssistantBoxPannelRight" id="seatAssistantBoxPannelRight">
                <div class="aiDetectionTimeWrap" id="aiDetectionTimeWrap">
                    <div class="aiDetectionWrap" id="aiDetectionWrap">
                        <div class="aiRecognitionWrap" style="padding-bottom: 0px;">
                            <div class="aiRecognitionItem">
                                <div class="aiRecognitionTitle i18nFromOritxt" data-oritxt="负面情绪" >负面情绪</div>
                                <div class="aiRecognitionCount" id="aiNegativeEmotionsCount" >0</div>
                            </div>
                            <div class="aiRecognitionItem">
                                <div class="aiRecognitionTitle i18nFromOritxt" data-oritxt="静音" >静音</div>
                                <div class="aiRecognitionCount" id="aiMuteCount" >0</div>
                                <img class="aiRecognitionItemImg" src="${resourceUrl}/images/seatAiImages/aiMuteImg.png" />
                            </div>
                        </div>
                        <div class="speedSpeechWrap" >
                            <div class="speedSpeechTitle i18nFromOritxt" data-oritxt="语速">语速</div>
                            <img class="speedSpeechImg" src="${resourceUrl}/images/seatAiImages/speedImg.gif" />
                            <div class="speedIsFastTxt i18nFromOritxt" data-oritxt="正常" id="speedIsFastTxt">正常</div>
                        </div>
                        <div class="aiRecognitionWrap" style="padding-top: 0px;">
                            <div class="aiRecognitionItem">
                                <div class="aiRecognitionTitle i18nFromOritxt" data-oritxt="抢话" >抢话</div>
                                <div class="aiRecognitionCount" id="aiRobWordCount" >0</div>
                            </div>
                            <div class="aiRecognitionItem">
                                <div class="aiRecognitionTitle i18nFromOritxt" data-oritxt="违规词" >违规词</div>
                                <div class="aiRecognitionCount" id="aiIllegalWordsCount" >0</div>
                            </div>
                        </div>
                    </div>
                    <div class="aiRecognitionTabsContainer" >
                        <div class="aiRecognitionTabsWrap" >
                            <div class="aiRecognitionTabItem i18nFromOritxt" data-oritxt="实体提取" data-type="1" id="extractionTab">实体提取</div>
                            <div class="aiRecognitionTabItem i18nFromOritxt" data-oritxt="实时质检" data-type="2" id="qualityCheckTab">实时质检</div>
                            <div class="aiRecognitionTabItem i18nFromOritxt" data-oritxt="对话总结" data-type="3" id="dialogueSummaryTab">对话总结</div>
                        </div>
                        <div class="aiRecognitionTabsContent" >
                            <div class="aiRecognitionTab aiRecognitionTabOneWrap" id="aiRecognitionTabOneWrap">
                                
                            </div>
                            <div class="aiRecognitionTab aiRecognitionTabTwoWrap" id="aiRecognitionTabTwoWrap">
                                <div class="aiRecognitionTabTwoContent" >
                                    <div class="i18nFromOritxt" data-oritxt="本次会话您的评分为" >本次会话您的评分为</div>
                                    <div class="aiRecognitionTabTwoUnit">:</div>
                                    <div class="aiRecognitionTabTwoTxt" id="qualityScoreId">100</div>
                                    <div class="aiRecognitionTabTwoTxt i18nFromOritxt" data-oritxt="分">分</div>
                                </div>
                            </div>
                            <div class="aiRecognitionTab aiRecognitionTabThreeWrap" id="aiRecognitionTabThreeWrap">
                                
                            </div>
                        </div>
                    </div>
                </div>
                <div class="knowledgeRecommentWrap" id="knowledgeRecommentWrap" >
                    <div class="knowledgeRecommentTitleWrap" >
                        <div class="knowledgeRecommentTitle i18nFromOritxt" data-oritxt="知识推荐" >知识推荐</div>
                    </div>
                    <div class="knowledgeRecommentContentWrap" id="knowledgeRecommentContentWrap">

                    </div>
                </div>
            </div>
        </div>
    </div>
    `;
    document.getElementById('seatAssistantBox').innerHTML = str;
    dragDomPannel($('#seatAssistantBoxPannel'));

    setSeatAssistantBoxPannelRightEmptyFun()
}

function createKnowledgeModal() {
    let str = `
    <div id="knowledgeModalContainer">
        <div class="knowledgeModalHeader" >
            <div  class="knowledgeModalHeaderTitle i18nFromOritxt" data-oritxt="详情">${i18ntc("详情")}</div>
            <div style="flex: 1;" ></div>
            <div onclick="hideKnowledgeDetailPop()" class="knowledgeModalCloseWrap">
                <img alt="" class='knowledgeModalCloseImg' src="${resourceUrl}/images/seatAiImages/close.png" />
            </div>
        </div>
        <div id="knowledgeModalContent" class="knowledgeModalContent" ></div>
    </div>
    `;
    document.getElementById('knowledgeModal').innerHTML = str;
    dragDomPannel($('#knowledgeModalContainer'));
}

{/* <div class="seatABoxNeckItem">
    <div class="seatABoxNeckItemLabel i18n">自动滚屏</div>
    <label class="switch">
        <input type="checkbox" id="myRollScreenSwitch" />
        <span class="slider round"></span>
    </label>
</div> */}

function dragDomPannel(dragElement) {
    var Moving = false;
    var clickMoveX = 0;
    var clickMoveY = 0;
    var nowMarginX = 0;
    var nowMarginY = 0;
    $(document).mousemove(function(e){
        //窗口拖动
        if(Moving==true){
            var changeX = e.clientX - Number(clickMoveX);
            var changeY = e.clientY - Number(clickMoveY);
            dragElement.css('left',changeX + Number(nowMarginX) + 'px');
            dragElement.css('top',changeY + Number(nowMarginY) + 'px');
        }
    });
    dragElement.mousedown(function(e){
        e.stopPropagation()
        if (e.stopPropagation) {
            e.stopPropagation();
        }else if (window.e) {
            window.e.cancelBubble = true;
        }
        $('body').css('user-select','none');
        if(dragElement.width() - 30 < e.offsetX || dragElement.height() - 30 < e.offsetY){
        }else{
            clickMoveX =  e.clientX;
            clickMoveY =  e.clientY;
            nowMarginX = dragElement.css('left').slice(0,-2);
            nowMarginY = dragElement.css('top').slice(0,-2);
            Moving = true;
        }

    });
    $('body').mouseup(function(){
        $('body').css('user-select','text')
        Moving = false
    })
}
function handleCopyText(text) {
    try {
      navigator.clipboard.writeText(text);
      toastMessage(i18ntc('复制成功'));
    } catch (err) {
      toastMessage(i18ntc('复制失败'));
    }
}
function formatDate(date) {
    var year = date.getFullYear();
    var month = String(date.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的
    var day = String(date.getDate()).padStart(2, '0');
    var hours = String(date.getHours()).padStart(2, '0');
    var minutes = String(date.getMinutes()).padStart(2, '0');
    var seconds = String(date.getSeconds()).padStart(2, '0');
    return `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`;
}
async function translateText(parentDom = '', data = {}){
    if(!assistantEnablePermission['2']) {
        return;
    }
    if(!data.trans_lang_id) {
        let seatABoxTargetLanguage = document.getElementById("seatABoxTargetLanguage").innerHTML;
        Object.keys(textTargetKeys).map(item => {
            let language = textTargetKeys[item];
            if(language == seatABoxTargetLanguage) {
                data.trans_lang_id = item;
            }
        });
    }
    if(!data.trans_send_lang_id) {
        let seatABoxSendLanguage = document.getElementById("seatABoxSendLanguage").innerHTML;
        Object.keys(audioTargetKeys).map(item => {
            let language = audioTargetKeys[item];
            if(language == seatABoxSendLanguage) {
                data.trans_send_lang_id = item;
            }
        });
    }
    if(!data.src_lang_id){
        data.src_lang_id = "auto";
    }
    clearTimeout(window[`traLoadingImgShowTime${data.rollId}`]);
    // loading
    parentDom.children('.seatABoxContentTraTxt').hide();
    parentDom.children('.seatABoxContentTraBtn').hide();
    parentDom.children('.seatABoxContentTraLoadingWrap').show();

    await getToken({
        company_code,
        agent_pwd,
        agent_id: company_code + '_' + agent_id,
        msg_type: "get_token",
        os: system,
        req_id: generateUUID(),
    })
    ajax({
        type: 'POST',
        url: dominUrl + 'cloudcc-client-server/openapi/translateText',
        data: {
            req_id: generateUUID(),
            company_code: company_code,
            src_text: data.src_text,
            src_lang_id: data.src_lang_id,
            trans_lang_id: data.trans_lang_id,
        },
        success: function (res) {
            setTimeout(() => {
                let result = JSON.parse(res)
                if(result.code == 0) {
                    let trans_text = result.transText;
                    parentDom.children('.seatABoxContentTraTxt').show();
                    parentDom.children('.seatABoxContentTraTxt').html(trans_text);
                    parentDom.children('.seatABoxContentTraBtn').hide();
                    parentDom.children('.seatABoxContentTraLoadingWrap').hide();
                }else{
                    parentDom.children('.seatABoxContentTraTxt').hide();
                    parentDom.children('.seatABoxContentTraBtn').hide();
                    parentDom.children('.seatABoxContentTraLoadingWrap').hide();
                    parentDom.children('.seatABoxContentTraError').show();
                }
            }, 500);
        }, error: function(err){
            setTimeout(() => {
                parentDom.children('.seatABoxContentTraTxt').hide();
                parentDom.children('.seatABoxContentTraBtn').hide();
                parentDom.children('.seatABoxContentTraLoadingWrap').hide();
                parentDom.children('.seatABoxContentTraError').show();
            }, 500);
        }
    })
}
function handleSeatABoxUserRightArrow(){
    setTimeout(() => {
        let seatABoxUserItemWidth = 56+6;
        let seatABoxUserWrap = document.getElementById('seatABoxUserWrap');
        if(seatABoxUserWrap) {
            let width = seatABoxUserWrap ? seatABoxUserWrap.clientWidth : 0;
            let allWidth = seatABoxUserList.length * seatABoxUserItemWidth;
            if(allWidth > width) {
                let seatABoxUserRightArrowBtn = document.getElementById('seatABoxUserRightArrowBtn');
                if(seatABoxUserRightArrowBtn) {
                    seatABoxUserRightArrowBtn.style.display = 'block';
                }
            }
        }
    }, 100);
}
function handleSeatABoxUserToRight() {
    setTimeout(() => {
        let seatABoxUserWrap = document.getElementById('seatABoxUserWrap');
        if(seatABoxUserWrap) {
            let scrollWidth = seatABoxUserWrap.scrollWidth;
            let currentScrollLeft = seatABoxUserWrap.scrollLeft;
            let clientWidth = seatABoxUserWrap.clientWidth;
            if(currentScrollLeft + clientWidth >= scrollWidth-15){
                let seatABoxUserRightArrowBtn = document.getElementById('seatABoxUserRightArrowBtn');
                if(seatABoxUserRightArrowBtn) {
                    seatABoxUserRightArrowBtn.style.display = 'none';
                }
            }
        }
    }, 100);
}
function handleSeatAssistantBoxEnlarge(){
    let seatAssistantBoxPannel = document.getElementById("seatAssistantBoxPannel");
    let availableWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
    let availableHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
    if(seatAssistantBoxPannel) {
        seatAssistantBoxPannel.style.position = "fixed";
        seatAssistantBoxPannel.style.width = availableWidth - 2 + 'px';
        seatAssistantBoxPannel.style.height = availableHeight - 2 + 'px';
        seatAssistantBoxPannel.style.top = "0";
        seatAssistantBoxPannel.style.left = "0";
    }
    handleSeatABoxUserArrow();
}
function handleSeatABoxUserLeftArrow(){
    let seatABoxUserWrap = document.getElementById('seatABoxUserWrap');
    if(seatABoxUserWrap) {
        let scrollLeft = seatABoxUserWrap.scrollLeft;
        if(scrollLeft == 0) {
            let seatABoxUserLeftArrowBtnWrap = document.getElementById('seatABoxUserLeftArrowBtnWrap');
            if(seatABoxUserLeftArrowBtnWrap) {
                seatABoxUserLeftArrowBtnWrap.style.display = "none";
            }
        }
    }
}
function handleSeatABoxUserArrow() {
    handleSeatABoxUserLeftArrow();
    handleSeatABoxUserRightArrow();
    handleSeatABoxUserToRight();
}
function setSeatABoxUserHistory() {
    let seatABoxUserHistoryStorageKey = `${company_code}_${agent_id}_seatABoxUserHistory`;
    try{
        localStorage.setItem(seatABoxUserHistoryStorageKey, JSON.stringify(seatABoxUserHistory));
    }catch(res) {
        localStorage.removeItem(seatABoxUserHistoryStorageKey);
    }
}
function handleAddSeatABoxUserName(data = {}){
    // user_phone, active
    let user_phone = data.user_phone;
    let user_default_uuid = data.user_default_uuid;
    let active = data.active;
    let seatABoxUserName = user_phone.toString().substring(0,3) + "****";
    let headerTxt = `<div data-calluuid="${user_default_uuid}" class="seatABoxUserItem ${active?'active':''}">
        <img class="seatABoxUserImg" src="${resourceUrl}/images/seatAiImages/userImg.png" alt="user"/>
        <div class="seatABoxUserName">${seatABoxUserName}</div>
    </div>`
    $('#seatABoxUserWrap').append(headerTxt);
    if(active){
        let scrollWidth = seatABoxUserWrap.scrollWidth;
        seatABoxUserWrap.scrollLeft = scrollWidth;
    }
    handleSeatABoxUserArrow();
}
function handleCloseSeatAssistantBox(){
    let seatABoxUserHistoryStorageKey = `${company_code}_${agent_id}_seatABoxUserHistory`;
    localStorage.removeItem(seatABoxUserHistoryStorageKey);
    $('#seatABoxUserWrap').empty();
    $('#seatABoxContent').empty();
    seatABoxUserList = [];
    seatABoxUserHistory = {};
    activeUserPhone = '';

    let seatABoxQualityCheckHistory = `${company_code}_${agent_id}_seatABoxQualityCheckHistory`;
    localStorage.removeItem(seatABoxQualityCheckHistory);
    seatABoxQualityCheckHistory = {};
    setSeatAssistantBoxPannelRightEmptyFun();
    
}
window.addEventListener('resize', function() {
    handleSeatABoxUserArrow();
    let seatAssistantBoxPannel = document.getElementById("seatAssistantBoxPannel");
    if(seatAssistantBoxPannel && seatAssistantBoxPannel.style.position == "fixed") {
        handleSeatAssistantBoxEnlarge();
    }
});
window.addEventListener('message', function() {
    let data = {}
    try{
    data = event.data ? JSON.parse(event.data) : '';
    }catch(res) {
    // console.log(res);
    }
    if(event.origin == window.location.origin && data.type == 'FillInFormFinish' && data.received) {
        sendFillInFormTimer && clearTimeout(sendFillInFormTimer);
    }
});
function handleSeatAssistantBoxInitFun() {
    if(!baseConfig.showCallDefault){
        try{
            getSeatAssistantConfig();
        }catch(res){}
        let seatABoxUserHistoryStorageKey = `${company_code}_${agent_id}_seatABoxUserHistory`;
        let seatABoxUserHistoryObj = localStorage.getItem(seatABoxUserHistoryStorageKey);
        seatABoxUserHistory = seatABoxUserHistoryObj ? JSON.parse(seatABoxUserHistoryObj) : {};
        if(Object.keys(seatABoxUserHistory).length > 0) {
            Object.keys(seatABoxUserHistory).map(item => {
                let result = seatABoxUserHistory[item].find(hisItem => hisItem.user_phone);
                let user_phone = result.user_phone || '';
                seatABoxUserList.push({
                    user_phone: user_phone,
                    user_default_uuid: item,
                });
            })
        }

        // quality_check
        let seatABoxQualityCheckHistoryStorageKey = `${company_code}_${agent_id}_seatABoxQualityCheckHistory`;
        let seatABoxQualityCheckHistoryObj = localStorage.getItem(seatABoxQualityCheckHistoryStorageKey);
        seatABoxQualityCheckHistory = seatABoxQualityCheckHistoryObj ? JSON.parse(seatABoxQualityCheckHistoryObj) : {};
        // 默认选中第一条
        if(seatABoxUserList.length > 0) {
            let user_default_uuid = seatABoxUserList[0].user_default_uuid;
            seatABoxUserList.map((item, index) => {
                if(index == 0) {
                    handleAddSeatABoxUserName({
                        user_phone: item.user_phone,
                        user_default_uuid: item.user_default_uuid,
                        active: true,
                    });
                    activeUserCallUuid = item.user_default_uuid;
                }else{
                    handleAddSeatABoxUserName({
                        user_phone: item.user_phone,
                        user_default_uuid: item.user_default_uuid,
                        active: false,
                    });
                }
            });
            handleUseHistoryCallLog(user_default_uuid);
            updateUserQualityCheckHistory(activeUserCallUuid);
        }
    }
}

function updateUserQualityCheckHistory(uuid) {
    setSeatAssistantBoxPannelRightEmptyFun()
    if(seatABoxQualityCheckHistory[uuid]) {
        
        let qualityCheckObj = seatABoxQualityCheckHistory[uuid].qualityCheckObj || '';
        let extractionList = seatABoxQualityCheckHistory[uuid].extractionList || [];
        let dialogueSummary = seatABoxQualityCheckHistory[uuid].dialogueSummary || '';
        let knowhistoryList = seatABoxQualityCheckHistory[uuid].knowhistoryList || [];
        knowhistoryList.forEach(item => {
            if(!item.knowledge_id) {
                item.knowledge_id = generateUUID();
            }
        })
        seatABoxQualityCheckHistory[uuid].knowhistoryList = knowhistoryList;
        if(qualityCheckObj) {
            getQualityCheck(qualityCheckObj);
        }else{
            resetQualityCheck();
        }
        
        resetAndAppendTextExtraction(extractionList);
        resetAndAppendDialogueSummary(dialogueSummary);
        resetAndAppendKnowhistorySearch(knowhistoryList);
    }else{
    }
}
async function updateVoiceTranslateSwitch(data = {}){
    await getToken({
        company_code,
        agent_pwd,
        agent_id: company_code + '_' + agent_id,
        msg_type: "get_token",
        os: system,
        req_id: generateUUID(),
    })
    ajax({
        type: 'POST',
        url: dominUrl + 'cloudcc-client-server/openapi/voiceTranslateSwitch',
        data: {
            req_id: generateUUID(),
            company_code,
            voice_type: data.translate_type == 1 ? 0 : 1,
            ...data,
        },
        success: function (res) {
            let result = JSON.parse(res)
            if (result.code == 0){
                getVoiceTranslateSwitch(data);
            } else {
                toastMessage(result.msg)
            }
        }, error: function(err){
        }
    })
}

function getVoiceTranslateSwitch(data = {}){
    if(data.uuid == asrCustomUuid) {
        let myCustomAudioTranslateSwitch = document.getElementById('myCustomAudioTranslateSwitch');
        if(data.translate_type == 1) {
            myCustomAudioTranslateSwitch.checked = true;
        }else{
            myCustomAudioTranslateSwitch.checked = false;
        }

        let textContent = "";
        Object.keys(audioTargetKeys).map(item => {
            if(item == data.trans_lang_id) {
                textContent = audioTargetKeys[item];
            }
        });
        if(textContent) {
            document.getElementById('seatABoxCustomSendLanguage').innerHTML = textContent;
        }
    }else if(data.uuid == asrMyUuid) {
        let myAudioTranslateSwitch = document.getElementById('myAudioTranslateSwitch');
        if(data.translate_type == 1) {
            myAudioTranslateSwitch.checked = true;
        }else{
            myAudioTranslateSwitch.checked = false;
        }
        let textContent = "";
        Object.keys(audioTargetKeys).map(item => {
            if(item == data.trans_lang_id) {
                textContent = audioTargetKeys[item];
            }
        });
        if(textContent) {
            document.getElementById('seatABoxSendLanguage').innerHTML = textContent;
        }
    }
}
function handleSeatABoxHangUp() {
    if(window.isHangUped) {
        return;
    }
    window.isHangUped = true;
    setTimeout(() => {
        window.isHangUped = false;
    }, 500);
    getVoiceTranslateSwitch({
        uuid: asrCustomUuid,
        translate_type: 0,
        trans_lang_id: 0,
    });
    getVoiceTranslateSwitch({
        uuid: asrMyUuid,
        translate_type: 0,
        trans_lang_id: 0,
    });
    getDialogueSummary(defaultUserCallUuid);
    asrMyUuid = "";
    asrCustomUuid = "";
    defaultUserCallUuid = ""
}

function setAsrMyUuid(uuid){
    if(uuid) {
        asrMyUuid = uuid;
    }
}
function setAsrCustomUuid(uuid){
    if(uuid) {
        asrCustomUuid = uuid;
    }
}

function handleSeatABoxSearch() {
    let seatABoxSearchWrap = document.getElementById('seatABoxSearchWrap');
    let seatABoxNeckList = document.querySelectorAll('.seatABoxNeck');
    let seatABoxContent = document.getElementById('seatABoxContent');
    let height = 56 + 10;
    let seatABoxContentHeight = 0;
    seatABoxNeckList.forEach(function(element) {
        if(element && element.style.display != 'none') {
            seatABoxContentHeight = seatABoxContentHeight + element.offsetHeight;
        }
    });
    if(seatABoxSearchWrap) {
        height = height + seatABoxContentHeight;
        if(seatABoxSearchWrap) {
            seatABoxSearchWrap.style.top = height + 'px';
        }
        if(seatABoxContent){
            seatABoxContent.style.height = `calc(100% - 56px - 22px - ${seatABoxContentHeight - 66}px)`;
        }
    }
}

function hideKnowledgeRecommentWrap() {
    let knowledgeRecommentWrap = document.getElementById('knowledgeRecommentWrap');
    if(knowledgeRecommentWrap && knowledgeRecommentWrap.style.display && knowledgeRecommentWrap.style.display != 'none') {
        if(knowledgeRecommentWrap) {
            knowledgeRecommentWrap.style.display = 'none';
        }
        let knowledgeWidth = getKnowledgeWidth();
        let seatAssistantBoxPannelWidth = getSeatAssistantBoxPannelWidth();
        let aiDetectionTimeWrapWidth = getAiDetectionTimeWrapWidth();
        let seatAssistantBoxPannelRightWidth = getSeatAssistantBoxPannelRightWidth();
        let seatAssistantBoxPannel = document.getElementById('seatAssistantBoxPannel');

        let aiDetectionTimeWrap = document.getElementById('aiDetectionTimeWrap');
        if(aiDetectionTimeWrap && (!aiDetectionTimeWrap.style.display || aiDetectionTimeWrap.style.display == 'none')) {
            // seatAssistantBoxPannelWidth = seatAssistantBoxPannelWidth - aiDetectionTimeWrapWidth;
            seatAssistantBoxPannelRightWidth = seatAssistantBoxPannelRightWidth - aiDetectionTimeWrapWidth;
            if(!getAiDetectionTimePermission() && !assistantEnablePermission['15']) {
                hideSeatABoxPullIconWrap()
            }
        }
        // if(seatAssistantBoxPannel) {
        //     let width = seatAssistantBoxPannelWidth - knowledgeWidth;
        //     seatAssistantBoxPannel.style.width = `${width}px`;
        // }
        let seatAssistantBoxPannelRight = document.getElementById('seatAssistantBoxPannelRight');
        if(seatAssistantBoxPannelRight) {
            seatAssistantBoxPannelRightWidth = seatAssistantBoxPannelRightWidth - knowledgeWidth;
            seatAssistantBoxPannelRight.style.width = `${seatAssistantBoxPannelRightWidth}px`;
        }
        if(seatAssistantBoxPannel) {
            if(seatAssistantBoxPannelRightWidth > 0) {
                let width = seatAssistantBoxPannelWidth + seatAssistantBoxPannelRightWidth;
                seatAssistantBoxPannel.style.width = `${width}px`;
            }else{
                seatAssistantBoxPannel.style.width = `${seatAssistantBoxPannelWidth}px`;
            }
        }
    }
}

function showKnowledgeRecommentWrap() {
    if(assistantEnablePermission['15']) {
        let knowledgeRecommentWrap = document.getElementById('knowledgeRecommentWrap');
        if(knowledgeRecommentWrap && knowledgeRecommentWrap.style.display != 'block') {
            if(knowledgeRecommentWrap) {
                knowledgeRecommentWrap.style.display = 'block';
            }
            let aiDetectionTimeWrapWidth = getAiDetectionTimeWrapWidth();
            let seatAssistantBoxPannelWidth = getSeatAssistantBoxPannelWidth();
            let seatAssistantBoxPannelRightWidth = getSeatAssistantBoxPannelRightWidth();
            let seatAssistantBoxPannel = document.getElementById('seatAssistantBoxPannel');

            let aiDetectionTimeWrap = document.getElementById('aiDetectionTimeWrap');
            let marginLeft = 0;
            if(aiDetectionTimeWrap && (!aiDetectionTimeWrap.style.display || aiDetectionTimeWrap.style.display == 'none')) {
                // seatAssistantBoxPannelWidth = seatAssistantBoxPannelWidth - aiDetectionTimeWrapWidth - 10;
                seatAssistantBoxPannelRightWidth = seatAssistantBoxPannelRightWidth - aiDetectionTimeWrapWidth - 10;
                showSeatABoxPullIconWrap()
                marginLeft = 0;
                setKnowledgeRecommentWrapLeft(marginLeft);
            }else{
                marginLeft = 10;
                setKnowledgeRecommentWrapLeft(marginLeft);
            }

        
            let seatAssistantBoxPannelRight = document.getElementById('seatAssistantBoxPannelRight');
            if(seatAssistantBoxPannelRight) {
                seatAssistantBoxPannelRight.style.width = `${seatAssistantBoxPannelRightWidth}px`;
                seatAssistantBoxPannelRight.style.display = 'flex';
            }
            if(seatAssistantBoxPannel) {
                seatAssistantBoxPannel.style.width = `${seatAssistantBoxPannelWidth + seatAssistantBoxPannelRightWidth}px`;
            }
        }
    }else{
        hideKnowledgeRecommentWrap();
    }
}

function hideAiDetectionTimeWrap() {
    let aiDetectionTimeWrap = document.getElementById('aiDetectionTimeWrap');
    if(aiDetectionTimeWrap && aiDetectionTimeWrap.style.display && aiDetectionTimeWrap.style.display != 'none') {
        if(aiDetectionTimeWrap) {
            aiDetectionTimeWrap.style.display = 'none';
        }
        let knowledgeWidth = getKnowledgeWidth();
        let seatAssistantBoxPannelWidth = getSeatAssistantBoxPannelWidth();
        let aiDetectionTimeWrapWidth = getAiDetectionTimeWrapWidth();
        let seatAssistantBoxPannelRightWidth = getSeatAssistantBoxPannelRightWidth();
        let seatAssistantBoxPannel = document.getElementById('seatAssistantBoxPannel');

        let knowledgeRecommentWrap = document.getElementById('knowledgeRecommentWrap');
        if(knowledgeRecommentWrap && (!knowledgeRecommentWrap.style.display || knowledgeRecommentWrap.style.display == 'none')) {
            // seatAssistantBoxPannelWidth = seatAssistantBoxPannelWidth - knowledgeWidth;
            seatAssistantBoxPannelRightWidth = seatAssistantBoxPannelRightWidth - knowledgeWidth;
            if(!getAiDetectionTimePermission() && !assistantEnablePermission['15']) {
                hideSeatABoxPullIconWrap()
            }
        }
        let seatAssistantBoxPannelRight = document.getElementById('seatAssistantBoxPannelRight');
        if(seatAssistantBoxPannelRight) {
            seatAssistantBoxPannelRightWidth = seatAssistantBoxPannelRightWidth - aiDetectionTimeWrapWidth;
            seatAssistantBoxPannelRight.style.width = `${seatAssistantBoxPannelRightWidth}px`;
        }
        if(seatAssistantBoxPannel) {
            if(seatAssistantBoxPannelRightWidth > 0) {
                let width = seatAssistantBoxPannelWidth + seatAssistantBoxPannelRightWidth;
                seatAssistantBoxPannel.style.width = `${width}px`;
            }else{
                seatAssistantBoxPannel.style.width = `${seatAssistantBoxPannelWidth}px`;
            }
        }
    }
}

function showAiDetectionTimeWrap() {
    
    if(getAiDetectionTimePermission()) {
        if(assistantEnablePermission['5']) {
            $('#extractionTab').show();
            // $('#aiRecognitionTabOneWrap').show();
        }else{
            $('#extractionTab').hide();
            // $('#aiRecognitionTabOneWrap').hide();
        }
        if(assistantEnablePermission['4']) {
            $('#qualityCheckTab').show();
            $('#aiDetectionWrap').show();
            // $('#aiRecognitionTabTwoWrap').show();
        }else{
            $('#qualityCheckTab').hide();
            $('#aiDetectionWrap').hide();
            // $('#aiRecognitionTabTwoWrap').hide();
        }
        if(assistantEnablePermission['6']) {
            $('#dialogueSummaryTab').show();
            // $('#aiRecognitionTabThreeWrap').hide();
        }else{
            $('#dialogueSummaryTab').hide();
            // $('#aiRecognitionTabThreeWrap').hide();
        }

        let aiDetectionTimeWrap = document.getElementById('aiDetectionTimeWrap');
        if(aiDetectionTimeWrap && aiDetectionTimeWrap.style.display != 'flex') {
            if(aiDetectionTimeWrap) {
                aiDetectionTimeWrap.style.display = 'flex';
            }

            let knowledgeWidth = getKnowledgeWidth();
            let aiDetectionTimeWrapWidth = getAiDetectionTimeWrapWidth();
            let seatAssistantBoxPannelWidth = getSeatAssistantBoxPannelWidth();
            let seatAssistantBoxPannelRightWidth = getSeatAssistantBoxPannelRightWidth();
            let seatAssistantBoxPannel = document.getElementById('seatAssistantBoxPannel');

            let knowledgeRecommentWrap = document.getElementById('knowledgeRecommentWrap');
            let marginLeft = 0;
            if(knowledgeRecommentWrap && (!knowledgeRecommentWrap.style.display || knowledgeRecommentWrap.style.display == 'none')) {
                // seatAssistantBoxPannelWidth = seatAssistantBoxPannelWidth - knowledgeWidth;
                seatAssistantBoxPannelRightWidth = seatAssistantBoxPannelRightWidth - knowledgeWidth;
                showSeatABoxPullIconWrap()
            }else{
                marginLeft = 10;
                setKnowledgeRecommentWrapLeft(marginLeft);
            }

            let seatAssistantBoxPannelRight = document.getElementById('seatAssistantBoxPannelRight');
            if(seatAssistantBoxPannelRight) {
                seatAssistantBoxPannelRight.style.width = `${seatAssistantBoxPannelRightWidth}px`;
                seatAssistantBoxPannelRight.style.display = 'flex';
            }
            if(seatAssistantBoxPannel) {
                seatAssistantBoxPannel.style.width = `${seatAssistantBoxPannelWidth + seatAssistantBoxPannelRightWidth}px`;
            }
        }

    }else{
        hideAiDetectionTimeWrap()
    }
}

function getAiDetectionTimePermission() {
    return assistantEnablePermission['4'] || assistantEnablePermission['5'] || assistantEnablePermission['6']
}

function setKnowledgeRecommentWrapLeft(value = '') {
    let knowledgeRecommentWrap = document.getElementById('knowledgeRecommentWrap');
    if(knowledgeRecommentWrap) {
        knowledgeRecommentWrap.style.marginLeft = `${value}px`;
    }
}

function hideSeatABoxPullIconWrap() {
    let seatABoxPullIconWrap = document.getElementById('seatABoxPullIconWrap');
    if(seatABoxPullIconWrap) {
        seatABoxPullIconWrap.style.display = 'none';
    }
}
function showSeatABoxPullIconWrap() {
    let seatABoxPullIconWrap = document.getElementById('seatABoxPullIconWrap');
    if(seatABoxPullIconWrap) {
        seatABoxPullIconWrap.style.display = 'flex';
    }
}

function getAiDetectionTimeWrapWidth() {
    return 238;
}

function getKnowledgeWidth() {
    return 316;
}

function getSeatAssistantBoxPannelRightWidth() {
    return 554;
}

function getSeatAssistantBoxPannelWidth() {
    let minWidthValue = parseFloat($("#seatAssistantBoxPannel").css("min-width"));
    if($('#seatABoxContent').outerWidth() < minWidthValue) {
        return minWidthValue + $('#seatABoxPullIconWrap').width();
    }else{
        return $('#seatABoxContent').outerWidth() + $('#seatABoxPullIconWrap').width();
    }
}

function resetQualityCheck() {
    let qualityScoreId = document.getElementById('qualityScoreId');
    if(qualityScoreId) {
        qualityScoreId.innerHTML = '100';
    }

    let aiNegativeEmotionsCount = document.getElementById('aiNegativeEmotionsCount');
    let aiMuteCount = document.getElementById('aiMuteCount');
    let speedIsFastTxt = document.getElementById('speedIsFastTxt');
    let aiRobWordCount = document.getElementById('aiRobWordCount');
    let aiIllegalWordsCount = document.getElementById('aiIllegalWordsCount');
    if(aiNegativeEmotionsCount) {
        aiNegativeEmotionsCount.innerHTML = 0;
    }
    if(aiMuteCount) {
        aiMuteCount.innerHTML = 0;
    }
    if(aiNegativeEmotionsCount) {
        speedIsFastTxt.innerHTML = i18ntc('正常');
        speedIsFastTxt.setAttribute('data-oritxt', '正常');
    }
    if(aiRobWordCount) {
        aiRobWordCount.innerHTML = 0;
    }
    if(aiIllegalWordsCount) {
        aiIllegalWordsCount.innerHTML = 0;
    }

    let aiRecognitionTabThreeWrap = document.getElementById('aiRecognitionTabThreeWrap');
    aiRecognitionTabThreeWrap.innerHTML = '';
    
}

function getQualityCheck(data = {}) {
    // data = {
    //             "quality_score":"96",
    //             "rule_message":{
    //                 "负面情绪": ["0","1","2"],
    //                 "静音": ["3"],
    //                 "抢话": ["3"],
    //                 "违规词": [],
    //                 "语速过慢":[],
    //                 "语速正常":[],
    //                 "语速过快":[]
    //             },
    //             "message_rule":{
    //                 "0":["负面情绪","静音"],
    //                 "1":["抢话"],
    //                 "2":["违规词"],
    //                 "3":["语速过快"]
    //             }
    //         }
    let quality_score = data.quality_score;
    let qualityScoreId = document.getElementById('qualityScoreId');
    if(qualityScoreId) {
        qualityScoreId.innerHTML = quality_score;
    }

    let rule_message = data.rule_message;
    let aiNegativeEmotionsCount = document.getElementById('aiNegativeEmotionsCount');
    let aiMuteCount = document.getElementById('aiMuteCount');
    let speedIsFastTxt = document.getElementById('speedIsFastTxt');
    let aiRobWordCount = document.getElementById('aiRobWordCount');
    let aiIllegalWordsCount = document.getElementById('aiIllegalWordsCount');
    if(aiNegativeEmotionsCount) {
        aiNegativeEmotionsCount.innerHTML = rule_message["负面情绪"].length;
    }
    if(aiMuteCount) {
        aiMuteCount.innerHTML = rule_message["静音"].length;
    }
    if(speedIsFastTxt) {
        let message_rule = data.message_rule;
        let arrAll = Object.keys(message_rule);
        let key = arrAll[arrAll.length - 1];
        let valueArr = message_rule[key];
        if(valueArr.includes('语速过慢')) {
            speedIsFastTxt.innerHTML = i18ntc('过慢');
            speedIsFastTxt.setAttribute('data-oritxt', '过慢');
            $(`#${key} #aiTipTxtContent`).data('语速过慢');
            $(`#${key} #aiTipTxtContent`).text(i18ntc('语速过慢'));
            $(`#${key} .aiTipWrap`).css('display', 'flex');
            $(`#${key} .aiTipWrap`).siblings('.seatABoxRightContentBody').children('.seatABoxContentRightTxtWrap').addClass('active');
        }else if(valueArr.includes('语速过快')) {
            speedIsFastTxt.innerHTML = i18ntc('过快');
            speedIsFastTxt.setAttribute('data-oritxt', '过快');
            $(`#${key} #aiTipTxtContent`).data('语速过快');
            $(`#${key} #aiTipTxtContent`).text(i18ntc('语速过快'));
            $(`#${key} .aiTipWrap`).css('display', 'flex');
            $(`#${key} .aiTipWrap`).siblings('.seatABoxRightContentBody').children('.seatABoxContentRightTxtWrap').addClass('active');
        }else{
            speedIsFastTxt.innerHTML = i18ntc('正常');
            speedIsFastTxt.setAttribute('data-oritxt', '正常');
        }
    }
    if(aiRobWordCount) {
        aiRobWordCount.innerHTML = rule_message["抢话"].length;
    }
    if(aiIllegalWordsCount) {
        aiIllegalWordsCount.innerHTML = rule_message["违规词"].length;
    }
}

function setSeatABoxQualityCheckHistory() {
    let seatABoxQualityCheckHistoryStorageKey = `${company_code}_${agent_id}_seatABoxQualityCheckHistory`;
    try{
        localStorage.setItem(seatABoxQualityCheckHistoryStorageKey, JSON.stringify(seatABoxQualityCheckHistory));
    }catch(res) {
        localStorage.removeItem(seatABoxQualityCheckHistoryStorageKey);
    }
}

function getFromByAgentId(){
    let params = {
        agentId: `${company_code}_${agent_id}`,
    };
    ajax({
        type: 'GET',
        url: dominUrl + 'cloudcc-client-server/openapi/getTemplateByAgentId',
        data: params,
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
        success: function (res) {
            let data = JSON.parse(res);
            if(data.success || data.code == 200) {
                let arr = data.result;
                let contentHtml = '';
                let isSelected = false;
                arr.map((item, index) => {
                    // class="marginLeft"
                    let className = index > 0 ? 'marginLeft' : '';
                    let checked = setParam.companyCustomFromId && item.id == setParam.companyCustomFromId ? 'true' : '';
                    let inputHtml = `<input type="radio" class="choseRadio" onclick="changeSetRadio(this)" name="companyCustomFromId" value="${item.id}">`;
                    if(checked) {
                        isSelected = true;
                        inputHtml = `<input type="radio" class="choseRadio" onclick="changeSetRadio(this)" checked name="companyCustomFromId" value="${item.id}">`;
                    }
                    let strHtml = `<div class="${className}">
                            ${inputHtml}
                            <span class="radioTextClass i18nFromOritxt" data-oritxt="${item.name}">${i18ntc(item.name)}</span>
                        </div>`
                    contentHtml = contentHtml + strHtml;
                });
                //no select
                let inputHtml = `<input type="radio" class="choseRadio" onclick="changeSetRadio(this)" name="companyCustomFromId" value="">`;
                if(!isSelected) {
                    inputHtml = `<input type="radio" class="choseRadio" onclick="changeSetRadio(this)" checked name="companyCustomFromId" value="">`;
                }
                let className = arr.length > 0 ? 'marginLeft' : '';
                let strHtml = `<div class="${className}">
                        ${inputHtml}
                        <span class="radioTextClass i18nFromOritxt" data-oritxt="不选择">${i18ntc('不选择')}</span>
                    </div>`
                contentHtml = contentHtml + strHtml;
                let str = `
                    <span class="smallTitle">
                        <span class="i18nFromOritxt" data-oritxt="弹屏工单">${i18ntc('弹屏工单')}</span>
                        <span class="smallTitleTips i18nFromOritxt" data-oritxt="注：切换类型后，立即生效">${i18ntc('注：切换类型后，立即生效')}</span>
                    </span>
                    <div class="radioItems">
                        ${contentHtml}
                    </div>
                `;
                $('#workOrderTemplateWrap').empty();
                $('#workOrderTemplateWrap').append(str);
            }
        }, error: function(err){}
    })
}

function createdChangeWorkOrder(){
    let div = document.createElement('div')
    div.id = 'changeWorkOrderBox'
    let str = ''
    str += `
            <div class="tipsBoxClass">
                <span class="hangupTitle i18n">${i18ntc('提示')}</span>
                <span class="hangupText i18n">${i18ntc('该操作会删除已填写工单的内容，是否确认操作')}</span>
                <div class='hangupBtns'>
                    <span id="changeWorkOrderSure" data-name="" data-value="" class="hangupSure i18n">${i18ntc('确定')}</span>
                    <span id="changeWorkOrderCancel" class="hangupCancel i18n">${i18ntc('取消')}</span>
                </div>
            </div>
            `
    document.body.appendChild(div);
    document.getElementById('changeWorkOrderBox').innerHTML = str
}

function changeSetRadio(val){
    let popupScreenList = []
    if(window.getTabsMenu && window.getTabsMenu().length > 0) {
        popupScreenList = window.getTabsMenu().filter(item => item.keyPath && item.keyPath.includes('/popupScreen/index/'));
    }
    if(popupScreenList.length > 0) {
        if(document.getElementById('changeWorkOrderBox')) {
            document.getElementById('changeWorkOrderBox').style.display = 'flex';
        }
        let changeWorkOrderSure = document.getElementById('changeWorkOrderSure');
        changeWorkOrderSure.setAttribute('data-name', val.getAttribute('name'));
        changeWorkOrderSure.setAttribute('data-value', val.getAttribute('value'));
    }else{
        setParam[val.getAttribute('name')] = val.getAttribute('value');
    }
}
function getDialogueSummary(call_uuid = '') {
    if(!assistantEnablePermission['6']) return;
    let data = seatABoxUserHistory[call_uuid] || [];
    let str = '';
    data.map(item => {
        if(item.type == 'agent') {
            if(str) {
                str = `${str}customer service:${item.src_text};`;
            }else{
                str = `customer service:${item.src_text};`;
            }
        }else if(item.type == 'client'){
            if(str) {
                str = `${str}customer:${item.src_text};`;
            }else{
                str = `customer:${item.src_text};`;
            }
        }
    });
    let formData = new FormData();
    let blob = new Blob([str], { type: 'text/plain' });
    formData.append('file', blob, 'text.txt');
    ajax({
        type: 'FormData',
        url: dominUrl + 'cloudcc-client-server/openapi/summarizeConversation',
        data: formData,
        // contentType: 'application/x-www-form-urlencoded',
        // contentType: "multipart/form-data",
        // contentType: "application/octet-stream",
        success: function (res) {
            let data = JSON.parse(res);
            if(data.success || data.code == 200) {
                let content = data.result;
                if(!seatABoxQualityCheckHistory[call_uuid]) {
                    seatABoxQualityCheckHistory[call_uuid] = {};
                    seatABoxQualityCheckHistory[call_uuid].dialogueSummary = '';
                }
                seatABoxQualityCheckHistory[call_uuid].dialogueSummary = content;
                setSeatABoxQualityCheckHistory();
                setDialogueSummary(content);
            }
        }, error: function(err){}
    });
}

function resetAndAppendDialogueSummary(content) {
    setAiRecognitionTabThreeWrapEmpty();
    if(content) {
        $('#aiRecognitionTabThreeWrap').empty();
        setDialogueSummary(content)
    }
}

function setDialogueSummary(content) {
    let dialogItem = `<div class="aiRecognitionTabThreeContent" >
        <div class="aiRecognitionTabThreeContentDot" ></div>
        <div class="aiRecognitionTabThreeContentTxt" >
            ${content}
        </div>
    </div>`;
    $('#aiRecognitionTabThreeWrap').empty();
    $('#aiRecognitionTabThreeWrap').append(dialogItem);
}

// 实时提取
function getTextExtraction(content = ''){
    if(!assistantEnablePermission['5']) return;
    if(setParam.companyCustomFromId && content) {
        let params = {
            companyCustomId: setParam.companyCustomFromId,
            content: content,
        };
        ajax({
            type: 'POST',
            url: dominUrl + 'cloudcc-ms-ai/ai/api/textExtraction',
            data: params,
            success: function (res) {
                let data = JSON.parse(res);
                if(data.success || data.code == 200) {
                    let arr = data.result || [];
                    if(arr.length > 0 && defaultUserCallUuid) {
                        if(!seatABoxQualityCheckHistory[defaultUserCallUuid]) {
                            seatABoxQualityCheckHistory[defaultUserCallUuid] = {};
                            seatABoxQualityCheckHistory[defaultUserCallUuid].extractionList = [];
                        }else if(!seatABoxQualityCheckHistory[defaultUserCallUuid].extractionList){
                            seatABoxQualityCheckHistory[defaultUserCallUuid].extractionList = [];
                        }
                        let originList = seatABoxQualityCheckHistory[defaultUserCallUuid].extractionList || [];
                        console.log("originList:", originList)
                        seatABoxQualityCheckHistory[defaultUserCallUuid].extractionList = [
                            ...originList,
                            ...arr,
                        ];
                        setSeatABoxQualityCheckHistory();
                        if($('#aiRecognitionTabOneWrap .seatAiEmptyImgWrap').length > 0) {
                            $('#aiRecognitionTabOneWrap').empty();
                        }
                        appendTextExtraction(arr);
                    }
                }
            }, error: function(err){}
        })
    }
}
function resetAndAppendTextExtraction(arr) {
    setAiRecognitionTabOneWrapEmpty();
    if(arr && arr.length > 0) {
        $('#aiRecognitionTabOneWrap').empty();
        appendTextExtraction(arr)       
    }
}
function setSeatAssistantBoxPannelRightEmptyFun() {
    setAiRecognitionTabOneWrapEmpty();
    resetQualityCheck();
    setAiRecognitionTabThreeWrapEmpty();
    setKnowledgeRecommentContentWrapEmpty();
}
function getSeatAiEmptyImgDom() {
    let strHtml = `
        <div class="seatAiEmptyImgWrap" >
            <img class="seatAiEmptyImg" src="${resourceUrl}/images/seatAiImages/empty.png" alt="">
        </div>
    `;
    return strHtml;
}
function setAiRecognitionTabOneWrapEmpty() {
    $('#aiRecognitionTabOneWrap').empty();
    let strHtml = getSeatAiEmptyImgDom();
    $('#aiRecognitionTabOneWrap').append(strHtml);
}
function setAiRecognitionTabThreeWrapEmpty() {
    $('#aiRecognitionTabThreeWrap').empty();
    let strHtml = getSeatAiEmptyImgDom();
    $('#aiRecognitionTabThreeWrap').append(strHtml);
}
function setKnowledgeRecommentContentWrapEmpty() {
    $('#knowledgeRecommentContentWrap').empty();
    let strHtml = getSeatAiEmptyImgDom();
    $('#knowledgeRecommentContentWrap').append(strHtml);
}
function appendTextExtraction(arr) {
    arr.map(item => {
        let resultList = item.resultList;
        resultList.map(listItem => {
            let strHtml = `
                <div class="aiRecognitionTabOneItem" >
                    <div class="aiRecognitionTabOneTitle i18nFromOritxt" data-oritxt="${item.label}">${i18ntc(item.label)}</div>
                    <div class="aiRecognitionTabOneContent i18nFromOritxt">${listItem}</div>
                    <div class="aiRecognitionTabOneBtn i18nFromOritxt" onclick="handleFillInForm(this)" data-modelid="${item.model}" data-resultString="${listItem}" data-oritxt="填入表单" >${i18ntc('填入表单')}</div>
                </div>
            `;
            $('#aiRecognitionTabOneWrap').prepend(strHtml);
        });
    });
}

function handleFillInForm(that) {
    if(window.isFormClick) {
        return;
    }
    window.isFormClick = true;
    setTimeout(() => {
        window.isFormClick = false;
    }, 1000);
    let modelId = that.getAttribute('data-modelid');
    let resultString = that.getAttribute('data-resultString');
    if(!setParam.companyCustomFromId) {
        toastMessage('请先选择弹屏工单类型');
    }else{
        if(resultString && activeUserCallUuid) {
            let asrMyUuid = seatABoxQualityCheckHistory[activeUserCallUuid] ? seatABoxQualityCheckHistory[activeUserCallUuid].asrMyUuid : '';
            let asrCustomUuid = seatABoxQualityCheckHistory[activeUserCallUuid] ? seatABoxQualityCheckHistory[activeUserCallUuid].asrCustomUuid : '';
            if(asrMyUuid && asrCustomUuid) {
                let params = {
                    type: 'FillInForm',
                    text: resultString,
                    modelId: modelId,
                    asrMyUuid: asrMyUuid,
                    asrCustomUuid: asrCustomUuid,
                    companyCustomFromId: setParam.companyCustomFromId,
                };
                handlePostFillInForm(params);
                sendFillInFormTimer = setTimeout(() => {
                    toastMessage('填入失败，表单不存在');
                }, 1500)
            }
        }
    }
}

function handleInitPopWork() {
    // if(activeUserCallUuid) {
    //     let asrMyUuid = seatABoxQualityCheckHistory[activeUserCallUuid] ? seatABoxQualityCheckHistory[activeUserCallUuid].asrMyUuid : '';
    //     let asrCustomUuid = seatABoxQualityCheckHistory[activeUserCallUuid] ? seatABoxQualityCheckHistory[activeUserCallUuid].asrCustomUuid : '';
    //     if(asrMyUuid && asrCustomUuid) {
    //         let params = {
    //             type: 'FillInForm',
    //             text: '',
    //             modelId: '',
    //             asrMyUuid: asrMyUuid,
    //             asrCustomUuid: asrCustomUuid,
    //             companyCustomFromId: setParam.companyCustomFromId,
    //         };
    //         handlePostFillInForm(params)
    //     }
    // }
    let params = {
        type: 'FillInForm',
        text: '',
        modelId: '',
        asrMyUuid: '',
        asrCustomUuid: '',
        companyCustomFromId: setParam.companyCustomFromId,
    };
    handlePostFillInForm(params)
}

function handlePostFillInForm(params = {}) {
    window.postMessage(
        JSON.stringify(params), window.location.origin,
    );
}

function ak(data) {
    if(data.answer && (Array.isArray(data.answer) && data.answer.length > 0) && defaultUserCallUuid) {
        if(!seatABoxQualityCheckHistory[defaultUserCallUuid]) {
            seatABoxQualityCheckHistory[defaultUserCallUuid] = {};
            seatABoxQualityCheckHistory[defaultUserCallUuid].knowhistoryList = [];
        }else if(!seatABoxQualityCheckHistory[defaultUserCallUuid].knowhistoryList){
            seatABoxQualityCheckHistory[defaultUserCallUuid].knowhistoryList = [];
        }
        data.knowledge_id = generateUUID();
        seatABoxQualityCheckHistory[defaultUserCallUuid].knowhistoryList.push(data);
        setSeatABoxQualityCheckHistory();
        if($('#knowledgeRecommentContentWrap .seatAiEmptyImgWrap').length > 0) {
            $('#knowledgeRecommentContentWrap').empty();
        }
        let arr = [data];
        appendKnowhistorySearch(arr)
    }
}

function getKnowhistorySearch(content = ''){
    if(content && assistantEnablePermission['15']) {
        let params = {
            companyCode: company_code,
            problem: content,
        };
        ajax({
            type: 'POST',
            url: dominUrl + `cloudcc-client-server/openapi/knowhistorySearch?companyCode=${company_code}&problem=${content}`,
            data: params,
            success: function (res) {
                let result = JSON.parse(res);
                if(result.success || result.code == 0) {
                    let data = result.data || {};
                    if(data.answer && (Array.isArray(data.answer) && data.answer.length > 0) && defaultUserCallUuid) {
                        if(!seatABoxQualityCheckHistory[defaultUserCallUuid]) {
                            seatABoxQualityCheckHistory[defaultUserCallUuid] = {};
                            seatABoxQualityCheckHistory[defaultUserCallUuid].knowhistoryList = [];
                        }else if(!seatABoxQualityCheckHistory[defaultUserCallUuid].knowhistoryList){
                            seatABoxQualityCheckHistory[defaultUserCallUuid].knowhistoryList = [];
                        }
                        data.knowledge_id = generateUUID();
                        seatABoxQualityCheckHistory[defaultUserCallUuid].knowhistoryList.push(data);
                        setSeatABoxQualityCheckHistory();
                        if($('#knowledgeRecommentContentWrap .seatAiEmptyImgWrap').length > 0) {
                            $('#knowledgeRecommentContentWrap').empty();
                        }
                        let arr = [data];
                        appendKnowhistorySearch(arr)
                    }
                }
            }, error: function(err){}
        });
    }
}

function resetAndAppendKnowhistorySearch(arr) {
    setKnowledgeRecommentContentWrapEmpty();
    if(arr && arr.length > 0) {
        $('#knowledgeRecommentContentWrap').empty();
        appendKnowhistorySearch(arr)   
    }
}
function appendKnowhistorySearch(arr) {
    arr.map(item => {
        let contentArr = [];
        let maxCount = 300;
        if(item.answer) {
            item.answer.forEach(answerItem => {
                let content = '';
                if(answerItem.length < maxCount) {
                    content = `<div >${answerItem}</div>`;
                }else{
                    content = `<div>${answerItem.substring(0,maxCount)}......</div>`
                }
                contentArr.push(content)
            })
        }
        let knowledge_id = item.knowledge_id
        let answerListDom = '';
        contentArr.forEach((contentItem, index) => {
            answerListDom += `<div class="knowledgeRecommentItemAnswerWrap">
                ${contentItem}
                <div class="knowledgeRecommentItemAnswerBtnWrap i18nFromOritxt">
                    <span onclick="handleKnowledgeDetailPop('${knowledge_id}',${index})" class="knowledgeRecommentItemAnswerBtn i18nFromOritxt" data-oritxt="详情">${i18ntc("详情")}</span>
                </div>
            </div>
            `;
        });
        let questionContent = ''
        if(item.problem) {
            questionContent = `
                <div class="knowledgeRecommentItemQuestionWrap">
                    <img class="knowledgeRecommentItemQuestionImg" src="${resourceUrl}/images/seatAiImages/questionImg.png" />
                    <div class="knowledgeRecommentItemQuestionContent">${item.problem}</div>
                </div>
            `
        }
        let strHtml = `<div>
            <div class="knowledgeRecommentItem">
                ${questionContent}
                ${answerListDom}
            </div>
        `;
        if(contentArr.length > 0) {
            $('#knowledgeRecommentContentWrap').prepend(strHtml);
        }
    });
}

function getSeatAssistantConfig() {
    // targetKeys
    setTimeout(() => {
        getDefaultTextTranslationTargetLanguage();
        getDefaultAudioTranslationTargetLanguage();
        getAssistantEnable();
    }, 200);
}

function getDefaultTextTranslationTargetLanguage() {
    ajax({
        type: 'POST',
        url: dominUrl + `cloudcc-client-server/openapi/defaultTextTranslationTargetLanguage?companyCode=${company_code}`,
        // url: dominUrl + 'system/dicSet/getDicItemByCode.api?code=defaultTextTranslationTargetLanguage',
        data: {},
        success: function (res) {
            let result = JSON.parse(res);
            if(result.success || result.code == 0) {
                let dictList = result.data;
                textTargetKeys = {};
                dictList.map(item => {
                    if(!textTargetKeys[item.dicItemCode]) {
                        textTargetKeys[item.dicItemCode] = {};
                    }
                    textTargetKeys[item.dicItemCode] = item.dicItemName;

                    let str = `<div class="targetLanguageSelectItem i18nFromOritxt" data-oritxt="${item.dicItemName}" data-value="${item.dicItemCode}">${item.dicItemName}</div>`;
                    $('#targetCustomLanguageSelectWrap').append(str);
                    $('#targetLanguageSelectWrap').append(str);
                });
                getAssistantConfig();
            }
        }
    })
}

function getDefaultAudioTranslationTargetLanguage() {
    ajax({
        type: 'POST',
        url: dominUrl + `cloudcc-client-server/openapi/defaultAudioTranslationTargetLanguage?companyCode=${company_code}`,
        // url: dominUrl + 'system/dicSet/getDicItemByCode.api?code=defaultAudioTranslationTargetLanguage',
        data: {},
        success: function (res) {
            let result = JSON.parse(res);
            if(result.success || result.code == 0) {
                let dictList = result.data;
                audioTargetKeys = {};
                dictList.map(item => {
                    if(!audioTargetKeys[item.dicItemCode]) {
                        audioTargetKeys[item.dicItemCode] = {};
                    }
                    audioTargetKeys[item.dicItemCode] = item.dicItemName;

                    let str = `<div class="targetLanguageSelectItem i18nFromOritxt" data-oritxt="${item.dicItemName}" data-value="${item.dicItemCode}">${item.dicItemName}</div>`;
                    $('#sendCustomLanguageSelectWrap').append(str);
                    $('#sendLanguageSelectWrap').append(str);
                });
            }
            getAssistantConfig();
        }
    })
}

function getAssistantConfig() {
    ajax({
        type: 'POST',
        url: dominUrl + `cloudcc-client-server/openapi/assistantConfig?companyCode=${company_code}`,
        data: {},
        success: function (res) {
            let result = JSON.parse(res);
            if(result.success || result.code == 0) {
                let data = result.data;
                setDefaultAssistantLanguage(data);
            }
        }
    })
}

function setDefaultAssistantLanguage(data = {}) {
    let defaultTxt = '中文';
    let seatABoxCustomTargetLanguage = document.getElementById('seatABoxCustomTargetLanguage');
    if(seatABoxCustomTargetLanguage) {
        seatABoxCustomTargetLanguage.innerHTML = textTargetKeys[data.textTargetLanguage] || defaultTxt;
    }
    
    let seatABoxTargetLanguage = document.getElementById('seatABoxTargetLanguage');
    if(seatABoxTargetLanguage) {
        seatABoxTargetLanguage.innerHTML = textTargetKeys[data.textTargetLanguage] || defaultTxt;
    }

    let seatABoxCustomSendLanguage = document.getElementById('seatABoxCustomSendLanguage');
    if(seatABoxCustomSendLanguage) {
        seatABoxCustomSendLanguage.innerHTML = audioTargetKeys[data.audioTargetLanguage] || defaultTxt;
    }

    let seatABoxSendLanguage = document.getElementById('seatABoxSendLanguage');
    if(seatABoxSendLanguage) {
        seatABoxSendLanguage.innerHTML = audioTargetKeys[data.audioTargetLanguage] || defaultTxt;
    }
}

function getAssistantEnable() {
    ajax({
        type: 'POST',
        url: dominUrl + `cloudcc-client-server/openapi/assistantEnable?companyCode=${company_code}&agentId=${agent_id}`,
        data: {},
        success: function (res) {
            let result = JSON.parse(res);
            if(result.success || result.code == 0) {
                let data = result.data;
                assistantEnablePermission = data;
                let seatAssistantServersOpen = false;
                [1, 2, 3, 4, 5, 6, 15].map(item => {
                    if(data[item]){
                        seatAssistantServersOpen = true;
                    }
                });
                if(seatAssistantServersOpen && data.assistantEnable) {
                    $('#seatAssistant').show();
                }else{
                    $('#seatAssistant').hide();
                }

                showAiDetectionTimeWrap();

                showKnowledgeRecommentWrap();

                if(data['13'] && data['14']) {
                    videoCall = true;
                }else if(data['13'] && !data['14']) {
                    videoCall = false;
                    handleOpenVideoCall()
                }else if(!data['13'] && data['14']) {
                    videoCall = true;
                    const startCallElement = document.getElementById('startCall');
                    if(startCallElement.children[0]) {
                        startCallElement.children[0].style.visibility = 'hidden';
                        startCallElement.children[0].style.width = '0px'
                    }
                }

                let activeTab = '';
                [5, 4, 6].map(item => {
                    if(assistantEnablePermission[item]) {
                        if(!activeTab) {
                            activeTab = item;
                        }
                    }
                });
                setTimeout(() => {
                    if(getAiDetectionTimePermission()) {
                        if(activeTab) {
                            $('.aiRecognitionTabsWrap > div').removeClass('active');
                            if(activeTab == 5) {
                                $('#extractionTab').addClass('active');
                                $('#aiRecognitionTabOneWrap').show();
                                $('#aiRecognitionTabTwoWrap').hide();
                                $('#aiRecognitionTabThreeWrap').hide();
                            }else if(activeTab == 4) {
                                $('#qualityCheckTab').addClass('active');
                                $('#aiRecognitionTabOneWrap').hide();
                                $('#aiRecognitionTabTwoWrap').show();
                                $('#aiRecognitionTabThreeWrap').hide();
                            }else if(activeTab == 6) {
                                $('#dialogueSummaryTab').addClass('active');
                                $('#aiRecognitionTabOneWrap').hide();
                                $('#aiRecognitionTabTwoWrap').hide();
                                $('#aiRecognitionTabThreeWrap').show();
                            }
                        }
                    }
                }, 500);
            }
        }
    })
}

function handleKnowledgeDetailPop(id, index){
    let knowhistoryList = seatABoxQualityCheckHistory[activeUserCallUuid].knowhistoryList;
    let data = ''
    if(knowhistoryList && knowhistoryList.length) {
        knowhistoryList.forEach(item => {
            if(item.knowledge_id == id) {
                data = item;
            }
        })
    }
    if(data) {
        let title = data.problem;
        let content = data.answer[index];
        showKnowledgeDetailPop(content, title)
    }else{
        toastMessage('暂无详情')
    }
}

function showKnowledgeDetailPop(content, title) {
    $('#knowledgeModalContent').empty();
    let problemJtml = ''
    if(title) {
        problemJtml = `
            <div class="knowledgeModalContentItemQuestionWrap">
                <img class="knowledgeModalContentItemQuestionImg" src="${resourceUrl}/images/seatAiImages/questionImg.png" />
                <div class="knowledgeModalContentItemQuestionContent">${title}</div>
            </div>
        `
    }
    let strHtml =  `
    <div class="knowledgeModalContentItem">
        ${problemJtml}
        <div class="knowledgeModalContentItemAnswerWrap">${content}</div>
    </div>
    `

    $('#knowledgeModalContent').append(strHtml);
    
    $('#knowledgeModal').css({
        display: 'flex',
    });
}

function hideKnowledgeDetailPop(){
    $('#knowledgeModal').hide();
}