ysyt-agent-sdk 2.0.25 → 2.0.27
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -9,4 +9,4 @@
|
|
|
9
9
|
* @copyright Chen, Yi-Cyuan 2014-2023
|
|
10
10
|
* @license MIT
|
|
11
11
|
*/
|
|
12
|
-
Mt=Bt,function(){var s="input is invalid type",i="object"==typeof window,r=i?window:{};r.JS_MD5_NO_WINDOW&&(i=!1);var n=!i&&"object"==typeof self,o=!r.JS_MD5_NO_NODE_JS&&"object"==typeof process&&process.versions&&process.versions.node;o?r=jt:n&&(r=self);var a,c=!r.JS_MD5_NO_COMMON_JS&&Mt.exports,h=!r.JS_MD5_NO_ARRAY_BUFFER&&"undefined"!=typeof ArrayBuffer,d="0123456789abcdef".split(""),l=[128,32768,8388608,-2147483648],g=[0,8,16,24],u=["hex","array","digest","buffer","arrayBuffer","base64"],p="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),f=[];if(h){var m=new ArrayBuffer(68);a=new Uint8Array(m),f=new Uint32Array(m)}var _=Array.isArray;!r.JS_MD5_NO_NODE_JS&&_||(_=function(e){return"[object Array]"===Object.prototype.toString.call(e)});var E=ArrayBuffer.isView;!h||!r.JS_MD5_NO_ARRAY_BUFFER_IS_VIEW&&E||(E=function(e){return"object"==typeof e&&e.buffer&&e.buffer.constructor===ArrayBuffer});var T=function(e){var t=typeof e;if("string"===t)return[e,!0];if("object"!==t||null===e)throw new Error(s);if(h&&e.constructor===ArrayBuffer)return[new Uint8Array(e),!1];if(!_(e)&&!E(e))throw new Error(s);return[e,!1]},w=function(e){return function(t){return new I(!0).update(t)[e]()}},C=function(i){var n,o=e,a=t.Buffer;return n=a.from&&!r.JS_MD5_NO_BUFFER_FROM?a.from:function(e){return new a(e)},function(e){if("string"==typeof e)return o.createHash("md5").update(e,"utf8").digest("hex");if(null==e)throw new Error(s);return e.constructor===ArrayBuffer&&(e=new Uint8Array(e)),_(e)||E(e)||e.constructor===a?o.createHash("md5").update(n(e)).digest("hex"):i(e)}},S=function(e){return function(t,s){return new v(t,!0).update(s)[e]()}};function I(e){if(e)f[0]=f[16]=f[1]=f[2]=f[3]=f[4]=f[5]=f[6]=f[7]=f[8]=f[9]=f[10]=f[11]=f[12]=f[13]=f[14]=f[15]=0,this.blocks=f,this.buffer8=a;else if(h){var t=new ArrayBuffer(68);this.buffer8=new Uint8Array(t),this.blocks=new Uint32Array(t)}else this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];this.h0=this.h1=this.h2=this.h3=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0}function v(e,t){var s,i=T(e);if(e=i[0],i[1]){var r,n=[],o=e.length,a=0;for(s=0;s<o;++s)(r=e.charCodeAt(s))<128?n[a++]=r:r<2048?(n[a++]=192|r>>>6,n[a++]=128|63&r):r<55296||r>=57344?(n[a++]=224|r>>>12,n[a++]=128|r>>>6&63,n[a++]=128|63&r):(r=65536+((1023&r)<<10|1023&e.charCodeAt(++s)),n[a++]=240|r>>>18,n[a++]=128|r>>>12&63,n[a++]=128|r>>>6&63,n[a++]=128|63&r);e=n}e.length>64&&(e=new I(!0).update(e).array());var c=[],h=[];for(s=0;s<64;++s){var d=e[s]||0;c[s]=92^d,h[s]=54^d}I.call(this,t),this.update(h),this.oKeyPad=c,this.inner=!0,this.sharedMemory=t}I.prototype.update=function(e){if(this.finalized)throw new Error("finalize already called");var t=T(e);e=t[0];for(var s,i,r=t[1],n=0,o=e.length,a=this.blocks,c=this.buffer8;n<o;){if(this.hashed&&(this.hashed=!1,a[0]=a[16],a[16]=a[1]=a[2]=a[3]=a[4]=a[5]=a[6]=a[7]=a[8]=a[9]=a[10]=a[11]=a[12]=a[13]=a[14]=a[15]=0),r)if(h)for(i=this.start;n<o&&i<64;++n)(s=e.charCodeAt(n))<128?c[i++]=s:s<2048?(c[i++]=192|s>>>6,c[i++]=128|63&s):s<55296||s>=57344?(c[i++]=224|s>>>12,c[i++]=128|s>>>6&63,c[i++]=128|63&s):(s=65536+((1023&s)<<10|1023&e.charCodeAt(++n)),c[i++]=240|s>>>18,c[i++]=128|s>>>12&63,c[i++]=128|s>>>6&63,c[i++]=128|63&s);else for(i=this.start;n<o&&i<64;++n)(s=e.charCodeAt(n))<128?a[i>>>2]|=s<<g[3&i++]:s<2048?(a[i>>>2]|=(192|s>>>6)<<g[3&i++],a[i>>>2]|=(128|63&s)<<g[3&i++]):s<55296||s>=57344?(a[i>>>2]|=(224|s>>>12)<<g[3&i++],a[i>>>2]|=(128|s>>>6&63)<<g[3&i++],a[i>>>2]|=(128|63&s)<<g[3&i++]):(s=65536+((1023&s)<<10|1023&e.charCodeAt(++n)),a[i>>>2]|=(240|s>>>18)<<g[3&i++],a[i>>>2]|=(128|s>>>12&63)<<g[3&i++],a[i>>>2]|=(128|s>>>6&63)<<g[3&i++],a[i>>>2]|=(128|63&s)<<g[3&i++]);else if(h)for(i=this.start;n<o&&i<64;++n)c[i++]=e[n];else for(i=this.start;n<o&&i<64;++n)a[i>>>2]|=e[n]<<g[3&i++];this.lastByteIndex=i,this.bytes+=i-this.start,i>=64?(this.start=i-64,this.hash(),this.hashed=!0):this.start=i}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296|0,this.bytes=this.bytes%4294967296),this},I.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex;e[t>>>2]|=l[3&t],t>=56&&(this.hashed||this.hash(),e[0]=e[16],e[16]=e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=e[7]=e[8]=e[9]=e[10]=e[11]=e[12]=e[13]=e[14]=e[15]=0),e[14]=this.bytes<<3,e[15]=this.hBytes<<3|this.bytes>>>29,this.hash()}},I.prototype.hash=function(){var e,t,s,i,r,n,o=this.blocks;this.first?t=((t=((e=((e=o[0]-680876937)<<7|e>>>25)-271733879|0)^(s=((s=(-271733879^(i=((i=(-1732584194^2004318071&e)+o[1]-117830708)<<12|i>>>20)+e|0)&(-271733879^e))+o[2]-1126478375)<<17|s>>>15)+i|0)&(i^e))+o[3]-1316259209)<<22|t>>>10)+s|0:(e=this.h0,t=this.h1,s=this.h2,t=((t+=((e=((e+=((i=this.h3)^t&(s^i))+o[0]-680876936)<<7|e>>>25)+t|0)^(s=((s+=(t^(i=((i+=(s^e&(t^s))+o[1]-389564586)<<12|i>>>20)+e|0)&(e^t))+o[2]+606105819)<<17|s>>>15)+i|0)&(i^e))+o[3]-1044525330)<<22|t>>>10)+s|0),t=((t+=((e=((e+=(i^t&(s^i))+o[4]-176418897)<<7|e>>>25)+t|0)^(s=((s+=(t^(i=((i+=(s^e&(t^s))+o[5]+1200080426)<<12|i>>>20)+e|0)&(e^t))+o[6]-1473231341)<<17|s>>>15)+i|0)&(i^e))+o[7]-45705983)<<22|t>>>10)+s|0,t=((t+=((e=((e+=(i^t&(s^i))+o[8]+1770035416)<<7|e>>>25)+t|0)^(s=((s+=(t^(i=((i+=(s^e&(t^s))+o[9]-1958414417)<<12|i>>>20)+e|0)&(e^t))+o[10]-42063)<<17|s>>>15)+i|0)&(i^e))+o[11]-1990404162)<<22|t>>>10)+s|0,t=((t+=((e=((e+=(i^t&(s^i))+o[12]+1804603682)<<7|e>>>25)+t|0)^(s=((s+=(t^(i=((i+=(s^e&(t^s))+o[13]-40341101)<<12|i>>>20)+e|0)&(e^t))+o[14]-1502002290)<<17|s>>>15)+i|0)&(i^e))+o[15]+1236535329)<<22|t>>>10)+s|0,t=((t+=((i=((i+=(t^s&((e=((e+=(s^i&(t^s))+o[1]-165796510)<<5|e>>>27)+t|0)^t))+o[6]-1069501632)<<9|i>>>23)+e|0)^e&((s=((s+=(e^t&(i^e))+o[11]+643717713)<<14|s>>>18)+i|0)^i))+o[0]-373897302)<<20|t>>>12)+s|0,t=((t+=((i=((i+=(t^s&((e=((e+=(s^i&(t^s))+o[5]-701558691)<<5|e>>>27)+t|0)^t))+o[10]+38016083)<<9|i>>>23)+e|0)^e&((s=((s+=(e^t&(i^e))+o[15]-660478335)<<14|s>>>18)+i|0)^i))+o[4]-405537848)<<20|t>>>12)+s|0,t=((t+=((i=((i+=(t^s&((e=((e+=(s^i&(t^s))+o[9]+568446438)<<5|e>>>27)+t|0)^t))+o[14]-1019803690)<<9|i>>>23)+e|0)^e&((s=((s+=(e^t&(i^e))+o[3]-187363961)<<14|s>>>18)+i|0)^i))+o[8]+1163531501)<<20|t>>>12)+s|0,t=((t+=((i=((i+=(t^s&((e=((e+=(s^i&(t^s))+o[13]-1444681467)<<5|e>>>27)+t|0)^t))+o[2]-51403784)<<9|i>>>23)+e|0)^e&((s=((s+=(e^t&(i^e))+o[7]+1735328473)<<14|s>>>18)+i|0)^i))+o[12]-1926607734)<<20|t>>>12)+s|0,t=((t+=((n=(i=((i+=((r=t^s)^(e=((e+=(r^i)+o[5]-378558)<<4|e>>>28)+t|0))+o[8]-2022574463)<<11|i>>>21)+e|0)^e)^(s=((s+=(n^t)+o[11]+1839030562)<<16|s>>>16)+i|0))+o[14]-35309556)<<23|t>>>9)+s|0,t=((t+=((n=(i=((i+=((r=t^s)^(e=((e+=(r^i)+o[1]-1530992060)<<4|e>>>28)+t|0))+o[4]+1272893353)<<11|i>>>21)+e|0)^e)^(s=((s+=(n^t)+o[7]-155497632)<<16|s>>>16)+i|0))+o[10]-1094730640)<<23|t>>>9)+s|0,t=((t+=((n=(i=((i+=((r=t^s)^(e=((e+=(r^i)+o[13]+681279174)<<4|e>>>28)+t|0))+o[0]-358537222)<<11|i>>>21)+e|0)^e)^(s=((s+=(n^t)+o[3]-722521979)<<16|s>>>16)+i|0))+o[6]+76029189)<<23|t>>>9)+s|0,t=((t+=((n=(i=((i+=((r=t^s)^(e=((e+=(r^i)+o[9]-640364487)<<4|e>>>28)+t|0))+o[12]-421815835)<<11|i>>>21)+e|0)^e)^(s=((s+=(n^t)+o[15]+530742520)<<16|s>>>16)+i|0))+o[2]-995338651)<<23|t>>>9)+s|0,t=((t+=((i=((i+=(t^((e=((e+=(s^(t|~i))+o[0]-198630844)<<6|e>>>26)+t|0)|~s))+o[7]+1126891415)<<10|i>>>22)+e|0)^((s=((s+=(e^(i|~t))+o[14]-1416354905)<<15|s>>>17)+i|0)|~e))+o[5]-57434055)<<21|t>>>11)+s|0,t=((t+=((i=((i+=(t^((e=((e+=(s^(t|~i))+o[12]+1700485571)<<6|e>>>26)+t|0)|~s))+o[3]-1894986606)<<10|i>>>22)+e|0)^((s=((s+=(e^(i|~t))+o[10]-1051523)<<15|s>>>17)+i|0)|~e))+o[1]-2054922799)<<21|t>>>11)+s|0,t=((t+=((i=((i+=(t^((e=((e+=(s^(t|~i))+o[8]+1873313359)<<6|e>>>26)+t|0)|~s))+o[15]-30611744)<<10|i>>>22)+e|0)^((s=((s+=(e^(i|~t))+o[6]-1560198380)<<15|s>>>17)+i|0)|~e))+o[13]+1309151649)<<21|t>>>11)+s|0,t=((t+=((i=((i+=(t^((e=((e+=(s^(t|~i))+o[4]-145523070)<<6|e>>>26)+t|0)|~s))+o[11]-1120210379)<<10|i>>>22)+e|0)^((s=((s+=(e^(i|~t))+o[2]+718787259)<<15|s>>>17)+i|0)|~e))+o[9]-343485551)<<21|t>>>11)+s|0,this.first?(this.h0=e+1732584193|0,this.h1=t-271733879|0,this.h2=s-1732584194|0,this.h3=i+271733878|0,this.first=!1):(this.h0=this.h0+e|0,this.h1=this.h1+t|0,this.h2=this.h2+s|0,this.h3=this.h3+i|0)},I.prototype.hex=function(){this.finalize();var e=this.h0,t=this.h1,s=this.h2,i=this.h3;return d[e>>>4&15]+d[15&e]+d[e>>>12&15]+d[e>>>8&15]+d[e>>>20&15]+d[e>>>16&15]+d[e>>>28&15]+d[e>>>24&15]+d[t>>>4&15]+d[15&t]+d[t>>>12&15]+d[t>>>8&15]+d[t>>>20&15]+d[t>>>16&15]+d[t>>>28&15]+d[t>>>24&15]+d[s>>>4&15]+d[15&s]+d[s>>>12&15]+d[s>>>8&15]+d[s>>>20&15]+d[s>>>16&15]+d[s>>>28&15]+d[s>>>24&15]+d[i>>>4&15]+d[15&i]+d[i>>>12&15]+d[i>>>8&15]+d[i>>>20&15]+d[i>>>16&15]+d[i>>>28&15]+d[i>>>24&15]},I.prototype.toString=I.prototype.hex,I.prototype.digest=function(){this.finalize();var e=this.h0,t=this.h1,s=this.h2,i=this.h3;return[255&e,e>>>8&255,e>>>16&255,e>>>24&255,255&t,t>>>8&255,t>>>16&255,t>>>24&255,255&s,s>>>8&255,s>>>16&255,s>>>24&255,255&i,i>>>8&255,i>>>16&255,i>>>24&255]},I.prototype.array=I.prototype.digest,I.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(16),t=new Uint32Array(e);return t[0]=this.h0,t[1]=this.h1,t[2]=this.h2,t[3]=this.h3,e},I.prototype.buffer=I.prototype.arrayBuffer,I.prototype.base64=function(){for(var e,t,s,i="",r=this.array(),n=0;n<15;)e=r[n++],t=r[n++],s=r[n++],i+=p[e>>>2]+p[63&(e<<4|t>>>4)]+p[63&(t<<2|s>>>6)]+p[63&s];return e=r[n],i+=p[e>>>2]+p[e<<4&63]+"=="},v.prototype=new I,v.prototype.finalize=function(){if(I.prototype.finalize.call(this),this.inner){this.inner=!1;var e=this.array();I.call(this,this.sharedMemory),this.update(this.oKeyPad),this.update(e),I.prototype.finalize.call(this)}};var y=function(){var e=w("hex");o&&(e=C(e)),e.create=function(){return new I},e.update=function(t){return e.create().update(t)};for(var t=0;t<u.length;++t){var s=u[t];e[s]=w(s)}return e}();y.md5=y,y.md5.hmac=function(){var e=S("hex");e.create=function(e){return new v(e)},e.update=function(t,s){return e.create(t).update(s)};for(var t=0;t<u.length;++t){var s=u[t];e[s]=S(s)}return e}(),c?Mt.exports=y:r.md5=y}();var Wt=Bt.exports;const Vt=(e,t)=>{const s=Date.now(),i=`${e}:${s}:${Wt.md5(`${t}${s}`)}`,r=(new TextEncoder).encode(i);return btoa(String.fromCharCode(...r))},Jt=e=>{if(/^\d+$/.test(e))return!1;if(!e||"string"!=typeof e||e.length%4!=0)return!1;if(!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e))return!1;try{const t=atob(e);return btoa(t)===e}catch(e){return!1}},Kt="/v1/aicc/bmserver",Yt="/v1/aicc/ccs";let Zt="",zt="",Xt="",Qt="";function es(e){const t=Vt(zt,Xt);return Gt.create({prefixUrl:`${Zt}`,timeout:!1,headers:{Authorization:t,...e},hooks:{afterResponse:[async(e,t,s)=>{if(-1!==s.url.indexOf("heartbeat"))return s;const i=await s.clone().json();if(0!==i.code)throw new Error(JSON.stringify(i)||"请求失败");return s.json=async()=>i,s}]}})}async function ts(e,t,s){const i=es(s),r="api/"+e.replace(/^\/+/,"");return i.post(r,{json:t}).json()}class ss{static requestPermission(){"Notification"in window&&"default"===Notification.permission&&Notification.requestPermission()}static async requestMediaPermissions(){try{const e=await navigator.mediaDevices.enumerateDevices();if(e.some(e=>"audioinput"===e.kind&&""!==e.label))return null;return await navigator.mediaDevices.getUserMedia({audio:!0})}catch(e){return console.warn("获取音频权限失败:",e),null}}static show(e,t,s,i){if("Notification"in window&&"granted"===Notification.permission){const r=new Notification(e,{body:t,tag:`xy-global-notification${(new Date).getTime()}`,renotify:!0});r.onclick=()=>{window.focus(),r.close(),s?.()},setTimeout(()=>r.close(),1e3*(i||3))}}static async checkMediaPermissions(){try{return(await navigator.mediaDevices.enumerateDevices()).some(e=>"audioinput"===e.kind&&""!==e.label)}catch(e){return console.warn("无法检查设备权限:",e),!1}}}const is=(e,t)=>ts(`${Yt}/state/change?h=${t}`,e,{h:t}),rs=()=>async function(e,t){const s=es(),i=e.replace(/^\/+/,"");return s.post(i,{json:t}).json()}("/heartbeat",{}),ns=[],os=["call_number"],as=["call_number"],cs=["hangup"],hs=["hold","hangup","mute","transfer","consult","satisfaction","dtmf"],ds=["hold","hangup","mute","transfer","consult"],ls=["consult_transfer","conference","consult_retrieve"],gs=["hangup"],us=["hangup"],ps=["answer","reject"],fs=["hangup","consult","transfer","hold","mute","satisfaction","dtmf"],ms=["hangup","whisper","force_insert","force_disconnect"],_s=["hangup"],Es=["hangup","cancel_whisper","force_insert"],Ts=["hangup"],ws=["hangup"];class Cs{constructor(){this.roleData={agentInfo:()=>{if(!dt.agentInfo?.agent_no)throw new Error(JSON.stringify({code:1,msg:"请先登录"}))},requestInfo:e=>{if(!e.data)throw new Error(JSON.stringify({code:1,msg:'Parameter "data" is required'}))},changeDevice:e=>{if(!e)throw new Error(JSON.stringify({code:1,msg:'Parameter "device" is required'}));const{answer_devices:t}=dt.agentInfo;if(!t.split(",").map(e=>Number(e)).includes(e))throw new Error(JSON.stringify({code:1,msg:"当前状态不支持"}))},changeState:(e,t)=>{if(!e)throw new Error(JSON.stringify({code:1,msg:'Parameter "state" is required'}));if(!t)throw new Error(JSON.stringify({code:1,msg:'Parameter "state_name" is required'}));if(2===e&&("通话中"===t||"整理"===t))throw new Error(JSON.stringify({code:1,msg:"当前状态不支持"}));if(![1,2].includes(e))throw new Error(JSON.stringify({code:1,msg:"当前状态不支持"}))},setAgentExplicit:e=>{const{out_display_select_switch:t,out_display_data:s}=dt.agentInfo;if(1!==t)throw new Error(JSON.stringify({code:1,msg:"当前坐席设置未开启允许指定外显"}));if(!e)throw new Error(JSON.stringify({code:1,msg:'Parameter "number" is required'}));if(!(s||"").split("#").includes(e))throw new Error(JSON.stringify({code:1,msg:"当前外显号码不存在"}))}},this.changeDevice=async e=>{try{if(gt.get("isCalling"))throw new Error(JSON.stringify({code:1,msg:"当前正在通话中,请勿切换设备"}));this.roleData.agentInfo(),this.roleData.requestInfo(e);const{data:t,success:s}=e,{device:i}=t;1===i&&await Cs.initRtcFn(),this.roleData.changeDevice(i);const{agent_no:r}=dt.agentInfo;await(e=>ts(`${Yt}/device/change`,e))({agent_no:r,answer_device:i}),gt.updateAnswerDevice(i);const n=gt.get("actionConfigs");gt.updateActionConfigs(n),2===i&&dt.stateObject.state===exports.AgentStatus.UNREGISTERED&&await this._changeState({data:{...dt.stateBeforeChange,state_name:dt.stateBeforeChange.state===exports.AgentStatus.IDLE?"空闲":"忙碌"}},"q"),s?.({code:0,msg:"请求成功"})}catch(e){throw ht.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}}formatDate(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")} ${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}:${String(e.getSeconds()).padStart(2,"0")}`}static setInitRtcFn(e){this.initRtcFn=e}async _agentLogin(e){try{const s=await(t={agent_no:e},ts(`${Yt}/agent/login`,t));dt.agentInfo=s.data}catch(e){throw ht.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}var t}async _changeState(e,t){try{dt.autoStateTimer&&(clearTimeout(dt.autoStateTimer),dt.autoStateTimer=null),this.roleData.agentInfo(),this.roleData.requestInfo(e);const{data:s,success:i}=e,{state:r,state_name:n}=s,{agent_no:o}=dt.agentInfo;await is({agent_no:o,state_name:n,state:r},t),r===exports.AgentStatus.IDLE?gt.updateActionConfigs(os):r===exports.AgentStatus.BUSY&>.updateActionConfigs(as),dt.stateObject={state:r,state_name:n},i?.({code:0,msg:"请求成功"})}catch(e){throw ht.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}async _getInCallCrmDetail(e){try{const{phone:t}=e.data,s={};Jt(t)?s.trace_id=t:s.phone=t.replace(/[\s\r\n-]+/g,"");const i=await(e=>ts(`${Kt}/crm/popups`,e))({...s});e.success?.(i)}catch(e){throw ht.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}async changeState(e,t){try{if(gt.get("isCalling"))throw new Error(JSON.stringify({code:1,msg:"当前正在通话中,请勿切换设备"}));dt.autoStateTimer&&(clearTimeout(dt.autoStateTimer),dt.autoStateTimer=null),this.roleData.agentInfo(),this.roleData.requestInfo(e);const{data:s,success:i}=e,{state:r,state_name:n}=s;this.roleData.changeState(r,n);const{agent_no:o}=dt.agentInfo;await is({agent_no:o,state_name:n,state:r},t),(dt.stateObject.state===exports.AgentStatus.IDLE||dt.stateObject.state===exports.AgentStatus.BUSY&&"整理"!==n)&&(dt.stateBeforeChange=dt.stateObject),r===exports.AgentStatus.IDLE?gt.updateActionConfigs(os):r===exports.AgentStatus.BUSY&>.updateActionConfigs(as),dt.stateObject={state:r,state_name:n},i?.({code:0,msg:"请求成功"})}catch(e){throw ht.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}async getIdleAgentList(e){const{agent_no:t}=dt.agentInfo;try{this.roleData.agentInfo();const s=await(e=>ts(`${Yt}/agent/free`,e))({agent_no:t});e.success?.(s)}catch(e){throw ht.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}async getAgentState(e){try{const t=await ts(`${Kt}/agent/statecfg/list`,{}),s=(t.data||[]).filter(e=>0===e.enable).filter(e=>0!==e.state&&3!==e.state).filter(e=>"通话中"!==e.state_name&&"整理"!==e.state_name&&"未注册"!==e.state_name&&"离线接听"!==e.state_name).map(e=>({state:e.state,state_name:e.state_name})).reverse();e.success?.({...t,data:s})}catch(e){throw ht.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}async setAgentExplicit(e){try{this.roleData.agentInfo(),this.roleData.requestInfo(e),this.roleData.setAgentExplicit(e.data.number);const{agent_id:t}=dt.agentInfo;await(e=>ts(`${Kt}/agent/update`,e))({agent_id:t,out_display_number:e.data.number}),gt.updateSelectOutNumber(e.data.number),e.success?.({code:0,msg:"请求成功"})}catch(e){throw ht.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}async checkAgentLogin(e){try{this.roleData.requestInfo(e);const{agent_no:t}=e.data;if(!t)throw new Error(JSON.stringify({code:1,msg:'Parameter "agent_no" is required'}));const s=await(e=>ts(`${Yt}/agent/islogin`,e))({agent_no:t});e.success?.(s)}catch(e){throw ht.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}async getCallRecord(e){try{this.roleData.agentInfo();const{success:t}=e,s=new Date,i=new Date(s.getFullYear(),s.getMonth(),s.getDate(),0,0,0),r=new Date(s.getFullYear(),s.getMonth(),s.getDate(),23,59,59),n=[this.formatDate(i),this.formatDate(r)],{agent_no:o}=dt.agentInfo,a=await(e=>ts(`${Kt}/agent/recordpage`,e))({start_time:n[0],end_time:n[1],page_no:1,page_size:10,agent_no:o}),{code:c,msg:h,data:d}=a;t?.({code:c,msg:h,data:d})}catch(e){throw ht.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}async logout(e){this.roleData.agentInfo();try{const{agent_no:t}=dt.agentInfo,{data:s,success:i}=e;await(e=>ts(`${Yt}/agent/logout`,e))({...s,agent_no:t}),i?.({code:0,msg:""})}catch(e){throw ht.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}async listenCall(e){try{const{agent_no:t}=dt.agentInfo,{data:s,success:i}=e;if(this.roleData.agentInfo(),this.roleData.requestInfo(e),!s.monitored_agent_no)throw new Error(JSON.stringify({code:1,msg:'Parameter "monitored_agent_no" is required'}));await(e=>ts(`${Yt}/call/monitor`,e))({...s,monitor_agent_no:t}),dt.monitoredAgentNo=s.monitored_agent_no,i?.({code:0,msg:""})}catch(e){throw ht.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}async earCall(e){try{const{agentInfo:t,monitoredAgentNo:s}=dt,{agent_no:i}=t;this.roleData.agentInfo();const{success:r}=e;if(!s)throw new Error(JSON.stringify({code:1,msg:"当前未有监听坐席"}));await(e=>ts(`${Yt}/call/whisper`,e))({monitored_agent_no:s,monitor_agent_no:i}),r?.({code:0,msg:""})}catch(e){throw ht.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}async stopEarCall(e){try{const{agentInfo:t,earSpeakAgent:s}=dt;if(!s)throw new Error(JSON.stringify({code:1,msg:"当前没有正在耳语的坐席"}));const{agent_no:i}=t;this.roleData.agentInfo();const{success:r}=e;await(e=>ts(`${Yt}/call/stopwhisper`,e))({monitor_agent_no:i,monitored_agent_no:s}),r?.({code:0,msg:""})}catch(e){throw ht.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}async forceInsert(e){try{const{agentInfo:t,monitoredAgentNo:s}=dt,{agent_no:i}=t;this.roleData.agentInfo();const{success:r}=e;if(!s)throw new Error(JSON.stringify({code:1,msg:"当前未有监听坐席"}));await(e=>ts(`${Yt}/call/bargein`,e))({monitored_agent_no:s,monitor_agent_no:i}),r?.({code:0,msg:""})}catch(e){throw ht.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}async forceDisconnect(e){try{const{agentInfo:t,monitoredAgentNo:s}=dt,{agent_no:i}=t;this.roleData.agentInfo();const{success:r}=e;if(!s)throw new Error(JSON.stringify({code:1,msg:"当前未有监听坐席"}));await(e=>ts(`${Yt}/call/intercept`,e))({monitored_agent_no:s,monitor_agent_no:i}),r?.({code:0,msg:""})}catch(e){throw ht.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}}const Ss=console.log,Is=(...e)=>{dt.logBuiltinEnabled&&Ss(...e)};let vs=null;class ys{constructor(e,t){this.url=e,this.onOpenCallback=t,this.ws=null,this.heartbeatWorker=null,this.reconnectDelay=3e3,this.manualClose=!1,this.apiClient=new Cs,this.sipClient=null,this.pendingMessages=new Map,this.initWebSocket()}static getInstance({url:e,sipClient:t,onOpen:s}){if(!vs){if(!e)throw new Error("WebSocket 尚未初始化");vs=new ys(e,s),vs.sipClient=t}return vs}setSipClient(e){this.sipClient=e}stateIdleChange(e){const{state:t}=dt.stateObject;t!==exports.AgentStatus.IDLE&&this.apiClient._changeState({data:{...dt.stateBeforeChange,state_name:dt.stateBeforeChange.state===exports.AgentStatus.IDLE?"空闲":"忙碌"}},e)}inCallAutoAnswer(){const{soft_device_auto_answer:e,auto_answer_time:t}=dt.agentInfo,s=1===e,i=gt.get("direction");if(s&&i===exports.DirectionEnum.INCOMING){const e=Number(t)||0;e>0&&(dt.autoAnswerTimer=setTimeout(()=>{this.sipClient?.answerCall(),dt.autoAnswerTimer=null},1e3*e-500))}}async getCustomerInfo(e){try{await this.apiClient._getInCallCrmDetail({data:{phone:e},success:e=>{gt.updateCustomerInfo(e.data||{phone:e.data.phone,is_vip:0,customer_name:"未知客户",city:"未知",province:"未知",contact_count:0,in_contact_count:0,trace_id:e.data.trace_id,contact_count_month:0,in_contact_count_month:0})}})}catch(e){}}putAgentState(e,t){if(!e)return;if(5===t)return void this.stateIdleChange("device_type5");dt.sessionId="";const{post_call_process_time:s}=dt.agentInfo,i=s||0;if(dt.autoStateTimer&&(clearTimeout(dt.autoStateTimer),dt.autoStateTimer=null),gt.updateCustomerInfo(void 0),i>0){const{state:e}=dt.stateObject;if(e===exports.AgentStatus.IDLE)return;this.apiClient._changeState({data:{state:exports.AgentStatus.BUSY,state_name:"整理"}},"ez"),dt.autoStateTimer=setTimeout(()=>{dt.autoStateTimer=null,this.stateIdleChange(`delay${i}`)},1e3*i)}else this.stateIdleChange("delay0")}stateBusyChange(){dt.sessionId="",clearTimeout(dt.autoStateTimer),gt.updateCustomerInfo(void 0),this.apiClient._changeState({data:{state:exports.AgentStatus.BUSY,state_name:"忙碌"}},"dm")}initWebSocket(){if(1===this.ws?.readyState)return;if(!gt.get("isNextState")||this.manualClose)return;const e=Vt(zt,Xt);this.ws=new WebSocket(this.url+e),this.ws.onopen=()=>{const e=(new Date).getTime();this.sendMessage({type:0,msg_id:e}),this.pendingMessages.set(e,performance.now()),this.startHeartbeat(),this.manualClose=!1,this.onOpenCallback&&this.onOpenCallback()},this.ws.onmessage=async e=>{const t=JSON.parse(e.data),{type:s,data:i,code:r,msg:n,msg_id:o}=t;if(0===s&&o){const e=this.pendingMessages.get(o),t=performance.now()-e;dt.latency=parseFloat(t.toFixed(2)),this.pendingMessages.delete(o)}if(0!==s&&Is("%cWebSocket 收到消息:","color: blue; font-weight: bold;",t),s!==exports.WebsocketTypeEnum.OUT_CALL&&s!==exports.WebsocketTypeEnum.PREVIEW_OUT_CALL||(0!==r?(gt.reset(),ht.emit(exports.CallSipCallEventEnum.OUT_FAILED,n),ht.emit(exports.EventName.FAIL_NOTIFICATION,n),gt.updateActionConfigs(os),setTimeout(()=>{gt.updateCustomerInfo(void 0)},500),this.stateIdleChange("h")):0===r&&(ht.emit(exports.CallSipCallEventEnum.OUT_SUCCESS),clearTimeout(dt.autoStateTimer))),s===exports.WebsocketTypeEnum.AGENT_STATE){const{state:e,state_name:t}=i;dt.stateObject={state:e,state_name:t},dt.stateBeforeChange?.state||dt.stateObject.state!==exports.AgentStatus.IDLE&&(dt.stateObject.state!==exports.AgentStatus.BUSY||"整理"===t)||(dt.stateBeforeChange=dt.stateObject),"振铃中"===t&>.updateDisplayText(exports.DisplayTextEnum.AGENT_RINGING);const s=gt.get("isCalling");e!==exports.AgentStatus.UNREGISTERED||s||gt.updateActionConfigs(ns),e===exports.AgentStatus.IDLE&&dt.stateObject.state===exports.AgentStatus.UNREGISTERED&>.updateActionConfigs(os),ht.emit(exports.CallSipCallEventEnum.AGENT_STATE,{state:e,state_name:t})}else if(s===exports.WebsocketTypeEnum.OUT_CALL_INCOMING_CALL){try{await this.getCustomerInfo(i.trace_id||i.customer_phone)}catch(e){console.error(e)}i.preview_task_id?ht.emit(exports.CallSipCallEventEnum.PREVIEW_OUT_INCOMING_CALL,{customer_phone:i.customer_phone,session_id:i.session_id,preview_task_id:i.preview_task_id,trace_id:i.trace_id}):1===i.direction?ht.emit(exports.CallSipCallEventEnum.OUT_INCOMING_CALL,{customer_phone:i.customer_phone,session_id:i.session_id,trace_id:i.trace_id}):8===i.direction&&ht.emit(exports.CallSipCallEventEnum.INTERNAL_OUT_INCOMING_CALL,{customer_phone:i.customer_phone,session_id:i.session_id,trace_id:i.trace_id}),dt.sessionId=i.session_id,gt.updateActionConfigs(cs,8!==i.direction)}else if(s===exports.WebsocketTypeEnum.OUT_CALL_END){if(dt.sessionId!==i.session_id)return;if(gt.updateDisplayText(""),1===i.device_type&&i.agent_no===dt.agentInfo.agent_no)gt.reset(),ht.emit(exports.CallSipCallEventEnum.OUT_HANGUP,{session_id:i.session_id}),gt.updateActionConfigs(os),this.putAgentState(!0);else if(2===i.device_type&&i.agent_no===dt.agentInfo.agent_no)gt.reset(),ht.emit(exports.CallSipCallEventEnum.OUR_SIDE_CONSULT_HANGUP,{session_id:i.session_id}),gt.updateActionConfigs(os),this.putAgentState(!0);else if(2===i.device_type&&i.agent_no!==dt.agentInfo.agent_no){gt.get("isCalling")&&(gt.updateDisplayText(exports.DisplayTextEnum.CALLING),ht.emit(exports.CallSipCallEventEnum.OTHER_SIDE_CONSULT_HANGUP,{session_id:i.session_id}),gt.updateActionConfigs(hs))}else if(3===i.device_type&&i.agent_no===dt.agentInfo.agent_no)gt.reset(),ht.emit(exports.CallSipCallEventEnum.THREE_WAY_OUR_SIDE_HANGUP,{session_id:i.session_id}),gt.updateActionConfigs(os),this.putAgentState(!0);else if(4===i.device_type&&i.agent_no===dt.agentInfo.agent_no)gt.reset(),ht.emit(exports.CallSipCallEventEnum.TRANSFER_END,{session_id:i.session_id}),gt.updateActionConfigs(os),this.putAgentState(!0);else if(4===i.device_type&&i.agent_no!==dt.agentInfo.agent_no){ht.emit(exports.CallSipCallEventEnum.TRANSFER_FAILED,"未知原因"),ht.emit(exports.EventName.FAIL_NOTIFICATION,"转接失败");const e=gt.get("direction");e===exports.DirectionEnum.OUTGOING?gt.updateActionConfigs(hs):e===exports.DirectionEnum.INCOMING&>.updateActionConfigs(fs)}else 5===i.device_type&&i.agent_no===dt.agentInfo.agent_no&&(dt.monitoredAgentNo="",dt.earSpeakAgent="",gt.reset(),ht.emit(exports.CallSipCallEventEnum.LISTEN_HANGUP,{session_id:i.session_id}),gt.updateActionConfigs(os),this.putAgentState(!0,5))}else if(s===exports.WebsocketTypeEnum.OUT_CALL_RINGING)1===i.type&&(ht.emit(exports.CallSipCallEventEnum.OUT_RINGING,{session_id:dt.sessionId,type:i.type}),gt.updateDisplayText(exports.DisplayTextEnum.RINGING));else if(s===exports.WebsocketTypeEnum.OUT_CALL_ANSWER)clearTimeout(dt.autoStateTimer),gt.updateIsCalling(!0),gt.updateOutCallIsAnswer(!0),gt.updateDisplayText(exports.DisplayTextEnum.CALLING),8===i.direction?(ht.emit(exports.CallSipCallEventEnum.INTERNAL_OUT_OFF_ANSWER,{session_id:dt.sessionId}),gt.updateActionConfigs(ds)):(ht.emit(exports.CallSipCallEventEnum.OUT_OFF_ANSWER,{session_id:dt.sessionId}),gt.updateActionConfigs(hs));else if(s===exports.WebsocketTypeEnum.CONSULT_RINGING)ht.emit(exports.CallSipCallEventEnum.CONSULT_RINGING,{session_id:i.session_id}),gt.updateDisplayText(exports.DisplayTextEnum.AGENT_RINGING),gt.updateActionConfigs([]),clearTimeout(dt.autoStateTimer);else if(s===exports.WebsocketTypeEnum.CONSULT_ANSWER)ht.emit(exports.CallSipCallEventEnum.CONSULT_OFF_HOOK,{session_id:i.session_id}),gt.updateConsultIsAnswer(!0),gt.updateDisplayText(exports.DisplayTextEnum.CONSULTING),gt.updateActionConfigs(ls);else if(s===exports.WebsocketTypeEnum.CONSULT_FAIL)ht.emit(exports.CallSipCallEventEnum.CONSULT_FAILED,{custom_reason:i.custom_reason}),gt.updateDisplayText(exports.DisplayTextEnum.CALLING),gt.updateActionConfigs(hs);else if(s===exports.WebsocketTypeEnum.CONSULT_CALL_IN)ht.emit(exports.CallSipCallEventEnum.CONSULT_INCOMING,{agent_no:i.agent_no,agent_mane:i.agent_name,session_id:i.session_id}),dt.sessionId=i.session_id,gt.updateIsCalling(!0),gt.updateDirection(exports.DirectionEnum.CONSULT),gt.updateDisplayText(exports.DisplayTextEnum.CONSULT_CALL_IN),gt.updateActionConfigs(ps),dt.enableBrowserAlert&&ss.show("📞 咨询来电",`坐席 [${i.agent_name}] 正在咨询...`,()=>{ht.emit(exports.EventName.NOTIFICATION_CLICK,{agent_mane:i.agent_name,agent_no:i.agent_no})},dt.browserAlertTime);else if(s===exports.WebsocketTypeEnum.CONSULT_CALL_IN_SUCCESS)ht.emit(exports.CallSipCallEventEnum.CONSULT_CALL_IN_SUCCESS,{session_id:i.session_id}),gt.updateConsultIsAnswer(!0),gt.updateDisplayText(exports.DisplayTextEnum.CALLING),gt.updateActionConfigs(gs);else if(s===exports.WebsocketTypeEnum.CONSULT_RETURN_CALL_SUCCESS)"success"===i.status?(gt.updateConsultIsAnswer(!1),ht.emit(exports.CallSipCallEventEnum.CONSULT_RETURN_CALL_SUCCESS),gt.updateDisplayText(exports.DisplayTextEnum.CALLING),ht.emit(exports.CallSipCallEventEnum.OTHER_SIDE_CONSULT_HANGUP),gt.updateActionConfigs(hs)):ht.emit(exports.EventName.FAIL_NOTIFICATION,"媒体失败");else if(s===exports.WebsocketTypeEnum.MUTE)0===r?(gt.updateIsMuted(!0),ht.emit(exports.CallSipCallEventEnum.MUTE_SUCCESS),gt.updateDisplayText(exports.DisplayTextEnum.MUTING)):(ht.emit(exports.CallSipCallEventEnum.MUTE_FAILED,n),ht.emit(exports.EventName.FAIL_NOTIFICATION,n));else if(s===exports.WebsocketTypeEnum.UNMUTE)0===r?(gt.updateIsMuted(!1),ht.emit(exports.CallSipCallEventEnum.UNMUTE_SUCCESS),gt.updateDisplayText(exports.DisplayTextEnum.CALLING)):(ht.emit(exports.CallSipCallEventEnum.UNMUTE_FAILED,n),ht.emit(exports.EventName.FAIL_NOTIFICATION,n));else if(s===exports.WebsocketTypeEnum.CALL_HOLD)0===r?(gt.updateIsHold(!0),gt.updateDisplayText(exports.DisplayTextEnum.HOLDING),ht.emit(exports.CallSipCallEventEnum.HOLD_SUCCESS)):(ht.emit(exports.CallSipCallEventEnum.HOLD_FAILED,n),ht.emit(exports.EventName.FAIL_NOTIFICATION,n));else if(s===exports.WebsocketTypeEnum.CALL_UNHOLD)0===r?(gt.updateDisplayText(exports.DisplayTextEnum.CALLING),gt.updateIsHold(!1),ht.emit(exports.CallSipCallEventEnum.UNHOLD_SUCCESS)):(ht.emit(exports.CallSipCallEventEnum.UNHOLD_FAILED,n),ht.emit(exports.EventName.FAIL_NOTIFICATION,n));else if(s===exports.WebsocketTypeEnum.CONSULT_TRANSFER)0===r?ht.emit(exports.CallSipCallEventEnum.CONSULT_TRANSFER_SUCCESS):(ht.emit(exports.CallSipCallEventEnum.CONSULT_TRANSFER_FAILED,n),ht.emit(exports.EventName.FAIL_NOTIFICATION,n));else if(s===exports.WebsocketTypeEnum.CONSULT_TRANSFER_FAILED)ht.emit(exports.CallSipCallEventEnum.CONSULT_TRANSFER_FAILED,i.status);else if(s===exports.WebsocketTypeEnum.CONSULT_TRANSFER_OFF_HOOK)gt.updateDirection(exports.DirectionEnum.INCOMING),gt.updateDisplayText(exports.DisplayTextEnum.CALLING),ht.emit(exports.CallSipCallEventEnum.CONSULT_TRANSFER_OFF_HOOK),gt.updateActionConfigs(fs),gt.updateIncomingIsAnswer(!0),gt.updateConsultIsAnswer(!1);else if(s===exports.WebsocketTypeEnum.INCOMING_CALL){clearTimeout(dt.autoStateTimer),dt.sessionId=i.session_id;try{await this.getCustomerInfo(i.trace_id||i.customer_phone)}catch(e){console.error(e)}gt.updateIsCalling(!0),gt.updateDirection(exports.DirectionEnum.INCOMING),gt.updateDisplayText(exports.DisplayTextEnum.INCOMING_CALL),this.inCallAutoAnswer(),1===i.direction&&ht.emit(exports.CallSipCallEventEnum.INCOMING_CALL,{customer_phone:i.customer_phone,trace_id:i.trace_id,session_id:i.session_id}),8===i.direction&&ht.emit(exports.CallSipCallEventEnum.INCOMING_CALL_IN,{customer_phone:i.customer_phone,trace_id:i.trace_id,session_id:i.session_id}),3===i.direction&&ht.emit(exports.CallSipCallEventEnum.PREDICT_INCOMING_CALL,{customer_phone:i.customer_phone,trace_id:i.trace_id,session_id:i.session_id}),6===i.direction&&ht.emit(exports.CallSipCallEventEnum.DUAL_CALL_INCOMING_CALL,{customer_phone:i.customer_phone,trace_id:i.trace_id,session_id:i.session_id}),gt.updateActionConfigs(ps),dt.enableBrowserAlert&&ss.show("📞 客户来电",`客户 [${i.customer_phone}] 正在呼入...`,()=>{ht.emit(exports.EventName.NOTIFICATION_CLICK,{customer_phone:i.customer_phone})},dt.browserAlertTime)}else if(s===exports.WebsocketTypeEnum.INCOMING_CALL_OFF_HOOK)gt.updateIncomingIsAnswer(!0),8===i.direction?(gt.updateActionConfigs(ds),ht.emit(exports.CallSipCallEventEnum.INCOMING_CALL_IN_OFF_HOOK,{session_id:dt.sessionId})):(gt.updateActionConfigs(fs),ht.emit(exports.CallSipCallEventEnum.INCOMING_CALL_OFF_HOOK,{session_id:dt.sessionId})),gt.updateDisplayText(exports.DisplayTextEnum.CALLING);else if(s===exports.WebsocketTypeEnum.INCOMING_CALL_END){if(dt.sessionId!==i.session_id)return;if(gt.updateDisplayText(""),1!==i.device_type&&7!==i.device_type||i.agent_no!==dt.agentInfo.agent_no)if(2===i.device_type&&i.agent_no===dt.agentInfo.agent_no)gt.reset(),ht.emit(exports.CallSipCallEventEnum.OUR_SIDE_CONSULT_HANGUP,{session_id:i.session_id}),this.putAgentState(!0),gt.updateActionConfigs(os);else if(2===i.device_type&&i.agent_no!==dt.agentInfo.agent_no)gt.updateDisplayText(exports.DisplayTextEnum.CALLING),ht.emit(exports.CallSipCallEventEnum.OTHER_SIDE_CONSULT_HANGUP,{session_id:i.session_id}),gt.updateActionConfigs(hs);else if(3===i.device_type&&i.agent_no===dt.agentInfo.agent_no)this.putAgentState(!0),gt.reset(),ht.emit(exports.CallSipCallEventEnum.THREE_WAY_OUR_SIDE_HANGUP,{session_id:i.session_id}),gt.updateActionConfigs(os);else if(4===i.device_type&&i.agent_no===dt.agentInfo.agent_no)this.putAgentState(!0),gt.reset(),ht.emit(exports.CallSipCallEventEnum.TRANSFER_END,{session_id:i.session_id}),gt.updateActionConfigs(os);else if(4===i.device_type&&i.agent_no!==dt.agentInfo.agent_no){ht.emit(exports.CallSipCallEventEnum.TRANSFER_FAILED,"未知原因"),ht.emit(exports.EventName.FAIL_NOTIFICATION,"转接失败");const e=gt.get("direction");e===exports.DirectionEnum.OUTGOING?gt.updateActionConfigs(hs):e===exports.DirectionEnum.INCOMING&>.updateActionConfigs(fs)}else 5===i.device_type&&i.agent_no===dt.agentInfo.agent_no&&(this.putAgentState(!0,5),dt.monitoredAgentNo="",dt.earSpeakAgent="",gt.reset(),ht.emit(exports.CallSipCallEventEnum.LISTEN_HANGUP,{session_id:i.session_id}),gt.updateActionConfigs(os));else this.putAgentState(!0),gt.reset(),ht.emit(exports.CallSipCallEventEnum.INCOMING_CALL_END,{session_id:i.session_id}),gt.updateActionConfigs(os)}else if(s===exports.WebsocketTypeEnum.SATISFACTION_EVALUATION)0===r?ht.emit(exports.CallSipCallEventEnum.SATISFACTION_EVALUATION_SUCCESS):(ht.emit(exports.CallSipCallEventEnum.SATISFACTION_EVALUATION_FAILED,n),ht.emit(exports.EventName.FAIL_NOTIFICATION,n));else if(s===exports.WebsocketTypeEnum.CONSULT_THREE_WAY)0!==r?(ht.emit(exports.CallSipCallEventEnum.CONSULT_THREE_WAY_FAILED,n),ht.emit(exports.EventName.FAIL_NOTIFICATION,n)):0===r&>.updateIsMeeting(!0);else if(s===exports.WebsocketTypeEnum.CONSULT_THREE_WAY_RESULT)"success"===i.status?(gt.updateDirection(exports.DirectionEnum.MEETING),gt.updateDisplayText(exports.DisplayTextEnum.MEETING),gt.updateActionConfigs(us),ht.emit(exports.CallSipCallEventEnum.CONSULT_THREE_WAY_SUCCESS)):(ht.emit(exports.CallSipCallEventEnum.CONSULT_THREE_WAY_FAILED,{conf_name:i.conf_name}),gt.updateIsMeeting(!1));else if(s===exports.WebsocketTypeEnum.TRANSFER_INCOMING_CALL)clearTimeout(dt.autoStateTimer),i.agent_no===dt.agentInfo.agent_no?(gt.updateDisplayText(exports.DisplayTextEnum.TRANSFERRING),ht.emit(exports.CallSipCallEventEnum.TRANSFER_PROGRESS),gt.updateActionConfigs([]),gt.updateTransferIsAnswer(!0)):(dt.sessionId=i.session_id,ht.emit(exports.CallSipCallEventEnum.TRANSFER_INCOMING_CALL,{agent_no:i.agent_no,agent_name:i.agent_name,session_id:i.session_id}),gt.updateIsCalling(!0),gt.updateDirection(exports.DirectionEnum.TRANSFER),gt.updateDisplayText(exports.DisplayTextEnum.TRANSFER_INCOMING_CALL),gt.updateActionConfigs(ps),dt.enableBrowserAlert&&ss.show("📞 转接来电",`坐席 [${i.agent_no}] 正在转接...`,()=>{ht.emit(exports.EventName.NOTIFICATION_CLICK,{agent_no:i.agent_no})},dt.browserAlertTime));else if(s===exports.WebsocketTypeEnum.TRANSFER_OFF_HOOK)ht.emit(exports.CallSipCallEventEnum.TRANSFER_OFF_HOOK,{session_id:dt.sessionId}),gt.updateTransferIsAnswer(!1),gt.updateDisplayText(exports.DisplayTextEnum.CALLING),gt.updateActionConfigs(fs,8!==i.direction);else if(s===exports.WebsocketTypeEnum.TRANSFER_FAILED){if("failed"===i.status){ht.emit(exports.CallSipCallEventEnum.TRANSFER_FAILED,"未知原因"),ht.emit(exports.EventName.FAIL_NOTIFICATION,"转接失败");const e=gt.get("direction");e===exports.DirectionEnum.OUTGOING?gt.updateActionConfigs(hs):e===exports.DirectionEnum.INCOMING&>.updateActionConfigs(fs)}}else s===exports.WebsocketTypeEnum.KICK_OFFLINE?ht.emit(exports.EventName.KICK_OFF):s===exports.WebsocketTypeEnum.CONTINUOUS_NOT_ANSWER?(ht.emit(exports.EventName.FAIL_NOTIFICATION,`已连续 ${i.miss_count} 次未接, 设置忙碌`),this.stateBusyChange()):s===exports.WebsocketTypeEnum.SIGN_OUT?ht.emit(exports.EventName.SIGN_OUT):s===exports.WebsocketTypeEnum.SIGN_IN_SWITCH_DEVICE?ht.emit(exports.EventName.SIGN_IN_SWITCH_DEVICE,i):s===exports.WebsocketTypeEnum.LISTEN_INCOMING_CALL?(clearTimeout(dt.autoStateTimer),dt.sessionId=i.session_id,gt.updateIsCalling(!0),gt.updateDirection(exports.DirectionEnum.INCOMING),this.inCallAutoAnswer(),gt.updateDisplayText(exports.DisplayTextEnum.LISTENING),gt.updateActionConfigs(ps),ht.emit(exports.CallSipCallEventEnum.LISTEN_INCOMING_CALL,{session_id:i.session_id}),dt.enableBrowserAlert&&ss.show("📞 监听来电","正在来电...",()=>{ht.emit(exports.EventName.NOTIFICATION_CLICK,{customer_phone:i.customer_phone})},dt.browserAlertTime)):s===exports.WebsocketTypeEnum.LISTEN_INCOMING_CALL_OFF_HOOK?(dt.monitoredAgentNo=i.monitored_agent_no,dt.earSpeakAgent="",gt.updateIncomingIsAnswer(!0),ht.emit(exports.CallSipCallEventEnum.LISTEN_INCOMING_CALL_OFF_HOOK,{session_id:dt.sessionId,monitored_agent_no:i.monitored_agent_no}),gt.updateActionConfigs(ms),gt.updateDisplayText(exports.DisplayTextEnum.CALLING)):s===exports.WebsocketTypeEnum.LISTEN_CALL_FAILED?"failed"===i.status&&(ht.emit(exports.CallSipCallEventEnum.LISTEN_CALL_FAILED),dt.monitoredAgentNo=""):s===exports.WebsocketTypeEnum.EAR_SPEECH?"success"===i.status?(i.monitored_agent_no===dt.agentInfo.agent_no&&(gt.updateActionConfigs(_s),ht.emit(exports.CallSipCallEventEnum.EAR_SPEECH_BE_SUCCESS)),i.monitor_agent_no===dt.agentInfo.agent_no&&(gt.updateActionConfigs(Es),ht.emit(exports.CallSipCallEventEnum.EAR_SPEECH_SUCCESS,{monitored_agent_no:i.monitored_agent_no,monitor_agent_no:i.monitor_agent_no}),dt.earSpeakAgent=i.monitored_agent_no)):ht.emit(exports.CallSipCallEventEnum.EAR_SPEECH_FAILED):s===exports.WebsocketTypeEnum.STOP_EAR_SPEECH?"success"===i.status?(i.monitored_agent_no===dt.agentInfo.agent_no&>.updateActionConfigs(fs),i.monitor_agent_no===dt.agentInfo.agent_no&>.updateActionConfigs(ms),dt.earSpeakAgent="",ht.emit(exports.CallSipCallEventEnum.STOP_EAR_SPEECH_SUCCESS)):ht.emit(exports.CallSipCallEventEnum.STOP_EAR_SPEECH_FAILED):s===exports.WebsocketTypeEnum.CALL_FORCE_INSERT?"success"===i.status?(i.monitored_agent_no===dt.agentInfo.agent_no&&(gt.updateActionConfigs(ws),ht.emit(exports.CallSipCallEventEnum.CALL_FORCE_INSERT_SUCCESS,{monitored_agent_no:i.monitored_agent_no,monitor_agent_no:i.monitor_agent_no})),i.monitor_agent_no===dt.agentInfo.agent_no&&(gt.updateActionConfigs(Ts),ht.emit(exports.CallSipCallEventEnum.CALL_FORCE_INSERT_SUCCESS_LISTENER,{monitored_agent_no:i.monitored_agent_no,monitor_agent_no:i.monitor_agent_no}))):ht.emit(exports.CallSipCallEventEnum.CALL_FORCE_INSERT_FAILED):s===exports.WebsocketTypeEnum.INTERNAL_CALL_START_CONSULT?i.agent_no===dt.agentInfo.agent_no?(gt.updateConsultIsAnswer(!0),gt.updateActionConfigs(ls),gt.updateDisplayText(exports.DisplayTextEnum.CONSULTING)):(gt.updateDisplayText(exports.DisplayTextEnum.OTHER_SIDE_CONSULTING),gt.updateActionConfigs([])):s===exports.WebsocketTypeEnum.INTERNAL_CALL_END_CONSULT?(gt.updateActionConfigs(ds),gt.updateDisplayText(""),gt.updateConsultIsAnswer(!1)):s===exports.WebsocketTypeEnum.CALL_SIP_INCOMING_CALL&&ht.emit(exports.CallSipCallEventEnum.CALL_SIP_INCOMING_CALL)},this.ws.onclose=e=>{ht.emit(exports.EventName.FAIL_NOTIFICATION,"链接已断开,请检查网络"),this.stopHeartbeat();const t=gt.get("isNextState");!this.manualClose&&t&&setTimeout(()=>this.initWebSocket(),this.reconnectDelay)},this.ws.onerror=e=>{ht.emit(exports.EventName.FAIL_NOTIFICATION,"连接失败,请检查网络"),this.ws?.close()}}startHeartbeat(){const e=new Blob(["\n let timer;\n self.onmessage = function (e) {\n if (e.data === 'start') {\n timer = setInterval(() => {\n self.postMessage('heartbeat');\n }, 5000);\n } else if (e.data === 'stop') {\n clearInterval(timer);\n }\n };\n "],{type:"application/javascript"}),t=URL.createObjectURL(e);this.heartbeatWorker=new Worker(t),this.heartbeatWorker.onmessage=()=>{const e=(new Date).getTime();this.sendMessage({type:0,msg_id:e}),this.pendingMessages.set(e,performance.now())},this.heartbeatWorker.postMessage("start")}stopHeartbeat(){this.heartbeatWorker&&(this.heartbeatWorker.postMessage("stop"),this.heartbeatWorker.terminate(),this.heartbeatWorker=null)}sendMessage(e){this.ws?.readyState===WebSocket.OPEN?(this.ws.send(JSON.stringify(e)),0!==e.type&&Is("%cWebSocket 发送消息:","color: green; font-weight: bold;",e)):console.warn("WebSocket 未连接,消息未发送")}close(){this.manualClose=!0,this.stopHeartbeat(),this.ws?.close()}reconnect(){this.initWebSocket()}static __internalClose(){vs&&(vs.close(),vs=null)}static __internalSend(e){if(!vs)throw new Error("WebSocket 尚未初始化");vs.sendMessage(e)}}class As{constructor(e){this.sipClient=null,this.sipClient=e}roleMute(){const e=gt.get("isCalling"),t=dt.sessionId;if(!e)throw new Error(JSON.stringify({code:1,msg:"当前没有通话"}));if(!t)throw new Error(JSON.stringify({code:1,msg:"当前没有通话"}))}holdCall(){this.roleMute();const e=gt.get("isHold"),{sessionId:t}=dt;if(!t)return;if(!gt.get("actionConfigs").includes("hold"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿保持"}));if(e)throw new Error(JSON.stringify({code:1,msg:"当前已处于保持状态"}));ys.__internalSend({type:exports.WebsocketTypeEnum.CALL_HOLD,data:{session_id:t}})}unholdCall(){this.roleMute();const{isHold:e}=gt.getState(),{sessionId:t}=dt;if(!gt.get("actionConfigs").includes("unhold"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿取消保持"}));if(t){if(!e)throw new Error(JSON.stringify({code:1,msg:"当前未处于保持状态"}));ys.__internalSend({type:exports.WebsocketTypeEnum.CALL_UNHOLD,data:{session_id:t}})}}sendDTMF(e){if(1!==gt.get("answerDevice"))throw new Error(JSON.stringify({code:1,msg:"当前设备不支持此功能"}));if(!gt.get("actionConfigs").includes("dtmf"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿发送按键"}));const{isCalling:t}=gt.getState();if(!t)throw new Error(JSON.stringify({code:1,msg:"当前没有通话"}));this.sipClient.sendDTMF(e)}cancelCall(){if(!gt.get("isCalling"))throw new Error(JSON.stringify({code:1,msg:"当前没有通话"}));const e=dt.sessionId;ht.emit(exports.CallSipCallEventEnum.REJECT,{session_id:e}),ys.__internalSend({type:exports.WebsocketTypeEnum.AGENT_HANGUP,data:{session_id:e}})}async consultCall(e){this.roleMute();const{isCalling:t,outCallIsAnswer:s,consultIsAnswer:i,incomingIsAnswer:r}=gt.getState(),n=dt.sessionId;if(!gt.get("actionConfigs").includes("consult"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿调用咨询"}));if(i)throw new Error(JSON.stringify({code:1,msg:"当前正在咨询"}));if(!(t||s||r))throw new Error(JSON.stringify({code:1,msg:"当前没有通话"}));if(!n)throw new Error(JSON.stringify({code:1,msg:"sessionId不存在"}));ys.__internalSend({type:exports.WebsocketTypeEnum.CONSULT_REQUEST,data:{session_id:n,consultation_agent_no:e}})}async answerCall(){if(1!==gt.get("answerDevice"))throw new Error(JSON.stringify({code:1,msg:"当前设备不支持此功能"}));await this.sipClient.answerCall()}makeCall(e){if("string"!=typeof e||""===e.trim())throw new Error(JSON.stringify({code:1,msg:"外呼号码非法"}));const t={};Jt(e)?t.trace_id=e:t.customer_phone=e.replace(/[\s\r\n-]+/g,"");const s=gt.get("isCalling"),i=gt.get("selectOutNumber")||"";if(s)throw new Error(JSON.stringify({code:1,msg:"正在呼叫中,请勿重复点击"}));gt.updateIsCalling(!0),gt.updateDirection(exports.DirectionEnum.OUTGOING),ys.__internalSend({type:exports.WebsocketTypeEnum.OUT_CALL,data:{...t,caller:i.replace(/[\s\r\n-]+/g,"")}})}previewCall(e,t){const s={};Jt(e)?s.trace_id=e:s.customer_phone=e.replace(/[\s\r\n-]+/g,"");const i=gt.get("isCalling"),r=gt.get("selectOutNumber")||"";if(i)throw new Error(JSON.stringify({code:1,msg:"正在呼叫中,请勿重复点击"}));if("string"!=typeof e||""===e.trim())throw new Error(JSON.stringify({code:1,msg:"外呼号码非法"}));gt.updateIsCalling(!0),gt.updateDirection(exports.DirectionEnum.OUTGOING),ys.__internalSend({type:exports.WebsocketTypeEnum.PREVIEW_OUT_CALL,data:{...s,caller:r,preview_task_id:t}})}async hangup(){if(!gt.get("isCalling"))throw new Error(JSON.stringify({code:1,msg:"当前没有通话"}));const e=dt.sessionId;ys.__internalSend({type:exports.WebsocketTypeEnum.AGENT_HANGUP,data:{session_id:e}})}mute(){this.roleMute();const e=gt.get("actionConfigs"),t=gt.get("isMuted"),s=dt.sessionId;if(t)throw new Error(JSON.stringify({code:1,msg:"当前未处于静音状态"}));if(!e.includes("mute"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿调用静音"}));ys.__internalSend({type:exports.WebsocketTypeEnum.MUTE,data:{session_id:s}})}unmute(){this.roleMute();const e=gt.get("actionConfigs"),t=gt.get("isMuted"),s=dt.sessionId;if(!t)throw new Error(JSON.stringify({code:1,msg:"当前未处于未静音状态"}));if(!e.includes("unmute"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿调用静音"}));ys.__internalSend({type:exports.WebsocketTypeEnum.UNMUTE,data:{session_id:s}})}consultTransfer(){this.roleMute();const e=gt.get("consultIsAnswer"),t=dt.sessionId;if(!gt.get("actionConfigs").includes("consult_transfer"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿调用咨询转移"}));if(!e)throw new Error(JSON.stringify({code:1,msg:"当前未处于咨询中"}));ys.__internalSend({type:exports.WebsocketTypeEnum.CONSULT_TRANSFER,data:{session_id:t}})}satisfactionEvaluation(){this.roleMute();const e=dt.sessionId;if(!gt.get("actionConfigs").includes("satisfaction"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿调用满意度评价"}));ys.__internalSend({type:exports.WebsocketTypeEnum.SATISFACTION_EVALUATION,data:{session_id:e}})}startConference(){this.roleMute();if(!gt.get("actionConfigs").includes("conference"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿调用三方会议"}));const e=dt.sessionId;if(!gt.get("consultIsAnswer"))throw new Error(JSON.stringify({code:1,msg:"当前未处于咨询中"}));ys.__internalSend({type:exports.WebsocketTypeEnum.CONSULT_THREE_WAY,data:{session_id:e}})}consultRetrieve(){this.roleMute();if(!gt.get("actionConfigs").includes("consult_retrieve"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿取回通话"}));const e=dt.sessionId;if(!gt.get("consultIsAnswer"))throw new Error(JSON.stringify({code:1,msg:"当前未处于咨询中"}));ys.__internalSend({type:exports.WebsocketTypeEnum.CONSULT_RETURN_CALL,data:{session_id:e}})}async transferAgent(e){this.roleMute();if(!gt.get("actionConfigs").includes("transfer"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿转接"}));const{transferIsAnswer:t}=gt.getState(),s=dt.sessionId;if(t)throw new Error(JSON.stringify({code:1,msg:"当前正在转接"}));ys.__internalSend({type:exports.WebsocketTypeEnum.TRANSFER,data:{session_id:s,transfer_type:0,transfer_dest:e}})}async transferOutline(e){this.roleMute();if(!gt.get("actionConfigs").includes("transfer"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿转接"}));if(!e)throw new Error(JSON.stringify({code:1,msg:"号码不能为空"}));if(!/^\d+$/.test(e))throw new Error(JSON.stringify({code:1,msg:"号码格式错误"}));const{transferIsAnswer:t}=gt.getState(),s=dt.sessionId;if(t)throw new Error(JSON.stringify({code:1,msg:"当前正在转接"}));if(t)throw new Error(JSON.stringify({code:1,msg:"当前正在转接"}));ys.__internalSend({type:exports.WebsocketTypeEnum.TRANSFER,data:{session_id:s,transfer_type:2,transfer_dest:e}})}}var bs;class Rs{static{this._instance=null}#e;#t;#s;#i;#r;#n;#o;static{this._timer=null}constructor(){if(this.#e=null,this.#t=new Cs,this.#i=null,this.#o=!1,this.#a=()=>{},this.#c=()=>{},this.initWebRtc=async()=>{if(this.#e)return;const e=dt.agentInfo.sip_account_list.find(e=>1===e.device_type);if(!e)throw new Error(JSON.stringify({code:1,msg:"未找到 sip_account_list"}));{const t=e.sip_register_addr;this.#e=new pt({server:t.split(":")[0],user:e.sip_account,password:e.sip_password,webSocket:`wss://${t}`,callTimeout:3e4},this.#h),await this.#e.start()}},this.#h=e=>{const{type:t,data:s}=e;ht.emit(t,s)},!bs._creatingInstance)throw new Error("请使用 YSYTAgentSdk.getInstance() 获取实例");clearInterval(this.#i),this.#i=setInterval(async()=>{const e=await this.#d();ut.updateRttObject(e)},2e3),ss.requestMediaPermissions(),this.#n=gt.subscribeKey("isNextState",async e=>{if(e){1===gt.get("answerDevice")&&await this.#e.reconnect();let e="";const t=new URL(Zt).host;e=Zt.includes("https")?`wss://${t}`:`ws://${t}`;const{agent_no:s}=dt.agentInfo;ys.getInstance({url:`${e}/ccs-ws/api/v1/ws/call/${s}?Authorization=`,sipClient:this.#e}),setTimeout(()=>{this.#t._changeState({data:{state:exports.AgentStatus.BUSY,state_name:"忙碌"},success:()=>{gt.updateDisplayText(""),ht.emit(exports.CallSipCallEventEnum.AGENT_STATE,{state:exports.AgentStatus.BUSY,state_name:"忙碌"})}},"d")},10)}else ys.__internalClose(),gt.updateDisplayText("离线")}),this.#r=gt.subscribeKey("answerDevice",async e=>{1===e?dt.stateObject.state===exports.AgentStatus.UNREGISTERED&&await this.#t._changeState({data:{...dt.stateBeforeChange,state_name:dt.stateBeforeChange.state===exports.AgentStatus.IDLE?"空闲":"忙碌"}},"qq"):await this.destroyRtc()}),this.on(exports.EventName.KICK_OFF,()=>{this.destroy()}),window.addEventListener("beforeunload",e=>{e.returnValue="",this.destroy()}),window.addEventListener("online",this.#a),window.addEventListener("offline",this.#c)}#a;#c;async#l(){const e=gt.get("isNextState");try{await rs(),e||gt.updateIsNextState(!0)}catch(t){ht.emit(exports.EventName.FAIL_NOTIFICATION,"网络断开,请检查网络"),e&>.updateIsNextState(!1)}}#g(){bs._timer||(bs._timer=setInterval(()=>this.#l(),3e3))}static get instance(){return this._instance}static async destroyInstance(){this._instance&&(await this._instance.destroy(),this._instance=null)}static getInstance(e){if(!this._instance){if(!e)throw new Error("首次调用必须传入配置参数");const{url:t,appKey:s,appSecret:i,agentNo:r}=e;Zt=t||"https://aicc-api.yescloudy.com",zt=s,Xt=i,Qt=r,bs._creatingInstance=!0,this._instance=new bs,delete bs._creatingInstance}return this._instance}getInit(){return this.#o}async init({enableBrowserAlert:e,logBuiltinEnabled:t,browserAlertTime:s}){try{let i="";const r=new URL(Zt).host;i=Zt.includes("https")?`wss://${r}`:`ws://${r}`;const n=ys.getInstance({url:`${i}/ccs-ws/api/v1/ws/call/${Qt}?Authorization=`,sipClient:null,onOpen:async()=>{dt.logBuiltinEnabled=t||!1,dt.browserAlertTime=s||5e3,await this.#t._agentLogin(Qt);const{current_answer_device:i,current_state:r,out_display_number:o,out_display_select_switch:a}=dt.agentInfo;r===exports.AgentStatus.IDLE?(gt.updateActionConfigs(os),dt.stateObject={state:r,state_name:"空闲"},dt.stateBeforeChange=dt.stateObject):r===exports.AgentStatus.BUSY?(gt.updateActionConfigs(as),dt.stateObject={state:r,state_name:"忙碌"},dt.stateBeforeChange=dt.stateObject):r===exports.AgentStatus.UNREGISTERED&&(gt.updateActionConfigs(as),dt.stateObject={state:r,state_name:"未注册"}),1===a?gt.updateSelectOutNumber(o):gt.updateSelectOutNumber(""),gt.updateAnswerDevice(i),Cs.setInitRtcFn(this.initWebRtc),1===i&&(await this.initWebRtc(),n.setSipClient(this.#e)),this.#s=new As(this.#e),dt.enableBrowserAlert=e,e&&ss.requestPermission(),ht.emit(exports.EventName.AGENT_INIT_STATUS,!0),this.#o=!0,clearInterval(bs._timer),bs._timer=null,this.#g()}})}catch(e){ht.emit(exports.EventName.AGENT_INIT_STATUS,!1),this.#o=!1}}#h;on(e,t){return ht.on(e,t),this}off(e,t){ht.off(e,t)}offAll(){ht.clearAllListeners()}async destroyRtc(){await(this.#e?.destroy()),this.#e=null}async destroy(){bs._instance&&(await this.destroyRtc(),this.#r?.(),this.#n?.(),clearInterval(this.#i),ys.__internalClose(),ht.emit(exports.EventName.DESTROY),this.offAll(),bs._instance=null,gt.reset(),gt.updateSelectOutNumber(""),clearInterval(bs._timer),bs._timer=null)}async#d(){return this.#e?this.#e.getNetworkStats():{}}get call_api(){const e=e=>(...t)=>e.apply(this,t);return{answerCall:e(()=>this.#s.answerCall()),makeCall:e=>this.#s.makeCall(e),previewMakeCall:(e,t)=>this.#s.previewCall(e,t),cancelCall:e(()=>this.#s.cancelCall()),hangup:e(()=>this.#s.hangup()),sendDTMF:e(e=>this.#s.sendDTMF(e)),holdCall:e(()=>this.#s.holdCall()),unholdCall:e(()=>this.#s.unholdCall()),consultCall:e(async e=>{try{await this.#s.consultCall(e)}catch(e){throw console.warn(e),e}}),consultRetrieve:e(()=>this.#s.consultRetrieve()),consultTransfer:e(()=>this.#s.consultTransfer()),mute:e(()=>this.#s.mute()),unmute:e(()=>this.#s.unmute()),satisfactionEvaluation:e(()=>this.#s.satisfactionEvaluation()),startConference:e(()=>this.#s.startConference()),transferAgent:e(e=>this.#s.transferAgent(e)),transferOutline:e(e=>this.#s.transferOutline(e)),earSpeakStart:e(e=>this.#t.earCall(e)),earSpeakStop:e(e=>this.#t.stopEarCall(e)),forceInsert:e(e=>this.#t.forceInsert(e)),forceDisconnect:e(e=>this.#t.forceDisconnect(e))}}get agent_api(){const e=e=>(...t)=>e.apply(this,t);return{changeDevice:e(e=>this.#t.changeDevice(e)),changeState:e(e=>this.#t.changeState(e,"c")),getIdleAgentList:e(e=>this.#t.getIdleAgentList(e)),getAgentState:e(e=>this.#t.getAgentState(e)),setAgentExplicit:e(e=>this.#t.setAgentExplicit(e)),checkAgentLogin:e=>this.#t.checkAgentLogin(e),getCallRecord:e=>this.#t.getCallRecord(e),agentLogout:async(e,t)=>{try{await this.#t.logout(e),await this.destroy(),t?.({code:0,msg:""})}catch(e){}},listenAgentCall:e=>this.#t.listenCall(e)}}getAgentData(){const{agent_no:e,agent_name:t,answer_devices:s,out_display_data:i,out_display_select_switch:r,current_state:n}=dt.agentInfo,{stateObject:o}=dt,a={1:"软电话",2:"手机模式",3:"SIP话机"};return{agent_no:e,agent_name:t,init_state:n,default_device:gt.get("answerDevice"),out_display_data:i,out_display_select_switch:r,answer_devices:(s||"").split(",").map(e=>({value:Number(e),label:a[Number(e)]})),stateObject:o}}async getRealTimeCustomerInfo(){return gt.get("customerObject")}setBrowserAlert(e){if("boolean"!=typeof e)throw new Error(JSON.stringify({code:1,msg:"参数类型错误"}));dt.logBuiltinEnabled=e||!1}setBrowserAlertTime(e){if("number"!=typeof e)throw new Error(JSON.stringify({code:1,msg:"参数类型错误"}));dt.browserAlertTime=e||3e3}}bs=Rs,exports.default=Rs;
|
|
12
|
+
Mt=Bt,function(){var s="input is invalid type",i="object"==typeof window,r=i?window:{};r.JS_MD5_NO_WINDOW&&(i=!1);var n=!i&&"object"==typeof self,o=!r.JS_MD5_NO_NODE_JS&&"object"==typeof process&&process.versions&&process.versions.node;o?r=jt:n&&(r=self);var a,c=!r.JS_MD5_NO_COMMON_JS&&Mt.exports,h=!r.JS_MD5_NO_ARRAY_BUFFER&&"undefined"!=typeof ArrayBuffer,d="0123456789abcdef".split(""),l=[128,32768,8388608,-2147483648],g=[0,8,16,24],u=["hex","array","digest","buffer","arrayBuffer","base64"],p="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),f=[];if(h){var m=new ArrayBuffer(68);a=new Uint8Array(m),f=new Uint32Array(m)}var _=Array.isArray;!r.JS_MD5_NO_NODE_JS&&_||(_=function(e){return"[object Array]"===Object.prototype.toString.call(e)});var E=ArrayBuffer.isView;!h||!r.JS_MD5_NO_ARRAY_BUFFER_IS_VIEW&&E||(E=function(e){return"object"==typeof e&&e.buffer&&e.buffer.constructor===ArrayBuffer});var T=function(e){var t=typeof e;if("string"===t)return[e,!0];if("object"!==t||null===e)throw new Error(s);if(h&&e.constructor===ArrayBuffer)return[new Uint8Array(e),!1];if(!_(e)&&!E(e))throw new Error(s);return[e,!1]},w=function(e){return function(t){return new I(!0).update(t)[e]()}},C=function(i){var n,o=e,a=t.Buffer;return n=a.from&&!r.JS_MD5_NO_BUFFER_FROM?a.from:function(e){return new a(e)},function(e){if("string"==typeof e)return o.createHash("md5").update(e,"utf8").digest("hex");if(null==e)throw new Error(s);return e.constructor===ArrayBuffer&&(e=new Uint8Array(e)),_(e)||E(e)||e.constructor===a?o.createHash("md5").update(n(e)).digest("hex"):i(e)}},S=function(e){return function(t,s){return new v(t,!0).update(s)[e]()}};function I(e){if(e)f[0]=f[16]=f[1]=f[2]=f[3]=f[4]=f[5]=f[6]=f[7]=f[8]=f[9]=f[10]=f[11]=f[12]=f[13]=f[14]=f[15]=0,this.blocks=f,this.buffer8=a;else if(h){var t=new ArrayBuffer(68);this.buffer8=new Uint8Array(t),this.blocks=new Uint32Array(t)}else this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];this.h0=this.h1=this.h2=this.h3=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0}function v(e,t){var s,i=T(e);if(e=i[0],i[1]){var r,n=[],o=e.length,a=0;for(s=0;s<o;++s)(r=e.charCodeAt(s))<128?n[a++]=r:r<2048?(n[a++]=192|r>>>6,n[a++]=128|63&r):r<55296||r>=57344?(n[a++]=224|r>>>12,n[a++]=128|r>>>6&63,n[a++]=128|63&r):(r=65536+((1023&r)<<10|1023&e.charCodeAt(++s)),n[a++]=240|r>>>18,n[a++]=128|r>>>12&63,n[a++]=128|r>>>6&63,n[a++]=128|63&r);e=n}e.length>64&&(e=new I(!0).update(e).array());var c=[],h=[];for(s=0;s<64;++s){var d=e[s]||0;c[s]=92^d,h[s]=54^d}I.call(this,t),this.update(h),this.oKeyPad=c,this.inner=!0,this.sharedMemory=t}I.prototype.update=function(e){if(this.finalized)throw new Error("finalize already called");var t=T(e);e=t[0];for(var s,i,r=t[1],n=0,o=e.length,a=this.blocks,c=this.buffer8;n<o;){if(this.hashed&&(this.hashed=!1,a[0]=a[16],a[16]=a[1]=a[2]=a[3]=a[4]=a[5]=a[6]=a[7]=a[8]=a[9]=a[10]=a[11]=a[12]=a[13]=a[14]=a[15]=0),r)if(h)for(i=this.start;n<o&&i<64;++n)(s=e.charCodeAt(n))<128?c[i++]=s:s<2048?(c[i++]=192|s>>>6,c[i++]=128|63&s):s<55296||s>=57344?(c[i++]=224|s>>>12,c[i++]=128|s>>>6&63,c[i++]=128|63&s):(s=65536+((1023&s)<<10|1023&e.charCodeAt(++n)),c[i++]=240|s>>>18,c[i++]=128|s>>>12&63,c[i++]=128|s>>>6&63,c[i++]=128|63&s);else for(i=this.start;n<o&&i<64;++n)(s=e.charCodeAt(n))<128?a[i>>>2]|=s<<g[3&i++]:s<2048?(a[i>>>2]|=(192|s>>>6)<<g[3&i++],a[i>>>2]|=(128|63&s)<<g[3&i++]):s<55296||s>=57344?(a[i>>>2]|=(224|s>>>12)<<g[3&i++],a[i>>>2]|=(128|s>>>6&63)<<g[3&i++],a[i>>>2]|=(128|63&s)<<g[3&i++]):(s=65536+((1023&s)<<10|1023&e.charCodeAt(++n)),a[i>>>2]|=(240|s>>>18)<<g[3&i++],a[i>>>2]|=(128|s>>>12&63)<<g[3&i++],a[i>>>2]|=(128|s>>>6&63)<<g[3&i++],a[i>>>2]|=(128|63&s)<<g[3&i++]);else if(h)for(i=this.start;n<o&&i<64;++n)c[i++]=e[n];else for(i=this.start;n<o&&i<64;++n)a[i>>>2]|=e[n]<<g[3&i++];this.lastByteIndex=i,this.bytes+=i-this.start,i>=64?(this.start=i-64,this.hash(),this.hashed=!0):this.start=i}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296|0,this.bytes=this.bytes%4294967296),this},I.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex;e[t>>>2]|=l[3&t],t>=56&&(this.hashed||this.hash(),e[0]=e[16],e[16]=e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=e[7]=e[8]=e[9]=e[10]=e[11]=e[12]=e[13]=e[14]=e[15]=0),e[14]=this.bytes<<3,e[15]=this.hBytes<<3|this.bytes>>>29,this.hash()}},I.prototype.hash=function(){var e,t,s,i,r,n,o=this.blocks;this.first?t=((t=((e=((e=o[0]-680876937)<<7|e>>>25)-271733879|0)^(s=((s=(-271733879^(i=((i=(-1732584194^2004318071&e)+o[1]-117830708)<<12|i>>>20)+e|0)&(-271733879^e))+o[2]-1126478375)<<17|s>>>15)+i|0)&(i^e))+o[3]-1316259209)<<22|t>>>10)+s|0:(e=this.h0,t=this.h1,s=this.h2,t=((t+=((e=((e+=((i=this.h3)^t&(s^i))+o[0]-680876936)<<7|e>>>25)+t|0)^(s=((s+=(t^(i=((i+=(s^e&(t^s))+o[1]-389564586)<<12|i>>>20)+e|0)&(e^t))+o[2]+606105819)<<17|s>>>15)+i|0)&(i^e))+o[3]-1044525330)<<22|t>>>10)+s|0),t=((t+=((e=((e+=(i^t&(s^i))+o[4]-176418897)<<7|e>>>25)+t|0)^(s=((s+=(t^(i=((i+=(s^e&(t^s))+o[5]+1200080426)<<12|i>>>20)+e|0)&(e^t))+o[6]-1473231341)<<17|s>>>15)+i|0)&(i^e))+o[7]-45705983)<<22|t>>>10)+s|0,t=((t+=((e=((e+=(i^t&(s^i))+o[8]+1770035416)<<7|e>>>25)+t|0)^(s=((s+=(t^(i=((i+=(s^e&(t^s))+o[9]-1958414417)<<12|i>>>20)+e|0)&(e^t))+o[10]-42063)<<17|s>>>15)+i|0)&(i^e))+o[11]-1990404162)<<22|t>>>10)+s|0,t=((t+=((e=((e+=(i^t&(s^i))+o[12]+1804603682)<<7|e>>>25)+t|0)^(s=((s+=(t^(i=((i+=(s^e&(t^s))+o[13]-40341101)<<12|i>>>20)+e|0)&(e^t))+o[14]-1502002290)<<17|s>>>15)+i|0)&(i^e))+o[15]+1236535329)<<22|t>>>10)+s|0,t=((t+=((i=((i+=(t^s&((e=((e+=(s^i&(t^s))+o[1]-165796510)<<5|e>>>27)+t|0)^t))+o[6]-1069501632)<<9|i>>>23)+e|0)^e&((s=((s+=(e^t&(i^e))+o[11]+643717713)<<14|s>>>18)+i|0)^i))+o[0]-373897302)<<20|t>>>12)+s|0,t=((t+=((i=((i+=(t^s&((e=((e+=(s^i&(t^s))+o[5]-701558691)<<5|e>>>27)+t|0)^t))+o[10]+38016083)<<9|i>>>23)+e|0)^e&((s=((s+=(e^t&(i^e))+o[15]-660478335)<<14|s>>>18)+i|0)^i))+o[4]-405537848)<<20|t>>>12)+s|0,t=((t+=((i=((i+=(t^s&((e=((e+=(s^i&(t^s))+o[9]+568446438)<<5|e>>>27)+t|0)^t))+o[14]-1019803690)<<9|i>>>23)+e|0)^e&((s=((s+=(e^t&(i^e))+o[3]-187363961)<<14|s>>>18)+i|0)^i))+o[8]+1163531501)<<20|t>>>12)+s|0,t=((t+=((i=((i+=(t^s&((e=((e+=(s^i&(t^s))+o[13]-1444681467)<<5|e>>>27)+t|0)^t))+o[2]-51403784)<<9|i>>>23)+e|0)^e&((s=((s+=(e^t&(i^e))+o[7]+1735328473)<<14|s>>>18)+i|0)^i))+o[12]-1926607734)<<20|t>>>12)+s|0,t=((t+=((n=(i=((i+=((r=t^s)^(e=((e+=(r^i)+o[5]-378558)<<4|e>>>28)+t|0))+o[8]-2022574463)<<11|i>>>21)+e|0)^e)^(s=((s+=(n^t)+o[11]+1839030562)<<16|s>>>16)+i|0))+o[14]-35309556)<<23|t>>>9)+s|0,t=((t+=((n=(i=((i+=((r=t^s)^(e=((e+=(r^i)+o[1]-1530992060)<<4|e>>>28)+t|0))+o[4]+1272893353)<<11|i>>>21)+e|0)^e)^(s=((s+=(n^t)+o[7]-155497632)<<16|s>>>16)+i|0))+o[10]-1094730640)<<23|t>>>9)+s|0,t=((t+=((n=(i=((i+=((r=t^s)^(e=((e+=(r^i)+o[13]+681279174)<<4|e>>>28)+t|0))+o[0]-358537222)<<11|i>>>21)+e|0)^e)^(s=((s+=(n^t)+o[3]-722521979)<<16|s>>>16)+i|0))+o[6]+76029189)<<23|t>>>9)+s|0,t=((t+=((n=(i=((i+=((r=t^s)^(e=((e+=(r^i)+o[9]-640364487)<<4|e>>>28)+t|0))+o[12]-421815835)<<11|i>>>21)+e|0)^e)^(s=((s+=(n^t)+o[15]+530742520)<<16|s>>>16)+i|0))+o[2]-995338651)<<23|t>>>9)+s|0,t=((t+=((i=((i+=(t^((e=((e+=(s^(t|~i))+o[0]-198630844)<<6|e>>>26)+t|0)|~s))+o[7]+1126891415)<<10|i>>>22)+e|0)^((s=((s+=(e^(i|~t))+o[14]-1416354905)<<15|s>>>17)+i|0)|~e))+o[5]-57434055)<<21|t>>>11)+s|0,t=((t+=((i=((i+=(t^((e=((e+=(s^(t|~i))+o[12]+1700485571)<<6|e>>>26)+t|0)|~s))+o[3]-1894986606)<<10|i>>>22)+e|0)^((s=((s+=(e^(i|~t))+o[10]-1051523)<<15|s>>>17)+i|0)|~e))+o[1]-2054922799)<<21|t>>>11)+s|0,t=((t+=((i=((i+=(t^((e=((e+=(s^(t|~i))+o[8]+1873313359)<<6|e>>>26)+t|0)|~s))+o[15]-30611744)<<10|i>>>22)+e|0)^((s=((s+=(e^(i|~t))+o[6]-1560198380)<<15|s>>>17)+i|0)|~e))+o[13]+1309151649)<<21|t>>>11)+s|0,t=((t+=((i=((i+=(t^((e=((e+=(s^(t|~i))+o[4]-145523070)<<6|e>>>26)+t|0)|~s))+o[11]-1120210379)<<10|i>>>22)+e|0)^((s=((s+=(e^(i|~t))+o[2]+718787259)<<15|s>>>17)+i|0)|~e))+o[9]-343485551)<<21|t>>>11)+s|0,this.first?(this.h0=e+1732584193|0,this.h1=t-271733879|0,this.h2=s-1732584194|0,this.h3=i+271733878|0,this.first=!1):(this.h0=this.h0+e|0,this.h1=this.h1+t|0,this.h2=this.h2+s|0,this.h3=this.h3+i|0)},I.prototype.hex=function(){this.finalize();var e=this.h0,t=this.h1,s=this.h2,i=this.h3;return d[e>>>4&15]+d[15&e]+d[e>>>12&15]+d[e>>>8&15]+d[e>>>20&15]+d[e>>>16&15]+d[e>>>28&15]+d[e>>>24&15]+d[t>>>4&15]+d[15&t]+d[t>>>12&15]+d[t>>>8&15]+d[t>>>20&15]+d[t>>>16&15]+d[t>>>28&15]+d[t>>>24&15]+d[s>>>4&15]+d[15&s]+d[s>>>12&15]+d[s>>>8&15]+d[s>>>20&15]+d[s>>>16&15]+d[s>>>28&15]+d[s>>>24&15]+d[i>>>4&15]+d[15&i]+d[i>>>12&15]+d[i>>>8&15]+d[i>>>20&15]+d[i>>>16&15]+d[i>>>28&15]+d[i>>>24&15]},I.prototype.toString=I.prototype.hex,I.prototype.digest=function(){this.finalize();var e=this.h0,t=this.h1,s=this.h2,i=this.h3;return[255&e,e>>>8&255,e>>>16&255,e>>>24&255,255&t,t>>>8&255,t>>>16&255,t>>>24&255,255&s,s>>>8&255,s>>>16&255,s>>>24&255,255&i,i>>>8&255,i>>>16&255,i>>>24&255]},I.prototype.array=I.prototype.digest,I.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(16),t=new Uint32Array(e);return t[0]=this.h0,t[1]=this.h1,t[2]=this.h2,t[3]=this.h3,e},I.prototype.buffer=I.prototype.arrayBuffer,I.prototype.base64=function(){for(var e,t,s,i="",r=this.array(),n=0;n<15;)e=r[n++],t=r[n++],s=r[n++],i+=p[e>>>2]+p[63&(e<<4|t>>>4)]+p[63&(t<<2|s>>>6)]+p[63&s];return e=r[n],i+=p[e>>>2]+p[e<<4&63]+"=="},v.prototype=new I,v.prototype.finalize=function(){if(I.prototype.finalize.call(this),this.inner){this.inner=!1;var e=this.array();I.call(this,this.sharedMemory),this.update(this.oKeyPad),this.update(e),I.prototype.finalize.call(this)}};var y=function(){var e=w("hex");o&&(e=C(e)),e.create=function(){return new I},e.update=function(t){return e.create().update(t)};for(var t=0;t<u.length;++t){var s=u[t];e[s]=w(s)}return e}();y.md5=y,y.md5.hmac=function(){var e=S("hex");e.create=function(e){return new v(e)},e.update=function(t,s){return e.create(t).update(s)};for(var t=0;t<u.length;++t){var s=u[t];e[s]=S(s)}return e}(),c?Mt.exports=y:r.md5=y}();var Wt=Bt.exports;const Vt=(e,t)=>{const s=Date.now(),i=`${e}:${s}:${Wt.md5(`${t}${s}`)}`,r=(new TextEncoder).encode(i);return btoa(String.fromCharCode(...r))},Jt=e=>{if(/^\d+$/.test(e))return!1;if(!e||"string"!=typeof e||e.length%4!=0)return!1;if(!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e))return!1;try{const t=atob(e);return btoa(t)===e}catch(e){return!1}},Kt="/v1/aicc/bmserver",Yt="/v1/aicc/ccs";let Zt="",zt="",Xt="",Qt="";function es(e){const t=Vt(zt,Xt);return Gt.create({prefixUrl:`${Zt}`,timeout:!1,headers:{Authorization:t,...e},hooks:{afterResponse:[async(e,t,s)=>{if(-1!==s.url.indexOf("heartbeat"))return s;const i=await s.clone().json();if(0!==i.code)throw new Error(JSON.stringify(i)||"请求失败");return s.json=async()=>i,s}]}})}async function ts(e,t,s){const i=es(s),r="api/"+e.replace(/^\/+/,"");return i.post(r,{json:t}).json()}class ss{static requestPermission(){"Notification"in window&&"default"===Notification.permission&&Notification.requestPermission()}static async requestMediaPermissions(){try{const e=await navigator.mediaDevices.enumerateDevices();if(e.some(e=>"audioinput"===e.kind&&""!==e.label))return null;return await navigator.mediaDevices.getUserMedia({audio:!0})}catch(e){return console.warn("获取音频权限失败:",e),null}}static show(e,t,s,i){if("Notification"in window&&"granted"===Notification.permission){const r=new Notification(e,{body:t,tag:`xy-global-notification${(new Date).getTime()}`,renotify:!0});r.onclick=()=>{window.focus(),r.close(),s?.()},setTimeout(()=>r.close(),1e3*(i||3))}}static async checkMediaPermissions(){try{return(await navigator.mediaDevices.enumerateDevices()).some(e=>"audioinput"===e.kind&&""!==e.label)}catch(e){return console.warn("无法检查设备权限:",e),!1}}}const is=(e,t)=>ts(`${Yt}/state/change?h=${t}`,e,{h:t}),rs=()=>async function(e,t){const s=es(),i=e.replace(/^\/+/,"");return s.post(i,{json:t}).json()}("/heartbeat",{}),ns=[],os=["call_number"],as=["call_number"],cs=["hangup"],hs=["hold","hangup","mute","transfer","consult","satisfaction","dtmf"],ds=["hold","hangup","mute","transfer","consult"],ls=["consult_transfer","conference","consult_retrieve"],gs=["hangup"],us=["hangup"],ps=["answer","reject"],fs=["hangup","consult","transfer","hold","mute","satisfaction","dtmf"],ms=["hangup","whisper","force_insert","force_disconnect"],_s=["hangup"],Es=["hangup","cancel_whisper","force_insert"],Ts=["hangup"],ws=["hangup"];class Cs{constructor(){this.roleData={agentInfo:()=>{if(!dt.agentInfo?.agent_no)throw new Error(JSON.stringify({code:1,msg:"请先登录"}))},requestInfo:e=>{if(!e.data)throw new Error(JSON.stringify({code:1,msg:'Parameter "data" is required'}))},changeDevice:e=>{if(!e)throw new Error(JSON.stringify({code:1,msg:'Parameter "device" is required'}));const{answer_devices:t}=dt.agentInfo;if(!t.split(",").map(e=>Number(e)).includes(e))throw new Error(JSON.stringify({code:1,msg:"当前状态不支持"}))},changeState:(e,t)=>{if(!e)throw new Error(JSON.stringify({code:1,msg:'Parameter "state" is required'}));if(!t)throw new Error(JSON.stringify({code:1,msg:'Parameter "state_name" is required'}));if(2===e&&("通话中"===t||"整理"===t))throw new Error(JSON.stringify({code:1,msg:"当前状态不支持"}));if(![1,2].includes(e))throw new Error(JSON.stringify({code:1,msg:"当前状态不支持"}))},setAgentExplicit:e=>{const{out_display_select_switch:t,out_display_data:s}=dt.agentInfo;if(1!==t)throw new Error(JSON.stringify({code:1,msg:"当前坐席设置未开启允许指定外显"}));if(!e)throw new Error(JSON.stringify({code:1,msg:'Parameter "number" is required'}));if(!(s||"").split("#").includes(e))throw new Error(JSON.stringify({code:1,msg:"当前外显号码不存在"}))}},this.changeDevice=async e=>{try{if(gt.get("isCalling"))throw new Error(JSON.stringify({code:1,msg:"当前正在通话中,请勿切换设备"}));this.roleData.agentInfo(),this.roleData.requestInfo(e);const{data:t,success:s}=e,{device:i}=t;1===i&&await Cs.initRtcFn(),this.roleData.changeDevice(i);const{agent_no:r}=dt.agentInfo;await(e=>ts(`${Yt}/device/change`,e))({agent_no:r,answer_device:i}),gt.updateAnswerDevice(i);const n=gt.get("actionConfigs");gt.updateActionConfigs(n),2===i&&dt.stateObject.state===exports.AgentStatus.UNREGISTERED&&await this._changeState({data:{...dt.stateBeforeChange,state_name:dt.stateBeforeChange.state===exports.AgentStatus.IDLE?"空闲":"忙碌"}},"q"),s?.({code:0,msg:"请求成功"})}catch(e){throw ht.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}}formatDate(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")} ${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}:${String(e.getSeconds()).padStart(2,"0")}`}static setInitRtcFn(e){this.initRtcFn=e}async _agentLogin(e){try{const s=await(t={agent_no:e},ts(`${Yt}/agent/login`,t));dt.agentInfo=s.data}catch(e){throw ht.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}var t}async _changeState(e,t){try{dt.autoStateTimer&&(clearTimeout(dt.autoStateTimer),dt.autoStateTimer=null),this.roleData.agentInfo(),this.roleData.requestInfo(e);const{data:s,success:i}=e,{state:r,state_name:n}=s,{agent_no:o}=dt.agentInfo;await is({agent_no:o,state_name:n,state:r},t),r===exports.AgentStatus.IDLE?gt.updateActionConfigs(os):r===exports.AgentStatus.BUSY&>.updateActionConfigs(as),dt.stateObject={state:r,state_name:n},i?.({code:0,msg:"请求成功"})}catch(e){throw ht.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}async _getInCallCrmDetail(e){try{const{phone:t}=e.data,s={};Jt(t)?s.trace_id=t:s.phone=t.replace(/[\s\r\n-]+/g,"");const i=await(e=>ts(`${Kt}/crm/popups`,e))({...s});e.success?.(i)}catch(e){throw ht.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}async changeState(e,t){try{if(gt.get("isCalling"))throw new Error(JSON.stringify({code:1,msg:"当前正在通话中,请勿切换设备"}));dt.autoStateTimer&&(clearTimeout(dt.autoStateTimer),dt.autoStateTimer=null),this.roleData.agentInfo(),this.roleData.requestInfo(e);const{data:s,success:i}=e,{state:r,state_name:n}=s;this.roleData.changeState(r,n);const{agent_no:o}=dt.agentInfo;await is({agent_no:o,state_name:n,state:r},t),(dt.stateObject.state===exports.AgentStatus.IDLE||dt.stateObject.state===exports.AgentStatus.BUSY&&"整理"!==n)&&(dt.stateBeforeChange=dt.stateObject),r===exports.AgentStatus.IDLE?gt.updateActionConfigs(os):r===exports.AgentStatus.BUSY&>.updateActionConfigs(as),dt.stateObject={state:r,state_name:n},i?.({code:0,msg:"请求成功"})}catch(e){throw ht.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}async getIdleAgentList(e){const{agent_no:t}=dt.agentInfo;try{this.roleData.agentInfo();const s=await(e=>ts(`${Yt}/agent/free`,e))({agent_no:t});e.success?.(s)}catch(e){throw ht.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}async getAgentState(e){try{const t=await ts(`${Kt}/agent/statecfg/list`,{}),s=(t.data||[]).filter(e=>0===e.enable).filter(e=>0!==e.state&&3!==e.state).filter(e=>"通话中"!==e.state_name&&"整理"!==e.state_name&&"未注册"!==e.state_name&&"离线接听"!==e.state_name).map(e=>({state:e.state,state_name:e.state_name})).reverse();e.success?.({...t,data:s})}catch(e){throw ht.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}async setAgentExplicit(e){try{this.roleData.agentInfo(),this.roleData.requestInfo(e),this.roleData.setAgentExplicit(e.data.number);const{agent_id:t}=dt.agentInfo;await(e=>ts(`${Kt}/agent/update`,e))({agent_id:t,out_display_number:e.data.number}),gt.updateSelectOutNumber(e.data.number),e.success?.({code:0,msg:"请求成功"})}catch(e){throw ht.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}async checkAgentLogin(e){try{this.roleData.requestInfo(e);const{agent_no:t}=e.data;if(!t)throw new Error(JSON.stringify({code:1,msg:'Parameter "agent_no" is required'}));const s=await(e=>ts(`${Yt}/agent/islogin`,e))({agent_no:t});e.success?.(s)}catch(e){throw ht.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}async getCallRecord(e){try{this.roleData.agentInfo();const{success:t}=e,s=new Date,i=new Date(s.getFullYear(),s.getMonth(),s.getDate(),0,0,0),r=new Date(s.getFullYear(),s.getMonth(),s.getDate(),23,59,59),n=[this.formatDate(i),this.formatDate(r)],{agent_no:o}=dt.agentInfo,a=await(e=>ts(`${Kt}/agent/recordpage`,e))({start_time:n[0],end_time:n[1],page_no:1,page_size:10,agent_no:o}),{code:c,msg:h,data:d}=a;t?.({code:c,msg:h,data:d})}catch(e){throw ht.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}async logout(e){this.roleData.agentInfo();try{const{agent_no:t}=dt.agentInfo,{data:s,success:i}=e;await(e=>ts(`${Yt}/agent/logout`,e))({...s,agent_no:t}),i?.({code:0,msg:""})}catch(e){throw ht.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}async listenCall(e){try{const{agent_no:t}=dt.agentInfo,{data:s,success:i}=e;if(this.roleData.agentInfo(),this.roleData.requestInfo(e),!s.monitored_agent_no)throw new Error(JSON.stringify({code:1,msg:'Parameter "monitored_agent_no" is required'}));await(e=>ts(`${Yt}/call/monitor`,e))({...s,monitor_agent_no:t}),dt.monitoredAgentNo=s.monitored_agent_no,i?.({code:0,msg:""})}catch(e){throw ht.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}async earCall(e){try{const{agentInfo:t,monitoredAgentNo:s}=dt,{agent_no:i}=t;this.roleData.agentInfo();const{success:r}=e;if(!s)throw new Error(JSON.stringify({code:1,msg:"当前未有监听坐席"}));await(e=>ts(`${Yt}/call/whisper`,e))({monitored_agent_no:s,monitor_agent_no:i}),r?.({code:0,msg:""})}catch(e){throw ht.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}async stopEarCall(e){try{const{agentInfo:t,earSpeakAgent:s}=dt;if(!s)throw new Error(JSON.stringify({code:1,msg:"当前没有正在耳语的坐席"}));const{agent_no:i}=t;this.roleData.agentInfo();const{success:r}=e;await(e=>ts(`${Yt}/call/stopwhisper`,e))({monitor_agent_no:i,monitored_agent_no:s}),r?.({code:0,msg:""})}catch(e){throw ht.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}async forceInsert(e){try{const{agentInfo:t,monitoredAgentNo:s}=dt,{agent_no:i}=t;this.roleData.agentInfo();const{success:r}=e;if(!s)throw new Error(JSON.stringify({code:1,msg:"当前未有监听坐席"}));await(e=>ts(`${Yt}/call/bargein`,e))({monitored_agent_no:s,monitor_agent_no:i}),r?.({code:0,msg:""})}catch(e){throw ht.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}async forceDisconnect(e){try{const{agentInfo:t,monitoredAgentNo:s}=dt,{agent_no:i}=t;this.roleData.agentInfo();const{success:r}=e;if(!s)throw new Error(JSON.stringify({code:1,msg:"当前未有监听坐席"}));await(e=>ts(`${Yt}/call/intercept`,e))({monitored_agent_no:s,monitor_agent_no:i}),r?.({code:0,msg:""})}catch(e){throw ht.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}}const Ss=console.log,Is=(...e)=>{dt.logBuiltinEnabled&&Ss(...e)};let vs=null;class ys{constructor(e,t){this.url=e,this.onOpenCallback=t,this.ws=null,this.heartbeatWorker=null,this.reconnectDelay=3e3,this.manualClose=!1,this.apiClient=new Cs,this.sipClient=null,this.pendingMessages=new Map,this.initWebSocket()}static getInstance({url:e,sipClient:t,onOpen:s}){if(!vs){if(!e)throw new Error("WebSocket 尚未初始化");vs=new ys(e,s),vs.sipClient=t}return vs}setSipClient(e){this.sipClient=e}stateIdleChange(e){const{state:t}=dt.stateObject;t!==exports.AgentStatus.IDLE&&this.apiClient._changeState({data:{...dt.stateBeforeChange,state_name:dt.stateBeforeChange.state===exports.AgentStatus.IDLE?"空闲":"忙碌"}},e)}inCallAutoAnswer(){const{soft_device_auto_answer:e,auto_answer_time:t}=dt.agentInfo,s=1===e,i=gt.get("direction");if(s&&i===exports.DirectionEnum.INCOMING){const e=Number(t)||0;e>0&&(dt.autoAnswerTimer=setTimeout(()=>{this.sipClient?.answerCall(),dt.autoAnswerTimer=null},1e3*e-500))}}async getCustomerInfo(e){try{await this.apiClient._getInCallCrmDetail({data:{phone:e},success:e=>{gt.updateCustomerInfo(e.data||{phone:e.data.phone,is_vip:0,customer_name:"未知客户",city:"未知",province:"未知",contact_count:0,in_contact_count:0,trace_id:e.data.trace_id,contact_count_month:0,in_contact_count_month:0})}})}catch(e){}}putAgentState(e,t){if(!e)return;if(5===t)return void this.stateIdleChange("device_type5");dt.sessionId="";const{post_call_process_time:s}=dt.agentInfo,i=s||0;if(dt.autoStateTimer&&(clearTimeout(dt.autoStateTimer),dt.autoStateTimer=null),gt.updateCustomerInfo(void 0),i>0){const{state:e}=dt.stateObject;if(e===exports.AgentStatus.IDLE)return;this.apiClient._changeState({data:{state:exports.AgentStatus.BUSY,state_name:"整理"}},"ez"),dt.autoStateTimer=setTimeout(()=>{dt.autoStateTimer=null,this.stateIdleChange(`delay${i}`)},1e3*i)}else this.stateIdleChange("delay0")}stateBusyChange(){dt.sessionId="",clearTimeout(dt.autoStateTimer),gt.updateCustomerInfo(void 0),this.apiClient._changeState({data:{state:exports.AgentStatus.BUSY,state_name:"忙碌"}},"dm")}initWebSocket(){if(1===this.ws?.readyState)return;if(!gt.get("isNextState")||this.manualClose)return;const e=Vt(zt,Xt);this.ws=new WebSocket(this.url+e),this.ws.onopen=()=>{const e=(new Date).getTime();this.sendMessage({type:0,msg_id:e}),this.pendingMessages.set(e,performance.now()),this.startHeartbeat(),this.manualClose=!1,this.onOpenCallback&&this.onOpenCallback()},this.ws.onmessage=async e=>{const t=JSON.parse(e.data),{type:s,data:i,code:r,msg:n,msg_id:o}=t;if(0===s&&o){const e=this.pendingMessages.get(o),t=performance.now()-e;dt.latency=parseFloat(t.toFixed(2)),this.pendingMessages.delete(o)}if(0!==s&&Is("%cWebSocket 收到消息:","color: blue; font-weight: bold;",t),s!==exports.WebsocketTypeEnum.OUT_CALL&&s!==exports.WebsocketTypeEnum.PREVIEW_OUT_CALL||(0!==r?(gt.reset(),ht.emit(exports.CallSipCallEventEnum.OUT_FAILED,n),ht.emit(exports.EventName.FAIL_NOTIFICATION,n),gt.updateActionConfigs(os),setTimeout(()=>{gt.updateCustomerInfo(void 0)},500),this.stateIdleChange("h")):0===r&&(ht.emit(exports.CallSipCallEventEnum.OUT_SUCCESS),clearTimeout(dt.autoStateTimer))),s===exports.WebsocketTypeEnum.AGENT_STATE){const{state:e,state_name:t}=i;dt.stateObject={state:e,state_name:t},dt.stateBeforeChange?.state||dt.stateObject.state!==exports.AgentStatus.IDLE&&(dt.stateObject.state!==exports.AgentStatus.BUSY||"整理"===t)||(dt.stateBeforeChange=dt.stateObject),"振铃中"===t&>.updateDisplayText(exports.DisplayTextEnum.AGENT_RINGING);const s=gt.get("isCalling");e!==exports.AgentStatus.UNREGISTERED||s||gt.updateActionConfigs(ns),e===exports.AgentStatus.IDLE&&dt.stateObject.state===exports.AgentStatus.UNREGISTERED&>.updateActionConfigs(os),ht.emit(exports.CallSipCallEventEnum.AGENT_STATE,{state:e,state_name:t})}else if(s===exports.WebsocketTypeEnum.OUT_CALL_INCOMING_CALL){try{await this.getCustomerInfo(i.trace_id||i.customer_phone)}catch(e){console.error(e)}i.preview_task_id?ht.emit(exports.CallSipCallEventEnum.PREVIEW_OUT_INCOMING_CALL,{customer_phone:i.customer_phone,session_id:i.session_id,preview_task_id:i.preview_task_id,trace_id:i.trace_id}):0===i.direction?ht.emit(exports.CallSipCallEventEnum.OUT_INCOMING_CALL,{customer_phone:i.customer_phone,session_id:i.session_id,trace_id:i.trace_id}):8===i.direction&&ht.emit(exports.CallSipCallEventEnum.INTERNAL_OUT_INCOMING_CALL,{customer_phone:i.customer_phone,session_id:i.session_id,trace_id:i.trace_id}),dt.sessionId=i.session_id,gt.updateActionConfigs(cs,8!==i.direction)}else if(s===exports.WebsocketTypeEnum.OUT_CALL_END){if(dt.sessionId!==i.session_id)return;if(gt.updateDisplayText(""),1===i.device_type&&i.agent_no===dt.agentInfo.agent_no)gt.reset(),ht.emit(exports.CallSipCallEventEnum.OUT_HANGUP,{session_id:i.session_id}),gt.updateActionConfigs(os),this.putAgentState(!0);else if(2===i.device_type&&i.agent_no===dt.agentInfo.agent_no)gt.reset(),ht.emit(exports.CallSipCallEventEnum.OUR_SIDE_CONSULT_HANGUP,{session_id:i.session_id}),gt.updateActionConfigs(os),this.putAgentState(!0);else if(2===i.device_type&&i.agent_no!==dt.agentInfo.agent_no){gt.get("isCalling")&&(gt.updateDisplayText(exports.DisplayTextEnum.CALLING),ht.emit(exports.CallSipCallEventEnum.OTHER_SIDE_CONSULT_HANGUP,{session_id:i.session_id}),gt.updateActionConfigs(hs))}else if(3===i.device_type&&i.agent_no===dt.agentInfo.agent_no)gt.reset(),ht.emit(exports.CallSipCallEventEnum.THREE_WAY_OUR_SIDE_HANGUP,{session_id:i.session_id}),gt.updateActionConfigs(os),this.putAgentState(!0);else if(4===i.device_type&&i.agent_no===dt.agentInfo.agent_no)gt.reset(),ht.emit(exports.CallSipCallEventEnum.TRANSFER_END,{session_id:i.session_id}),gt.updateActionConfigs(os),this.putAgentState(!0);else if(4===i.device_type&&i.agent_no!==dt.agentInfo.agent_no){ht.emit(exports.CallSipCallEventEnum.TRANSFER_FAILED,"未知原因"),ht.emit(exports.EventName.FAIL_NOTIFICATION,"转接失败");const e=gt.get("direction");e===exports.DirectionEnum.OUTGOING?gt.updateActionConfigs(hs):e===exports.DirectionEnum.INCOMING&>.updateActionConfigs(fs)}else 5===i.device_type&&i.agent_no===dt.agentInfo.agent_no&&(dt.monitoredAgentNo="",dt.earSpeakAgent="",gt.reset(),ht.emit(exports.CallSipCallEventEnum.LISTEN_HANGUP,{session_id:i.session_id}),gt.updateActionConfigs(os),this.putAgentState(!0,5))}else if(s===exports.WebsocketTypeEnum.OUT_CALL_RINGING)1===i.type&&(ht.emit(exports.CallSipCallEventEnum.OUT_RINGING,{session_id:dt.sessionId,type:i.type}),gt.updateDisplayText(exports.DisplayTextEnum.RINGING));else if(s===exports.WebsocketTypeEnum.OUT_CALL_ANSWER)clearTimeout(dt.autoStateTimer),gt.updateIsCalling(!0),gt.updateOutCallIsAnswer(!0),gt.updateDisplayText(exports.DisplayTextEnum.CALLING),8===i.direction?(ht.emit(exports.CallSipCallEventEnum.INTERNAL_OUT_OFF_ANSWER,{session_id:dt.sessionId}),gt.updateActionConfigs(ds)):(ht.emit(exports.CallSipCallEventEnum.OUT_OFF_ANSWER,{session_id:dt.sessionId}),gt.updateActionConfigs(hs));else if(s===exports.WebsocketTypeEnum.CONSULT_RINGING)ht.emit(exports.CallSipCallEventEnum.CONSULT_RINGING,{session_id:i.session_id}),gt.updateDisplayText(exports.DisplayTextEnum.AGENT_RINGING),gt.updateActionConfigs([]),clearTimeout(dt.autoStateTimer);else if(s===exports.WebsocketTypeEnum.CONSULT_ANSWER)ht.emit(exports.CallSipCallEventEnum.CONSULT_OFF_HOOK,{session_id:i.session_id}),gt.updateConsultIsAnswer(!0),gt.updateDisplayText(exports.DisplayTextEnum.CONSULTING),gt.updateActionConfigs(ls);else if(s===exports.WebsocketTypeEnum.CONSULT_FAIL)ht.emit(exports.CallSipCallEventEnum.CONSULT_FAILED,{custom_reason:i.custom_reason}),gt.updateDisplayText(exports.DisplayTextEnum.CALLING),gt.updateActionConfigs(hs);else if(s===exports.WebsocketTypeEnum.CONSULT_CALL_IN)ht.emit(exports.CallSipCallEventEnum.CONSULT_INCOMING,{agent_no:i.agent_no,agent_mane:i.agent_name,session_id:i.session_id}),dt.sessionId=i.session_id,gt.updateIsCalling(!0),gt.updateDirection(exports.DirectionEnum.CONSULT),gt.updateDisplayText(exports.DisplayTextEnum.CONSULT_CALL_IN),gt.updateActionConfigs(ps),dt.enableBrowserAlert&&ss.show("📞 咨询来电",`坐席 [${i.agent_name}] 正在咨询...`,()=>{ht.emit(exports.EventName.NOTIFICATION_CLICK,{agent_mane:i.agent_name,agent_no:i.agent_no})},dt.browserAlertTime);else if(s===exports.WebsocketTypeEnum.CONSULT_CALL_IN_SUCCESS)ht.emit(exports.CallSipCallEventEnum.CONSULT_CALL_IN_SUCCESS,{session_id:i.session_id}),gt.updateConsultIsAnswer(!0),gt.updateDisplayText(exports.DisplayTextEnum.CALLING),gt.updateActionConfigs(gs);else if(s===exports.WebsocketTypeEnum.CONSULT_RETURN_CALL_SUCCESS)"success"===i.status?(gt.updateConsultIsAnswer(!1),ht.emit(exports.CallSipCallEventEnum.CONSULT_RETURN_CALL_SUCCESS),gt.updateDisplayText(exports.DisplayTextEnum.CALLING),ht.emit(exports.CallSipCallEventEnum.OTHER_SIDE_CONSULT_HANGUP),gt.updateActionConfigs(hs)):ht.emit(exports.EventName.FAIL_NOTIFICATION,"媒体失败");else if(s===exports.WebsocketTypeEnum.MUTE)0===r?(gt.updateIsMuted(!0),ht.emit(exports.CallSipCallEventEnum.MUTE_SUCCESS),gt.updateDisplayText(exports.DisplayTextEnum.MUTING)):(ht.emit(exports.CallSipCallEventEnum.MUTE_FAILED,n),ht.emit(exports.EventName.FAIL_NOTIFICATION,n));else if(s===exports.WebsocketTypeEnum.UNMUTE)0===r?(gt.updateIsMuted(!1),ht.emit(exports.CallSipCallEventEnum.UNMUTE_SUCCESS),gt.updateDisplayText(exports.DisplayTextEnum.CALLING)):(ht.emit(exports.CallSipCallEventEnum.UNMUTE_FAILED,n),ht.emit(exports.EventName.FAIL_NOTIFICATION,n));else if(s===exports.WebsocketTypeEnum.CALL_HOLD)0===r?(gt.updateIsHold(!0),gt.updateDisplayText(exports.DisplayTextEnum.HOLDING),ht.emit(exports.CallSipCallEventEnum.HOLD_SUCCESS)):(ht.emit(exports.CallSipCallEventEnum.HOLD_FAILED,n),ht.emit(exports.EventName.FAIL_NOTIFICATION,n));else if(s===exports.WebsocketTypeEnum.CALL_UNHOLD)0===r?(gt.updateDisplayText(exports.DisplayTextEnum.CALLING),gt.updateIsHold(!1),ht.emit(exports.CallSipCallEventEnum.UNHOLD_SUCCESS)):(ht.emit(exports.CallSipCallEventEnum.UNHOLD_FAILED,n),ht.emit(exports.EventName.FAIL_NOTIFICATION,n));else if(s===exports.WebsocketTypeEnum.CONSULT_TRANSFER)0===r?ht.emit(exports.CallSipCallEventEnum.CONSULT_TRANSFER_SUCCESS):(ht.emit(exports.CallSipCallEventEnum.CONSULT_TRANSFER_FAILED,n),ht.emit(exports.EventName.FAIL_NOTIFICATION,n));else if(s===exports.WebsocketTypeEnum.CONSULT_TRANSFER_FAILED)ht.emit(exports.CallSipCallEventEnum.CONSULT_TRANSFER_FAILED,i.status);else if(s===exports.WebsocketTypeEnum.CONSULT_TRANSFER_OFF_HOOK)gt.updateDirection(exports.DirectionEnum.INCOMING),gt.updateDisplayText(exports.DisplayTextEnum.CALLING),ht.emit(exports.CallSipCallEventEnum.CONSULT_TRANSFER_OFF_HOOK),gt.updateActionConfigs(fs),gt.updateIncomingIsAnswer(!0),gt.updateConsultIsAnswer(!1);else if(s===exports.WebsocketTypeEnum.INCOMING_CALL){clearTimeout(dt.autoStateTimer),dt.sessionId=i.session_id;try{await this.getCustomerInfo(i.trace_id||i.customer_phone)}catch(e){console.error(e)}gt.updateIsCalling(!0),gt.updateDirection(exports.DirectionEnum.INCOMING),gt.updateDisplayText(exports.DisplayTextEnum.INCOMING_CALL),this.inCallAutoAnswer(),1===i.direction&&ht.emit(exports.CallSipCallEventEnum.INCOMING_CALL,{customer_phone:i.customer_phone,trace_id:i.trace_id,session_id:i.session_id}),8===i.direction&&ht.emit(exports.CallSipCallEventEnum.INCOMING_CALL_IN,{customer_phone:i.customer_phone,trace_id:i.trace_id,session_id:i.session_id}),3===i.direction&&ht.emit(exports.CallSipCallEventEnum.PREDICT_INCOMING_CALL,{customer_phone:i.customer_phone,trace_id:i.trace_id,session_id:i.session_id}),6===i.direction&&ht.emit(exports.CallSipCallEventEnum.DUAL_CALL_INCOMING_CALL,{customer_phone:i.customer_phone,trace_id:i.trace_id,session_id:i.session_id}),gt.updateActionConfigs(ps),dt.enableBrowserAlert&&ss.show("📞 客户来电",`客户 [${i.customer_phone}] 正在呼入...`,()=>{ht.emit(exports.EventName.NOTIFICATION_CLICK,{customer_phone:i.customer_phone})},dt.browserAlertTime)}else if(s===exports.WebsocketTypeEnum.INCOMING_CALL_OFF_HOOK)gt.updateIncomingIsAnswer(!0),8===i.direction?(gt.updateActionConfigs(ds),ht.emit(exports.CallSipCallEventEnum.INCOMING_CALL_IN_OFF_HOOK,{session_id:dt.sessionId})):(gt.updateActionConfigs(fs),ht.emit(exports.CallSipCallEventEnum.INCOMING_CALL_OFF_HOOK,{session_id:dt.sessionId})),gt.updateDisplayText(exports.DisplayTextEnum.CALLING);else if(s===exports.WebsocketTypeEnum.INCOMING_CALL_END){if(dt.sessionId!==i.session_id)return;if(gt.updateDisplayText(""),1!==i.device_type&&7!==i.device_type||i.agent_no!==dt.agentInfo.agent_no)if(2===i.device_type&&i.agent_no===dt.agentInfo.agent_no)gt.reset(),ht.emit(exports.CallSipCallEventEnum.OUR_SIDE_CONSULT_HANGUP,{session_id:i.session_id}),this.putAgentState(!0),gt.updateActionConfigs(os);else if(2===i.device_type&&i.agent_no!==dt.agentInfo.agent_no)gt.updateDisplayText(exports.DisplayTextEnum.CALLING),ht.emit(exports.CallSipCallEventEnum.OTHER_SIDE_CONSULT_HANGUP,{session_id:i.session_id}),gt.updateActionConfigs(hs);else if(3===i.device_type&&i.agent_no===dt.agentInfo.agent_no)this.putAgentState(!0),gt.reset(),ht.emit(exports.CallSipCallEventEnum.THREE_WAY_OUR_SIDE_HANGUP,{session_id:i.session_id}),gt.updateActionConfigs(os);else if(4===i.device_type&&i.agent_no===dt.agentInfo.agent_no)this.putAgentState(!0),gt.reset(),ht.emit(exports.CallSipCallEventEnum.TRANSFER_END,{session_id:i.session_id}),gt.updateActionConfigs(os);else if(4===i.device_type&&i.agent_no!==dt.agentInfo.agent_no){ht.emit(exports.CallSipCallEventEnum.TRANSFER_FAILED,"未知原因"),ht.emit(exports.EventName.FAIL_NOTIFICATION,"转接失败");const e=gt.get("direction");e===exports.DirectionEnum.OUTGOING?gt.updateActionConfigs(hs):e===exports.DirectionEnum.INCOMING&>.updateActionConfigs(fs)}else 5===i.device_type&&i.agent_no===dt.agentInfo.agent_no&&(this.putAgentState(!0,5),dt.monitoredAgentNo="",dt.earSpeakAgent="",gt.reset(),ht.emit(exports.CallSipCallEventEnum.LISTEN_HANGUP,{session_id:i.session_id}),gt.updateActionConfigs(os));else this.putAgentState(!0),gt.reset(),ht.emit(exports.CallSipCallEventEnum.INCOMING_CALL_END,{session_id:i.session_id}),gt.updateActionConfigs(os)}else if(s===exports.WebsocketTypeEnum.SATISFACTION_EVALUATION)0===r?ht.emit(exports.CallSipCallEventEnum.SATISFACTION_EVALUATION_SUCCESS):(ht.emit(exports.CallSipCallEventEnum.SATISFACTION_EVALUATION_FAILED,n),ht.emit(exports.EventName.FAIL_NOTIFICATION,n));else if(s===exports.WebsocketTypeEnum.CONSULT_THREE_WAY)0!==r?(ht.emit(exports.CallSipCallEventEnum.CONSULT_THREE_WAY_FAILED,n),ht.emit(exports.EventName.FAIL_NOTIFICATION,n)):0===r&>.updateIsMeeting(!0);else if(s===exports.WebsocketTypeEnum.CONSULT_THREE_WAY_RESULT)"success"===i.status?(gt.updateDirection(exports.DirectionEnum.MEETING),gt.updateDisplayText(exports.DisplayTextEnum.MEETING),gt.updateActionConfigs(us),ht.emit(exports.CallSipCallEventEnum.CONSULT_THREE_WAY_SUCCESS)):(ht.emit(exports.CallSipCallEventEnum.CONSULT_THREE_WAY_FAILED,{conf_name:i.conf_name}),gt.updateIsMeeting(!1));else if(s===exports.WebsocketTypeEnum.TRANSFER_INCOMING_CALL)clearTimeout(dt.autoStateTimer),i.agent_no===dt.agentInfo.agent_no?(gt.updateDisplayText(exports.DisplayTextEnum.TRANSFERRING),ht.emit(exports.CallSipCallEventEnum.TRANSFER_PROGRESS),gt.updateActionConfigs([]),gt.updateTransferIsAnswer(!0)):(dt.sessionId=i.session_id,ht.emit(exports.CallSipCallEventEnum.TRANSFER_INCOMING_CALL,{agent_no:i.agent_no,agent_name:i.agent_name,session_id:i.session_id}),gt.updateIsCalling(!0),gt.updateDirection(exports.DirectionEnum.TRANSFER),gt.updateDisplayText(exports.DisplayTextEnum.TRANSFER_INCOMING_CALL),gt.updateActionConfigs(ps),dt.enableBrowserAlert&&ss.show("📞 转接来电",`坐席 [${i.agent_no}] 正在转接...`,()=>{ht.emit(exports.EventName.NOTIFICATION_CLICK,{agent_no:i.agent_no})},dt.browserAlertTime));else if(s===exports.WebsocketTypeEnum.TRANSFER_OFF_HOOK)ht.emit(exports.CallSipCallEventEnum.TRANSFER_OFF_HOOK,{session_id:dt.sessionId}),gt.updateTransferIsAnswer(!1),gt.updateDisplayText(exports.DisplayTextEnum.CALLING),gt.updateActionConfigs(fs,8!==i.direction);else if(s===exports.WebsocketTypeEnum.TRANSFER_FAILED){if("failed"===i.status){ht.emit(exports.CallSipCallEventEnum.TRANSFER_FAILED,"未知原因"),ht.emit(exports.EventName.FAIL_NOTIFICATION,"转接失败");const e=gt.get("direction");e===exports.DirectionEnum.OUTGOING?gt.updateActionConfigs(hs):e===exports.DirectionEnum.INCOMING&>.updateActionConfigs(fs)}}else s===exports.WebsocketTypeEnum.KICK_OFFLINE?ht.emit(exports.EventName.KICK_OFF):s===exports.WebsocketTypeEnum.CONTINUOUS_NOT_ANSWER?(ht.emit(exports.EventName.FAIL_NOTIFICATION,`已连续 ${i.miss_count} 次未接, 设置忙碌`),this.stateBusyChange()):s===exports.WebsocketTypeEnum.SIGN_OUT?ht.emit(exports.EventName.SIGN_OUT):s===exports.WebsocketTypeEnum.SIGN_IN_SWITCH_DEVICE?ht.emit(exports.EventName.SIGN_IN_SWITCH_DEVICE,i):s===exports.WebsocketTypeEnum.LISTEN_INCOMING_CALL?(clearTimeout(dt.autoStateTimer),dt.sessionId=i.session_id,gt.updateIsCalling(!0),gt.updateDirection(exports.DirectionEnum.INCOMING),this.inCallAutoAnswer(),gt.updateDisplayText(exports.DisplayTextEnum.LISTENING),gt.updateActionConfigs(ps),ht.emit(exports.CallSipCallEventEnum.LISTEN_INCOMING_CALL,{session_id:i.session_id}),dt.enableBrowserAlert&&ss.show("📞 监听来电","正在来电...",()=>{ht.emit(exports.EventName.NOTIFICATION_CLICK,{customer_phone:i.customer_phone})},dt.browserAlertTime)):s===exports.WebsocketTypeEnum.LISTEN_INCOMING_CALL_OFF_HOOK?(dt.monitoredAgentNo=i.monitored_agent_no,dt.earSpeakAgent="",gt.updateIncomingIsAnswer(!0),ht.emit(exports.CallSipCallEventEnum.LISTEN_INCOMING_CALL_OFF_HOOK,{session_id:dt.sessionId,monitored_agent_no:i.monitored_agent_no}),gt.updateActionConfigs(ms),gt.updateDisplayText(exports.DisplayTextEnum.CALLING)):s===exports.WebsocketTypeEnum.LISTEN_CALL_FAILED?"failed"===i.status&&(ht.emit(exports.CallSipCallEventEnum.LISTEN_CALL_FAILED),dt.monitoredAgentNo=""):s===exports.WebsocketTypeEnum.EAR_SPEECH?"success"===i.status?(i.monitored_agent_no===dt.agentInfo.agent_no&&(gt.updateActionConfigs(_s),ht.emit(exports.CallSipCallEventEnum.EAR_SPEECH_BE_SUCCESS)),i.monitor_agent_no===dt.agentInfo.agent_no&&(gt.updateActionConfigs(Es),ht.emit(exports.CallSipCallEventEnum.EAR_SPEECH_SUCCESS,{monitored_agent_no:i.monitored_agent_no,monitor_agent_no:i.monitor_agent_no}),dt.earSpeakAgent=i.monitored_agent_no)):ht.emit(exports.CallSipCallEventEnum.EAR_SPEECH_FAILED):s===exports.WebsocketTypeEnum.STOP_EAR_SPEECH?"success"===i.status?(i.monitored_agent_no===dt.agentInfo.agent_no&>.updateActionConfigs(fs),i.monitor_agent_no===dt.agentInfo.agent_no&>.updateActionConfigs(ms),dt.earSpeakAgent="",ht.emit(exports.CallSipCallEventEnum.STOP_EAR_SPEECH_SUCCESS)):ht.emit(exports.CallSipCallEventEnum.STOP_EAR_SPEECH_FAILED):s===exports.WebsocketTypeEnum.CALL_FORCE_INSERT?"success"===i.status?(i.monitored_agent_no===dt.agentInfo.agent_no&&(gt.updateActionConfigs(ws),ht.emit(exports.CallSipCallEventEnum.CALL_FORCE_INSERT_SUCCESS,{monitored_agent_no:i.monitored_agent_no,monitor_agent_no:i.monitor_agent_no})),i.monitor_agent_no===dt.agentInfo.agent_no&&(gt.updateActionConfigs(Ts),ht.emit(exports.CallSipCallEventEnum.CALL_FORCE_INSERT_SUCCESS_LISTENER,{monitored_agent_no:i.monitored_agent_no,monitor_agent_no:i.monitor_agent_no}))):ht.emit(exports.CallSipCallEventEnum.CALL_FORCE_INSERT_FAILED):s===exports.WebsocketTypeEnum.INTERNAL_CALL_START_CONSULT?i.agent_no===dt.agentInfo.agent_no?(gt.updateConsultIsAnswer(!0),gt.updateActionConfigs(ls),gt.updateDisplayText(exports.DisplayTextEnum.CONSULTING)):(gt.updateDisplayText(exports.DisplayTextEnum.OTHER_SIDE_CONSULTING),gt.updateActionConfigs([])):s===exports.WebsocketTypeEnum.INTERNAL_CALL_END_CONSULT?(gt.updateActionConfigs(ds),gt.updateDisplayText(""),gt.updateConsultIsAnswer(!1)):s===exports.WebsocketTypeEnum.CALL_SIP_INCOMING_CALL&&ht.emit(exports.CallSipCallEventEnum.CALL_SIP_INCOMING_CALL)},this.ws.onclose=e=>{ht.emit(exports.EventName.FAIL_NOTIFICATION,"链接已断开,请检查网络"),this.stopHeartbeat();const t=gt.get("isNextState");!this.manualClose&&t&&setTimeout(()=>this.initWebSocket(),this.reconnectDelay)},this.ws.onerror=e=>{ht.emit(exports.EventName.FAIL_NOTIFICATION,"连接失败,请检查网络"),this.ws?.close()}}startHeartbeat(){const e=new Blob(["\n let timer;\n self.onmessage = function (e) {\n if (e.data === 'start') {\n timer = setInterval(() => {\n self.postMessage('heartbeat');\n }, 5000);\n } else if (e.data === 'stop') {\n clearInterval(timer);\n }\n };\n "],{type:"application/javascript"}),t=URL.createObjectURL(e);this.heartbeatWorker=new Worker(t),this.heartbeatWorker.onmessage=()=>{const e=(new Date).getTime();this.sendMessage({type:0,msg_id:e}),this.pendingMessages.set(e,performance.now())},this.heartbeatWorker.postMessage("start")}stopHeartbeat(){this.heartbeatWorker&&(this.heartbeatWorker.postMessage("stop"),this.heartbeatWorker.terminate(),this.heartbeatWorker=null)}sendMessage(e){this.ws?.readyState===WebSocket.OPEN?(this.ws.send(JSON.stringify(e)),0!==e.type&&Is("%cWebSocket 发送消息:","color: green; font-weight: bold;",e)):console.warn("WebSocket 未连接,消息未发送")}close(){this.manualClose=!0,this.stopHeartbeat(),this.ws?.close()}reconnect(){this.initWebSocket()}static __internalClose(){vs&&(vs.close(),vs=null)}static __internalSend(e){if(!vs)throw new Error("WebSocket 尚未初始化");vs.sendMessage(e)}}class As{constructor(e){this.sipClient=null,this.sipClient=e}roleMute(){const e=gt.get("isCalling"),t=dt.sessionId;if(!e)throw new Error(JSON.stringify({code:1,msg:"当前没有通话"}));if(!t)throw new Error(JSON.stringify({code:1,msg:"当前没有通话"}))}holdCall(){this.roleMute();const e=gt.get("isHold"),{sessionId:t}=dt;if(!t)return;if(!gt.get("actionConfigs").includes("hold"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿保持"}));if(e)throw new Error(JSON.stringify({code:1,msg:"当前已处于保持状态"}));ys.__internalSend({type:exports.WebsocketTypeEnum.CALL_HOLD,data:{session_id:t}})}unholdCall(){this.roleMute();const{isHold:e}=gt.getState(),{sessionId:t}=dt;if(!gt.get("actionConfigs").includes("unhold"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿取消保持"}));if(t){if(!e)throw new Error(JSON.stringify({code:1,msg:"当前未处于保持状态"}));ys.__internalSend({type:exports.WebsocketTypeEnum.CALL_UNHOLD,data:{session_id:t}})}}sendDTMF(e){if(1!==gt.get("answerDevice"))throw new Error(JSON.stringify({code:1,msg:"当前设备不支持此功能"}));if(!gt.get("actionConfigs").includes("dtmf"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿发送按键"}));const{isCalling:t}=gt.getState();if(!t)throw new Error(JSON.stringify({code:1,msg:"当前没有通话"}));this.sipClient.sendDTMF(e)}cancelCall(){if(!gt.get("isCalling"))throw new Error(JSON.stringify({code:1,msg:"当前没有通话"}));const e=dt.sessionId;ht.emit(exports.CallSipCallEventEnum.REJECT,{session_id:e}),ys.__internalSend({type:exports.WebsocketTypeEnum.AGENT_HANGUP,data:{session_id:e}})}async consultCall(e){this.roleMute();const{isCalling:t,outCallIsAnswer:s,consultIsAnswer:i,incomingIsAnswer:r}=gt.getState(),n=dt.sessionId;if(!gt.get("actionConfigs").includes("consult"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿调用咨询"}));if(i)throw new Error(JSON.stringify({code:1,msg:"当前正在咨询"}));if(!(t||s||r))throw new Error(JSON.stringify({code:1,msg:"当前没有通话"}));if(!n)throw new Error(JSON.stringify({code:1,msg:"sessionId不存在"}));ys.__internalSend({type:exports.WebsocketTypeEnum.CONSULT_REQUEST,data:{session_id:n,consultation_agent_no:e}})}async answerCall(){if(1!==gt.get("answerDevice"))throw new Error(JSON.stringify({code:1,msg:"当前设备不支持此功能"}));await this.sipClient.answerCall()}makeCall(e){if("string"!=typeof e||""===e.trim())throw new Error(JSON.stringify({code:1,msg:"外呼号码非法"}));const t={};Jt(e)?t.trace_id=e:t.customer_phone=e.replace(/[\s\r\n-]+/g,"");const s=gt.get("isCalling"),i=gt.get("selectOutNumber")||"";if(s)throw new Error(JSON.stringify({code:1,msg:"正在呼叫中,请勿重复点击"}));gt.updateIsCalling(!0),gt.updateDirection(exports.DirectionEnum.OUTGOING),ys.__internalSend({type:exports.WebsocketTypeEnum.OUT_CALL,data:{...t,caller:i.replace(/[\s\r\n-]+/g,"")}})}previewCall(e,t){const s={};Jt(e)?s.trace_id=e:s.customer_phone=e.replace(/[\s\r\n-]+/g,"");const i=gt.get("isCalling"),r=gt.get("selectOutNumber")||"";if(i)throw new Error(JSON.stringify({code:1,msg:"正在呼叫中,请勿重复点击"}));if("string"!=typeof e||""===e.trim())throw new Error(JSON.stringify({code:1,msg:"外呼号码非法"}));gt.updateIsCalling(!0),gt.updateDirection(exports.DirectionEnum.OUTGOING),ys.__internalSend({type:exports.WebsocketTypeEnum.PREVIEW_OUT_CALL,data:{...s,caller:r,preview_task_id:t}})}async hangup(){if(!gt.get("isCalling"))throw new Error(JSON.stringify({code:1,msg:"当前没有通话"}));const e=dt.sessionId;ys.__internalSend({type:exports.WebsocketTypeEnum.AGENT_HANGUP,data:{session_id:e}})}mute(){this.roleMute();const e=gt.get("actionConfigs"),t=gt.get("isMuted"),s=dt.sessionId;if(t)throw new Error(JSON.stringify({code:1,msg:"当前未处于静音状态"}));if(!e.includes("mute"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿调用静音"}));ys.__internalSend({type:exports.WebsocketTypeEnum.MUTE,data:{session_id:s}})}unmute(){this.roleMute();const e=gt.get("actionConfigs"),t=gt.get("isMuted"),s=dt.sessionId;if(!t)throw new Error(JSON.stringify({code:1,msg:"当前未处于未静音状态"}));if(!e.includes("unmute"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿调用静音"}));ys.__internalSend({type:exports.WebsocketTypeEnum.UNMUTE,data:{session_id:s}})}consultTransfer(){this.roleMute();const e=gt.get("consultIsAnswer"),t=dt.sessionId;if(!gt.get("actionConfigs").includes("consult_transfer"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿调用咨询转移"}));if(!e)throw new Error(JSON.stringify({code:1,msg:"当前未处于咨询中"}));ys.__internalSend({type:exports.WebsocketTypeEnum.CONSULT_TRANSFER,data:{session_id:t}})}satisfactionEvaluation(){this.roleMute();const e=dt.sessionId;if(!gt.get("actionConfigs").includes("satisfaction"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿调用满意度评价"}));ys.__internalSend({type:exports.WebsocketTypeEnum.SATISFACTION_EVALUATION,data:{session_id:e}})}startConference(){this.roleMute();if(!gt.get("actionConfigs").includes("conference"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿调用三方会议"}));const e=dt.sessionId;if(!gt.get("consultIsAnswer"))throw new Error(JSON.stringify({code:1,msg:"当前未处于咨询中"}));ys.__internalSend({type:exports.WebsocketTypeEnum.CONSULT_THREE_WAY,data:{session_id:e}})}consultRetrieve(){this.roleMute();if(!gt.get("actionConfigs").includes("consult_retrieve"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿取回通话"}));const e=dt.sessionId;if(!gt.get("consultIsAnswer"))throw new Error(JSON.stringify({code:1,msg:"当前未处于咨询中"}));ys.__internalSend({type:exports.WebsocketTypeEnum.CONSULT_RETURN_CALL,data:{session_id:e}})}async transferAgent(e){this.roleMute();if(!gt.get("actionConfigs").includes("transfer"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿转接"}));const{transferIsAnswer:t}=gt.getState(),s=dt.sessionId;if(t)throw new Error(JSON.stringify({code:1,msg:"当前正在转接"}));ys.__internalSend({type:exports.WebsocketTypeEnum.TRANSFER,data:{session_id:s,transfer_type:0,transfer_dest:e}})}async transferOutline(e){this.roleMute();if(!gt.get("actionConfigs").includes("transfer"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿转接"}));if(!e)throw new Error(JSON.stringify({code:1,msg:"号码不能为空"}));if(!/^\d+$/.test(e))throw new Error(JSON.stringify({code:1,msg:"号码格式错误"}));const{transferIsAnswer:t}=gt.getState(),s=dt.sessionId;if(t)throw new Error(JSON.stringify({code:1,msg:"当前正在转接"}));if(t)throw new Error(JSON.stringify({code:1,msg:"当前正在转接"}));ys.__internalSend({type:exports.WebsocketTypeEnum.TRANSFER,data:{session_id:s,transfer_type:2,transfer_dest:e}})}}var bs;class Rs{static{this._instance=null}#e;#t;#s;#i;#r;#n;#o;static{this._timer=null}constructor(){if(this.#e=null,this.#t=new Cs,this.#i=null,this.#o=!1,this.#a=()=>{},this.#c=()=>{},this.initWebRtc=async()=>{if(this.#e)return;const e=dt.agentInfo.sip_account_list.find(e=>1===e.device_type);if(!e)throw new Error(JSON.stringify({code:1,msg:"未找到 sip_account_list"}));{const t=e.sip_register_addr;this.#e=new pt({server:t.split(":")[0],user:e.sip_account,password:e.sip_password,webSocket:`wss://${t}`,callTimeout:3e4},this.#h),await this.#e.start()}},this.#h=e=>{const{type:t,data:s}=e;ht.emit(t,s)},!bs._creatingInstance)throw new Error("请使用 YSYTAgentSdk.getInstance() 获取实例");clearInterval(this.#i),this.#i=setInterval(async()=>{const e=await this.#d();ut.updateRttObject(e)},2e3),ss.requestMediaPermissions(),this.#n=gt.subscribeKey("isNextState",async e=>{if(e){1===gt.get("answerDevice")&&await this.#e.reconnect();let e="";const t=new URL(Zt).host;e=Zt.includes("https")?`wss://${t}`:`ws://${t}`;const{agent_no:s}=dt.agentInfo;ys.getInstance({url:`${e}/ccs-ws/api/v1/ws/call/${s}?Authorization=`,sipClient:this.#e}),setTimeout(()=>{this.#t._changeState({data:{state:exports.AgentStatus.BUSY,state_name:"忙碌"},success:()=>{gt.updateDisplayText(""),ht.emit(exports.CallSipCallEventEnum.AGENT_STATE,{state:exports.AgentStatus.BUSY,state_name:"忙碌"})}},"d")},10)}else ys.__internalClose(),gt.updateIsCalling(!1),gt.updateOutCallIsAnswer(!1),gt.updateIncomingIsAnswer(!1),gt.updateIsMuted(!1),gt.updateConsultIsAnswer(!1),gt.updateIsHold(!1),gt.updateCustomerInfo(void 0),gt.updateDisplayText("离线")}),this.#r=gt.subscribeKey("answerDevice",async e=>{1===e?dt.stateObject.state===exports.AgentStatus.UNREGISTERED&&await this.#t._changeState({data:{...dt.stateBeforeChange,state_name:dt.stateBeforeChange.state===exports.AgentStatus.IDLE?"空闲":"忙碌"}},"qq"):await this.destroyRtc()}),this.on(exports.EventName.KICK_OFF,()=>{this.destroy()}),window.addEventListener("beforeunload",e=>{e.returnValue="",this.destroy()}),window.addEventListener("online",this.#a),window.addEventListener("offline",this.#c)}#a;#c;async#l(){const e=gt.get("isNextState");try{await rs(),e||gt.updateIsNextState(!0)}catch(t){ht.emit(exports.EventName.FAIL_NOTIFICATION,"网络断开,请检查网络"),e&>.updateIsNextState(!1)}}#g(){bs._timer||(bs._timer=setInterval(()=>this.#l(),3e3))}static get instance(){return this._instance}static async destroyInstance(){this._instance&&(await this._instance.destroy(),this._instance=null)}static getInstance(e){if(!this._instance){if(!e)throw new Error("首次调用必须传入配置参数");const{url:t,appKey:s,appSecret:i,agentNo:r}=e;Zt=t||"https://aicc-api.yescloudy.com",zt=s,Xt=i,Qt=r,bs._creatingInstance=!0,this._instance=new bs,delete bs._creatingInstance}return this._instance}getInit(){return this.#o}async init({enableBrowserAlert:e,logBuiltinEnabled:t,browserAlertTime:s}){try{let i="";const r=new URL(Zt).host;i=Zt.includes("https")?`wss://${r}`:`ws://${r}`;const n=ys.getInstance({url:`${i}/ccs-ws/api/v1/ws/call/${Qt}?Authorization=`,sipClient:null,onOpen:async()=>{dt.logBuiltinEnabled=t||!1,dt.browserAlertTime=s||5e3,await this.#t._agentLogin(Qt);const{current_answer_device:i,current_state:r,out_display_number:o,out_display_select_switch:a}=dt.agentInfo;r===exports.AgentStatus.IDLE?(gt.updateActionConfigs(os),dt.stateObject={state:r,state_name:"空闲"},dt.stateBeforeChange=dt.stateObject):r===exports.AgentStatus.BUSY?(gt.updateActionConfigs(as),dt.stateObject={state:r,state_name:"忙碌"},dt.stateBeforeChange=dt.stateObject):r===exports.AgentStatus.UNREGISTERED&&(gt.updateActionConfigs(as),dt.stateObject={state:r,state_name:"未注册"}),1===a?gt.updateSelectOutNumber(o):gt.updateSelectOutNumber(""),gt.updateAnswerDevice(i),Cs.setInitRtcFn(this.initWebRtc),1===i&&(await this.initWebRtc(),n.setSipClient(this.#e)),this.#s=new As(this.#e),dt.enableBrowserAlert=e,e&&ss.requestPermission(),ht.emit(exports.EventName.AGENT_INIT_STATUS,!0),this.#o=!0,clearInterval(bs._timer),bs._timer=null,this.#g()}})}catch(e){ht.emit(exports.EventName.AGENT_INIT_STATUS,!1),this.#o=!1}}#h;on(e,t){return ht.on(e,t),this}off(e,t){ht.off(e,t)}offAll(){ht.clearAllListeners()}async destroyRtc(){await(this.#e?.destroy()),this.#e=null}async destroy(){bs._instance&&(await this.destroyRtc(),this.#r?.(),this.#n?.(),clearInterval(this.#i),ys.__internalClose(),ht.emit(exports.EventName.DESTROY),this.offAll(),bs._instance=null,gt.reset(),gt.updateSelectOutNumber(""),clearInterval(bs._timer),bs._timer=null)}async#d(){return this.#e?this.#e.getNetworkStats():{}}get call_api(){const e=e=>(...t)=>e.apply(this,t);return{answerCall:e(()=>this.#s.answerCall()),makeCall:e=>this.#s.makeCall(e),previewMakeCall:(e,t)=>this.#s.previewCall(e,t),cancelCall:e(()=>this.#s.cancelCall()),hangup:e(()=>this.#s.hangup()),sendDTMF:e(e=>this.#s.sendDTMF(e)),holdCall:e(()=>this.#s.holdCall()),unholdCall:e(()=>this.#s.unholdCall()),consultCall:e(async e=>{try{await this.#s.consultCall(e)}catch(e){throw console.warn(e),e}}),consultRetrieve:e(()=>this.#s.consultRetrieve()),consultTransfer:e(()=>this.#s.consultTransfer()),mute:e(()=>this.#s.mute()),unmute:e(()=>this.#s.unmute()),satisfactionEvaluation:e(()=>this.#s.satisfactionEvaluation()),startConference:e(()=>this.#s.startConference()),transferAgent:e(e=>this.#s.transferAgent(e)),transferOutline:e(e=>this.#s.transferOutline(e)),earSpeakStart:e(e=>this.#t.earCall(e)),earSpeakStop:e(e=>this.#t.stopEarCall(e)),forceInsert:e(e=>this.#t.forceInsert(e)),forceDisconnect:e(e=>this.#t.forceDisconnect(e))}}get agent_api(){const e=e=>(...t)=>e.apply(this,t);return{changeDevice:e(e=>this.#t.changeDevice(e)),changeState:e(async e=>{const t=gt.get("answerDevice");if(dt.stateObject.state===exports.AgentStatus.UNREGISTERED&&1===t){await this.#e.reconnect();let e="";const t=new URL(Zt).host;e=Zt.includes("https")?`wss://${t}`:`ws://${t}`;const{agent_no:s}=dt.agentInfo;ys.getInstance({url:`${e}/ccs-ws/api/v1/ws/call/${s}?Authorization=`,sipClient:this.#e})}await this.#t.changeState(e,"c")}),getIdleAgentList:e(e=>this.#t.getIdleAgentList(e)),getAgentState:e(e=>this.#t.getAgentState(e)),setAgentExplicit:e(e=>this.#t.setAgentExplicit(e)),checkAgentLogin:e=>this.#t.checkAgentLogin(e),getCallRecord:e=>this.#t.getCallRecord(e),agentLogout:async(e,t)=>{try{await this.#t.logout(e),await this.destroy(),t?.({code:0,msg:""})}catch(e){}},listenAgentCall:e=>this.#t.listenCall(e)}}getAgentData(){const{agent_no:e,agent_name:t,answer_devices:s,out_display_data:i,out_display_select_switch:r,current_state:n}=dt.agentInfo,{stateObject:o}=dt,a={1:"软电话",2:"手机模式",3:"SIP话机"};return{agent_no:e,agent_name:t,init_state:n,default_device:gt.get("answerDevice"),out_display_data:i,out_display_select_switch:r,answer_devices:(s||"").split(",").map(e=>({value:Number(e),label:a[Number(e)]})),stateObject:o}}async getRealTimeCustomerInfo(){return gt.get("customerObject")}setBrowserAlert(e){if("boolean"!=typeof e)throw new Error(JSON.stringify({code:1,msg:"参数类型错误"}));dt.logBuiltinEnabled=e||!1}setBrowserAlertTime(e){if("number"!=typeof e)throw new Error(JSON.stringify({code:1,msg:"参数类型错误"}));dt.browserAlertTime=e||3e3}}bs=Rs,exports.default=Rs;
|
|
@@ -9,4 +9,4 @@ import e from"crypto";import t from"buffer";class s extends Error{constructor(e)
|
|
|
9
9
|
* @copyright Chen, Yi-Cyuan 2014-2023
|
|
10
10
|
* @license MIT
|
|
11
11
|
*/
|
|
12
|
-
Mt=Bt,function(){var s="input is invalid type",i="object"==typeof window,r=i?window:{};r.JS_MD5_NO_WINDOW&&(i=!1);var n=!i&&"object"==typeof self,o=!r.JS_MD5_NO_NODE_JS&&"object"==typeof process&&process.versions&&process.versions.node;o?r=jt:n&&(r=self);var a,c=!r.JS_MD5_NO_COMMON_JS&&Mt.exports,h=!r.JS_MD5_NO_ARRAY_BUFFER&&"undefined"!=typeof ArrayBuffer,d="0123456789abcdef".split(""),l=[128,32768,8388608,-2147483648],g=[0,8,16,24],u=["hex","array","digest","buffer","arrayBuffer","base64"],p="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),f=[];if(h){var m=new ArrayBuffer(68);a=new Uint8Array(m),f=new Uint32Array(m)}var _=Array.isArray;!r.JS_MD5_NO_NODE_JS&&_||(_=function(e){return"[object Array]"===Object.prototype.toString.call(e)});var w=ArrayBuffer.isView;!h||!r.JS_MD5_NO_ARRAY_BUFFER_IS_VIEW&&w||(w=function(e){return"object"==typeof e&&e.buffer&&e.buffer.constructor===ArrayBuffer});var T=function(e){var t=typeof e;if("string"===t)return[e,!0];if("object"!==t||null===e)throw new Error(s);if(h&&e.constructor===ArrayBuffer)return[new Uint8Array(e),!1];if(!_(e)&&!w(e))throw new Error(s);return[e,!1]},I=function(e){return function(t){return new E(!0).update(t)[e]()}},S=function(i){var n,o=e,a=t.Buffer;return n=a.from&&!r.JS_MD5_NO_BUFFER_FROM?a.from:function(e){return new a(e)},function(e){if("string"==typeof e)return o.createHash("md5").update(e,"utf8").digest("hex");if(null==e)throw new Error(s);return e.constructor===ArrayBuffer&&(e=new Uint8Array(e)),_(e)||w(e)||e.constructor===a?o.createHash("md5").update(n(e)).digest("hex"):i(e)}},C=function(e){return function(t,s){return new v(t,!0).update(s)[e]()}};function E(e){if(e)f[0]=f[16]=f[1]=f[2]=f[3]=f[4]=f[5]=f[6]=f[7]=f[8]=f[9]=f[10]=f[11]=f[12]=f[13]=f[14]=f[15]=0,this.blocks=f,this.buffer8=a;else if(h){var t=new ArrayBuffer(68);this.buffer8=new Uint8Array(t),this.blocks=new Uint32Array(t)}else this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];this.h0=this.h1=this.h2=this.h3=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0}function v(e,t){var s,i=T(e);if(e=i[0],i[1]){var r,n=[],o=e.length,a=0;for(s=0;s<o;++s)(r=e.charCodeAt(s))<128?n[a++]=r:r<2048?(n[a++]=192|r>>>6,n[a++]=128|63&r):r<55296||r>=57344?(n[a++]=224|r>>>12,n[a++]=128|r>>>6&63,n[a++]=128|63&r):(r=65536+((1023&r)<<10|1023&e.charCodeAt(++s)),n[a++]=240|r>>>18,n[a++]=128|r>>>12&63,n[a++]=128|r>>>6&63,n[a++]=128|63&r);e=n}e.length>64&&(e=new E(!0).update(e).array());var c=[],h=[];for(s=0;s<64;++s){var d=e[s]||0;c[s]=92^d,h[s]=54^d}E.call(this,t),this.update(h),this.oKeyPad=c,this.inner=!0,this.sharedMemory=t}E.prototype.update=function(e){if(this.finalized)throw new Error("finalize already called");var t=T(e);e=t[0];for(var s,i,r=t[1],n=0,o=e.length,a=this.blocks,c=this.buffer8;n<o;){if(this.hashed&&(this.hashed=!1,a[0]=a[16],a[16]=a[1]=a[2]=a[3]=a[4]=a[5]=a[6]=a[7]=a[8]=a[9]=a[10]=a[11]=a[12]=a[13]=a[14]=a[15]=0),r)if(h)for(i=this.start;n<o&&i<64;++n)(s=e.charCodeAt(n))<128?c[i++]=s:s<2048?(c[i++]=192|s>>>6,c[i++]=128|63&s):s<55296||s>=57344?(c[i++]=224|s>>>12,c[i++]=128|s>>>6&63,c[i++]=128|63&s):(s=65536+((1023&s)<<10|1023&e.charCodeAt(++n)),c[i++]=240|s>>>18,c[i++]=128|s>>>12&63,c[i++]=128|s>>>6&63,c[i++]=128|63&s);else for(i=this.start;n<o&&i<64;++n)(s=e.charCodeAt(n))<128?a[i>>>2]|=s<<g[3&i++]:s<2048?(a[i>>>2]|=(192|s>>>6)<<g[3&i++],a[i>>>2]|=(128|63&s)<<g[3&i++]):s<55296||s>=57344?(a[i>>>2]|=(224|s>>>12)<<g[3&i++],a[i>>>2]|=(128|s>>>6&63)<<g[3&i++],a[i>>>2]|=(128|63&s)<<g[3&i++]):(s=65536+((1023&s)<<10|1023&e.charCodeAt(++n)),a[i>>>2]|=(240|s>>>18)<<g[3&i++],a[i>>>2]|=(128|s>>>12&63)<<g[3&i++],a[i>>>2]|=(128|s>>>6&63)<<g[3&i++],a[i>>>2]|=(128|63&s)<<g[3&i++]);else if(h)for(i=this.start;n<o&&i<64;++n)c[i++]=e[n];else for(i=this.start;n<o&&i<64;++n)a[i>>>2]|=e[n]<<g[3&i++];this.lastByteIndex=i,this.bytes+=i-this.start,i>=64?(this.start=i-64,this.hash(),this.hashed=!0):this.start=i}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296|0,this.bytes=this.bytes%4294967296),this},E.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex;e[t>>>2]|=l[3&t],t>=56&&(this.hashed||this.hash(),e[0]=e[16],e[16]=e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=e[7]=e[8]=e[9]=e[10]=e[11]=e[12]=e[13]=e[14]=e[15]=0),e[14]=this.bytes<<3,e[15]=this.hBytes<<3|this.bytes>>>29,this.hash()}},E.prototype.hash=function(){var e,t,s,i,r,n,o=this.blocks;this.first?t=((t=((e=((e=o[0]-680876937)<<7|e>>>25)-271733879|0)^(s=((s=(-271733879^(i=((i=(-1732584194^2004318071&e)+o[1]-117830708)<<12|i>>>20)+e|0)&(-271733879^e))+o[2]-1126478375)<<17|s>>>15)+i|0)&(i^e))+o[3]-1316259209)<<22|t>>>10)+s|0:(e=this.h0,t=this.h1,s=this.h2,t=((t+=((e=((e+=((i=this.h3)^t&(s^i))+o[0]-680876936)<<7|e>>>25)+t|0)^(s=((s+=(t^(i=((i+=(s^e&(t^s))+o[1]-389564586)<<12|i>>>20)+e|0)&(e^t))+o[2]+606105819)<<17|s>>>15)+i|0)&(i^e))+o[3]-1044525330)<<22|t>>>10)+s|0),t=((t+=((e=((e+=(i^t&(s^i))+o[4]-176418897)<<7|e>>>25)+t|0)^(s=((s+=(t^(i=((i+=(s^e&(t^s))+o[5]+1200080426)<<12|i>>>20)+e|0)&(e^t))+o[6]-1473231341)<<17|s>>>15)+i|0)&(i^e))+o[7]-45705983)<<22|t>>>10)+s|0,t=((t+=((e=((e+=(i^t&(s^i))+o[8]+1770035416)<<7|e>>>25)+t|0)^(s=((s+=(t^(i=((i+=(s^e&(t^s))+o[9]-1958414417)<<12|i>>>20)+e|0)&(e^t))+o[10]-42063)<<17|s>>>15)+i|0)&(i^e))+o[11]-1990404162)<<22|t>>>10)+s|0,t=((t+=((e=((e+=(i^t&(s^i))+o[12]+1804603682)<<7|e>>>25)+t|0)^(s=((s+=(t^(i=((i+=(s^e&(t^s))+o[13]-40341101)<<12|i>>>20)+e|0)&(e^t))+o[14]-1502002290)<<17|s>>>15)+i|0)&(i^e))+o[15]+1236535329)<<22|t>>>10)+s|0,t=((t+=((i=((i+=(t^s&((e=((e+=(s^i&(t^s))+o[1]-165796510)<<5|e>>>27)+t|0)^t))+o[6]-1069501632)<<9|i>>>23)+e|0)^e&((s=((s+=(e^t&(i^e))+o[11]+643717713)<<14|s>>>18)+i|0)^i))+o[0]-373897302)<<20|t>>>12)+s|0,t=((t+=((i=((i+=(t^s&((e=((e+=(s^i&(t^s))+o[5]-701558691)<<5|e>>>27)+t|0)^t))+o[10]+38016083)<<9|i>>>23)+e|0)^e&((s=((s+=(e^t&(i^e))+o[15]-660478335)<<14|s>>>18)+i|0)^i))+o[4]-405537848)<<20|t>>>12)+s|0,t=((t+=((i=((i+=(t^s&((e=((e+=(s^i&(t^s))+o[9]+568446438)<<5|e>>>27)+t|0)^t))+o[14]-1019803690)<<9|i>>>23)+e|0)^e&((s=((s+=(e^t&(i^e))+o[3]-187363961)<<14|s>>>18)+i|0)^i))+o[8]+1163531501)<<20|t>>>12)+s|0,t=((t+=((i=((i+=(t^s&((e=((e+=(s^i&(t^s))+o[13]-1444681467)<<5|e>>>27)+t|0)^t))+o[2]-51403784)<<9|i>>>23)+e|0)^e&((s=((s+=(e^t&(i^e))+o[7]+1735328473)<<14|s>>>18)+i|0)^i))+o[12]-1926607734)<<20|t>>>12)+s|0,t=((t+=((n=(i=((i+=((r=t^s)^(e=((e+=(r^i)+o[5]-378558)<<4|e>>>28)+t|0))+o[8]-2022574463)<<11|i>>>21)+e|0)^e)^(s=((s+=(n^t)+o[11]+1839030562)<<16|s>>>16)+i|0))+o[14]-35309556)<<23|t>>>9)+s|0,t=((t+=((n=(i=((i+=((r=t^s)^(e=((e+=(r^i)+o[1]-1530992060)<<4|e>>>28)+t|0))+o[4]+1272893353)<<11|i>>>21)+e|0)^e)^(s=((s+=(n^t)+o[7]-155497632)<<16|s>>>16)+i|0))+o[10]-1094730640)<<23|t>>>9)+s|0,t=((t+=((n=(i=((i+=((r=t^s)^(e=((e+=(r^i)+o[13]+681279174)<<4|e>>>28)+t|0))+o[0]-358537222)<<11|i>>>21)+e|0)^e)^(s=((s+=(n^t)+o[3]-722521979)<<16|s>>>16)+i|0))+o[6]+76029189)<<23|t>>>9)+s|0,t=((t+=((n=(i=((i+=((r=t^s)^(e=((e+=(r^i)+o[9]-640364487)<<4|e>>>28)+t|0))+o[12]-421815835)<<11|i>>>21)+e|0)^e)^(s=((s+=(n^t)+o[15]+530742520)<<16|s>>>16)+i|0))+o[2]-995338651)<<23|t>>>9)+s|0,t=((t+=((i=((i+=(t^((e=((e+=(s^(t|~i))+o[0]-198630844)<<6|e>>>26)+t|0)|~s))+o[7]+1126891415)<<10|i>>>22)+e|0)^((s=((s+=(e^(i|~t))+o[14]-1416354905)<<15|s>>>17)+i|0)|~e))+o[5]-57434055)<<21|t>>>11)+s|0,t=((t+=((i=((i+=(t^((e=((e+=(s^(t|~i))+o[12]+1700485571)<<6|e>>>26)+t|0)|~s))+o[3]-1894986606)<<10|i>>>22)+e|0)^((s=((s+=(e^(i|~t))+o[10]-1051523)<<15|s>>>17)+i|0)|~e))+o[1]-2054922799)<<21|t>>>11)+s|0,t=((t+=((i=((i+=(t^((e=((e+=(s^(t|~i))+o[8]+1873313359)<<6|e>>>26)+t|0)|~s))+o[15]-30611744)<<10|i>>>22)+e|0)^((s=((s+=(e^(i|~t))+o[6]-1560198380)<<15|s>>>17)+i|0)|~e))+o[13]+1309151649)<<21|t>>>11)+s|0,t=((t+=((i=((i+=(t^((e=((e+=(s^(t|~i))+o[4]-145523070)<<6|e>>>26)+t|0)|~s))+o[11]-1120210379)<<10|i>>>22)+e|0)^((s=((s+=(e^(i|~t))+o[2]+718787259)<<15|s>>>17)+i|0)|~e))+o[9]-343485551)<<21|t>>>11)+s|0,this.first?(this.h0=e+1732584193|0,this.h1=t-271733879|0,this.h2=s-1732584194|0,this.h3=i+271733878|0,this.first=!1):(this.h0=this.h0+e|0,this.h1=this.h1+t|0,this.h2=this.h2+s|0,this.h3=this.h3+i|0)},E.prototype.hex=function(){this.finalize();var e=this.h0,t=this.h1,s=this.h2,i=this.h3;return d[e>>>4&15]+d[15&e]+d[e>>>12&15]+d[e>>>8&15]+d[e>>>20&15]+d[e>>>16&15]+d[e>>>28&15]+d[e>>>24&15]+d[t>>>4&15]+d[15&t]+d[t>>>12&15]+d[t>>>8&15]+d[t>>>20&15]+d[t>>>16&15]+d[t>>>28&15]+d[t>>>24&15]+d[s>>>4&15]+d[15&s]+d[s>>>12&15]+d[s>>>8&15]+d[s>>>20&15]+d[s>>>16&15]+d[s>>>28&15]+d[s>>>24&15]+d[i>>>4&15]+d[15&i]+d[i>>>12&15]+d[i>>>8&15]+d[i>>>20&15]+d[i>>>16&15]+d[i>>>28&15]+d[i>>>24&15]},E.prototype.toString=E.prototype.hex,E.prototype.digest=function(){this.finalize();var e=this.h0,t=this.h1,s=this.h2,i=this.h3;return[255&e,e>>>8&255,e>>>16&255,e>>>24&255,255&t,t>>>8&255,t>>>16&255,t>>>24&255,255&s,s>>>8&255,s>>>16&255,s>>>24&255,255&i,i>>>8&255,i>>>16&255,i>>>24&255]},E.prototype.array=E.prototype.digest,E.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(16),t=new Uint32Array(e);return t[0]=this.h0,t[1]=this.h1,t[2]=this.h2,t[3]=this.h3,e},E.prototype.buffer=E.prototype.arrayBuffer,E.prototype.base64=function(){for(var e,t,s,i="",r=this.array(),n=0;n<15;)e=r[n++],t=r[n++],s=r[n++],i+=p[e>>>2]+p[63&(e<<4|t>>>4)]+p[63&(t<<2|s>>>6)]+p[63&s];return e=r[n],i+=p[e>>>2]+p[e<<4&63]+"=="},v.prototype=new E,v.prototype.finalize=function(){if(E.prototype.finalize.call(this),this.inner){this.inner=!1;var e=this.array();E.call(this,this.sharedMemory),this.update(this.oKeyPad),this.update(e),E.prototype.finalize.call(this)}};var y=function(){var e=I("hex");o&&(e=S(e)),e.create=function(){return new E},e.update=function(t){return e.create().update(t)};for(var t=0;t<u.length;++t){var s=u[t];e[s]=I(s)}return e}();y.md5=y,y.md5.hmac=function(){var e=C("hex");e.create=function(e){return new v(e)},e.update=function(t,s){return e.create(t).update(s)};for(var t=0;t<u.length;++t){var s=u[t];e[s]=C(s)}return e}(),c?Mt.exports=y:r.md5=y}();var Wt=Bt.exports;const Vt=(e,t)=>{const s=Date.now(),i=`${e}:${s}:${Wt.md5(`${t}${s}`)}`,r=(new TextEncoder).encode(i);return btoa(String.fromCharCode(...r))},Jt=e=>{if(/^\d+$/.test(e))return!1;if(!e||"string"!=typeof e||e.length%4!=0)return!1;if(!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e))return!1;try{const t=atob(e);return btoa(t)===e}catch(e){return!1}},Kt="/v1/aicc/bmserver",Yt="/v1/aicc/ccs";let Zt="",zt="",Xt="",Qt="";function es(e){const t=Vt(zt,Xt);return Gt.create({prefixUrl:`${Zt}`,timeout:!1,headers:{Authorization:t,...e},hooks:{afterResponse:[async(e,t,s)=>{if(-1!==s.url.indexOf("heartbeat"))return s;const i=await s.clone().json();if(0!==i.code)throw new Error(JSON.stringify(i)||"请求失败");return s.json=async()=>i,s}]}})}async function ts(e,t,s){const i=es(s),r="api/"+e.replace(/^\/+/,"");return i.post(r,{json:t}).json()}class ss{static requestPermission(){"Notification"in window&&"default"===Notification.permission&&Notification.requestPermission()}static async requestMediaPermissions(){try{const e=await navigator.mediaDevices.enumerateDevices();if(e.some(e=>"audioinput"===e.kind&&""!==e.label))return null;return await navigator.mediaDevices.getUserMedia({audio:!0})}catch(e){return console.warn("获取音频权限失败:",e),null}}static show(e,t,s,i){if("Notification"in window&&"granted"===Notification.permission){const r=new Notification(e,{body:t,tag:`xy-global-notification${(new Date).getTime()}`,renotify:!0});r.onclick=()=>{window.focus(),r.close(),s?.()},setTimeout(()=>r.close(),1e3*(i||3))}}static async checkMediaPermissions(){try{return(await navigator.mediaDevices.enumerateDevices()).some(e=>"audioinput"===e.kind&&""!==e.label)}catch(e){return console.warn("无法检查设备权限:",e),!1}}}const is=(e,t)=>ts(`${Yt}/state/change?h=${t}`,e,{h:t}),rs=()=>async function(e,t){const s=es(),i=e.replace(/^\/+/,"");return s.post(i,{json:t}).json()}("/heartbeat",{}),ns=[],os=["call_number"],as=["call_number"],cs=["hangup"],hs=["hold","hangup","mute","transfer","consult","satisfaction","dtmf"],ds=["hold","hangup","mute","transfer","consult"],ls=["consult_transfer","conference","consult_retrieve"],gs=["hangup"],us=["hangup"],ps=["answer","reject"],fs=["hangup","consult","transfer","hold","mute","satisfaction","dtmf"],ms=["hangup","whisper","force_insert","force_disconnect"],_s=["hangup"],ws=["hangup","cancel_whisper","force_insert"],Ts=["hangup"],Is=["hangup"];class Ss{constructor(){this.roleData={agentInfo:()=>{if(!dt.agentInfo?.agent_no)throw new Error(JSON.stringify({code:1,msg:"请先登录"}))},requestInfo:e=>{if(!e.data)throw new Error(JSON.stringify({code:1,msg:'Parameter "data" is required'}))},changeDevice:e=>{if(!e)throw new Error(JSON.stringify({code:1,msg:'Parameter "device" is required'}));const{answer_devices:t}=dt.agentInfo;if(!t.split(",").map(e=>Number(e)).includes(e))throw new Error(JSON.stringify({code:1,msg:"当前状态不支持"}))},changeState:(e,t)=>{if(!e)throw new Error(JSON.stringify({code:1,msg:'Parameter "state" is required'}));if(!t)throw new Error(JSON.stringify({code:1,msg:'Parameter "state_name" is required'}));if(2===e&&("通话中"===t||"整理"===t))throw new Error(JSON.stringify({code:1,msg:"当前状态不支持"}));if(![1,2].includes(e))throw new Error(JSON.stringify({code:1,msg:"当前状态不支持"}))},setAgentExplicit:e=>{const{out_display_select_switch:t,out_display_data:s}=dt.agentInfo;if(1!==t)throw new Error(JSON.stringify({code:1,msg:"当前坐席设置未开启允许指定外显"}));if(!e)throw new Error(JSON.stringify({code:1,msg:'Parameter "number" is required'}));if(!(s||"").split("#").includes(e))throw new Error(JSON.stringify({code:1,msg:"当前外显号码不存在"}))}},this.changeDevice=async e=>{try{if(gt.get("isCalling"))throw new Error(JSON.stringify({code:1,msg:"当前正在通话中,请勿切换设备"}));this.roleData.agentInfo(),this.roleData.requestInfo(e);const{data:t,success:s}=e,{device:i}=t;1===i&&await Ss.initRtcFn(),this.roleData.changeDevice(i);const{agent_no:r}=dt.agentInfo;await(e=>ts(`${Yt}/device/change`,e))({agent_no:r,answer_device:i}),gt.updateAnswerDevice(i);const n=gt.get("actionConfigs");gt.updateActionConfigs(n),2===i&&dt.stateObject.state===et.UNREGISTERED&&await this._changeState({data:{...dt.stateBeforeChange,state_name:dt.stateBeforeChange.state===et.IDLE?"空闲":"忙碌"}},"q"),s?.({code:0,msg:"请求成功"})}catch(e){throw ht.emit(nt.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}}formatDate(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")} ${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}:${String(e.getSeconds()).padStart(2,"0")}`}static setInitRtcFn(e){this.initRtcFn=e}async _agentLogin(e){try{const s=await(t={agent_no:e},ts(`${Yt}/agent/login`,t));dt.agentInfo=s.data}catch(e){throw ht.emit(nt.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}var t}async _changeState(e,t){try{dt.autoStateTimer&&(clearTimeout(dt.autoStateTimer),dt.autoStateTimer=null),this.roleData.agentInfo(),this.roleData.requestInfo(e);const{data:s,success:i}=e,{state:r,state_name:n}=s,{agent_no:o}=dt.agentInfo;await is({agent_no:o,state_name:n,state:r},t),r===et.IDLE?gt.updateActionConfigs(os):r===et.BUSY&>.updateActionConfigs(as),dt.stateObject={state:r,state_name:n},i?.({code:0,msg:"请求成功"})}catch(e){throw ht.emit(nt.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}async _getInCallCrmDetail(e){try{const{phone:t}=e.data,s={};Jt(t)?s.trace_id=t:s.phone=t.replace(/[\s\r\n-]+/g,"");const i=await(e=>ts(`${Kt}/crm/popups`,e))({...s});e.success?.(i)}catch(e){throw ht.emit(nt.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}async changeState(e,t){try{if(gt.get("isCalling"))throw new Error(JSON.stringify({code:1,msg:"当前正在通话中,请勿切换设备"}));dt.autoStateTimer&&(clearTimeout(dt.autoStateTimer),dt.autoStateTimer=null),this.roleData.agentInfo(),this.roleData.requestInfo(e);const{data:s,success:i}=e,{state:r,state_name:n}=s;this.roleData.changeState(r,n);const{agent_no:o}=dt.agentInfo;await is({agent_no:o,state_name:n,state:r},t),(dt.stateObject.state===et.IDLE||dt.stateObject.state===et.BUSY&&"整理"!==n)&&(dt.stateBeforeChange=dt.stateObject),r===et.IDLE?gt.updateActionConfigs(os):r===et.BUSY&>.updateActionConfigs(as),dt.stateObject={state:r,state_name:n},i?.({code:0,msg:"请求成功"})}catch(e){throw ht.emit(nt.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}async getIdleAgentList(e){const{agent_no:t}=dt.agentInfo;try{this.roleData.agentInfo();const s=await(e=>ts(`${Yt}/agent/free`,e))({agent_no:t});e.success?.(s)}catch(e){throw ht.emit(nt.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}async getAgentState(e){try{const t=await ts(`${Kt}/agent/statecfg/list`,{}),s=(t.data||[]).filter(e=>0===e.enable).filter(e=>0!==e.state&&3!==e.state).filter(e=>"通话中"!==e.state_name&&"整理"!==e.state_name&&"未注册"!==e.state_name&&"离线接听"!==e.state_name).map(e=>({state:e.state,state_name:e.state_name})).reverse();e.success?.({...t,data:s})}catch(e){throw ht.emit(nt.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}async setAgentExplicit(e){try{this.roleData.agentInfo(),this.roleData.requestInfo(e),this.roleData.setAgentExplicit(e.data.number);const{agent_id:t}=dt.agentInfo;await(e=>ts(`${Kt}/agent/update`,e))({agent_id:t,out_display_number:e.data.number}),gt.updateSelectOutNumber(e.data.number),e.success?.({code:0,msg:"请求成功"})}catch(e){throw ht.emit(nt.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}async checkAgentLogin(e){try{this.roleData.requestInfo(e);const{agent_no:t}=e.data;if(!t)throw new Error(JSON.stringify({code:1,msg:'Parameter "agent_no" is required'}));const s=await(e=>ts(`${Yt}/agent/islogin`,e))({agent_no:t});e.success?.(s)}catch(e){throw ht.emit(nt.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}async getCallRecord(e){try{this.roleData.agentInfo();const{success:t}=e,s=new Date,i=new Date(s.getFullYear(),s.getMonth(),s.getDate(),0,0,0),r=new Date(s.getFullYear(),s.getMonth(),s.getDate(),23,59,59),n=[this.formatDate(i),this.formatDate(r)],{agent_no:o}=dt.agentInfo,a=await(e=>ts(`${Kt}/agent/recordpage`,e))({start_time:n[0],end_time:n[1],page_no:1,page_size:10,agent_no:o}),{code:c,msg:h,data:d}=a;t?.({code:c,msg:h,data:d})}catch(e){throw ht.emit(nt.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}async logout(e){this.roleData.agentInfo();try{const{agent_no:t}=dt.agentInfo,{data:s,success:i}=e;await(e=>ts(`${Yt}/agent/logout`,e))({...s,agent_no:t}),i?.({code:0,msg:""})}catch(e){throw ht.emit(nt.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}async listenCall(e){try{const{agent_no:t}=dt.agentInfo,{data:s,success:i}=e;if(this.roleData.agentInfo(),this.roleData.requestInfo(e),!s.monitored_agent_no)throw new Error(JSON.stringify({code:1,msg:'Parameter "monitored_agent_no" is required'}));await(e=>ts(`${Yt}/call/monitor`,e))({...s,monitor_agent_no:t}),dt.monitoredAgentNo=s.monitored_agent_no,i?.({code:0,msg:""})}catch(e){throw ht.emit(nt.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}async earCall(e){try{const{agentInfo:t,monitoredAgentNo:s}=dt,{agent_no:i}=t;this.roleData.agentInfo();const{success:r}=e;if(!s)throw new Error(JSON.stringify({code:1,msg:"当前未有监听坐席"}));await(e=>ts(`${Yt}/call/whisper`,e))({monitored_agent_no:s,monitor_agent_no:i}),r?.({code:0,msg:""})}catch(e){throw ht.emit(nt.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}async stopEarCall(e){try{const{agentInfo:t,earSpeakAgent:s}=dt;if(!s)throw new Error(JSON.stringify({code:1,msg:"当前没有正在耳语的坐席"}));const{agent_no:i}=t;this.roleData.agentInfo();const{success:r}=e;await(e=>ts(`${Yt}/call/stopwhisper`,e))({monitor_agent_no:i,monitored_agent_no:s}),r?.({code:0,msg:""})}catch(e){throw ht.emit(nt.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}async forceInsert(e){try{const{agentInfo:t,monitoredAgentNo:s}=dt,{agent_no:i}=t;this.roleData.agentInfo();const{success:r}=e;if(!s)throw new Error(JSON.stringify({code:1,msg:"当前未有监听坐席"}));await(e=>ts(`${Yt}/call/bargein`,e))({monitored_agent_no:s,monitor_agent_no:i}),r?.({code:0,msg:""})}catch(e){throw ht.emit(nt.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}async forceDisconnect(e){try{const{agentInfo:t,monitoredAgentNo:s}=dt,{agent_no:i}=t;this.roleData.agentInfo();const{success:r}=e;if(!s)throw new Error(JSON.stringify({code:1,msg:"当前未有监听坐席"}));await(e=>ts(`${Yt}/call/intercept`,e))({monitored_agent_no:s,monitor_agent_no:i}),r?.({code:0,msg:""})}catch(e){throw ht.emit(nt.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}}const Cs=console.log,Es=(...e)=>{dt.logBuiltinEnabled&&Cs(...e)};let vs=null;class ys{constructor(e,t){this.url=e,this.onOpenCallback=t,this.ws=null,this.heartbeatWorker=null,this.reconnectDelay=3e3,this.manualClose=!1,this.apiClient=new Ss,this.sipClient=null,this.pendingMessages=new Map,this.initWebSocket()}static getInstance({url:e,sipClient:t,onOpen:s}){if(!vs){if(!e)throw new Error("WebSocket 尚未初始化");vs=new ys(e,s),vs.sipClient=t}return vs}setSipClient(e){this.sipClient=e}stateIdleChange(e){const{state:t}=dt.stateObject;t!==et.IDLE&&this.apiClient._changeState({data:{...dt.stateBeforeChange,state_name:dt.stateBeforeChange.state===et.IDLE?"空闲":"忙碌"}},e)}inCallAutoAnswer(){const{soft_device_auto_answer:e,auto_answer_time:t}=dt.agentInfo,s=1===e,i=gt.get("direction");if(s&&i===tt.INCOMING){const e=Number(t)||0;e>0&&(dt.autoAnswerTimer=setTimeout(()=>{this.sipClient?.answerCall(),dt.autoAnswerTimer=null},1e3*e-500))}}async getCustomerInfo(e){try{await this.apiClient._getInCallCrmDetail({data:{phone:e},success:e=>{gt.updateCustomerInfo(e.data||{phone:e.data.phone,is_vip:0,customer_name:"未知客户",city:"未知",province:"未知",contact_count:0,in_contact_count:0,trace_id:e.data.trace_id,contact_count_month:0,in_contact_count_month:0})}})}catch(e){}}putAgentState(e,t){if(!e)return;if(5===t)return void this.stateIdleChange("device_type5");dt.sessionId="";const{post_call_process_time:s}=dt.agentInfo,i=s||0;if(dt.autoStateTimer&&(clearTimeout(dt.autoStateTimer),dt.autoStateTimer=null),gt.updateCustomerInfo(void 0),i>0){const{state:e}=dt.stateObject;if(e===et.IDLE)return;this.apiClient._changeState({data:{state:et.BUSY,state_name:"整理"}},"ez"),dt.autoStateTimer=setTimeout(()=>{dt.autoStateTimer=null,this.stateIdleChange(`delay${i}`)},1e3*i)}else this.stateIdleChange("delay0")}stateBusyChange(){dt.sessionId="",clearTimeout(dt.autoStateTimer),gt.updateCustomerInfo(void 0),this.apiClient._changeState({data:{state:et.BUSY,state_name:"忙碌"}},"dm")}initWebSocket(){if(1===this.ws?.readyState)return;if(!gt.get("isNextState")||this.manualClose)return;const e=Vt(zt,Xt);this.ws=new WebSocket(this.url+e),this.ws.onopen=()=>{const e=(new Date).getTime();this.sendMessage({type:0,msg_id:e}),this.pendingMessages.set(e,performance.now()),this.startHeartbeat(),this.manualClose=!1,this.onOpenCallback&&this.onOpenCallback()},this.ws.onmessage=async e=>{const t=JSON.parse(e.data),{type:s,data:i,code:r,msg:n,msg_id:o}=t;if(0===s&&o){const e=this.pendingMessages.get(o),t=performance.now()-e;dt.latency=parseFloat(t.toFixed(2)),this.pendingMessages.delete(o)}if(0!==s&&Es("%cWebSocket 收到消息:","color: blue; font-weight: bold;",t),s!==st.OUT_CALL&&s!==st.PREVIEW_OUT_CALL||(0!==r?(gt.reset(),ht.emit(rt.OUT_FAILED,n),ht.emit(nt.FAIL_NOTIFICATION,n),gt.updateActionConfigs(os),setTimeout(()=>{gt.updateCustomerInfo(void 0)},500),this.stateIdleChange("h")):0===r&&(ht.emit(rt.OUT_SUCCESS),clearTimeout(dt.autoStateTimer))),s===st.AGENT_STATE){const{state:e,state_name:t}=i;dt.stateObject={state:e,state_name:t},dt.stateBeforeChange?.state||dt.stateObject.state!==et.IDLE&&(dt.stateObject.state!==et.BUSY||"整理"===t)||(dt.stateBeforeChange=dt.stateObject),"振铃中"===t&>.updateDisplayText(ot.AGENT_RINGING);const s=gt.get("isCalling");e!==et.UNREGISTERED||s||gt.updateActionConfigs(ns),e===et.IDLE&&dt.stateObject.state===et.UNREGISTERED&>.updateActionConfigs(os),ht.emit(rt.AGENT_STATE,{state:e,state_name:t})}else if(s===st.OUT_CALL_INCOMING_CALL){try{await this.getCustomerInfo(i.trace_id||i.customer_phone)}catch(e){console.error(e)}i.preview_task_id?ht.emit(rt.PREVIEW_OUT_INCOMING_CALL,{customer_phone:i.customer_phone,session_id:i.session_id,preview_task_id:i.preview_task_id,trace_id:i.trace_id}):1===i.direction?ht.emit(rt.OUT_INCOMING_CALL,{customer_phone:i.customer_phone,session_id:i.session_id,trace_id:i.trace_id}):8===i.direction&&ht.emit(rt.INTERNAL_OUT_INCOMING_CALL,{customer_phone:i.customer_phone,session_id:i.session_id,trace_id:i.trace_id}),dt.sessionId=i.session_id,gt.updateActionConfigs(cs,8!==i.direction)}else if(s===st.OUT_CALL_END){if(dt.sessionId!==i.session_id)return;if(gt.updateDisplayText(""),1===i.device_type&&i.agent_no===dt.agentInfo.agent_no)gt.reset(),ht.emit(rt.OUT_HANGUP,{session_id:i.session_id}),gt.updateActionConfigs(os),this.putAgentState(!0);else if(2===i.device_type&&i.agent_no===dt.agentInfo.agent_no)gt.reset(),ht.emit(rt.OUR_SIDE_CONSULT_HANGUP,{session_id:i.session_id}),gt.updateActionConfigs(os),this.putAgentState(!0);else if(2===i.device_type&&i.agent_no!==dt.agentInfo.agent_no){gt.get("isCalling")&&(gt.updateDisplayText(ot.CALLING),ht.emit(rt.OTHER_SIDE_CONSULT_HANGUP,{session_id:i.session_id}),gt.updateActionConfigs(hs))}else if(3===i.device_type&&i.agent_no===dt.agentInfo.agent_no)gt.reset(),ht.emit(rt.THREE_WAY_OUR_SIDE_HANGUP,{session_id:i.session_id}),gt.updateActionConfigs(os),this.putAgentState(!0);else if(4===i.device_type&&i.agent_no===dt.agentInfo.agent_no)gt.reset(),ht.emit(rt.TRANSFER_END,{session_id:i.session_id}),gt.updateActionConfigs(os),this.putAgentState(!0);else if(4===i.device_type&&i.agent_no!==dt.agentInfo.agent_no){ht.emit(rt.TRANSFER_FAILED,"未知原因"),ht.emit(nt.FAIL_NOTIFICATION,"转接失败");const e=gt.get("direction");e===tt.OUTGOING?gt.updateActionConfigs(hs):e===tt.INCOMING&>.updateActionConfigs(fs)}else 5===i.device_type&&i.agent_no===dt.agentInfo.agent_no&&(dt.monitoredAgentNo="",dt.earSpeakAgent="",gt.reset(),ht.emit(rt.LISTEN_HANGUP,{session_id:i.session_id}),gt.updateActionConfigs(os),this.putAgentState(!0,5))}else if(s===st.OUT_CALL_RINGING)1===i.type&&(ht.emit(rt.OUT_RINGING,{session_id:dt.sessionId,type:i.type}),gt.updateDisplayText(ot.RINGING));else if(s===st.OUT_CALL_ANSWER)clearTimeout(dt.autoStateTimer),gt.updateIsCalling(!0),gt.updateOutCallIsAnswer(!0),gt.updateDisplayText(ot.CALLING),8===i.direction?(ht.emit(rt.INTERNAL_OUT_OFF_ANSWER,{session_id:dt.sessionId}),gt.updateActionConfigs(ds)):(ht.emit(rt.OUT_OFF_ANSWER,{session_id:dt.sessionId}),gt.updateActionConfigs(hs));else if(s===st.CONSULT_RINGING)ht.emit(rt.CONSULT_RINGING,{session_id:i.session_id}),gt.updateDisplayText(ot.AGENT_RINGING),gt.updateActionConfigs([]),clearTimeout(dt.autoStateTimer);else if(s===st.CONSULT_ANSWER)ht.emit(rt.CONSULT_OFF_HOOK,{session_id:i.session_id}),gt.updateConsultIsAnswer(!0),gt.updateDisplayText(ot.CONSULTING),gt.updateActionConfigs(ls);else if(s===st.CONSULT_FAIL)ht.emit(rt.CONSULT_FAILED,{custom_reason:i.custom_reason}),gt.updateDisplayText(ot.CALLING),gt.updateActionConfigs(hs);else if(s===st.CONSULT_CALL_IN)ht.emit(rt.CONSULT_INCOMING,{agent_no:i.agent_no,agent_mane:i.agent_name,session_id:i.session_id}),dt.sessionId=i.session_id,gt.updateIsCalling(!0),gt.updateDirection(tt.CONSULT),gt.updateDisplayText(ot.CONSULT_CALL_IN),gt.updateActionConfigs(ps),dt.enableBrowserAlert&&ss.show("📞 咨询来电",`坐席 [${i.agent_name}] 正在咨询...`,()=>{ht.emit(nt.NOTIFICATION_CLICK,{agent_mane:i.agent_name,agent_no:i.agent_no})},dt.browserAlertTime);else if(s===st.CONSULT_CALL_IN_SUCCESS)ht.emit(rt.CONSULT_CALL_IN_SUCCESS,{session_id:i.session_id}),gt.updateConsultIsAnswer(!0),gt.updateDisplayText(ot.CALLING),gt.updateActionConfigs(gs);else if(s===st.CONSULT_RETURN_CALL_SUCCESS)"success"===i.status?(gt.updateConsultIsAnswer(!1),ht.emit(rt.CONSULT_RETURN_CALL_SUCCESS),gt.updateDisplayText(ot.CALLING),ht.emit(rt.OTHER_SIDE_CONSULT_HANGUP),gt.updateActionConfigs(hs)):ht.emit(nt.FAIL_NOTIFICATION,"媒体失败");else if(s===st.MUTE)0===r?(gt.updateIsMuted(!0),ht.emit(rt.MUTE_SUCCESS),gt.updateDisplayText(ot.MUTING)):(ht.emit(rt.MUTE_FAILED,n),ht.emit(nt.FAIL_NOTIFICATION,n));else if(s===st.UNMUTE)0===r?(gt.updateIsMuted(!1),ht.emit(rt.UNMUTE_SUCCESS),gt.updateDisplayText(ot.CALLING)):(ht.emit(rt.UNMUTE_FAILED,n),ht.emit(nt.FAIL_NOTIFICATION,n));else if(s===st.CALL_HOLD)0===r?(gt.updateIsHold(!0),gt.updateDisplayText(ot.HOLDING),ht.emit(rt.HOLD_SUCCESS)):(ht.emit(rt.HOLD_FAILED,n),ht.emit(nt.FAIL_NOTIFICATION,n));else if(s===st.CALL_UNHOLD)0===r?(gt.updateDisplayText(ot.CALLING),gt.updateIsHold(!1),ht.emit(rt.UNHOLD_SUCCESS)):(ht.emit(rt.UNHOLD_FAILED,n),ht.emit(nt.FAIL_NOTIFICATION,n));else if(s===st.CONSULT_TRANSFER)0===r?ht.emit(rt.CONSULT_TRANSFER_SUCCESS):(ht.emit(rt.CONSULT_TRANSFER_FAILED,n),ht.emit(nt.FAIL_NOTIFICATION,n));else if(s===st.CONSULT_TRANSFER_FAILED)ht.emit(rt.CONSULT_TRANSFER_FAILED,i.status);else if(s===st.CONSULT_TRANSFER_OFF_HOOK)gt.updateDirection(tt.INCOMING),gt.updateDisplayText(ot.CALLING),ht.emit(rt.CONSULT_TRANSFER_OFF_HOOK),gt.updateActionConfigs(fs),gt.updateIncomingIsAnswer(!0),gt.updateConsultIsAnswer(!1);else if(s===st.INCOMING_CALL){clearTimeout(dt.autoStateTimer),dt.sessionId=i.session_id;try{await this.getCustomerInfo(i.trace_id||i.customer_phone)}catch(e){console.error(e)}gt.updateIsCalling(!0),gt.updateDirection(tt.INCOMING),gt.updateDisplayText(ot.INCOMING_CALL),this.inCallAutoAnswer(),1===i.direction&&ht.emit(rt.INCOMING_CALL,{customer_phone:i.customer_phone,trace_id:i.trace_id,session_id:i.session_id}),8===i.direction&&ht.emit(rt.INCOMING_CALL_IN,{customer_phone:i.customer_phone,trace_id:i.trace_id,session_id:i.session_id}),3===i.direction&&ht.emit(rt.PREDICT_INCOMING_CALL,{customer_phone:i.customer_phone,trace_id:i.trace_id,session_id:i.session_id}),6===i.direction&&ht.emit(rt.DUAL_CALL_INCOMING_CALL,{customer_phone:i.customer_phone,trace_id:i.trace_id,session_id:i.session_id}),gt.updateActionConfigs(ps),dt.enableBrowserAlert&&ss.show("📞 客户来电",`客户 [${i.customer_phone}] 正在呼入...`,()=>{ht.emit(nt.NOTIFICATION_CLICK,{customer_phone:i.customer_phone})},dt.browserAlertTime)}else if(s===st.INCOMING_CALL_OFF_HOOK)gt.updateIncomingIsAnswer(!0),8===i.direction?(gt.updateActionConfigs(ds),ht.emit(rt.INCOMING_CALL_IN_OFF_HOOK,{session_id:dt.sessionId})):(gt.updateActionConfigs(fs),ht.emit(rt.INCOMING_CALL_OFF_HOOK,{session_id:dt.sessionId})),gt.updateDisplayText(ot.CALLING);else if(s===st.INCOMING_CALL_END){if(dt.sessionId!==i.session_id)return;if(gt.updateDisplayText(""),1!==i.device_type&&7!==i.device_type||i.agent_no!==dt.agentInfo.agent_no)if(2===i.device_type&&i.agent_no===dt.agentInfo.agent_no)gt.reset(),ht.emit(rt.OUR_SIDE_CONSULT_HANGUP,{session_id:i.session_id}),this.putAgentState(!0),gt.updateActionConfigs(os);else if(2===i.device_type&&i.agent_no!==dt.agentInfo.agent_no)gt.updateDisplayText(ot.CALLING),ht.emit(rt.OTHER_SIDE_CONSULT_HANGUP,{session_id:i.session_id}),gt.updateActionConfigs(hs);else if(3===i.device_type&&i.agent_no===dt.agentInfo.agent_no)this.putAgentState(!0),gt.reset(),ht.emit(rt.THREE_WAY_OUR_SIDE_HANGUP,{session_id:i.session_id}),gt.updateActionConfigs(os);else if(4===i.device_type&&i.agent_no===dt.agentInfo.agent_no)this.putAgentState(!0),gt.reset(),ht.emit(rt.TRANSFER_END,{session_id:i.session_id}),gt.updateActionConfigs(os);else if(4===i.device_type&&i.agent_no!==dt.agentInfo.agent_no){ht.emit(rt.TRANSFER_FAILED,"未知原因"),ht.emit(nt.FAIL_NOTIFICATION,"转接失败");const e=gt.get("direction");e===tt.OUTGOING?gt.updateActionConfigs(hs):e===tt.INCOMING&>.updateActionConfigs(fs)}else 5===i.device_type&&i.agent_no===dt.agentInfo.agent_no&&(this.putAgentState(!0,5),dt.monitoredAgentNo="",dt.earSpeakAgent="",gt.reset(),ht.emit(rt.LISTEN_HANGUP,{session_id:i.session_id}),gt.updateActionConfigs(os));else this.putAgentState(!0),gt.reset(),ht.emit(rt.INCOMING_CALL_END,{session_id:i.session_id}),gt.updateActionConfigs(os)}else if(s===st.SATISFACTION_EVALUATION)0===r?ht.emit(rt.SATISFACTION_EVALUATION_SUCCESS):(ht.emit(rt.SATISFACTION_EVALUATION_FAILED,n),ht.emit(nt.FAIL_NOTIFICATION,n));else if(s===st.CONSULT_THREE_WAY)0!==r?(ht.emit(rt.CONSULT_THREE_WAY_FAILED,n),ht.emit(nt.FAIL_NOTIFICATION,n)):0===r&>.updateIsMeeting(!0);else if(s===st.CONSULT_THREE_WAY_RESULT)"success"===i.status?(gt.updateDirection(tt.MEETING),gt.updateDisplayText(ot.MEETING),gt.updateActionConfigs(us),ht.emit(rt.CONSULT_THREE_WAY_SUCCESS)):(ht.emit(rt.CONSULT_THREE_WAY_FAILED,{conf_name:i.conf_name}),gt.updateIsMeeting(!1));else if(s===st.TRANSFER_INCOMING_CALL)clearTimeout(dt.autoStateTimer),i.agent_no===dt.agentInfo.agent_no?(gt.updateDisplayText(ot.TRANSFERRING),ht.emit(rt.TRANSFER_PROGRESS),gt.updateActionConfigs([]),gt.updateTransferIsAnswer(!0)):(dt.sessionId=i.session_id,ht.emit(rt.TRANSFER_INCOMING_CALL,{agent_no:i.agent_no,agent_name:i.agent_name,session_id:i.session_id}),gt.updateIsCalling(!0),gt.updateDirection(tt.TRANSFER),gt.updateDisplayText(ot.TRANSFER_INCOMING_CALL),gt.updateActionConfigs(ps),dt.enableBrowserAlert&&ss.show("📞 转接来电",`坐席 [${i.agent_no}] 正在转接...`,()=>{ht.emit(nt.NOTIFICATION_CLICK,{agent_no:i.agent_no})},dt.browserAlertTime));else if(s===st.TRANSFER_OFF_HOOK)ht.emit(rt.TRANSFER_OFF_HOOK,{session_id:dt.sessionId}),gt.updateTransferIsAnswer(!1),gt.updateDisplayText(ot.CALLING),gt.updateActionConfigs(fs,8!==i.direction);else if(s===st.TRANSFER_FAILED){if("failed"===i.status){ht.emit(rt.TRANSFER_FAILED,"未知原因"),ht.emit(nt.FAIL_NOTIFICATION,"转接失败");const e=gt.get("direction");e===tt.OUTGOING?gt.updateActionConfigs(hs):e===tt.INCOMING&>.updateActionConfigs(fs)}}else s===st.KICK_OFFLINE?ht.emit(nt.KICK_OFF):s===st.CONTINUOUS_NOT_ANSWER?(ht.emit(nt.FAIL_NOTIFICATION,`已连续 ${i.miss_count} 次未接, 设置忙碌`),this.stateBusyChange()):s===st.SIGN_OUT?ht.emit(nt.SIGN_OUT):s===st.SIGN_IN_SWITCH_DEVICE?ht.emit(nt.SIGN_IN_SWITCH_DEVICE,i):s===st.LISTEN_INCOMING_CALL?(clearTimeout(dt.autoStateTimer),dt.sessionId=i.session_id,gt.updateIsCalling(!0),gt.updateDirection(tt.INCOMING),this.inCallAutoAnswer(),gt.updateDisplayText(ot.LISTENING),gt.updateActionConfigs(ps),ht.emit(rt.LISTEN_INCOMING_CALL,{session_id:i.session_id}),dt.enableBrowserAlert&&ss.show("📞 监听来电","正在来电...",()=>{ht.emit(nt.NOTIFICATION_CLICK,{customer_phone:i.customer_phone})},dt.browserAlertTime)):s===st.LISTEN_INCOMING_CALL_OFF_HOOK?(dt.monitoredAgentNo=i.monitored_agent_no,dt.earSpeakAgent="",gt.updateIncomingIsAnswer(!0),ht.emit(rt.LISTEN_INCOMING_CALL_OFF_HOOK,{session_id:dt.sessionId,monitored_agent_no:i.monitored_agent_no}),gt.updateActionConfigs(ms),gt.updateDisplayText(ot.CALLING)):s===st.LISTEN_CALL_FAILED?"failed"===i.status&&(ht.emit(rt.LISTEN_CALL_FAILED),dt.monitoredAgentNo=""):s===st.EAR_SPEECH?"success"===i.status?(i.monitored_agent_no===dt.agentInfo.agent_no&&(gt.updateActionConfigs(_s),ht.emit(rt.EAR_SPEECH_BE_SUCCESS)),i.monitor_agent_no===dt.agentInfo.agent_no&&(gt.updateActionConfigs(ws),ht.emit(rt.EAR_SPEECH_SUCCESS,{monitored_agent_no:i.monitored_agent_no,monitor_agent_no:i.monitor_agent_no}),dt.earSpeakAgent=i.monitored_agent_no)):ht.emit(rt.EAR_SPEECH_FAILED):s===st.STOP_EAR_SPEECH?"success"===i.status?(i.monitored_agent_no===dt.agentInfo.agent_no&>.updateActionConfigs(fs),i.monitor_agent_no===dt.agentInfo.agent_no&>.updateActionConfigs(ms),dt.earSpeakAgent="",ht.emit(rt.STOP_EAR_SPEECH_SUCCESS)):ht.emit(rt.STOP_EAR_SPEECH_FAILED):s===st.CALL_FORCE_INSERT?"success"===i.status?(i.monitored_agent_no===dt.agentInfo.agent_no&&(gt.updateActionConfigs(Is),ht.emit(rt.CALL_FORCE_INSERT_SUCCESS,{monitored_agent_no:i.monitored_agent_no,monitor_agent_no:i.monitor_agent_no})),i.monitor_agent_no===dt.agentInfo.agent_no&&(gt.updateActionConfigs(Ts),ht.emit(rt.CALL_FORCE_INSERT_SUCCESS_LISTENER,{monitored_agent_no:i.monitored_agent_no,monitor_agent_no:i.monitor_agent_no}))):ht.emit(rt.CALL_FORCE_INSERT_FAILED):s===st.INTERNAL_CALL_START_CONSULT?i.agent_no===dt.agentInfo.agent_no?(gt.updateConsultIsAnswer(!0),gt.updateActionConfigs(ls),gt.updateDisplayText(ot.CONSULTING)):(gt.updateDisplayText(ot.OTHER_SIDE_CONSULTING),gt.updateActionConfigs([])):s===st.INTERNAL_CALL_END_CONSULT?(gt.updateActionConfigs(ds),gt.updateDisplayText(""),gt.updateConsultIsAnswer(!1)):s===st.CALL_SIP_INCOMING_CALL&&ht.emit(rt.CALL_SIP_INCOMING_CALL)},this.ws.onclose=e=>{ht.emit(nt.FAIL_NOTIFICATION,"链接已断开,请检查网络"),this.stopHeartbeat();const t=gt.get("isNextState");!this.manualClose&&t&&setTimeout(()=>this.initWebSocket(),this.reconnectDelay)},this.ws.onerror=e=>{ht.emit(nt.FAIL_NOTIFICATION,"连接失败,请检查网络"),this.ws?.close()}}startHeartbeat(){const e=new Blob(["\n let timer;\n self.onmessage = function (e) {\n if (e.data === 'start') {\n timer = setInterval(() => {\n self.postMessage('heartbeat');\n }, 5000);\n } else if (e.data === 'stop') {\n clearInterval(timer);\n }\n };\n "],{type:"application/javascript"}),t=URL.createObjectURL(e);this.heartbeatWorker=new Worker(t),this.heartbeatWorker.onmessage=()=>{const e=(new Date).getTime();this.sendMessage({type:0,msg_id:e}),this.pendingMessages.set(e,performance.now())},this.heartbeatWorker.postMessage("start")}stopHeartbeat(){this.heartbeatWorker&&(this.heartbeatWorker.postMessage("stop"),this.heartbeatWorker.terminate(),this.heartbeatWorker=null)}sendMessage(e){this.ws?.readyState===WebSocket.OPEN?(this.ws.send(JSON.stringify(e)),0!==e.type&&Es("%cWebSocket 发送消息:","color: green; font-weight: bold;",e)):console.warn("WebSocket 未连接,消息未发送")}close(){this.manualClose=!0,this.stopHeartbeat(),this.ws?.close()}reconnect(){this.initWebSocket()}static __internalClose(){vs&&(vs.close(),vs=null)}static __internalSend(e){if(!vs)throw new Error("WebSocket 尚未初始化");vs.sendMessage(e)}}class As{constructor(e){this.sipClient=null,this.sipClient=e}roleMute(){const e=gt.get("isCalling"),t=dt.sessionId;if(!e)throw new Error(JSON.stringify({code:1,msg:"当前没有通话"}));if(!t)throw new Error(JSON.stringify({code:1,msg:"当前没有通话"}))}holdCall(){this.roleMute();const e=gt.get("isHold"),{sessionId:t}=dt;if(!t)return;if(!gt.get("actionConfigs").includes("hold"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿保持"}));if(e)throw new Error(JSON.stringify({code:1,msg:"当前已处于保持状态"}));ys.__internalSend({type:st.CALL_HOLD,data:{session_id:t}})}unholdCall(){this.roleMute();const{isHold:e}=gt.getState(),{sessionId:t}=dt;if(!gt.get("actionConfigs").includes("unhold"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿取消保持"}));if(t){if(!e)throw new Error(JSON.stringify({code:1,msg:"当前未处于保持状态"}));ys.__internalSend({type:st.CALL_UNHOLD,data:{session_id:t}})}}sendDTMF(e){if(1!==gt.get("answerDevice"))throw new Error(JSON.stringify({code:1,msg:"当前设备不支持此功能"}));if(!gt.get("actionConfigs").includes("dtmf"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿发送按键"}));const{isCalling:t}=gt.getState();if(!t)throw new Error(JSON.stringify({code:1,msg:"当前没有通话"}));this.sipClient.sendDTMF(e)}cancelCall(){if(!gt.get("isCalling"))throw new Error(JSON.stringify({code:1,msg:"当前没有通话"}));const e=dt.sessionId;ht.emit(rt.REJECT,{session_id:e}),ys.__internalSend({type:st.AGENT_HANGUP,data:{session_id:e}})}async consultCall(e){this.roleMute();const{isCalling:t,outCallIsAnswer:s,consultIsAnswer:i,incomingIsAnswer:r}=gt.getState(),n=dt.sessionId;if(!gt.get("actionConfigs").includes("consult"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿调用咨询"}));if(i)throw new Error(JSON.stringify({code:1,msg:"当前正在咨询"}));if(!(t||s||r))throw new Error(JSON.stringify({code:1,msg:"当前没有通话"}));if(!n)throw new Error(JSON.stringify({code:1,msg:"sessionId不存在"}));ys.__internalSend({type:st.CONSULT_REQUEST,data:{session_id:n,consultation_agent_no:e}})}async answerCall(){if(1!==gt.get("answerDevice"))throw new Error(JSON.stringify({code:1,msg:"当前设备不支持此功能"}));await this.sipClient.answerCall()}makeCall(e){if("string"!=typeof e||""===e.trim())throw new Error(JSON.stringify({code:1,msg:"外呼号码非法"}));const t={};Jt(e)?t.trace_id=e:t.customer_phone=e.replace(/[\s\r\n-]+/g,"");const s=gt.get("isCalling"),i=gt.get("selectOutNumber")||"";if(s)throw new Error(JSON.stringify({code:1,msg:"正在呼叫中,请勿重复点击"}));gt.updateIsCalling(!0),gt.updateDirection(tt.OUTGOING),ys.__internalSend({type:st.OUT_CALL,data:{...t,caller:i.replace(/[\s\r\n-]+/g,"")}})}previewCall(e,t){const s={};Jt(e)?s.trace_id=e:s.customer_phone=e.replace(/[\s\r\n-]+/g,"");const i=gt.get("isCalling"),r=gt.get("selectOutNumber")||"";if(i)throw new Error(JSON.stringify({code:1,msg:"正在呼叫中,请勿重复点击"}));if("string"!=typeof e||""===e.trim())throw new Error(JSON.stringify({code:1,msg:"外呼号码非法"}));gt.updateIsCalling(!0),gt.updateDirection(tt.OUTGOING),ys.__internalSend({type:st.PREVIEW_OUT_CALL,data:{...s,caller:r,preview_task_id:t}})}async hangup(){if(!gt.get("isCalling"))throw new Error(JSON.stringify({code:1,msg:"当前没有通话"}));const e=dt.sessionId;ys.__internalSend({type:st.AGENT_HANGUP,data:{session_id:e}})}mute(){this.roleMute();const e=gt.get("actionConfigs"),t=gt.get("isMuted"),s=dt.sessionId;if(t)throw new Error(JSON.stringify({code:1,msg:"当前未处于静音状态"}));if(!e.includes("mute"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿调用静音"}));ys.__internalSend({type:st.MUTE,data:{session_id:s}})}unmute(){this.roleMute();const e=gt.get("actionConfigs"),t=gt.get("isMuted"),s=dt.sessionId;if(!t)throw new Error(JSON.stringify({code:1,msg:"当前未处于未静音状态"}));if(!e.includes("unmute"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿调用静音"}));ys.__internalSend({type:st.UNMUTE,data:{session_id:s}})}consultTransfer(){this.roleMute();const e=gt.get("consultIsAnswer"),t=dt.sessionId;if(!gt.get("actionConfigs").includes("consult_transfer"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿调用咨询转移"}));if(!e)throw new Error(JSON.stringify({code:1,msg:"当前未处于咨询中"}));ys.__internalSend({type:st.CONSULT_TRANSFER,data:{session_id:t}})}satisfactionEvaluation(){this.roleMute();const e=dt.sessionId;if(!gt.get("actionConfigs").includes("satisfaction"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿调用满意度评价"}));ys.__internalSend({type:st.SATISFACTION_EVALUATION,data:{session_id:e}})}startConference(){this.roleMute();if(!gt.get("actionConfigs").includes("conference"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿调用三方会议"}));const e=dt.sessionId;if(!gt.get("consultIsAnswer"))throw new Error(JSON.stringify({code:1,msg:"当前未处于咨询中"}));ys.__internalSend({type:st.CONSULT_THREE_WAY,data:{session_id:e}})}consultRetrieve(){this.roleMute();if(!gt.get("actionConfigs").includes("consult_retrieve"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿取回通话"}));const e=dt.sessionId;if(!gt.get("consultIsAnswer"))throw new Error(JSON.stringify({code:1,msg:"当前未处于咨询中"}));ys.__internalSend({type:st.CONSULT_RETURN_CALL,data:{session_id:e}})}async transferAgent(e){this.roleMute();if(!gt.get("actionConfigs").includes("transfer"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿转接"}));const{transferIsAnswer:t}=gt.getState(),s=dt.sessionId;if(t)throw new Error(JSON.stringify({code:1,msg:"当前正在转接"}));ys.__internalSend({type:st.TRANSFER,data:{session_id:s,transfer_type:0,transfer_dest:e}})}async transferOutline(e){this.roleMute();if(!gt.get("actionConfigs").includes("transfer"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿转接"}));if(!e)throw new Error(JSON.stringify({code:1,msg:"号码不能为空"}));if(!/^\d+$/.test(e))throw new Error(JSON.stringify({code:1,msg:"号码格式错误"}));const{transferIsAnswer:t}=gt.getState(),s=dt.sessionId;if(t)throw new Error(JSON.stringify({code:1,msg:"当前正在转接"}));if(t)throw new Error(JSON.stringify({code:1,msg:"当前正在转接"}));ys.__internalSend({type:st.TRANSFER,data:{session_id:s,transfer_type:2,transfer_dest:e}})}}var bs;class Rs{static{this._instance=null}#e;#t;#s;#i;#r;#n;#o;static{this._timer=null}constructor(){if(this.#e=null,this.#t=new Ss,this.#i=null,this.#o=!1,this.#a=()=>{},this.#c=()=>{},this.initWebRtc=async()=>{if(this.#e)return;const e=dt.agentInfo.sip_account_list.find(e=>1===e.device_type);if(!e)throw new Error(JSON.stringify({code:1,msg:"未找到 sip_account_list"}));{const t=e.sip_register_addr;this.#e=new pt({server:t.split(":")[0],user:e.sip_account,password:e.sip_password,webSocket:`wss://${t}`,callTimeout:3e4},this.#h),await this.#e.start()}},this.#h=e=>{const{type:t,data:s}=e;ht.emit(t,s)},!bs._creatingInstance)throw new Error("请使用 YSYTAgentSdk.getInstance() 获取实例");clearInterval(this.#i),this.#i=setInterval(async()=>{const e=await this.#d();ut.updateRttObject(e)},2e3),ss.requestMediaPermissions(),this.#n=gt.subscribeKey("isNextState",async e=>{if(e){1===gt.get("answerDevice")&&await this.#e.reconnect();let e="";const t=new URL(Zt).host;e=Zt.includes("https")?`wss://${t}`:`ws://${t}`;const{agent_no:s}=dt.agentInfo;ys.getInstance({url:`${e}/ccs-ws/api/v1/ws/call/${s}?Authorization=`,sipClient:this.#e}),setTimeout(()=>{this.#t._changeState({data:{state:et.BUSY,state_name:"忙碌"},success:()=>{gt.updateDisplayText(""),ht.emit(rt.AGENT_STATE,{state:et.BUSY,state_name:"忙碌"})}},"d")},10)}else ys.__internalClose(),gt.updateDisplayText("离线")}),this.#r=gt.subscribeKey("answerDevice",async e=>{1===e?dt.stateObject.state===et.UNREGISTERED&&await this.#t._changeState({data:{...dt.stateBeforeChange,state_name:dt.stateBeforeChange.state===et.IDLE?"空闲":"忙碌"}},"qq"):await this.destroyRtc()}),this.on(nt.KICK_OFF,()=>{this.destroy()}),window.addEventListener("beforeunload",e=>{e.returnValue="",this.destroy()}),window.addEventListener("online",this.#a),window.addEventListener("offline",this.#c)}#a;#c;async#l(){const e=gt.get("isNextState");try{await rs(),e||gt.updateIsNextState(!0)}catch(t){ht.emit(nt.FAIL_NOTIFICATION,"网络断开,请检查网络"),e&>.updateIsNextState(!1)}}#g(){bs._timer||(bs._timer=setInterval(()=>this.#l(),3e3))}static get instance(){return this._instance}static async destroyInstance(){this._instance&&(await this._instance.destroy(),this._instance=null)}static getInstance(e){if(!this._instance){if(!e)throw new Error("首次调用必须传入配置参数");const{url:t,appKey:s,appSecret:i,agentNo:r}=e;Zt=t||"https://aicc-api.yescloudy.com",zt=s,Xt=i,Qt=r,bs._creatingInstance=!0,this._instance=new bs,delete bs._creatingInstance}return this._instance}getInit(){return this.#o}async init({enableBrowserAlert:e,logBuiltinEnabled:t,browserAlertTime:s}){try{let i="";const r=new URL(Zt).host;i=Zt.includes("https")?`wss://${r}`:`ws://${r}`;const n=ys.getInstance({url:`${i}/ccs-ws/api/v1/ws/call/${Qt}?Authorization=`,sipClient:null,onOpen:async()=>{dt.logBuiltinEnabled=t||!1,dt.browserAlertTime=s||5e3,await this.#t._agentLogin(Qt);const{current_answer_device:i,current_state:r,out_display_number:o,out_display_select_switch:a}=dt.agentInfo;r===et.IDLE?(gt.updateActionConfigs(os),dt.stateObject={state:r,state_name:"空闲"},dt.stateBeforeChange=dt.stateObject):r===et.BUSY?(gt.updateActionConfigs(as),dt.stateObject={state:r,state_name:"忙碌"},dt.stateBeforeChange=dt.stateObject):r===et.UNREGISTERED&&(gt.updateActionConfigs(as),dt.stateObject={state:r,state_name:"未注册"}),1===a?gt.updateSelectOutNumber(o):gt.updateSelectOutNumber(""),gt.updateAnswerDevice(i),Ss.setInitRtcFn(this.initWebRtc),1===i&&(await this.initWebRtc(),n.setSipClient(this.#e)),this.#s=new As(this.#e),dt.enableBrowserAlert=e,e&&ss.requestPermission(),ht.emit(nt.AGENT_INIT_STATUS,!0),this.#o=!0,clearInterval(bs._timer),bs._timer=null,this.#g()}})}catch(e){ht.emit(nt.AGENT_INIT_STATUS,!1),this.#o=!1}}#h;on(e,t){return ht.on(e,t),this}off(e,t){ht.off(e,t)}offAll(){ht.clearAllListeners()}async destroyRtc(){await(this.#e?.destroy()),this.#e=null}async destroy(){bs._instance&&(await this.destroyRtc(),this.#r?.(),this.#n?.(),clearInterval(this.#i),ys.__internalClose(),ht.emit(nt.DESTROY),this.offAll(),bs._instance=null,gt.reset(),gt.updateSelectOutNumber(""),clearInterval(bs._timer),bs._timer=null)}async#d(){return this.#e?this.#e.getNetworkStats():{}}get call_api(){const e=e=>(...t)=>e.apply(this,t);return{answerCall:e(()=>this.#s.answerCall()),makeCall:e=>this.#s.makeCall(e),previewMakeCall:(e,t)=>this.#s.previewCall(e,t),cancelCall:e(()=>this.#s.cancelCall()),hangup:e(()=>this.#s.hangup()),sendDTMF:e(e=>this.#s.sendDTMF(e)),holdCall:e(()=>this.#s.holdCall()),unholdCall:e(()=>this.#s.unholdCall()),consultCall:e(async e=>{try{await this.#s.consultCall(e)}catch(e){throw console.warn(e),e}}),consultRetrieve:e(()=>this.#s.consultRetrieve()),consultTransfer:e(()=>this.#s.consultTransfer()),mute:e(()=>this.#s.mute()),unmute:e(()=>this.#s.unmute()),satisfactionEvaluation:e(()=>this.#s.satisfactionEvaluation()),startConference:e(()=>this.#s.startConference()),transferAgent:e(e=>this.#s.transferAgent(e)),transferOutline:e(e=>this.#s.transferOutline(e)),earSpeakStart:e(e=>this.#t.earCall(e)),earSpeakStop:e(e=>this.#t.stopEarCall(e)),forceInsert:e(e=>this.#t.forceInsert(e)),forceDisconnect:e(e=>this.#t.forceDisconnect(e))}}get agent_api(){const e=e=>(...t)=>e.apply(this,t);return{changeDevice:e(e=>this.#t.changeDevice(e)),changeState:e(e=>this.#t.changeState(e,"c")),getIdleAgentList:e(e=>this.#t.getIdleAgentList(e)),getAgentState:e(e=>this.#t.getAgentState(e)),setAgentExplicit:e(e=>this.#t.setAgentExplicit(e)),checkAgentLogin:e=>this.#t.checkAgentLogin(e),getCallRecord:e=>this.#t.getCallRecord(e),agentLogout:async(e,t)=>{try{await this.#t.logout(e),await this.destroy(),t?.({code:0,msg:""})}catch(e){}},listenAgentCall:e=>this.#t.listenCall(e)}}getAgentData(){const{agent_no:e,agent_name:t,answer_devices:s,out_display_data:i,out_display_select_switch:r,current_state:n}=dt.agentInfo,{stateObject:o}=dt,a={1:"软电话",2:"手机模式",3:"SIP话机"};return{agent_no:e,agent_name:t,init_state:n,default_device:gt.get("answerDevice"),out_display_data:i,out_display_select_switch:r,answer_devices:(s||"").split(",").map(e=>({value:Number(e),label:a[Number(e)]})),stateObject:o}}async getRealTimeCustomerInfo(){return gt.get("customerObject")}setBrowserAlert(e){if("boolean"!=typeof e)throw new Error(JSON.stringify({code:1,msg:"参数类型错误"}));dt.logBuiltinEnabled=e||!1}setBrowserAlertTime(e){if("number"!=typeof e)throw new Error(JSON.stringify({code:1,msg:"参数类型错误"}));dt.browserAlertTime=e||3e3}}bs=Rs,import.meta.hot&&import.meta.hot.dispose(()=>{window.location.reload()});export{et as AgentStatus,rt as CallSipCallEventEnum,tt as DirectionEnum,ot as DisplayTextEnum,nt as EventName,it as WebRtcCallSipEventEnum,st as WebsocketTypeEnum,Rs as default};
|
|
12
|
+
Mt=Bt,function(){var s="input is invalid type",i="object"==typeof window,r=i?window:{};r.JS_MD5_NO_WINDOW&&(i=!1);var n=!i&&"object"==typeof self,o=!r.JS_MD5_NO_NODE_JS&&"object"==typeof process&&process.versions&&process.versions.node;o?r=jt:n&&(r=self);var a,c=!r.JS_MD5_NO_COMMON_JS&&Mt.exports,h=!r.JS_MD5_NO_ARRAY_BUFFER&&"undefined"!=typeof ArrayBuffer,d="0123456789abcdef".split(""),l=[128,32768,8388608,-2147483648],g=[0,8,16,24],u=["hex","array","digest","buffer","arrayBuffer","base64"],p="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),f=[];if(h){var m=new ArrayBuffer(68);a=new Uint8Array(m),f=new Uint32Array(m)}var _=Array.isArray;!r.JS_MD5_NO_NODE_JS&&_||(_=function(e){return"[object Array]"===Object.prototype.toString.call(e)});var w=ArrayBuffer.isView;!h||!r.JS_MD5_NO_ARRAY_BUFFER_IS_VIEW&&w||(w=function(e){return"object"==typeof e&&e.buffer&&e.buffer.constructor===ArrayBuffer});var T=function(e){var t=typeof e;if("string"===t)return[e,!0];if("object"!==t||null===e)throw new Error(s);if(h&&e.constructor===ArrayBuffer)return[new Uint8Array(e),!1];if(!_(e)&&!w(e))throw new Error(s);return[e,!1]},I=function(e){return function(t){return new E(!0).update(t)[e]()}},S=function(i){var n,o=e,a=t.Buffer;return n=a.from&&!r.JS_MD5_NO_BUFFER_FROM?a.from:function(e){return new a(e)},function(e){if("string"==typeof e)return o.createHash("md5").update(e,"utf8").digest("hex");if(null==e)throw new Error(s);return e.constructor===ArrayBuffer&&(e=new Uint8Array(e)),_(e)||w(e)||e.constructor===a?o.createHash("md5").update(n(e)).digest("hex"):i(e)}},C=function(e){return function(t,s){return new v(t,!0).update(s)[e]()}};function E(e){if(e)f[0]=f[16]=f[1]=f[2]=f[3]=f[4]=f[5]=f[6]=f[7]=f[8]=f[9]=f[10]=f[11]=f[12]=f[13]=f[14]=f[15]=0,this.blocks=f,this.buffer8=a;else if(h){var t=new ArrayBuffer(68);this.buffer8=new Uint8Array(t),this.blocks=new Uint32Array(t)}else this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];this.h0=this.h1=this.h2=this.h3=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0}function v(e,t){var s,i=T(e);if(e=i[0],i[1]){var r,n=[],o=e.length,a=0;for(s=0;s<o;++s)(r=e.charCodeAt(s))<128?n[a++]=r:r<2048?(n[a++]=192|r>>>6,n[a++]=128|63&r):r<55296||r>=57344?(n[a++]=224|r>>>12,n[a++]=128|r>>>6&63,n[a++]=128|63&r):(r=65536+((1023&r)<<10|1023&e.charCodeAt(++s)),n[a++]=240|r>>>18,n[a++]=128|r>>>12&63,n[a++]=128|r>>>6&63,n[a++]=128|63&r);e=n}e.length>64&&(e=new E(!0).update(e).array());var c=[],h=[];for(s=0;s<64;++s){var d=e[s]||0;c[s]=92^d,h[s]=54^d}E.call(this,t),this.update(h),this.oKeyPad=c,this.inner=!0,this.sharedMemory=t}E.prototype.update=function(e){if(this.finalized)throw new Error("finalize already called");var t=T(e);e=t[0];for(var s,i,r=t[1],n=0,o=e.length,a=this.blocks,c=this.buffer8;n<o;){if(this.hashed&&(this.hashed=!1,a[0]=a[16],a[16]=a[1]=a[2]=a[3]=a[4]=a[5]=a[6]=a[7]=a[8]=a[9]=a[10]=a[11]=a[12]=a[13]=a[14]=a[15]=0),r)if(h)for(i=this.start;n<o&&i<64;++n)(s=e.charCodeAt(n))<128?c[i++]=s:s<2048?(c[i++]=192|s>>>6,c[i++]=128|63&s):s<55296||s>=57344?(c[i++]=224|s>>>12,c[i++]=128|s>>>6&63,c[i++]=128|63&s):(s=65536+((1023&s)<<10|1023&e.charCodeAt(++n)),c[i++]=240|s>>>18,c[i++]=128|s>>>12&63,c[i++]=128|s>>>6&63,c[i++]=128|63&s);else for(i=this.start;n<o&&i<64;++n)(s=e.charCodeAt(n))<128?a[i>>>2]|=s<<g[3&i++]:s<2048?(a[i>>>2]|=(192|s>>>6)<<g[3&i++],a[i>>>2]|=(128|63&s)<<g[3&i++]):s<55296||s>=57344?(a[i>>>2]|=(224|s>>>12)<<g[3&i++],a[i>>>2]|=(128|s>>>6&63)<<g[3&i++],a[i>>>2]|=(128|63&s)<<g[3&i++]):(s=65536+((1023&s)<<10|1023&e.charCodeAt(++n)),a[i>>>2]|=(240|s>>>18)<<g[3&i++],a[i>>>2]|=(128|s>>>12&63)<<g[3&i++],a[i>>>2]|=(128|s>>>6&63)<<g[3&i++],a[i>>>2]|=(128|63&s)<<g[3&i++]);else if(h)for(i=this.start;n<o&&i<64;++n)c[i++]=e[n];else for(i=this.start;n<o&&i<64;++n)a[i>>>2]|=e[n]<<g[3&i++];this.lastByteIndex=i,this.bytes+=i-this.start,i>=64?(this.start=i-64,this.hash(),this.hashed=!0):this.start=i}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296|0,this.bytes=this.bytes%4294967296),this},E.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex;e[t>>>2]|=l[3&t],t>=56&&(this.hashed||this.hash(),e[0]=e[16],e[16]=e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=e[7]=e[8]=e[9]=e[10]=e[11]=e[12]=e[13]=e[14]=e[15]=0),e[14]=this.bytes<<3,e[15]=this.hBytes<<3|this.bytes>>>29,this.hash()}},E.prototype.hash=function(){var e,t,s,i,r,n,o=this.blocks;this.first?t=((t=((e=((e=o[0]-680876937)<<7|e>>>25)-271733879|0)^(s=((s=(-271733879^(i=((i=(-1732584194^2004318071&e)+o[1]-117830708)<<12|i>>>20)+e|0)&(-271733879^e))+o[2]-1126478375)<<17|s>>>15)+i|0)&(i^e))+o[3]-1316259209)<<22|t>>>10)+s|0:(e=this.h0,t=this.h1,s=this.h2,t=((t+=((e=((e+=((i=this.h3)^t&(s^i))+o[0]-680876936)<<7|e>>>25)+t|0)^(s=((s+=(t^(i=((i+=(s^e&(t^s))+o[1]-389564586)<<12|i>>>20)+e|0)&(e^t))+o[2]+606105819)<<17|s>>>15)+i|0)&(i^e))+o[3]-1044525330)<<22|t>>>10)+s|0),t=((t+=((e=((e+=(i^t&(s^i))+o[4]-176418897)<<7|e>>>25)+t|0)^(s=((s+=(t^(i=((i+=(s^e&(t^s))+o[5]+1200080426)<<12|i>>>20)+e|0)&(e^t))+o[6]-1473231341)<<17|s>>>15)+i|0)&(i^e))+o[7]-45705983)<<22|t>>>10)+s|0,t=((t+=((e=((e+=(i^t&(s^i))+o[8]+1770035416)<<7|e>>>25)+t|0)^(s=((s+=(t^(i=((i+=(s^e&(t^s))+o[9]-1958414417)<<12|i>>>20)+e|0)&(e^t))+o[10]-42063)<<17|s>>>15)+i|0)&(i^e))+o[11]-1990404162)<<22|t>>>10)+s|0,t=((t+=((e=((e+=(i^t&(s^i))+o[12]+1804603682)<<7|e>>>25)+t|0)^(s=((s+=(t^(i=((i+=(s^e&(t^s))+o[13]-40341101)<<12|i>>>20)+e|0)&(e^t))+o[14]-1502002290)<<17|s>>>15)+i|0)&(i^e))+o[15]+1236535329)<<22|t>>>10)+s|0,t=((t+=((i=((i+=(t^s&((e=((e+=(s^i&(t^s))+o[1]-165796510)<<5|e>>>27)+t|0)^t))+o[6]-1069501632)<<9|i>>>23)+e|0)^e&((s=((s+=(e^t&(i^e))+o[11]+643717713)<<14|s>>>18)+i|0)^i))+o[0]-373897302)<<20|t>>>12)+s|0,t=((t+=((i=((i+=(t^s&((e=((e+=(s^i&(t^s))+o[5]-701558691)<<5|e>>>27)+t|0)^t))+o[10]+38016083)<<9|i>>>23)+e|0)^e&((s=((s+=(e^t&(i^e))+o[15]-660478335)<<14|s>>>18)+i|0)^i))+o[4]-405537848)<<20|t>>>12)+s|0,t=((t+=((i=((i+=(t^s&((e=((e+=(s^i&(t^s))+o[9]+568446438)<<5|e>>>27)+t|0)^t))+o[14]-1019803690)<<9|i>>>23)+e|0)^e&((s=((s+=(e^t&(i^e))+o[3]-187363961)<<14|s>>>18)+i|0)^i))+o[8]+1163531501)<<20|t>>>12)+s|0,t=((t+=((i=((i+=(t^s&((e=((e+=(s^i&(t^s))+o[13]-1444681467)<<5|e>>>27)+t|0)^t))+o[2]-51403784)<<9|i>>>23)+e|0)^e&((s=((s+=(e^t&(i^e))+o[7]+1735328473)<<14|s>>>18)+i|0)^i))+o[12]-1926607734)<<20|t>>>12)+s|0,t=((t+=((n=(i=((i+=((r=t^s)^(e=((e+=(r^i)+o[5]-378558)<<4|e>>>28)+t|0))+o[8]-2022574463)<<11|i>>>21)+e|0)^e)^(s=((s+=(n^t)+o[11]+1839030562)<<16|s>>>16)+i|0))+o[14]-35309556)<<23|t>>>9)+s|0,t=((t+=((n=(i=((i+=((r=t^s)^(e=((e+=(r^i)+o[1]-1530992060)<<4|e>>>28)+t|0))+o[4]+1272893353)<<11|i>>>21)+e|0)^e)^(s=((s+=(n^t)+o[7]-155497632)<<16|s>>>16)+i|0))+o[10]-1094730640)<<23|t>>>9)+s|0,t=((t+=((n=(i=((i+=((r=t^s)^(e=((e+=(r^i)+o[13]+681279174)<<4|e>>>28)+t|0))+o[0]-358537222)<<11|i>>>21)+e|0)^e)^(s=((s+=(n^t)+o[3]-722521979)<<16|s>>>16)+i|0))+o[6]+76029189)<<23|t>>>9)+s|0,t=((t+=((n=(i=((i+=((r=t^s)^(e=((e+=(r^i)+o[9]-640364487)<<4|e>>>28)+t|0))+o[12]-421815835)<<11|i>>>21)+e|0)^e)^(s=((s+=(n^t)+o[15]+530742520)<<16|s>>>16)+i|0))+o[2]-995338651)<<23|t>>>9)+s|0,t=((t+=((i=((i+=(t^((e=((e+=(s^(t|~i))+o[0]-198630844)<<6|e>>>26)+t|0)|~s))+o[7]+1126891415)<<10|i>>>22)+e|0)^((s=((s+=(e^(i|~t))+o[14]-1416354905)<<15|s>>>17)+i|0)|~e))+o[5]-57434055)<<21|t>>>11)+s|0,t=((t+=((i=((i+=(t^((e=((e+=(s^(t|~i))+o[12]+1700485571)<<6|e>>>26)+t|0)|~s))+o[3]-1894986606)<<10|i>>>22)+e|0)^((s=((s+=(e^(i|~t))+o[10]-1051523)<<15|s>>>17)+i|0)|~e))+o[1]-2054922799)<<21|t>>>11)+s|0,t=((t+=((i=((i+=(t^((e=((e+=(s^(t|~i))+o[8]+1873313359)<<6|e>>>26)+t|0)|~s))+o[15]-30611744)<<10|i>>>22)+e|0)^((s=((s+=(e^(i|~t))+o[6]-1560198380)<<15|s>>>17)+i|0)|~e))+o[13]+1309151649)<<21|t>>>11)+s|0,t=((t+=((i=((i+=(t^((e=((e+=(s^(t|~i))+o[4]-145523070)<<6|e>>>26)+t|0)|~s))+o[11]-1120210379)<<10|i>>>22)+e|0)^((s=((s+=(e^(i|~t))+o[2]+718787259)<<15|s>>>17)+i|0)|~e))+o[9]-343485551)<<21|t>>>11)+s|0,this.first?(this.h0=e+1732584193|0,this.h1=t-271733879|0,this.h2=s-1732584194|0,this.h3=i+271733878|0,this.first=!1):(this.h0=this.h0+e|0,this.h1=this.h1+t|0,this.h2=this.h2+s|0,this.h3=this.h3+i|0)},E.prototype.hex=function(){this.finalize();var e=this.h0,t=this.h1,s=this.h2,i=this.h3;return d[e>>>4&15]+d[15&e]+d[e>>>12&15]+d[e>>>8&15]+d[e>>>20&15]+d[e>>>16&15]+d[e>>>28&15]+d[e>>>24&15]+d[t>>>4&15]+d[15&t]+d[t>>>12&15]+d[t>>>8&15]+d[t>>>20&15]+d[t>>>16&15]+d[t>>>28&15]+d[t>>>24&15]+d[s>>>4&15]+d[15&s]+d[s>>>12&15]+d[s>>>8&15]+d[s>>>20&15]+d[s>>>16&15]+d[s>>>28&15]+d[s>>>24&15]+d[i>>>4&15]+d[15&i]+d[i>>>12&15]+d[i>>>8&15]+d[i>>>20&15]+d[i>>>16&15]+d[i>>>28&15]+d[i>>>24&15]},E.prototype.toString=E.prototype.hex,E.prototype.digest=function(){this.finalize();var e=this.h0,t=this.h1,s=this.h2,i=this.h3;return[255&e,e>>>8&255,e>>>16&255,e>>>24&255,255&t,t>>>8&255,t>>>16&255,t>>>24&255,255&s,s>>>8&255,s>>>16&255,s>>>24&255,255&i,i>>>8&255,i>>>16&255,i>>>24&255]},E.prototype.array=E.prototype.digest,E.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(16),t=new Uint32Array(e);return t[0]=this.h0,t[1]=this.h1,t[2]=this.h2,t[3]=this.h3,e},E.prototype.buffer=E.prototype.arrayBuffer,E.prototype.base64=function(){for(var e,t,s,i="",r=this.array(),n=0;n<15;)e=r[n++],t=r[n++],s=r[n++],i+=p[e>>>2]+p[63&(e<<4|t>>>4)]+p[63&(t<<2|s>>>6)]+p[63&s];return e=r[n],i+=p[e>>>2]+p[e<<4&63]+"=="},v.prototype=new E,v.prototype.finalize=function(){if(E.prototype.finalize.call(this),this.inner){this.inner=!1;var e=this.array();E.call(this,this.sharedMemory),this.update(this.oKeyPad),this.update(e),E.prototype.finalize.call(this)}};var y=function(){var e=I("hex");o&&(e=S(e)),e.create=function(){return new E},e.update=function(t){return e.create().update(t)};for(var t=0;t<u.length;++t){var s=u[t];e[s]=I(s)}return e}();y.md5=y,y.md5.hmac=function(){var e=C("hex");e.create=function(e){return new v(e)},e.update=function(t,s){return e.create(t).update(s)};for(var t=0;t<u.length;++t){var s=u[t];e[s]=C(s)}return e}(),c?Mt.exports=y:r.md5=y}();var Wt=Bt.exports;const Vt=(e,t)=>{const s=Date.now(),i=`${e}:${s}:${Wt.md5(`${t}${s}`)}`,r=(new TextEncoder).encode(i);return btoa(String.fromCharCode(...r))},Jt=e=>{if(/^\d+$/.test(e))return!1;if(!e||"string"!=typeof e||e.length%4!=0)return!1;if(!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e))return!1;try{const t=atob(e);return btoa(t)===e}catch(e){return!1}},Kt="/v1/aicc/bmserver",Yt="/v1/aicc/ccs";let Zt="",zt="",Xt="",Qt="";function es(e){const t=Vt(zt,Xt);return Gt.create({prefixUrl:`${Zt}`,timeout:!1,headers:{Authorization:t,...e},hooks:{afterResponse:[async(e,t,s)=>{if(-1!==s.url.indexOf("heartbeat"))return s;const i=await s.clone().json();if(0!==i.code)throw new Error(JSON.stringify(i)||"请求失败");return s.json=async()=>i,s}]}})}async function ts(e,t,s){const i=es(s),r="api/"+e.replace(/^\/+/,"");return i.post(r,{json:t}).json()}class ss{static requestPermission(){"Notification"in window&&"default"===Notification.permission&&Notification.requestPermission()}static async requestMediaPermissions(){try{const e=await navigator.mediaDevices.enumerateDevices();if(e.some(e=>"audioinput"===e.kind&&""!==e.label))return null;return await navigator.mediaDevices.getUserMedia({audio:!0})}catch(e){return console.warn("获取音频权限失败:",e),null}}static show(e,t,s,i){if("Notification"in window&&"granted"===Notification.permission){const r=new Notification(e,{body:t,tag:`xy-global-notification${(new Date).getTime()}`,renotify:!0});r.onclick=()=>{window.focus(),r.close(),s?.()},setTimeout(()=>r.close(),1e3*(i||3))}}static async checkMediaPermissions(){try{return(await navigator.mediaDevices.enumerateDevices()).some(e=>"audioinput"===e.kind&&""!==e.label)}catch(e){return console.warn("无法检查设备权限:",e),!1}}}const is=(e,t)=>ts(`${Yt}/state/change?h=${t}`,e,{h:t}),rs=()=>async function(e,t){const s=es(),i=e.replace(/^\/+/,"");return s.post(i,{json:t}).json()}("/heartbeat",{}),ns=[],os=["call_number"],as=["call_number"],cs=["hangup"],hs=["hold","hangup","mute","transfer","consult","satisfaction","dtmf"],ds=["hold","hangup","mute","transfer","consult"],ls=["consult_transfer","conference","consult_retrieve"],gs=["hangup"],us=["hangup"],ps=["answer","reject"],fs=["hangup","consult","transfer","hold","mute","satisfaction","dtmf"],ms=["hangup","whisper","force_insert","force_disconnect"],_s=["hangup"],ws=["hangup","cancel_whisper","force_insert"],Ts=["hangup"],Is=["hangup"];class Ss{constructor(){this.roleData={agentInfo:()=>{if(!dt.agentInfo?.agent_no)throw new Error(JSON.stringify({code:1,msg:"请先登录"}))},requestInfo:e=>{if(!e.data)throw new Error(JSON.stringify({code:1,msg:'Parameter "data" is required'}))},changeDevice:e=>{if(!e)throw new Error(JSON.stringify({code:1,msg:'Parameter "device" is required'}));const{answer_devices:t}=dt.agentInfo;if(!t.split(",").map(e=>Number(e)).includes(e))throw new Error(JSON.stringify({code:1,msg:"当前状态不支持"}))},changeState:(e,t)=>{if(!e)throw new Error(JSON.stringify({code:1,msg:'Parameter "state" is required'}));if(!t)throw new Error(JSON.stringify({code:1,msg:'Parameter "state_name" is required'}));if(2===e&&("通话中"===t||"整理"===t))throw new Error(JSON.stringify({code:1,msg:"当前状态不支持"}));if(![1,2].includes(e))throw new Error(JSON.stringify({code:1,msg:"当前状态不支持"}))},setAgentExplicit:e=>{const{out_display_select_switch:t,out_display_data:s}=dt.agentInfo;if(1!==t)throw new Error(JSON.stringify({code:1,msg:"当前坐席设置未开启允许指定外显"}));if(!e)throw new Error(JSON.stringify({code:1,msg:'Parameter "number" is required'}));if(!(s||"").split("#").includes(e))throw new Error(JSON.stringify({code:1,msg:"当前外显号码不存在"}))}},this.changeDevice=async e=>{try{if(gt.get("isCalling"))throw new Error(JSON.stringify({code:1,msg:"当前正在通话中,请勿切换设备"}));this.roleData.agentInfo(),this.roleData.requestInfo(e);const{data:t,success:s}=e,{device:i}=t;1===i&&await Ss.initRtcFn(),this.roleData.changeDevice(i);const{agent_no:r}=dt.agentInfo;await(e=>ts(`${Yt}/device/change`,e))({agent_no:r,answer_device:i}),gt.updateAnswerDevice(i);const n=gt.get("actionConfigs");gt.updateActionConfigs(n),2===i&&dt.stateObject.state===et.UNREGISTERED&&await this._changeState({data:{...dt.stateBeforeChange,state_name:dt.stateBeforeChange.state===et.IDLE?"空闲":"忙碌"}},"q"),s?.({code:0,msg:"请求成功"})}catch(e){throw ht.emit(nt.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}}formatDate(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")} ${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}:${String(e.getSeconds()).padStart(2,"0")}`}static setInitRtcFn(e){this.initRtcFn=e}async _agentLogin(e){try{const s=await(t={agent_no:e},ts(`${Yt}/agent/login`,t));dt.agentInfo=s.data}catch(e){throw ht.emit(nt.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}var t}async _changeState(e,t){try{dt.autoStateTimer&&(clearTimeout(dt.autoStateTimer),dt.autoStateTimer=null),this.roleData.agentInfo(),this.roleData.requestInfo(e);const{data:s,success:i}=e,{state:r,state_name:n}=s,{agent_no:o}=dt.agentInfo;await is({agent_no:o,state_name:n,state:r},t),r===et.IDLE?gt.updateActionConfigs(os):r===et.BUSY&>.updateActionConfigs(as),dt.stateObject={state:r,state_name:n},i?.({code:0,msg:"请求成功"})}catch(e){throw ht.emit(nt.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}async _getInCallCrmDetail(e){try{const{phone:t}=e.data,s={};Jt(t)?s.trace_id=t:s.phone=t.replace(/[\s\r\n-]+/g,"");const i=await(e=>ts(`${Kt}/crm/popups`,e))({...s});e.success?.(i)}catch(e){throw ht.emit(nt.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}async changeState(e,t){try{if(gt.get("isCalling"))throw new Error(JSON.stringify({code:1,msg:"当前正在通话中,请勿切换设备"}));dt.autoStateTimer&&(clearTimeout(dt.autoStateTimer),dt.autoStateTimer=null),this.roleData.agentInfo(),this.roleData.requestInfo(e);const{data:s,success:i}=e,{state:r,state_name:n}=s;this.roleData.changeState(r,n);const{agent_no:o}=dt.agentInfo;await is({agent_no:o,state_name:n,state:r},t),(dt.stateObject.state===et.IDLE||dt.stateObject.state===et.BUSY&&"整理"!==n)&&(dt.stateBeforeChange=dt.stateObject),r===et.IDLE?gt.updateActionConfigs(os):r===et.BUSY&>.updateActionConfigs(as),dt.stateObject={state:r,state_name:n},i?.({code:0,msg:"请求成功"})}catch(e){throw ht.emit(nt.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}async getIdleAgentList(e){const{agent_no:t}=dt.agentInfo;try{this.roleData.agentInfo();const s=await(e=>ts(`${Yt}/agent/free`,e))({agent_no:t});e.success?.(s)}catch(e){throw ht.emit(nt.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}async getAgentState(e){try{const t=await ts(`${Kt}/agent/statecfg/list`,{}),s=(t.data||[]).filter(e=>0===e.enable).filter(e=>0!==e.state&&3!==e.state).filter(e=>"通话中"!==e.state_name&&"整理"!==e.state_name&&"未注册"!==e.state_name&&"离线接听"!==e.state_name).map(e=>({state:e.state,state_name:e.state_name})).reverse();e.success?.({...t,data:s})}catch(e){throw ht.emit(nt.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}async setAgentExplicit(e){try{this.roleData.agentInfo(),this.roleData.requestInfo(e),this.roleData.setAgentExplicit(e.data.number);const{agent_id:t}=dt.agentInfo;await(e=>ts(`${Kt}/agent/update`,e))({agent_id:t,out_display_number:e.data.number}),gt.updateSelectOutNumber(e.data.number),e.success?.({code:0,msg:"请求成功"})}catch(e){throw ht.emit(nt.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}async checkAgentLogin(e){try{this.roleData.requestInfo(e);const{agent_no:t}=e.data;if(!t)throw new Error(JSON.stringify({code:1,msg:'Parameter "agent_no" is required'}));const s=await(e=>ts(`${Yt}/agent/islogin`,e))({agent_no:t});e.success?.(s)}catch(e){throw ht.emit(nt.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}async getCallRecord(e){try{this.roleData.agentInfo();const{success:t}=e,s=new Date,i=new Date(s.getFullYear(),s.getMonth(),s.getDate(),0,0,0),r=new Date(s.getFullYear(),s.getMonth(),s.getDate(),23,59,59),n=[this.formatDate(i),this.formatDate(r)],{agent_no:o}=dt.agentInfo,a=await(e=>ts(`${Kt}/agent/recordpage`,e))({start_time:n[0],end_time:n[1],page_no:1,page_size:10,agent_no:o}),{code:c,msg:h,data:d}=a;t?.({code:c,msg:h,data:d})}catch(e){throw ht.emit(nt.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}async logout(e){this.roleData.agentInfo();try{const{agent_no:t}=dt.agentInfo,{data:s,success:i}=e;await(e=>ts(`${Yt}/agent/logout`,e))({...s,agent_no:t}),i?.({code:0,msg:""})}catch(e){throw ht.emit(nt.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}async listenCall(e){try{const{agent_no:t}=dt.agentInfo,{data:s,success:i}=e;if(this.roleData.agentInfo(),this.roleData.requestInfo(e),!s.monitored_agent_no)throw new Error(JSON.stringify({code:1,msg:'Parameter "monitored_agent_no" is required'}));await(e=>ts(`${Yt}/call/monitor`,e))({...s,monitor_agent_no:t}),dt.monitoredAgentNo=s.monitored_agent_no,i?.({code:0,msg:""})}catch(e){throw ht.emit(nt.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}async earCall(e){try{const{agentInfo:t,monitoredAgentNo:s}=dt,{agent_no:i}=t;this.roleData.agentInfo();const{success:r}=e;if(!s)throw new Error(JSON.stringify({code:1,msg:"当前未有监听坐席"}));await(e=>ts(`${Yt}/call/whisper`,e))({monitored_agent_no:s,monitor_agent_no:i}),r?.({code:0,msg:""})}catch(e){throw ht.emit(nt.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}async stopEarCall(e){try{const{agentInfo:t,earSpeakAgent:s}=dt;if(!s)throw new Error(JSON.stringify({code:1,msg:"当前没有正在耳语的坐席"}));const{agent_no:i}=t;this.roleData.agentInfo();const{success:r}=e;await(e=>ts(`${Yt}/call/stopwhisper`,e))({monitor_agent_no:i,monitored_agent_no:s}),r?.({code:0,msg:""})}catch(e){throw ht.emit(nt.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}async forceInsert(e){try{const{agentInfo:t,monitoredAgentNo:s}=dt,{agent_no:i}=t;this.roleData.agentInfo();const{success:r}=e;if(!s)throw new Error(JSON.stringify({code:1,msg:"当前未有监听坐席"}));await(e=>ts(`${Yt}/call/bargein`,e))({monitored_agent_no:s,monitor_agent_no:i}),r?.({code:0,msg:""})}catch(e){throw ht.emit(nt.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}async forceDisconnect(e){try{const{agentInfo:t,monitoredAgentNo:s}=dt,{agent_no:i}=t;this.roleData.agentInfo();const{success:r}=e;if(!s)throw new Error(JSON.stringify({code:1,msg:"当前未有监听坐席"}));await(e=>ts(`${Yt}/call/intercept`,e))({monitored_agent_no:s,monitor_agent_no:i}),r?.({code:0,msg:""})}catch(e){throw ht.emit(nt.FAIL_NOTIFICATION,JSON.parse(e.message).msg),e}}}const Cs=console.log,Es=(...e)=>{dt.logBuiltinEnabled&&Cs(...e)};let vs=null;class ys{constructor(e,t){this.url=e,this.onOpenCallback=t,this.ws=null,this.heartbeatWorker=null,this.reconnectDelay=3e3,this.manualClose=!1,this.apiClient=new Ss,this.sipClient=null,this.pendingMessages=new Map,this.initWebSocket()}static getInstance({url:e,sipClient:t,onOpen:s}){if(!vs){if(!e)throw new Error("WebSocket 尚未初始化");vs=new ys(e,s),vs.sipClient=t}return vs}setSipClient(e){this.sipClient=e}stateIdleChange(e){const{state:t}=dt.stateObject;t!==et.IDLE&&this.apiClient._changeState({data:{...dt.stateBeforeChange,state_name:dt.stateBeforeChange.state===et.IDLE?"空闲":"忙碌"}},e)}inCallAutoAnswer(){const{soft_device_auto_answer:e,auto_answer_time:t}=dt.agentInfo,s=1===e,i=gt.get("direction");if(s&&i===tt.INCOMING){const e=Number(t)||0;e>0&&(dt.autoAnswerTimer=setTimeout(()=>{this.sipClient?.answerCall(),dt.autoAnswerTimer=null},1e3*e-500))}}async getCustomerInfo(e){try{await this.apiClient._getInCallCrmDetail({data:{phone:e},success:e=>{gt.updateCustomerInfo(e.data||{phone:e.data.phone,is_vip:0,customer_name:"未知客户",city:"未知",province:"未知",contact_count:0,in_contact_count:0,trace_id:e.data.trace_id,contact_count_month:0,in_contact_count_month:0})}})}catch(e){}}putAgentState(e,t){if(!e)return;if(5===t)return void this.stateIdleChange("device_type5");dt.sessionId="";const{post_call_process_time:s}=dt.agentInfo,i=s||0;if(dt.autoStateTimer&&(clearTimeout(dt.autoStateTimer),dt.autoStateTimer=null),gt.updateCustomerInfo(void 0),i>0){const{state:e}=dt.stateObject;if(e===et.IDLE)return;this.apiClient._changeState({data:{state:et.BUSY,state_name:"整理"}},"ez"),dt.autoStateTimer=setTimeout(()=>{dt.autoStateTimer=null,this.stateIdleChange(`delay${i}`)},1e3*i)}else this.stateIdleChange("delay0")}stateBusyChange(){dt.sessionId="",clearTimeout(dt.autoStateTimer),gt.updateCustomerInfo(void 0),this.apiClient._changeState({data:{state:et.BUSY,state_name:"忙碌"}},"dm")}initWebSocket(){if(1===this.ws?.readyState)return;if(!gt.get("isNextState")||this.manualClose)return;const e=Vt(zt,Xt);this.ws=new WebSocket(this.url+e),this.ws.onopen=()=>{const e=(new Date).getTime();this.sendMessage({type:0,msg_id:e}),this.pendingMessages.set(e,performance.now()),this.startHeartbeat(),this.manualClose=!1,this.onOpenCallback&&this.onOpenCallback()},this.ws.onmessage=async e=>{const t=JSON.parse(e.data),{type:s,data:i,code:r,msg:n,msg_id:o}=t;if(0===s&&o){const e=this.pendingMessages.get(o),t=performance.now()-e;dt.latency=parseFloat(t.toFixed(2)),this.pendingMessages.delete(o)}if(0!==s&&Es("%cWebSocket 收到消息:","color: blue; font-weight: bold;",t),s!==st.OUT_CALL&&s!==st.PREVIEW_OUT_CALL||(0!==r?(gt.reset(),ht.emit(rt.OUT_FAILED,n),ht.emit(nt.FAIL_NOTIFICATION,n),gt.updateActionConfigs(os),setTimeout(()=>{gt.updateCustomerInfo(void 0)},500),this.stateIdleChange("h")):0===r&&(ht.emit(rt.OUT_SUCCESS),clearTimeout(dt.autoStateTimer))),s===st.AGENT_STATE){const{state:e,state_name:t}=i;dt.stateObject={state:e,state_name:t},dt.stateBeforeChange?.state||dt.stateObject.state!==et.IDLE&&(dt.stateObject.state!==et.BUSY||"整理"===t)||(dt.stateBeforeChange=dt.stateObject),"振铃中"===t&>.updateDisplayText(ot.AGENT_RINGING);const s=gt.get("isCalling");e!==et.UNREGISTERED||s||gt.updateActionConfigs(ns),e===et.IDLE&&dt.stateObject.state===et.UNREGISTERED&>.updateActionConfigs(os),ht.emit(rt.AGENT_STATE,{state:e,state_name:t})}else if(s===st.OUT_CALL_INCOMING_CALL){try{await this.getCustomerInfo(i.trace_id||i.customer_phone)}catch(e){console.error(e)}i.preview_task_id?ht.emit(rt.PREVIEW_OUT_INCOMING_CALL,{customer_phone:i.customer_phone,session_id:i.session_id,preview_task_id:i.preview_task_id,trace_id:i.trace_id}):0===i.direction?ht.emit(rt.OUT_INCOMING_CALL,{customer_phone:i.customer_phone,session_id:i.session_id,trace_id:i.trace_id}):8===i.direction&&ht.emit(rt.INTERNAL_OUT_INCOMING_CALL,{customer_phone:i.customer_phone,session_id:i.session_id,trace_id:i.trace_id}),dt.sessionId=i.session_id,gt.updateActionConfigs(cs,8!==i.direction)}else if(s===st.OUT_CALL_END){if(dt.sessionId!==i.session_id)return;if(gt.updateDisplayText(""),1===i.device_type&&i.agent_no===dt.agentInfo.agent_no)gt.reset(),ht.emit(rt.OUT_HANGUP,{session_id:i.session_id}),gt.updateActionConfigs(os),this.putAgentState(!0);else if(2===i.device_type&&i.agent_no===dt.agentInfo.agent_no)gt.reset(),ht.emit(rt.OUR_SIDE_CONSULT_HANGUP,{session_id:i.session_id}),gt.updateActionConfigs(os),this.putAgentState(!0);else if(2===i.device_type&&i.agent_no!==dt.agentInfo.agent_no){gt.get("isCalling")&&(gt.updateDisplayText(ot.CALLING),ht.emit(rt.OTHER_SIDE_CONSULT_HANGUP,{session_id:i.session_id}),gt.updateActionConfigs(hs))}else if(3===i.device_type&&i.agent_no===dt.agentInfo.agent_no)gt.reset(),ht.emit(rt.THREE_WAY_OUR_SIDE_HANGUP,{session_id:i.session_id}),gt.updateActionConfigs(os),this.putAgentState(!0);else if(4===i.device_type&&i.agent_no===dt.agentInfo.agent_no)gt.reset(),ht.emit(rt.TRANSFER_END,{session_id:i.session_id}),gt.updateActionConfigs(os),this.putAgentState(!0);else if(4===i.device_type&&i.agent_no!==dt.agentInfo.agent_no){ht.emit(rt.TRANSFER_FAILED,"未知原因"),ht.emit(nt.FAIL_NOTIFICATION,"转接失败");const e=gt.get("direction");e===tt.OUTGOING?gt.updateActionConfigs(hs):e===tt.INCOMING&>.updateActionConfigs(fs)}else 5===i.device_type&&i.agent_no===dt.agentInfo.agent_no&&(dt.monitoredAgentNo="",dt.earSpeakAgent="",gt.reset(),ht.emit(rt.LISTEN_HANGUP,{session_id:i.session_id}),gt.updateActionConfigs(os),this.putAgentState(!0,5))}else if(s===st.OUT_CALL_RINGING)1===i.type&&(ht.emit(rt.OUT_RINGING,{session_id:dt.sessionId,type:i.type}),gt.updateDisplayText(ot.RINGING));else if(s===st.OUT_CALL_ANSWER)clearTimeout(dt.autoStateTimer),gt.updateIsCalling(!0),gt.updateOutCallIsAnswer(!0),gt.updateDisplayText(ot.CALLING),8===i.direction?(ht.emit(rt.INTERNAL_OUT_OFF_ANSWER,{session_id:dt.sessionId}),gt.updateActionConfigs(ds)):(ht.emit(rt.OUT_OFF_ANSWER,{session_id:dt.sessionId}),gt.updateActionConfigs(hs));else if(s===st.CONSULT_RINGING)ht.emit(rt.CONSULT_RINGING,{session_id:i.session_id}),gt.updateDisplayText(ot.AGENT_RINGING),gt.updateActionConfigs([]),clearTimeout(dt.autoStateTimer);else if(s===st.CONSULT_ANSWER)ht.emit(rt.CONSULT_OFF_HOOK,{session_id:i.session_id}),gt.updateConsultIsAnswer(!0),gt.updateDisplayText(ot.CONSULTING),gt.updateActionConfigs(ls);else if(s===st.CONSULT_FAIL)ht.emit(rt.CONSULT_FAILED,{custom_reason:i.custom_reason}),gt.updateDisplayText(ot.CALLING),gt.updateActionConfigs(hs);else if(s===st.CONSULT_CALL_IN)ht.emit(rt.CONSULT_INCOMING,{agent_no:i.agent_no,agent_mane:i.agent_name,session_id:i.session_id}),dt.sessionId=i.session_id,gt.updateIsCalling(!0),gt.updateDirection(tt.CONSULT),gt.updateDisplayText(ot.CONSULT_CALL_IN),gt.updateActionConfigs(ps),dt.enableBrowserAlert&&ss.show("📞 咨询来电",`坐席 [${i.agent_name}] 正在咨询...`,()=>{ht.emit(nt.NOTIFICATION_CLICK,{agent_mane:i.agent_name,agent_no:i.agent_no})},dt.browserAlertTime);else if(s===st.CONSULT_CALL_IN_SUCCESS)ht.emit(rt.CONSULT_CALL_IN_SUCCESS,{session_id:i.session_id}),gt.updateConsultIsAnswer(!0),gt.updateDisplayText(ot.CALLING),gt.updateActionConfigs(gs);else if(s===st.CONSULT_RETURN_CALL_SUCCESS)"success"===i.status?(gt.updateConsultIsAnswer(!1),ht.emit(rt.CONSULT_RETURN_CALL_SUCCESS),gt.updateDisplayText(ot.CALLING),ht.emit(rt.OTHER_SIDE_CONSULT_HANGUP),gt.updateActionConfigs(hs)):ht.emit(nt.FAIL_NOTIFICATION,"媒体失败");else if(s===st.MUTE)0===r?(gt.updateIsMuted(!0),ht.emit(rt.MUTE_SUCCESS),gt.updateDisplayText(ot.MUTING)):(ht.emit(rt.MUTE_FAILED,n),ht.emit(nt.FAIL_NOTIFICATION,n));else if(s===st.UNMUTE)0===r?(gt.updateIsMuted(!1),ht.emit(rt.UNMUTE_SUCCESS),gt.updateDisplayText(ot.CALLING)):(ht.emit(rt.UNMUTE_FAILED,n),ht.emit(nt.FAIL_NOTIFICATION,n));else if(s===st.CALL_HOLD)0===r?(gt.updateIsHold(!0),gt.updateDisplayText(ot.HOLDING),ht.emit(rt.HOLD_SUCCESS)):(ht.emit(rt.HOLD_FAILED,n),ht.emit(nt.FAIL_NOTIFICATION,n));else if(s===st.CALL_UNHOLD)0===r?(gt.updateDisplayText(ot.CALLING),gt.updateIsHold(!1),ht.emit(rt.UNHOLD_SUCCESS)):(ht.emit(rt.UNHOLD_FAILED,n),ht.emit(nt.FAIL_NOTIFICATION,n));else if(s===st.CONSULT_TRANSFER)0===r?ht.emit(rt.CONSULT_TRANSFER_SUCCESS):(ht.emit(rt.CONSULT_TRANSFER_FAILED,n),ht.emit(nt.FAIL_NOTIFICATION,n));else if(s===st.CONSULT_TRANSFER_FAILED)ht.emit(rt.CONSULT_TRANSFER_FAILED,i.status);else if(s===st.CONSULT_TRANSFER_OFF_HOOK)gt.updateDirection(tt.INCOMING),gt.updateDisplayText(ot.CALLING),ht.emit(rt.CONSULT_TRANSFER_OFF_HOOK),gt.updateActionConfigs(fs),gt.updateIncomingIsAnswer(!0),gt.updateConsultIsAnswer(!1);else if(s===st.INCOMING_CALL){clearTimeout(dt.autoStateTimer),dt.sessionId=i.session_id;try{await this.getCustomerInfo(i.trace_id||i.customer_phone)}catch(e){console.error(e)}gt.updateIsCalling(!0),gt.updateDirection(tt.INCOMING),gt.updateDisplayText(ot.INCOMING_CALL),this.inCallAutoAnswer(),1===i.direction&&ht.emit(rt.INCOMING_CALL,{customer_phone:i.customer_phone,trace_id:i.trace_id,session_id:i.session_id}),8===i.direction&&ht.emit(rt.INCOMING_CALL_IN,{customer_phone:i.customer_phone,trace_id:i.trace_id,session_id:i.session_id}),3===i.direction&&ht.emit(rt.PREDICT_INCOMING_CALL,{customer_phone:i.customer_phone,trace_id:i.trace_id,session_id:i.session_id}),6===i.direction&&ht.emit(rt.DUAL_CALL_INCOMING_CALL,{customer_phone:i.customer_phone,trace_id:i.trace_id,session_id:i.session_id}),gt.updateActionConfigs(ps),dt.enableBrowserAlert&&ss.show("📞 客户来电",`客户 [${i.customer_phone}] 正在呼入...`,()=>{ht.emit(nt.NOTIFICATION_CLICK,{customer_phone:i.customer_phone})},dt.browserAlertTime)}else if(s===st.INCOMING_CALL_OFF_HOOK)gt.updateIncomingIsAnswer(!0),8===i.direction?(gt.updateActionConfigs(ds),ht.emit(rt.INCOMING_CALL_IN_OFF_HOOK,{session_id:dt.sessionId})):(gt.updateActionConfigs(fs),ht.emit(rt.INCOMING_CALL_OFF_HOOK,{session_id:dt.sessionId})),gt.updateDisplayText(ot.CALLING);else if(s===st.INCOMING_CALL_END){if(dt.sessionId!==i.session_id)return;if(gt.updateDisplayText(""),1!==i.device_type&&7!==i.device_type||i.agent_no!==dt.agentInfo.agent_no)if(2===i.device_type&&i.agent_no===dt.agentInfo.agent_no)gt.reset(),ht.emit(rt.OUR_SIDE_CONSULT_HANGUP,{session_id:i.session_id}),this.putAgentState(!0),gt.updateActionConfigs(os);else if(2===i.device_type&&i.agent_no!==dt.agentInfo.agent_no)gt.updateDisplayText(ot.CALLING),ht.emit(rt.OTHER_SIDE_CONSULT_HANGUP,{session_id:i.session_id}),gt.updateActionConfigs(hs);else if(3===i.device_type&&i.agent_no===dt.agentInfo.agent_no)this.putAgentState(!0),gt.reset(),ht.emit(rt.THREE_WAY_OUR_SIDE_HANGUP,{session_id:i.session_id}),gt.updateActionConfigs(os);else if(4===i.device_type&&i.agent_no===dt.agentInfo.agent_no)this.putAgentState(!0),gt.reset(),ht.emit(rt.TRANSFER_END,{session_id:i.session_id}),gt.updateActionConfigs(os);else if(4===i.device_type&&i.agent_no!==dt.agentInfo.agent_no){ht.emit(rt.TRANSFER_FAILED,"未知原因"),ht.emit(nt.FAIL_NOTIFICATION,"转接失败");const e=gt.get("direction");e===tt.OUTGOING?gt.updateActionConfigs(hs):e===tt.INCOMING&>.updateActionConfigs(fs)}else 5===i.device_type&&i.agent_no===dt.agentInfo.agent_no&&(this.putAgentState(!0,5),dt.monitoredAgentNo="",dt.earSpeakAgent="",gt.reset(),ht.emit(rt.LISTEN_HANGUP,{session_id:i.session_id}),gt.updateActionConfigs(os));else this.putAgentState(!0),gt.reset(),ht.emit(rt.INCOMING_CALL_END,{session_id:i.session_id}),gt.updateActionConfigs(os)}else if(s===st.SATISFACTION_EVALUATION)0===r?ht.emit(rt.SATISFACTION_EVALUATION_SUCCESS):(ht.emit(rt.SATISFACTION_EVALUATION_FAILED,n),ht.emit(nt.FAIL_NOTIFICATION,n));else if(s===st.CONSULT_THREE_WAY)0!==r?(ht.emit(rt.CONSULT_THREE_WAY_FAILED,n),ht.emit(nt.FAIL_NOTIFICATION,n)):0===r&>.updateIsMeeting(!0);else if(s===st.CONSULT_THREE_WAY_RESULT)"success"===i.status?(gt.updateDirection(tt.MEETING),gt.updateDisplayText(ot.MEETING),gt.updateActionConfigs(us),ht.emit(rt.CONSULT_THREE_WAY_SUCCESS)):(ht.emit(rt.CONSULT_THREE_WAY_FAILED,{conf_name:i.conf_name}),gt.updateIsMeeting(!1));else if(s===st.TRANSFER_INCOMING_CALL)clearTimeout(dt.autoStateTimer),i.agent_no===dt.agentInfo.agent_no?(gt.updateDisplayText(ot.TRANSFERRING),ht.emit(rt.TRANSFER_PROGRESS),gt.updateActionConfigs([]),gt.updateTransferIsAnswer(!0)):(dt.sessionId=i.session_id,ht.emit(rt.TRANSFER_INCOMING_CALL,{agent_no:i.agent_no,agent_name:i.agent_name,session_id:i.session_id}),gt.updateIsCalling(!0),gt.updateDirection(tt.TRANSFER),gt.updateDisplayText(ot.TRANSFER_INCOMING_CALL),gt.updateActionConfigs(ps),dt.enableBrowserAlert&&ss.show("📞 转接来电",`坐席 [${i.agent_no}] 正在转接...`,()=>{ht.emit(nt.NOTIFICATION_CLICK,{agent_no:i.agent_no})},dt.browserAlertTime));else if(s===st.TRANSFER_OFF_HOOK)ht.emit(rt.TRANSFER_OFF_HOOK,{session_id:dt.sessionId}),gt.updateTransferIsAnswer(!1),gt.updateDisplayText(ot.CALLING),gt.updateActionConfigs(fs,8!==i.direction);else if(s===st.TRANSFER_FAILED){if("failed"===i.status){ht.emit(rt.TRANSFER_FAILED,"未知原因"),ht.emit(nt.FAIL_NOTIFICATION,"转接失败");const e=gt.get("direction");e===tt.OUTGOING?gt.updateActionConfigs(hs):e===tt.INCOMING&>.updateActionConfigs(fs)}}else s===st.KICK_OFFLINE?ht.emit(nt.KICK_OFF):s===st.CONTINUOUS_NOT_ANSWER?(ht.emit(nt.FAIL_NOTIFICATION,`已连续 ${i.miss_count} 次未接, 设置忙碌`),this.stateBusyChange()):s===st.SIGN_OUT?ht.emit(nt.SIGN_OUT):s===st.SIGN_IN_SWITCH_DEVICE?ht.emit(nt.SIGN_IN_SWITCH_DEVICE,i):s===st.LISTEN_INCOMING_CALL?(clearTimeout(dt.autoStateTimer),dt.sessionId=i.session_id,gt.updateIsCalling(!0),gt.updateDirection(tt.INCOMING),this.inCallAutoAnswer(),gt.updateDisplayText(ot.LISTENING),gt.updateActionConfigs(ps),ht.emit(rt.LISTEN_INCOMING_CALL,{session_id:i.session_id}),dt.enableBrowserAlert&&ss.show("📞 监听来电","正在来电...",()=>{ht.emit(nt.NOTIFICATION_CLICK,{customer_phone:i.customer_phone})},dt.browserAlertTime)):s===st.LISTEN_INCOMING_CALL_OFF_HOOK?(dt.monitoredAgentNo=i.monitored_agent_no,dt.earSpeakAgent="",gt.updateIncomingIsAnswer(!0),ht.emit(rt.LISTEN_INCOMING_CALL_OFF_HOOK,{session_id:dt.sessionId,monitored_agent_no:i.monitored_agent_no}),gt.updateActionConfigs(ms),gt.updateDisplayText(ot.CALLING)):s===st.LISTEN_CALL_FAILED?"failed"===i.status&&(ht.emit(rt.LISTEN_CALL_FAILED),dt.monitoredAgentNo=""):s===st.EAR_SPEECH?"success"===i.status?(i.monitored_agent_no===dt.agentInfo.agent_no&&(gt.updateActionConfigs(_s),ht.emit(rt.EAR_SPEECH_BE_SUCCESS)),i.monitor_agent_no===dt.agentInfo.agent_no&&(gt.updateActionConfigs(ws),ht.emit(rt.EAR_SPEECH_SUCCESS,{monitored_agent_no:i.monitored_agent_no,monitor_agent_no:i.monitor_agent_no}),dt.earSpeakAgent=i.monitored_agent_no)):ht.emit(rt.EAR_SPEECH_FAILED):s===st.STOP_EAR_SPEECH?"success"===i.status?(i.monitored_agent_no===dt.agentInfo.agent_no&>.updateActionConfigs(fs),i.monitor_agent_no===dt.agentInfo.agent_no&>.updateActionConfigs(ms),dt.earSpeakAgent="",ht.emit(rt.STOP_EAR_SPEECH_SUCCESS)):ht.emit(rt.STOP_EAR_SPEECH_FAILED):s===st.CALL_FORCE_INSERT?"success"===i.status?(i.monitored_agent_no===dt.agentInfo.agent_no&&(gt.updateActionConfigs(Is),ht.emit(rt.CALL_FORCE_INSERT_SUCCESS,{monitored_agent_no:i.monitored_agent_no,monitor_agent_no:i.monitor_agent_no})),i.monitor_agent_no===dt.agentInfo.agent_no&&(gt.updateActionConfigs(Ts),ht.emit(rt.CALL_FORCE_INSERT_SUCCESS_LISTENER,{monitored_agent_no:i.monitored_agent_no,monitor_agent_no:i.monitor_agent_no}))):ht.emit(rt.CALL_FORCE_INSERT_FAILED):s===st.INTERNAL_CALL_START_CONSULT?i.agent_no===dt.agentInfo.agent_no?(gt.updateConsultIsAnswer(!0),gt.updateActionConfigs(ls),gt.updateDisplayText(ot.CONSULTING)):(gt.updateDisplayText(ot.OTHER_SIDE_CONSULTING),gt.updateActionConfigs([])):s===st.INTERNAL_CALL_END_CONSULT?(gt.updateActionConfigs(ds),gt.updateDisplayText(""),gt.updateConsultIsAnswer(!1)):s===st.CALL_SIP_INCOMING_CALL&&ht.emit(rt.CALL_SIP_INCOMING_CALL)},this.ws.onclose=e=>{ht.emit(nt.FAIL_NOTIFICATION,"链接已断开,请检查网络"),this.stopHeartbeat();const t=gt.get("isNextState");!this.manualClose&&t&&setTimeout(()=>this.initWebSocket(),this.reconnectDelay)},this.ws.onerror=e=>{ht.emit(nt.FAIL_NOTIFICATION,"连接失败,请检查网络"),this.ws?.close()}}startHeartbeat(){const e=new Blob(["\n let timer;\n self.onmessage = function (e) {\n if (e.data === 'start') {\n timer = setInterval(() => {\n self.postMessage('heartbeat');\n }, 5000);\n } else if (e.data === 'stop') {\n clearInterval(timer);\n }\n };\n "],{type:"application/javascript"}),t=URL.createObjectURL(e);this.heartbeatWorker=new Worker(t),this.heartbeatWorker.onmessage=()=>{const e=(new Date).getTime();this.sendMessage({type:0,msg_id:e}),this.pendingMessages.set(e,performance.now())},this.heartbeatWorker.postMessage("start")}stopHeartbeat(){this.heartbeatWorker&&(this.heartbeatWorker.postMessage("stop"),this.heartbeatWorker.terminate(),this.heartbeatWorker=null)}sendMessage(e){this.ws?.readyState===WebSocket.OPEN?(this.ws.send(JSON.stringify(e)),0!==e.type&&Es("%cWebSocket 发送消息:","color: green; font-weight: bold;",e)):console.warn("WebSocket 未连接,消息未发送")}close(){this.manualClose=!0,this.stopHeartbeat(),this.ws?.close()}reconnect(){this.initWebSocket()}static __internalClose(){vs&&(vs.close(),vs=null)}static __internalSend(e){if(!vs)throw new Error("WebSocket 尚未初始化");vs.sendMessage(e)}}class As{constructor(e){this.sipClient=null,this.sipClient=e}roleMute(){const e=gt.get("isCalling"),t=dt.sessionId;if(!e)throw new Error(JSON.stringify({code:1,msg:"当前没有通话"}));if(!t)throw new Error(JSON.stringify({code:1,msg:"当前没有通话"}))}holdCall(){this.roleMute();const e=gt.get("isHold"),{sessionId:t}=dt;if(!t)return;if(!gt.get("actionConfigs").includes("hold"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿保持"}));if(e)throw new Error(JSON.stringify({code:1,msg:"当前已处于保持状态"}));ys.__internalSend({type:st.CALL_HOLD,data:{session_id:t}})}unholdCall(){this.roleMute();const{isHold:e}=gt.getState(),{sessionId:t}=dt;if(!gt.get("actionConfigs").includes("unhold"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿取消保持"}));if(t){if(!e)throw new Error(JSON.stringify({code:1,msg:"当前未处于保持状态"}));ys.__internalSend({type:st.CALL_UNHOLD,data:{session_id:t}})}}sendDTMF(e){if(1!==gt.get("answerDevice"))throw new Error(JSON.stringify({code:1,msg:"当前设备不支持此功能"}));if(!gt.get("actionConfigs").includes("dtmf"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿发送按键"}));const{isCalling:t}=gt.getState();if(!t)throw new Error(JSON.stringify({code:1,msg:"当前没有通话"}));this.sipClient.sendDTMF(e)}cancelCall(){if(!gt.get("isCalling"))throw new Error(JSON.stringify({code:1,msg:"当前没有通话"}));const e=dt.sessionId;ht.emit(rt.REJECT,{session_id:e}),ys.__internalSend({type:st.AGENT_HANGUP,data:{session_id:e}})}async consultCall(e){this.roleMute();const{isCalling:t,outCallIsAnswer:s,consultIsAnswer:i,incomingIsAnswer:r}=gt.getState(),n=dt.sessionId;if(!gt.get("actionConfigs").includes("consult"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿调用咨询"}));if(i)throw new Error(JSON.stringify({code:1,msg:"当前正在咨询"}));if(!(t||s||r))throw new Error(JSON.stringify({code:1,msg:"当前没有通话"}));if(!n)throw new Error(JSON.stringify({code:1,msg:"sessionId不存在"}));ys.__internalSend({type:st.CONSULT_REQUEST,data:{session_id:n,consultation_agent_no:e}})}async answerCall(){if(1!==gt.get("answerDevice"))throw new Error(JSON.stringify({code:1,msg:"当前设备不支持此功能"}));await this.sipClient.answerCall()}makeCall(e){if("string"!=typeof e||""===e.trim())throw new Error(JSON.stringify({code:1,msg:"外呼号码非法"}));const t={};Jt(e)?t.trace_id=e:t.customer_phone=e.replace(/[\s\r\n-]+/g,"");const s=gt.get("isCalling"),i=gt.get("selectOutNumber")||"";if(s)throw new Error(JSON.stringify({code:1,msg:"正在呼叫中,请勿重复点击"}));gt.updateIsCalling(!0),gt.updateDirection(tt.OUTGOING),ys.__internalSend({type:st.OUT_CALL,data:{...t,caller:i.replace(/[\s\r\n-]+/g,"")}})}previewCall(e,t){const s={};Jt(e)?s.trace_id=e:s.customer_phone=e.replace(/[\s\r\n-]+/g,"");const i=gt.get("isCalling"),r=gt.get("selectOutNumber")||"";if(i)throw new Error(JSON.stringify({code:1,msg:"正在呼叫中,请勿重复点击"}));if("string"!=typeof e||""===e.trim())throw new Error(JSON.stringify({code:1,msg:"外呼号码非法"}));gt.updateIsCalling(!0),gt.updateDirection(tt.OUTGOING),ys.__internalSend({type:st.PREVIEW_OUT_CALL,data:{...s,caller:r,preview_task_id:t}})}async hangup(){if(!gt.get("isCalling"))throw new Error(JSON.stringify({code:1,msg:"当前没有通话"}));const e=dt.sessionId;ys.__internalSend({type:st.AGENT_HANGUP,data:{session_id:e}})}mute(){this.roleMute();const e=gt.get("actionConfigs"),t=gt.get("isMuted"),s=dt.sessionId;if(t)throw new Error(JSON.stringify({code:1,msg:"当前未处于静音状态"}));if(!e.includes("mute"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿调用静音"}));ys.__internalSend({type:st.MUTE,data:{session_id:s}})}unmute(){this.roleMute();const e=gt.get("actionConfigs"),t=gt.get("isMuted"),s=dt.sessionId;if(!t)throw new Error(JSON.stringify({code:1,msg:"当前未处于未静音状态"}));if(!e.includes("unmute"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿调用静音"}));ys.__internalSend({type:st.UNMUTE,data:{session_id:s}})}consultTransfer(){this.roleMute();const e=gt.get("consultIsAnswer"),t=dt.sessionId;if(!gt.get("actionConfigs").includes("consult_transfer"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿调用咨询转移"}));if(!e)throw new Error(JSON.stringify({code:1,msg:"当前未处于咨询中"}));ys.__internalSend({type:st.CONSULT_TRANSFER,data:{session_id:t}})}satisfactionEvaluation(){this.roleMute();const e=dt.sessionId;if(!gt.get("actionConfigs").includes("satisfaction"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿调用满意度评价"}));ys.__internalSend({type:st.SATISFACTION_EVALUATION,data:{session_id:e}})}startConference(){this.roleMute();if(!gt.get("actionConfigs").includes("conference"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿调用三方会议"}));const e=dt.sessionId;if(!gt.get("consultIsAnswer"))throw new Error(JSON.stringify({code:1,msg:"当前未处于咨询中"}));ys.__internalSend({type:st.CONSULT_THREE_WAY,data:{session_id:e}})}consultRetrieve(){this.roleMute();if(!gt.get("actionConfigs").includes("consult_retrieve"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿取回通话"}));const e=dt.sessionId;if(!gt.get("consultIsAnswer"))throw new Error(JSON.stringify({code:1,msg:"当前未处于咨询中"}));ys.__internalSend({type:st.CONSULT_RETURN_CALL,data:{session_id:e}})}async transferAgent(e){this.roleMute();if(!gt.get("actionConfigs").includes("transfer"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿转接"}));const{transferIsAnswer:t}=gt.getState(),s=dt.sessionId;if(t)throw new Error(JSON.stringify({code:1,msg:"当前正在转接"}));ys.__internalSend({type:st.TRANSFER,data:{session_id:s,transfer_type:0,transfer_dest:e}})}async transferOutline(e){this.roleMute();if(!gt.get("actionConfigs").includes("transfer"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿转接"}));if(!e)throw new Error(JSON.stringify({code:1,msg:"号码不能为空"}));if(!/^\d+$/.test(e))throw new Error(JSON.stringify({code:1,msg:"号码格式错误"}));const{transferIsAnswer:t}=gt.getState(),s=dt.sessionId;if(t)throw new Error(JSON.stringify({code:1,msg:"当前正在转接"}));if(t)throw new Error(JSON.stringify({code:1,msg:"当前正在转接"}));ys.__internalSend({type:st.TRANSFER,data:{session_id:s,transfer_type:2,transfer_dest:e}})}}var bs;class Rs{static{this._instance=null}#e;#t;#s;#i;#r;#n;#o;static{this._timer=null}constructor(){if(this.#e=null,this.#t=new Ss,this.#i=null,this.#o=!1,this.#a=()=>{},this.#c=()=>{},this.initWebRtc=async()=>{if(this.#e)return;const e=dt.agentInfo.sip_account_list.find(e=>1===e.device_type);if(!e)throw new Error(JSON.stringify({code:1,msg:"未找到 sip_account_list"}));{const t=e.sip_register_addr;this.#e=new pt({server:t.split(":")[0],user:e.sip_account,password:e.sip_password,webSocket:`wss://${t}`,callTimeout:3e4},this.#h),await this.#e.start()}},this.#h=e=>{const{type:t,data:s}=e;ht.emit(t,s)},!bs._creatingInstance)throw new Error("请使用 YSYTAgentSdk.getInstance() 获取实例");clearInterval(this.#i),this.#i=setInterval(async()=>{const e=await this.#d();ut.updateRttObject(e)},2e3),ss.requestMediaPermissions(),this.#n=gt.subscribeKey("isNextState",async e=>{if(e){1===gt.get("answerDevice")&&await this.#e.reconnect();let e="";const t=new URL(Zt).host;e=Zt.includes("https")?`wss://${t}`:`ws://${t}`;const{agent_no:s}=dt.agentInfo;ys.getInstance({url:`${e}/ccs-ws/api/v1/ws/call/${s}?Authorization=`,sipClient:this.#e}),setTimeout(()=>{this.#t._changeState({data:{state:et.BUSY,state_name:"忙碌"},success:()=>{gt.updateDisplayText(""),ht.emit(rt.AGENT_STATE,{state:et.BUSY,state_name:"忙碌"})}},"d")},10)}else ys.__internalClose(),gt.updateIsCalling(!1),gt.updateOutCallIsAnswer(!1),gt.updateIncomingIsAnswer(!1),gt.updateIsMuted(!1),gt.updateConsultIsAnswer(!1),gt.updateIsHold(!1),gt.updateCustomerInfo(void 0),gt.updateDisplayText("离线")}),this.#r=gt.subscribeKey("answerDevice",async e=>{1===e?dt.stateObject.state===et.UNREGISTERED&&await this.#t._changeState({data:{...dt.stateBeforeChange,state_name:dt.stateBeforeChange.state===et.IDLE?"空闲":"忙碌"}},"qq"):await this.destroyRtc()}),this.on(nt.KICK_OFF,()=>{this.destroy()}),window.addEventListener("beforeunload",e=>{e.returnValue="",this.destroy()}),window.addEventListener("online",this.#a),window.addEventListener("offline",this.#c)}#a;#c;async#l(){const e=gt.get("isNextState");try{await rs(),e||gt.updateIsNextState(!0)}catch(t){ht.emit(nt.FAIL_NOTIFICATION,"网络断开,请检查网络"),e&>.updateIsNextState(!1)}}#g(){bs._timer||(bs._timer=setInterval(()=>this.#l(),3e3))}static get instance(){return this._instance}static async destroyInstance(){this._instance&&(await this._instance.destroy(),this._instance=null)}static getInstance(e){if(!this._instance){if(!e)throw new Error("首次调用必须传入配置参数");const{url:t,appKey:s,appSecret:i,agentNo:r}=e;Zt=t||"https://aicc-api.yescloudy.com",zt=s,Xt=i,Qt=r,bs._creatingInstance=!0,this._instance=new bs,delete bs._creatingInstance}return this._instance}getInit(){return this.#o}async init({enableBrowserAlert:e,logBuiltinEnabled:t,browserAlertTime:s}){try{let i="";const r=new URL(Zt).host;i=Zt.includes("https")?`wss://${r}`:`ws://${r}`;const n=ys.getInstance({url:`${i}/ccs-ws/api/v1/ws/call/${Qt}?Authorization=`,sipClient:null,onOpen:async()=>{dt.logBuiltinEnabled=t||!1,dt.browserAlertTime=s||5e3,await this.#t._agentLogin(Qt);const{current_answer_device:i,current_state:r,out_display_number:o,out_display_select_switch:a}=dt.agentInfo;r===et.IDLE?(gt.updateActionConfigs(os),dt.stateObject={state:r,state_name:"空闲"},dt.stateBeforeChange=dt.stateObject):r===et.BUSY?(gt.updateActionConfigs(as),dt.stateObject={state:r,state_name:"忙碌"},dt.stateBeforeChange=dt.stateObject):r===et.UNREGISTERED&&(gt.updateActionConfigs(as),dt.stateObject={state:r,state_name:"未注册"}),1===a?gt.updateSelectOutNumber(o):gt.updateSelectOutNumber(""),gt.updateAnswerDevice(i),Ss.setInitRtcFn(this.initWebRtc),1===i&&(await this.initWebRtc(),n.setSipClient(this.#e)),this.#s=new As(this.#e),dt.enableBrowserAlert=e,e&&ss.requestPermission(),ht.emit(nt.AGENT_INIT_STATUS,!0),this.#o=!0,clearInterval(bs._timer),bs._timer=null,this.#g()}})}catch(e){ht.emit(nt.AGENT_INIT_STATUS,!1),this.#o=!1}}#h;on(e,t){return ht.on(e,t),this}off(e,t){ht.off(e,t)}offAll(){ht.clearAllListeners()}async destroyRtc(){await(this.#e?.destroy()),this.#e=null}async destroy(){bs._instance&&(await this.destroyRtc(),this.#r?.(),this.#n?.(),clearInterval(this.#i),ys.__internalClose(),ht.emit(nt.DESTROY),this.offAll(),bs._instance=null,gt.reset(),gt.updateSelectOutNumber(""),clearInterval(bs._timer),bs._timer=null)}async#d(){return this.#e?this.#e.getNetworkStats():{}}get call_api(){const e=e=>(...t)=>e.apply(this,t);return{answerCall:e(()=>this.#s.answerCall()),makeCall:e=>this.#s.makeCall(e),previewMakeCall:(e,t)=>this.#s.previewCall(e,t),cancelCall:e(()=>this.#s.cancelCall()),hangup:e(()=>this.#s.hangup()),sendDTMF:e(e=>this.#s.sendDTMF(e)),holdCall:e(()=>this.#s.holdCall()),unholdCall:e(()=>this.#s.unholdCall()),consultCall:e(async e=>{try{await this.#s.consultCall(e)}catch(e){throw console.warn(e),e}}),consultRetrieve:e(()=>this.#s.consultRetrieve()),consultTransfer:e(()=>this.#s.consultTransfer()),mute:e(()=>this.#s.mute()),unmute:e(()=>this.#s.unmute()),satisfactionEvaluation:e(()=>this.#s.satisfactionEvaluation()),startConference:e(()=>this.#s.startConference()),transferAgent:e(e=>this.#s.transferAgent(e)),transferOutline:e(e=>this.#s.transferOutline(e)),earSpeakStart:e(e=>this.#t.earCall(e)),earSpeakStop:e(e=>this.#t.stopEarCall(e)),forceInsert:e(e=>this.#t.forceInsert(e)),forceDisconnect:e(e=>this.#t.forceDisconnect(e))}}get agent_api(){const e=e=>(...t)=>e.apply(this,t);return{changeDevice:e(e=>this.#t.changeDevice(e)),changeState:e(async e=>{const t=gt.get("answerDevice");if(dt.stateObject.state===et.UNREGISTERED&&1===t){await this.#e.reconnect();let e="";const t=new URL(Zt).host;e=Zt.includes("https")?`wss://${t}`:`ws://${t}`;const{agent_no:s}=dt.agentInfo;ys.getInstance({url:`${e}/ccs-ws/api/v1/ws/call/${s}?Authorization=`,sipClient:this.#e})}await this.#t.changeState(e,"c")}),getIdleAgentList:e(e=>this.#t.getIdleAgentList(e)),getAgentState:e(e=>this.#t.getAgentState(e)),setAgentExplicit:e(e=>this.#t.setAgentExplicit(e)),checkAgentLogin:e=>this.#t.checkAgentLogin(e),getCallRecord:e=>this.#t.getCallRecord(e),agentLogout:async(e,t)=>{try{await this.#t.logout(e),await this.destroy(),t?.({code:0,msg:""})}catch(e){}},listenAgentCall:e=>this.#t.listenCall(e)}}getAgentData(){const{agent_no:e,agent_name:t,answer_devices:s,out_display_data:i,out_display_select_switch:r,current_state:n}=dt.agentInfo,{stateObject:o}=dt,a={1:"软电话",2:"手机模式",3:"SIP话机"};return{agent_no:e,agent_name:t,init_state:n,default_device:gt.get("answerDevice"),out_display_data:i,out_display_select_switch:r,answer_devices:(s||"").split(",").map(e=>({value:Number(e),label:a[Number(e)]})),stateObject:o}}async getRealTimeCustomerInfo(){return gt.get("customerObject")}setBrowserAlert(e){if("boolean"!=typeof e)throw new Error(JSON.stringify({code:1,msg:"参数类型错误"}));dt.logBuiltinEnabled=e||!1}setBrowserAlertTime(e){if("number"!=typeof e)throw new Error(JSON.stringify({code:1,msg:"参数类型错误"}));dt.browserAlertTime=e||3e3}}bs=Rs,import.meta.hot&&import.meta.hot.dispose(()=>{window.location.reload()});export{et as AgentStatus,rt as CallSipCallEventEnum,tt as DirectionEnum,ot as DisplayTextEnum,nt as EventName,it as WebRtcCallSipEventEnum,st as WebsocketTypeEnum,Rs as default};
|
|
@@ -9,4 +9,4 @@
|
|
|
9
9
|
* @copyright Chen, Yi-Cyuan 2014-2023
|
|
10
10
|
* @license MIT
|
|
11
11
|
*/
|
|
12
|
-
!function(e){!function(){var i="input is invalid type",r="object"==typeof window,n=r?window:{};n.JS_MD5_NO_WINDOW&&(r=!1);var o=!r&&"object"==typeof self,a=!n.JS_MD5_NO_NODE_JS&&"object"==typeof process&&process.versions&&process.versions.node;a?n=jt:o&&(n=self);var c,h=!n.JS_MD5_NO_COMMON_JS&&e.exports,d=!n.JS_MD5_NO_ARRAY_BUFFER&&"undefined"!=typeof ArrayBuffer,l="0123456789abcdef".split(""),g=[128,32768,8388608,-2147483648],u=[0,8,16,24],p=["hex","array","digest","buffer","arrayBuffer","base64"],f="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),m=[];if(d){var _=new ArrayBuffer(68);c=new Uint8Array(_),m=new Uint32Array(_)}var E=Array.isArray;!n.JS_MD5_NO_NODE_JS&&E||(E=function(e){return"[object Array]"===Object.prototype.toString.call(e)});var T=ArrayBuffer.isView;!d||!n.JS_MD5_NO_ARRAY_BUFFER_IS_VIEW&&T||(T=function(e){return"object"==typeof e&&e.buffer&&e.buffer.constructor===ArrayBuffer});var w=function(e){var t=typeof e;if("string"===t)return[e,!0];if("object"!==t||null===e)throw new Error(i);if(d&&e.constructor===ArrayBuffer)return[new Uint8Array(e),!1];if(!E(e)&&!T(e))throw new Error(i);return[e,!1]},C=function(e){return function(t){return new v(!0).update(t)[e]()}},S=function(e){var r,o=t,a=s.Buffer;r=a.from&&!n.JS_MD5_NO_BUFFER_FROM?a.from:function(e){return new a(e)};return function(t){if("string"==typeof t)return o.createHash("md5").update(t,"utf8").digest("hex");if(null==t)throw new Error(i);return t.constructor===ArrayBuffer&&(t=new Uint8Array(t)),E(t)||T(t)||t.constructor===a?o.createHash("md5").update(r(t)).digest("hex"):e(t)}},I=function(e){return function(t,s){return new y(t,!0).update(s)[e]()}};function v(e){if(e)m[0]=m[16]=m[1]=m[2]=m[3]=m[4]=m[5]=m[6]=m[7]=m[8]=m[9]=m[10]=m[11]=m[12]=m[13]=m[14]=m[15]=0,this.blocks=m,this.buffer8=c;else if(d){var t=new ArrayBuffer(68);this.buffer8=new Uint8Array(t),this.blocks=new Uint32Array(t)}else this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];this.h0=this.h1=this.h2=this.h3=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0}function y(e,t){var s,i=w(e);if(e=i[0],i[1]){var r,n=[],o=e.length,a=0;for(s=0;s<o;++s)(r=e.charCodeAt(s))<128?n[a++]=r:r<2048?(n[a++]=192|r>>>6,n[a++]=128|63&r):r<55296||r>=57344?(n[a++]=224|r>>>12,n[a++]=128|r>>>6&63,n[a++]=128|63&r):(r=65536+((1023&r)<<10|1023&e.charCodeAt(++s)),n[a++]=240|r>>>18,n[a++]=128|r>>>12&63,n[a++]=128|r>>>6&63,n[a++]=128|63&r);e=n}e.length>64&&(e=new v(!0).update(e).array());var c=[],h=[];for(s=0;s<64;++s){var d=e[s]||0;c[s]=92^d,h[s]=54^d}v.call(this,t),this.update(h),this.oKeyPad=c,this.inner=!0,this.sharedMemory=t}v.prototype.update=function(e){if(this.finalized)throw new Error("finalize already called");var t=w(e);e=t[0];for(var s,i,r=t[1],n=0,o=e.length,a=this.blocks,c=this.buffer8;n<o;){if(this.hashed&&(this.hashed=!1,a[0]=a[16],a[16]=a[1]=a[2]=a[3]=a[4]=a[5]=a[6]=a[7]=a[8]=a[9]=a[10]=a[11]=a[12]=a[13]=a[14]=a[15]=0),r)if(d)for(i=this.start;n<o&&i<64;++n)(s=e.charCodeAt(n))<128?c[i++]=s:s<2048?(c[i++]=192|s>>>6,c[i++]=128|63&s):s<55296||s>=57344?(c[i++]=224|s>>>12,c[i++]=128|s>>>6&63,c[i++]=128|63&s):(s=65536+((1023&s)<<10|1023&e.charCodeAt(++n)),c[i++]=240|s>>>18,c[i++]=128|s>>>12&63,c[i++]=128|s>>>6&63,c[i++]=128|63&s);else for(i=this.start;n<o&&i<64;++n)(s=e.charCodeAt(n))<128?a[i>>>2]|=s<<u[3&i++]:s<2048?(a[i>>>2]|=(192|s>>>6)<<u[3&i++],a[i>>>2]|=(128|63&s)<<u[3&i++]):s<55296||s>=57344?(a[i>>>2]|=(224|s>>>12)<<u[3&i++],a[i>>>2]|=(128|s>>>6&63)<<u[3&i++],a[i>>>2]|=(128|63&s)<<u[3&i++]):(s=65536+((1023&s)<<10|1023&e.charCodeAt(++n)),a[i>>>2]|=(240|s>>>18)<<u[3&i++],a[i>>>2]|=(128|s>>>12&63)<<u[3&i++],a[i>>>2]|=(128|s>>>6&63)<<u[3&i++],a[i>>>2]|=(128|63&s)<<u[3&i++]);else if(d)for(i=this.start;n<o&&i<64;++n)c[i++]=e[n];else for(i=this.start;n<o&&i<64;++n)a[i>>>2]|=e[n]<<u[3&i++];this.lastByteIndex=i,this.bytes+=i-this.start,i>=64?(this.start=i-64,this.hash(),this.hashed=!0):this.start=i}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296|0,this.bytes=this.bytes%4294967296),this},v.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex;e[t>>>2]|=g[3&t],t>=56&&(this.hashed||this.hash(),e[0]=e[16],e[16]=e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=e[7]=e[8]=e[9]=e[10]=e[11]=e[12]=e[13]=e[14]=e[15]=0),e[14]=this.bytes<<3,e[15]=this.hBytes<<3|this.bytes>>>29,this.hash()}},v.prototype.hash=function(){var e,t,s,i,r,n,o=this.blocks;this.first?t=((t=((e=((e=o[0]-680876937)<<7|e>>>25)-271733879|0)^(s=((s=(-271733879^(i=((i=(-1732584194^2004318071&e)+o[1]-117830708)<<12|i>>>20)+e|0)&(-271733879^e))+o[2]-1126478375)<<17|s>>>15)+i|0)&(i^e))+o[3]-1316259209)<<22|t>>>10)+s|0:(e=this.h0,t=this.h1,s=this.h2,t=((t+=((e=((e+=((i=this.h3)^t&(s^i))+o[0]-680876936)<<7|e>>>25)+t|0)^(s=((s+=(t^(i=((i+=(s^e&(t^s))+o[1]-389564586)<<12|i>>>20)+e|0)&(e^t))+o[2]+606105819)<<17|s>>>15)+i|0)&(i^e))+o[3]-1044525330)<<22|t>>>10)+s|0),t=((t+=((e=((e+=(i^t&(s^i))+o[4]-176418897)<<7|e>>>25)+t|0)^(s=((s+=(t^(i=((i+=(s^e&(t^s))+o[5]+1200080426)<<12|i>>>20)+e|0)&(e^t))+o[6]-1473231341)<<17|s>>>15)+i|0)&(i^e))+o[7]-45705983)<<22|t>>>10)+s|0,t=((t+=((e=((e+=(i^t&(s^i))+o[8]+1770035416)<<7|e>>>25)+t|0)^(s=((s+=(t^(i=((i+=(s^e&(t^s))+o[9]-1958414417)<<12|i>>>20)+e|0)&(e^t))+o[10]-42063)<<17|s>>>15)+i|0)&(i^e))+o[11]-1990404162)<<22|t>>>10)+s|0,t=((t+=((e=((e+=(i^t&(s^i))+o[12]+1804603682)<<7|e>>>25)+t|0)^(s=((s+=(t^(i=((i+=(s^e&(t^s))+o[13]-40341101)<<12|i>>>20)+e|0)&(e^t))+o[14]-1502002290)<<17|s>>>15)+i|0)&(i^e))+o[15]+1236535329)<<22|t>>>10)+s|0,t=((t+=((i=((i+=(t^s&((e=((e+=(s^i&(t^s))+o[1]-165796510)<<5|e>>>27)+t|0)^t))+o[6]-1069501632)<<9|i>>>23)+e|0)^e&((s=((s+=(e^t&(i^e))+o[11]+643717713)<<14|s>>>18)+i|0)^i))+o[0]-373897302)<<20|t>>>12)+s|0,t=((t+=((i=((i+=(t^s&((e=((e+=(s^i&(t^s))+o[5]-701558691)<<5|e>>>27)+t|0)^t))+o[10]+38016083)<<9|i>>>23)+e|0)^e&((s=((s+=(e^t&(i^e))+o[15]-660478335)<<14|s>>>18)+i|0)^i))+o[4]-405537848)<<20|t>>>12)+s|0,t=((t+=((i=((i+=(t^s&((e=((e+=(s^i&(t^s))+o[9]+568446438)<<5|e>>>27)+t|0)^t))+o[14]-1019803690)<<9|i>>>23)+e|0)^e&((s=((s+=(e^t&(i^e))+o[3]-187363961)<<14|s>>>18)+i|0)^i))+o[8]+1163531501)<<20|t>>>12)+s|0,t=((t+=((i=((i+=(t^s&((e=((e+=(s^i&(t^s))+o[13]-1444681467)<<5|e>>>27)+t|0)^t))+o[2]-51403784)<<9|i>>>23)+e|0)^e&((s=((s+=(e^t&(i^e))+o[7]+1735328473)<<14|s>>>18)+i|0)^i))+o[12]-1926607734)<<20|t>>>12)+s|0,t=((t+=((n=(i=((i+=((r=t^s)^(e=((e+=(r^i)+o[5]-378558)<<4|e>>>28)+t|0))+o[8]-2022574463)<<11|i>>>21)+e|0)^e)^(s=((s+=(n^t)+o[11]+1839030562)<<16|s>>>16)+i|0))+o[14]-35309556)<<23|t>>>9)+s|0,t=((t+=((n=(i=((i+=((r=t^s)^(e=((e+=(r^i)+o[1]-1530992060)<<4|e>>>28)+t|0))+o[4]+1272893353)<<11|i>>>21)+e|0)^e)^(s=((s+=(n^t)+o[7]-155497632)<<16|s>>>16)+i|0))+o[10]-1094730640)<<23|t>>>9)+s|0,t=((t+=((n=(i=((i+=((r=t^s)^(e=((e+=(r^i)+o[13]+681279174)<<4|e>>>28)+t|0))+o[0]-358537222)<<11|i>>>21)+e|0)^e)^(s=((s+=(n^t)+o[3]-722521979)<<16|s>>>16)+i|0))+o[6]+76029189)<<23|t>>>9)+s|0,t=((t+=((n=(i=((i+=((r=t^s)^(e=((e+=(r^i)+o[9]-640364487)<<4|e>>>28)+t|0))+o[12]-421815835)<<11|i>>>21)+e|0)^e)^(s=((s+=(n^t)+o[15]+530742520)<<16|s>>>16)+i|0))+o[2]-995338651)<<23|t>>>9)+s|0,t=((t+=((i=((i+=(t^((e=((e+=(s^(t|~i))+o[0]-198630844)<<6|e>>>26)+t|0)|~s))+o[7]+1126891415)<<10|i>>>22)+e|0)^((s=((s+=(e^(i|~t))+o[14]-1416354905)<<15|s>>>17)+i|0)|~e))+o[5]-57434055)<<21|t>>>11)+s|0,t=((t+=((i=((i+=(t^((e=((e+=(s^(t|~i))+o[12]+1700485571)<<6|e>>>26)+t|0)|~s))+o[3]-1894986606)<<10|i>>>22)+e|0)^((s=((s+=(e^(i|~t))+o[10]-1051523)<<15|s>>>17)+i|0)|~e))+o[1]-2054922799)<<21|t>>>11)+s|0,t=((t+=((i=((i+=(t^((e=((e+=(s^(t|~i))+o[8]+1873313359)<<6|e>>>26)+t|0)|~s))+o[15]-30611744)<<10|i>>>22)+e|0)^((s=((s+=(e^(i|~t))+o[6]-1560198380)<<15|s>>>17)+i|0)|~e))+o[13]+1309151649)<<21|t>>>11)+s|0,t=((t+=((i=((i+=(t^((e=((e+=(s^(t|~i))+o[4]-145523070)<<6|e>>>26)+t|0)|~s))+o[11]-1120210379)<<10|i>>>22)+e|0)^((s=((s+=(e^(i|~t))+o[2]+718787259)<<15|s>>>17)+i|0)|~e))+o[9]-343485551)<<21|t>>>11)+s|0,this.first?(this.h0=e+1732584193|0,this.h1=t-271733879|0,this.h2=s-1732584194|0,this.h3=i+271733878|0,this.first=!1):(this.h0=this.h0+e|0,this.h1=this.h1+t|0,this.h2=this.h2+s|0,this.h3=this.h3+i|0)},v.prototype.hex=function(){this.finalize();var e=this.h0,t=this.h1,s=this.h2,i=this.h3;return l[e>>>4&15]+l[15&e]+l[e>>>12&15]+l[e>>>8&15]+l[e>>>20&15]+l[e>>>16&15]+l[e>>>28&15]+l[e>>>24&15]+l[t>>>4&15]+l[15&t]+l[t>>>12&15]+l[t>>>8&15]+l[t>>>20&15]+l[t>>>16&15]+l[t>>>28&15]+l[t>>>24&15]+l[s>>>4&15]+l[15&s]+l[s>>>12&15]+l[s>>>8&15]+l[s>>>20&15]+l[s>>>16&15]+l[s>>>28&15]+l[s>>>24&15]+l[i>>>4&15]+l[15&i]+l[i>>>12&15]+l[i>>>8&15]+l[i>>>20&15]+l[i>>>16&15]+l[i>>>28&15]+l[i>>>24&15]},v.prototype.toString=v.prototype.hex,v.prototype.digest=function(){this.finalize();var e=this.h0,t=this.h1,s=this.h2,i=this.h3;return[255&e,e>>>8&255,e>>>16&255,e>>>24&255,255&t,t>>>8&255,t>>>16&255,t>>>24&255,255&s,s>>>8&255,s>>>16&255,s>>>24&255,255&i,i>>>8&255,i>>>16&255,i>>>24&255]},v.prototype.array=v.prototype.digest,v.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(16),t=new Uint32Array(e);return t[0]=this.h0,t[1]=this.h1,t[2]=this.h2,t[3]=this.h3,e},v.prototype.buffer=v.prototype.arrayBuffer,v.prototype.base64=function(){for(var e,t,s,i="",r=this.array(),n=0;n<15;)e=r[n++],t=r[n++],s=r[n++],i+=f[e>>>2]+f[63&(e<<4|t>>>4)]+f[63&(t<<2|s>>>6)]+f[63&s];return e=r[n],i+=f[e>>>2]+f[e<<4&63]+"=="},y.prototype=new v,y.prototype.finalize=function(){if(v.prototype.finalize.call(this),this.inner){this.inner=!1;var e=this.array();v.call(this,this.sharedMemory),this.update(this.oKeyPad),this.update(e),v.prototype.finalize.call(this)}};var A=function(){var e=C("hex");a&&(e=S(e)),e.create=function(){return new v},e.update=function(t){return e.create().update(t)};for(var t=0;t<p.length;++t){var s=p[t];e[s]=C(s)}return e}();A.md5=A,A.md5.hmac=function(){var e=I("hex");e.create=function(e){return new y(e)},e.update=function(t,s){return e.create(t).update(s)};for(var t=0;t<p.length;++t){var s=p[t];e[s]=I(s)}return e}(),h?e.exports=A:n.md5=A}()}(Bt);var Wt=Bt.exports;const Vt=(e,t)=>{const s=Date.now(),i=`${e}:${s}:${Wt.md5(`${t}${s}`)}`,r=(new TextEncoder).encode(i);return btoa(String.fromCharCode(...r))},Jt=e=>{if(/^\d+$/.test(e))return!1;if(!e||"string"!=typeof e||e.length%4!=0)return!1;if(!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e))return!1;try{const t=atob(e);return btoa(t)===e}catch(e){return!1}},Kt="/v1/aicc/bmserver",Yt="/v1/aicc/ccs";let Zt="",zt="",Xt="",Qt="";function es(e){const t=Vt(zt,Xt);return Gt.create({prefixUrl:`${Zt}`,timeout:!1,headers:{Authorization:t,...e},hooks:{afterResponse:[async(e,t,s)=>{if(-1!==s.url.indexOf("heartbeat"))return s;const i=await s.clone().json();if(0!==i.code)throw new Error(JSON.stringify(i)||"请求失败");return s.json=async()=>i,s}]}})}async function ts(e,t,s){const i=es(s),r="api/"+e.replace(/^\/+/,"");return i.post(r,{json:t}).json()}class ss{static requestPermission(){"Notification"in window&&"default"===Notification.permission&&Notification.requestPermission()}static async requestMediaPermissions(){try{const e=await navigator.mediaDevices.enumerateDevices();if(e.some(e=>"audioinput"===e.kind&&""!==e.label))return null;return await navigator.mediaDevices.getUserMedia({audio:!0})}catch(e){return console.warn("获取音频权限失败:",e),null}}static show(e,t,s,i){if("Notification"in window&&"granted"===Notification.permission){const r=new Notification(e,{body:t,tag:`xy-global-notification${(new Date).getTime()}`,renotify:!0});r.onclick=()=>{window.focus(),r.close(),s?.()},setTimeout(()=>r.close(),1e3*(i||3))}}static async checkMediaPermissions(){try{return(await navigator.mediaDevices.enumerateDevices()).some(e=>"audioinput"===e.kind&&""!==e.label)}catch(e){return console.warn("无法检查设备权限:",e),!1}}}const is=(e,t)=>ts(`${Yt}/state/change?h=${t}`,e,{h:t}),rs=()=>async function(e,t){const s=es(),i=e.replace(/^\/+/,"");return s.post(i,{json:t}).json()}("/heartbeat",{}),ns=[],os=["call_number"],as=["call_number"],cs=["hangup"],hs=["hold","hangup","mute","transfer","consult","satisfaction","dtmf"],ds=["hold","hangup","mute","transfer","consult"],ls=["consult_transfer","conference","consult_retrieve"],gs=["hangup"],us=["hangup"],ps=["answer","reject"],fs=["hangup","consult","transfer","hold","mute","satisfaction","dtmf"],ms=["hangup","whisper","force_insert","force_disconnect"],_s=["hangup"],Es=["hangup","cancel_whisper","force_insert"],Ts=["hangup"],ws=["hangup"];class Cs{constructor(){this.roleData={agentInfo:()=>{if(!lt.agentInfo?.agent_no)throw new Error(JSON.stringify({code:1,msg:"请先登录"}))},requestInfo:e=>{if(!e.data)throw new Error(JSON.stringify({code:1,msg:'Parameter "data" is required'}))},changeDevice:e=>{if(!e)throw new Error(JSON.stringify({code:1,msg:'Parameter "device" is required'}));const{answer_devices:t}=lt.agentInfo;if(!t.split(",").map(e=>Number(e)).includes(e))throw new Error(JSON.stringify({code:1,msg:"当前状态不支持"}))},changeState:(e,t)=>{if(!e)throw new Error(JSON.stringify({code:1,msg:'Parameter "state" is required'}));if(!t)throw new Error(JSON.stringify({code:1,msg:'Parameter "state_name" is required'}));if(2===e&&("通话中"===t||"整理"===t))throw new Error(JSON.stringify({code:1,msg:"当前状态不支持"}));if(![1,2].includes(e))throw new Error(JSON.stringify({code:1,msg:"当前状态不支持"}))},setAgentExplicit:e=>{const{out_display_select_switch:t,out_display_data:s}=lt.agentInfo;if(1!==t)throw new Error(JSON.stringify({code:1,msg:"当前坐席设置未开启允许指定外显"}));if(!e)throw new Error(JSON.stringify({code:1,msg:'Parameter "number" is required'}));if(!(s||"").split("#").includes(e))throw new Error(JSON.stringify({code:1,msg:"当前外显号码不存在"}))}},this.changeDevice=async t=>{try{if(ut.get("isCalling"))throw new Error(JSON.stringify({code:1,msg:"当前正在通话中,请勿切换设备"}));this.roleData.agentInfo(),this.roleData.requestInfo(t);const{data:s,success:i}=t,{device:r}=s;1===r&&await Cs.initRtcFn(),this.roleData.changeDevice(r);const{agent_no:n}=lt.agentInfo;await(e=>ts(`${Yt}/device/change`,e))({agent_no:n,answer_device:r}),ut.updateAnswerDevice(r);const o=ut.get("actionConfigs");ut.updateActionConfigs(o),2===r&<.stateObject.state===e.AgentStatus.UNREGISTERED&&await this._changeState({data:{...lt.stateBeforeChange,state_name:lt.stateBeforeChange.state===e.AgentStatus.IDLE?"空闲":"忙碌"}},"q"),i?.({code:0,msg:"请求成功"})}catch(t){throw dt.emit(e.EventName.FAIL_NOTIFICATION,JSON.parse(t.message).msg),t}}}formatDate(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")} ${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}:${String(e.getSeconds()).padStart(2,"0")}`}static setInitRtcFn(e){this.initRtcFn=e}async _agentLogin(t){try{const e=await(s={agent_no:t},ts(`${Yt}/agent/login`,s));lt.agentInfo=e.data}catch(t){throw dt.emit(e.EventName.FAIL_NOTIFICATION,JSON.parse(t.message).msg),t}var s}async _changeState(t,s){try{lt.autoStateTimer&&(clearTimeout(lt.autoStateTimer),lt.autoStateTimer=null),this.roleData.agentInfo(),this.roleData.requestInfo(t);const{data:i,success:r}=t,{state:n,state_name:o}=i,{agent_no:a}=lt.agentInfo;await is({agent_no:a,state_name:o,state:n},s),n===e.AgentStatus.IDLE?ut.updateActionConfigs(os):n===e.AgentStatus.BUSY&&ut.updateActionConfigs(as),lt.stateObject={state:n,state_name:o},r?.({code:0,msg:"请求成功"})}catch(t){throw dt.emit(e.EventName.FAIL_NOTIFICATION,JSON.parse(t.message).msg),t}}async _getInCallCrmDetail(t){try{const{phone:e}=t.data,s={};Jt(e)?s.trace_id=e:s.phone=e.replace(/[\s\r\n-]+/g,"");const i=await(e=>ts(`${Kt}/crm/popups`,e))({...s});t.success?.(i)}catch(t){throw dt.emit(e.EventName.FAIL_NOTIFICATION,JSON.parse(t.message).msg),t}}async changeState(t,s){try{if(ut.get("isCalling"))throw new Error(JSON.stringify({code:1,msg:"当前正在通话中,请勿切换设备"}));lt.autoStateTimer&&(clearTimeout(lt.autoStateTimer),lt.autoStateTimer=null),this.roleData.agentInfo(),this.roleData.requestInfo(t);const{data:i,success:r}=t,{state:n,state_name:o}=i;this.roleData.changeState(n,o);const{agent_no:a}=lt.agentInfo;await is({agent_no:a,state_name:o,state:n},s),(lt.stateObject.state===e.AgentStatus.IDLE||lt.stateObject.state===e.AgentStatus.BUSY&&"整理"!==o)&&(lt.stateBeforeChange=lt.stateObject),n===e.AgentStatus.IDLE?ut.updateActionConfigs(os):n===e.AgentStatus.BUSY&&ut.updateActionConfigs(as),lt.stateObject={state:n,state_name:o},r?.({code:0,msg:"请求成功"})}catch(t){throw dt.emit(e.EventName.FAIL_NOTIFICATION,JSON.parse(t.message).msg),t}}async getIdleAgentList(t){const{agent_no:s}=lt.agentInfo;try{this.roleData.agentInfo();const e=await(e=>ts(`${Yt}/agent/free`,e))({agent_no:s});t.success?.(e)}catch(t){throw dt.emit(e.EventName.FAIL_NOTIFICATION,JSON.parse(t.message).msg),t}}async getAgentState(t){try{const e=await ts(`${Kt}/agent/statecfg/list`,{}),s=(e.data||[]).filter(e=>0===e.enable).filter(e=>0!==e.state&&3!==e.state).filter(e=>"通话中"!==e.state_name&&"整理"!==e.state_name&&"未注册"!==e.state_name&&"离线接听"!==e.state_name).map(e=>({state:e.state,state_name:e.state_name})).reverse();t.success?.({...e,data:s})}catch(t){throw dt.emit(e.EventName.FAIL_NOTIFICATION,JSON.parse(t.message).msg),t}}async setAgentExplicit(t){try{this.roleData.agentInfo(),this.roleData.requestInfo(t),this.roleData.setAgentExplicit(t.data.number);const{agent_id:e}=lt.agentInfo;await(e=>ts(`${Kt}/agent/update`,e))({agent_id:e,out_display_number:t.data.number}),ut.updateSelectOutNumber(t.data.number),t.success?.({code:0,msg:"请求成功"})}catch(t){throw dt.emit(e.EventName.FAIL_NOTIFICATION,JSON.parse(t.message).msg),t}}async checkAgentLogin(t){try{this.roleData.requestInfo(t);const{agent_no:e}=t.data;if(!e)throw new Error(JSON.stringify({code:1,msg:'Parameter "agent_no" is required'}));const s=await(e=>ts(`${Yt}/agent/islogin`,e))({agent_no:e});t.success?.(s)}catch(t){throw dt.emit(e.EventName.FAIL_NOTIFICATION,JSON.parse(t.message).msg),t}}async getCallRecord(t){try{this.roleData.agentInfo();const{success:e}=t,s=new Date,i=new Date(s.getFullYear(),s.getMonth(),s.getDate(),0,0,0),r=new Date(s.getFullYear(),s.getMonth(),s.getDate(),23,59,59),n=[this.formatDate(i),this.formatDate(r)],{agent_no:o}=lt.agentInfo,a=await(e=>ts(`${Kt}/agent/recordpage`,e))({start_time:n[0],end_time:n[1],page_no:1,page_size:10,agent_no:o}),{code:c,msg:h,data:d}=a;e?.({code:c,msg:h,data:d})}catch(t){throw dt.emit(e.EventName.FAIL_NOTIFICATION,JSON.parse(t.message).msg),t}}async logout(t){this.roleData.agentInfo();try{const{agent_no:e}=lt.agentInfo,{data:s,success:i}=t;await(e=>ts(`${Yt}/agent/logout`,e))({...s,agent_no:e}),i?.({code:0,msg:""})}catch(t){throw dt.emit(e.EventName.FAIL_NOTIFICATION,JSON.parse(t.message).msg),t}}async listenCall(t){try{const{agent_no:e}=lt.agentInfo,{data:s,success:i}=t;if(this.roleData.agentInfo(),this.roleData.requestInfo(t),!s.monitored_agent_no)throw new Error(JSON.stringify({code:1,msg:'Parameter "monitored_agent_no" is required'}));await(e=>ts(`${Yt}/call/monitor`,e))({...s,monitor_agent_no:e}),lt.monitoredAgentNo=s.monitored_agent_no,i?.({code:0,msg:""})}catch(t){throw dt.emit(e.EventName.FAIL_NOTIFICATION,JSON.parse(t.message).msg),t}}async earCall(t){try{const{agentInfo:e,monitoredAgentNo:s}=lt,{agent_no:i}=e;this.roleData.agentInfo();const{success:r}=t;if(!s)throw new Error(JSON.stringify({code:1,msg:"当前未有监听坐席"}));await(e=>ts(`${Yt}/call/whisper`,e))({monitored_agent_no:s,monitor_agent_no:i}),r?.({code:0,msg:""})}catch(t){throw dt.emit(e.EventName.FAIL_NOTIFICATION,JSON.parse(t.message).msg),t}}async stopEarCall(t){try{const{agentInfo:e,earSpeakAgent:s}=lt;if(!s)throw new Error(JSON.stringify({code:1,msg:"当前没有正在耳语的坐席"}));const{agent_no:i}=e;this.roleData.agentInfo();const{success:r}=t;await(e=>ts(`${Yt}/call/stopwhisper`,e))({monitor_agent_no:i,monitored_agent_no:s}),r?.({code:0,msg:""})}catch(t){throw dt.emit(e.EventName.FAIL_NOTIFICATION,JSON.parse(t.message).msg),t}}async forceInsert(t){try{const{agentInfo:e,monitoredAgentNo:s}=lt,{agent_no:i}=e;this.roleData.agentInfo();const{success:r}=t;if(!s)throw new Error(JSON.stringify({code:1,msg:"当前未有监听坐席"}));await(e=>ts(`${Yt}/call/bargein`,e))({monitored_agent_no:s,monitor_agent_no:i}),r?.({code:0,msg:""})}catch(t){throw dt.emit(e.EventName.FAIL_NOTIFICATION,JSON.parse(t.message).msg),t}}async forceDisconnect(t){try{const{agentInfo:e,monitoredAgentNo:s}=lt,{agent_no:i}=e;this.roleData.agentInfo();const{success:r}=t;if(!s)throw new Error(JSON.stringify({code:1,msg:"当前未有监听坐席"}));await(e=>ts(`${Yt}/call/intercept`,e))({monitored_agent_no:s,monitor_agent_no:i}),r?.({code:0,msg:""})}catch(t){throw dt.emit(e.EventName.FAIL_NOTIFICATION,JSON.parse(t.message).msg),t}}}const Ss=console.log,Is=(...e)=>{lt.logBuiltinEnabled&&Ss(...e)};let vs=null;class ys{constructor(e,t){this.url=e,this.onOpenCallback=t,this.ws=null,this.heartbeatWorker=null,this.reconnectDelay=3e3,this.manualClose=!1,this.apiClient=new Cs,this.sipClient=null,this.pendingMessages=new Map,this.initWebSocket()}static getInstance({url:e,sipClient:t,onOpen:s}){if(!vs){if(!e)throw new Error("WebSocket 尚未初始化");vs=new ys(e,s),vs.sipClient=t}return vs}setSipClient(e){this.sipClient=e}stateIdleChange(t){const{state:s}=lt.stateObject;s!==e.AgentStatus.IDLE&&this.apiClient._changeState({data:{...lt.stateBeforeChange,state_name:lt.stateBeforeChange.state===e.AgentStatus.IDLE?"空闲":"忙碌"}},t)}inCallAutoAnswer(){const{soft_device_auto_answer:t,auto_answer_time:s}=lt.agentInfo,i=1===t,r=ut.get("direction");if(i&&r===e.DirectionEnum.INCOMING){const e=Number(s)||0;e>0&&(lt.autoAnswerTimer=setTimeout(()=>{this.sipClient?.answerCall(),lt.autoAnswerTimer=null},1e3*e-500))}}async getCustomerInfo(e){try{await this.apiClient._getInCallCrmDetail({data:{phone:e},success:e=>{ut.updateCustomerInfo(e.data||{phone:e.data.phone,is_vip:0,customer_name:"未知客户",city:"未知",province:"未知",contact_count:0,in_contact_count:0,trace_id:e.data.trace_id,contact_count_month:0,in_contact_count_month:0})}})}catch(e){}}putAgentState(t,s){if(!t)return;if(5===s)return void this.stateIdleChange("device_type5");lt.sessionId="";const{post_call_process_time:i}=lt.agentInfo,r=i||0;if(lt.autoStateTimer&&(clearTimeout(lt.autoStateTimer),lt.autoStateTimer=null),ut.updateCustomerInfo(void 0),r>0){const{state:t}=lt.stateObject;if(t===e.AgentStatus.IDLE)return;this.apiClient._changeState({data:{state:e.AgentStatus.BUSY,state_name:"整理"}},"ez"),lt.autoStateTimer=setTimeout(()=>{lt.autoStateTimer=null,this.stateIdleChange(`delay${r}`)},1e3*r)}else this.stateIdleChange("delay0")}stateBusyChange(){lt.sessionId="",clearTimeout(lt.autoStateTimer),ut.updateCustomerInfo(void 0),this.apiClient._changeState({data:{state:e.AgentStatus.BUSY,state_name:"忙碌"}},"dm")}initWebSocket(){if(1===this.ws?.readyState)return;if(!ut.get("isNextState")||this.manualClose)return;const t=Vt(zt,Xt);this.ws=new WebSocket(this.url+t),this.ws.onopen=()=>{const e=(new Date).getTime();this.sendMessage({type:0,msg_id:e}),this.pendingMessages.set(e,performance.now()),this.startHeartbeat(),this.manualClose=!1,this.onOpenCallback&&this.onOpenCallback()},this.ws.onmessage=async t=>{const s=JSON.parse(t.data),{type:i,data:r,code:n,msg:o,msg_id:a}=s;if(0===i&&a){const e=this.pendingMessages.get(a),t=performance.now()-e;lt.latency=parseFloat(t.toFixed(2)),this.pendingMessages.delete(a)}if(0!==i&&Is("%cWebSocket 收到消息:","color: blue; font-weight: bold;",s),i!==e.WebsocketTypeEnum.OUT_CALL&&i!==e.WebsocketTypeEnum.PREVIEW_OUT_CALL||(0!==n?(ut.reset(),dt.emit(e.CallSipCallEventEnum.OUT_FAILED,o),dt.emit(e.EventName.FAIL_NOTIFICATION,o),ut.updateActionConfigs(os),setTimeout(()=>{ut.updateCustomerInfo(void 0)},500),this.stateIdleChange("h")):0===n&&(dt.emit(e.CallSipCallEventEnum.OUT_SUCCESS),clearTimeout(lt.autoStateTimer))),i===e.WebsocketTypeEnum.AGENT_STATE){const{state:t,state_name:s}=r;lt.stateObject={state:t,state_name:s},lt.stateBeforeChange?.state||lt.stateObject.state!==e.AgentStatus.IDLE&&(lt.stateObject.state!==e.AgentStatus.BUSY||"整理"===s)||(lt.stateBeforeChange=lt.stateObject),"振铃中"===s&&ut.updateDisplayText(e.DisplayTextEnum.AGENT_RINGING);const i=ut.get("isCalling");t!==e.AgentStatus.UNREGISTERED||i||ut.updateActionConfigs(ns),t===e.AgentStatus.IDLE&<.stateObject.state===e.AgentStatus.UNREGISTERED&&ut.updateActionConfigs(os),dt.emit(e.CallSipCallEventEnum.AGENT_STATE,{state:t,state_name:s})}else if(i===e.WebsocketTypeEnum.OUT_CALL_INCOMING_CALL){try{await this.getCustomerInfo(r.trace_id||r.customer_phone)}catch(e){console.error(e)}r.preview_task_id?dt.emit(e.CallSipCallEventEnum.PREVIEW_OUT_INCOMING_CALL,{customer_phone:r.customer_phone,session_id:r.session_id,preview_task_id:r.preview_task_id,trace_id:r.trace_id}):1===r.direction?dt.emit(e.CallSipCallEventEnum.OUT_INCOMING_CALL,{customer_phone:r.customer_phone,session_id:r.session_id,trace_id:r.trace_id}):8===r.direction&&dt.emit(e.CallSipCallEventEnum.INTERNAL_OUT_INCOMING_CALL,{customer_phone:r.customer_phone,session_id:r.session_id,trace_id:r.trace_id}),lt.sessionId=r.session_id,ut.updateActionConfigs(cs,8!==r.direction)}else if(i===e.WebsocketTypeEnum.OUT_CALL_END){if(lt.sessionId!==r.session_id)return;if(ut.updateDisplayText(""),1===r.device_type&&r.agent_no===lt.agentInfo.agent_no)ut.reset(),dt.emit(e.CallSipCallEventEnum.OUT_HANGUP,{session_id:r.session_id}),ut.updateActionConfigs(os),this.putAgentState(!0);else if(2===r.device_type&&r.agent_no===lt.agentInfo.agent_no)ut.reset(),dt.emit(e.CallSipCallEventEnum.OUR_SIDE_CONSULT_HANGUP,{session_id:r.session_id}),ut.updateActionConfigs(os),this.putAgentState(!0);else if(2===r.device_type&&r.agent_no!==lt.agentInfo.agent_no){ut.get("isCalling")&&(ut.updateDisplayText(e.DisplayTextEnum.CALLING),dt.emit(e.CallSipCallEventEnum.OTHER_SIDE_CONSULT_HANGUP,{session_id:r.session_id}),ut.updateActionConfigs(hs))}else if(3===r.device_type&&r.agent_no===lt.agentInfo.agent_no)ut.reset(),dt.emit(e.CallSipCallEventEnum.THREE_WAY_OUR_SIDE_HANGUP,{session_id:r.session_id}),ut.updateActionConfigs(os),this.putAgentState(!0);else if(4===r.device_type&&r.agent_no===lt.agentInfo.agent_no)ut.reset(),dt.emit(e.CallSipCallEventEnum.TRANSFER_END,{session_id:r.session_id}),ut.updateActionConfigs(os),this.putAgentState(!0);else if(4===r.device_type&&r.agent_no!==lt.agentInfo.agent_no){dt.emit(e.CallSipCallEventEnum.TRANSFER_FAILED,"未知原因"),dt.emit(e.EventName.FAIL_NOTIFICATION,"转接失败");const t=ut.get("direction");t===e.DirectionEnum.OUTGOING?ut.updateActionConfigs(hs):t===e.DirectionEnum.INCOMING&&ut.updateActionConfigs(fs)}else 5===r.device_type&&r.agent_no===lt.agentInfo.agent_no&&(lt.monitoredAgentNo="",lt.earSpeakAgent="",ut.reset(),dt.emit(e.CallSipCallEventEnum.LISTEN_HANGUP,{session_id:r.session_id}),ut.updateActionConfigs(os),this.putAgentState(!0,5))}else if(i===e.WebsocketTypeEnum.OUT_CALL_RINGING)1===r.type&&(dt.emit(e.CallSipCallEventEnum.OUT_RINGING,{session_id:lt.sessionId,type:r.type}),ut.updateDisplayText(e.DisplayTextEnum.RINGING));else if(i===e.WebsocketTypeEnum.OUT_CALL_ANSWER)clearTimeout(lt.autoStateTimer),ut.updateIsCalling(!0),ut.updateOutCallIsAnswer(!0),ut.updateDisplayText(e.DisplayTextEnum.CALLING),8===r.direction?(dt.emit(e.CallSipCallEventEnum.INTERNAL_OUT_OFF_ANSWER,{session_id:lt.sessionId}),ut.updateActionConfigs(ds)):(dt.emit(e.CallSipCallEventEnum.OUT_OFF_ANSWER,{session_id:lt.sessionId}),ut.updateActionConfigs(hs));else if(i===e.WebsocketTypeEnum.CONSULT_RINGING)dt.emit(e.CallSipCallEventEnum.CONSULT_RINGING,{session_id:r.session_id}),ut.updateDisplayText(e.DisplayTextEnum.AGENT_RINGING),ut.updateActionConfigs([]),clearTimeout(lt.autoStateTimer);else if(i===e.WebsocketTypeEnum.CONSULT_ANSWER)dt.emit(e.CallSipCallEventEnum.CONSULT_OFF_HOOK,{session_id:r.session_id}),ut.updateConsultIsAnswer(!0),ut.updateDisplayText(e.DisplayTextEnum.CONSULTING),ut.updateActionConfigs(ls);else if(i===e.WebsocketTypeEnum.CONSULT_FAIL)dt.emit(e.CallSipCallEventEnum.CONSULT_FAILED,{custom_reason:r.custom_reason}),ut.updateDisplayText(e.DisplayTextEnum.CALLING),ut.updateActionConfigs(hs);else if(i===e.WebsocketTypeEnum.CONSULT_CALL_IN)dt.emit(e.CallSipCallEventEnum.CONSULT_INCOMING,{agent_no:r.agent_no,agent_mane:r.agent_name,session_id:r.session_id}),lt.sessionId=r.session_id,ut.updateIsCalling(!0),ut.updateDirection(e.DirectionEnum.CONSULT),ut.updateDisplayText(e.DisplayTextEnum.CONSULT_CALL_IN),ut.updateActionConfigs(ps),lt.enableBrowserAlert&&ss.show("📞 咨询来电",`坐席 [${r.agent_name}] 正在咨询...`,()=>{dt.emit(e.EventName.NOTIFICATION_CLICK,{agent_mane:r.agent_name,agent_no:r.agent_no})},lt.browserAlertTime);else if(i===e.WebsocketTypeEnum.CONSULT_CALL_IN_SUCCESS)dt.emit(e.CallSipCallEventEnum.CONSULT_CALL_IN_SUCCESS,{session_id:r.session_id}),ut.updateConsultIsAnswer(!0),ut.updateDisplayText(e.DisplayTextEnum.CALLING),ut.updateActionConfigs(gs);else if(i===e.WebsocketTypeEnum.CONSULT_RETURN_CALL_SUCCESS)"success"===r.status?(ut.updateConsultIsAnswer(!1),dt.emit(e.CallSipCallEventEnum.CONSULT_RETURN_CALL_SUCCESS),ut.updateDisplayText(e.DisplayTextEnum.CALLING),dt.emit(e.CallSipCallEventEnum.OTHER_SIDE_CONSULT_HANGUP),ut.updateActionConfigs(hs)):dt.emit(e.EventName.FAIL_NOTIFICATION,"媒体失败");else if(i===e.WebsocketTypeEnum.MUTE)0===n?(ut.updateIsMuted(!0),dt.emit(e.CallSipCallEventEnum.MUTE_SUCCESS),ut.updateDisplayText(e.DisplayTextEnum.MUTING)):(dt.emit(e.CallSipCallEventEnum.MUTE_FAILED,o),dt.emit(e.EventName.FAIL_NOTIFICATION,o));else if(i===e.WebsocketTypeEnum.UNMUTE)0===n?(ut.updateIsMuted(!1),dt.emit(e.CallSipCallEventEnum.UNMUTE_SUCCESS),ut.updateDisplayText(e.DisplayTextEnum.CALLING)):(dt.emit(e.CallSipCallEventEnum.UNMUTE_FAILED,o),dt.emit(e.EventName.FAIL_NOTIFICATION,o));else if(i===e.WebsocketTypeEnum.CALL_HOLD)0===n?(ut.updateIsHold(!0),ut.updateDisplayText(e.DisplayTextEnum.HOLDING),dt.emit(e.CallSipCallEventEnum.HOLD_SUCCESS)):(dt.emit(e.CallSipCallEventEnum.HOLD_FAILED,o),dt.emit(e.EventName.FAIL_NOTIFICATION,o));else if(i===e.WebsocketTypeEnum.CALL_UNHOLD)0===n?(ut.updateDisplayText(e.DisplayTextEnum.CALLING),ut.updateIsHold(!1),dt.emit(e.CallSipCallEventEnum.UNHOLD_SUCCESS)):(dt.emit(e.CallSipCallEventEnum.UNHOLD_FAILED,o),dt.emit(e.EventName.FAIL_NOTIFICATION,o));else if(i===e.WebsocketTypeEnum.CONSULT_TRANSFER)0===n?dt.emit(e.CallSipCallEventEnum.CONSULT_TRANSFER_SUCCESS):(dt.emit(e.CallSipCallEventEnum.CONSULT_TRANSFER_FAILED,o),dt.emit(e.EventName.FAIL_NOTIFICATION,o));else if(i===e.WebsocketTypeEnum.CONSULT_TRANSFER_FAILED)dt.emit(e.CallSipCallEventEnum.CONSULT_TRANSFER_FAILED,r.status);else if(i===e.WebsocketTypeEnum.CONSULT_TRANSFER_OFF_HOOK)ut.updateDirection(e.DirectionEnum.INCOMING),ut.updateDisplayText(e.DisplayTextEnum.CALLING),dt.emit(e.CallSipCallEventEnum.CONSULT_TRANSFER_OFF_HOOK),ut.updateActionConfigs(fs),ut.updateIncomingIsAnswer(!0),ut.updateConsultIsAnswer(!1);else if(i===e.WebsocketTypeEnum.INCOMING_CALL){clearTimeout(lt.autoStateTimer),lt.sessionId=r.session_id;try{await this.getCustomerInfo(r.trace_id||r.customer_phone)}catch(e){console.error(e)}ut.updateIsCalling(!0),ut.updateDirection(e.DirectionEnum.INCOMING),ut.updateDisplayText(e.DisplayTextEnum.INCOMING_CALL),this.inCallAutoAnswer(),1===r.direction&&dt.emit(e.CallSipCallEventEnum.INCOMING_CALL,{customer_phone:r.customer_phone,trace_id:r.trace_id,session_id:r.session_id}),8===r.direction&&dt.emit(e.CallSipCallEventEnum.INCOMING_CALL_IN,{customer_phone:r.customer_phone,trace_id:r.trace_id,session_id:r.session_id}),3===r.direction&&dt.emit(e.CallSipCallEventEnum.PREDICT_INCOMING_CALL,{customer_phone:r.customer_phone,trace_id:r.trace_id,session_id:r.session_id}),6===r.direction&&dt.emit(e.CallSipCallEventEnum.DUAL_CALL_INCOMING_CALL,{customer_phone:r.customer_phone,trace_id:r.trace_id,session_id:r.session_id}),ut.updateActionConfigs(ps),lt.enableBrowserAlert&&ss.show("📞 客户来电",`客户 [${r.customer_phone}] 正在呼入...`,()=>{dt.emit(e.EventName.NOTIFICATION_CLICK,{customer_phone:r.customer_phone})},lt.browserAlertTime)}else if(i===e.WebsocketTypeEnum.INCOMING_CALL_OFF_HOOK)ut.updateIncomingIsAnswer(!0),8===r.direction?(ut.updateActionConfigs(ds),dt.emit(e.CallSipCallEventEnum.INCOMING_CALL_IN_OFF_HOOK,{session_id:lt.sessionId})):(ut.updateActionConfigs(fs),dt.emit(e.CallSipCallEventEnum.INCOMING_CALL_OFF_HOOK,{session_id:lt.sessionId})),ut.updateDisplayText(e.DisplayTextEnum.CALLING);else if(i===e.WebsocketTypeEnum.INCOMING_CALL_END){if(lt.sessionId!==r.session_id)return;if(ut.updateDisplayText(""),1!==r.device_type&&7!==r.device_type||r.agent_no!==lt.agentInfo.agent_no)if(2===r.device_type&&r.agent_no===lt.agentInfo.agent_no)ut.reset(),dt.emit(e.CallSipCallEventEnum.OUR_SIDE_CONSULT_HANGUP,{session_id:r.session_id}),this.putAgentState(!0),ut.updateActionConfigs(os);else if(2===r.device_type&&r.agent_no!==lt.agentInfo.agent_no)ut.updateDisplayText(e.DisplayTextEnum.CALLING),dt.emit(e.CallSipCallEventEnum.OTHER_SIDE_CONSULT_HANGUP,{session_id:r.session_id}),ut.updateActionConfigs(hs);else if(3===r.device_type&&r.agent_no===lt.agentInfo.agent_no)this.putAgentState(!0),ut.reset(),dt.emit(e.CallSipCallEventEnum.THREE_WAY_OUR_SIDE_HANGUP,{session_id:r.session_id}),ut.updateActionConfigs(os);else if(4===r.device_type&&r.agent_no===lt.agentInfo.agent_no)this.putAgentState(!0),ut.reset(),dt.emit(e.CallSipCallEventEnum.TRANSFER_END,{session_id:r.session_id}),ut.updateActionConfigs(os);else if(4===r.device_type&&r.agent_no!==lt.agentInfo.agent_no){dt.emit(e.CallSipCallEventEnum.TRANSFER_FAILED,"未知原因"),dt.emit(e.EventName.FAIL_NOTIFICATION,"转接失败");const t=ut.get("direction");t===e.DirectionEnum.OUTGOING?ut.updateActionConfigs(hs):t===e.DirectionEnum.INCOMING&&ut.updateActionConfigs(fs)}else 5===r.device_type&&r.agent_no===lt.agentInfo.agent_no&&(this.putAgentState(!0,5),lt.monitoredAgentNo="",lt.earSpeakAgent="",ut.reset(),dt.emit(e.CallSipCallEventEnum.LISTEN_HANGUP,{session_id:r.session_id}),ut.updateActionConfigs(os));else this.putAgentState(!0),ut.reset(),dt.emit(e.CallSipCallEventEnum.INCOMING_CALL_END,{session_id:r.session_id}),ut.updateActionConfigs(os)}else if(i===e.WebsocketTypeEnum.SATISFACTION_EVALUATION)0===n?dt.emit(e.CallSipCallEventEnum.SATISFACTION_EVALUATION_SUCCESS):(dt.emit(e.CallSipCallEventEnum.SATISFACTION_EVALUATION_FAILED,o),dt.emit(e.EventName.FAIL_NOTIFICATION,o));else if(i===e.WebsocketTypeEnum.CONSULT_THREE_WAY)0!==n?(dt.emit(e.CallSipCallEventEnum.CONSULT_THREE_WAY_FAILED,o),dt.emit(e.EventName.FAIL_NOTIFICATION,o)):0===n&&ut.updateIsMeeting(!0);else if(i===e.WebsocketTypeEnum.CONSULT_THREE_WAY_RESULT)"success"===r.status?(ut.updateDirection(e.DirectionEnum.MEETING),ut.updateDisplayText(e.DisplayTextEnum.MEETING),ut.updateActionConfigs(us),dt.emit(e.CallSipCallEventEnum.CONSULT_THREE_WAY_SUCCESS)):(dt.emit(e.CallSipCallEventEnum.CONSULT_THREE_WAY_FAILED,{conf_name:r.conf_name}),ut.updateIsMeeting(!1));else if(i===e.WebsocketTypeEnum.TRANSFER_INCOMING_CALL)clearTimeout(lt.autoStateTimer),r.agent_no===lt.agentInfo.agent_no?(ut.updateDisplayText(e.DisplayTextEnum.TRANSFERRING),dt.emit(e.CallSipCallEventEnum.TRANSFER_PROGRESS),ut.updateActionConfigs([]),ut.updateTransferIsAnswer(!0)):(lt.sessionId=r.session_id,dt.emit(e.CallSipCallEventEnum.TRANSFER_INCOMING_CALL,{agent_no:r.agent_no,agent_name:r.agent_name,session_id:r.session_id}),ut.updateIsCalling(!0),ut.updateDirection(e.DirectionEnum.TRANSFER),ut.updateDisplayText(e.DisplayTextEnum.TRANSFER_INCOMING_CALL),ut.updateActionConfigs(ps),lt.enableBrowserAlert&&ss.show("📞 转接来电",`坐席 [${r.agent_no}] 正在转接...`,()=>{dt.emit(e.EventName.NOTIFICATION_CLICK,{agent_no:r.agent_no})},lt.browserAlertTime));else if(i===e.WebsocketTypeEnum.TRANSFER_OFF_HOOK)dt.emit(e.CallSipCallEventEnum.TRANSFER_OFF_HOOK,{session_id:lt.sessionId}),ut.updateTransferIsAnswer(!1),ut.updateDisplayText(e.DisplayTextEnum.CALLING),ut.updateActionConfigs(fs,8!==r.direction);else if(i===e.WebsocketTypeEnum.TRANSFER_FAILED){if("failed"===r.status){dt.emit(e.CallSipCallEventEnum.TRANSFER_FAILED,"未知原因"),dt.emit(e.EventName.FAIL_NOTIFICATION,"转接失败");const t=ut.get("direction");t===e.DirectionEnum.OUTGOING?ut.updateActionConfigs(hs):t===e.DirectionEnum.INCOMING&&ut.updateActionConfigs(fs)}}else i===e.WebsocketTypeEnum.KICK_OFFLINE?dt.emit(e.EventName.KICK_OFF):i===e.WebsocketTypeEnum.CONTINUOUS_NOT_ANSWER?(dt.emit(e.EventName.FAIL_NOTIFICATION,`已连续 ${r.miss_count} 次未接, 设置忙碌`),this.stateBusyChange()):i===e.WebsocketTypeEnum.SIGN_OUT?dt.emit(e.EventName.SIGN_OUT):i===e.WebsocketTypeEnum.SIGN_IN_SWITCH_DEVICE?dt.emit(e.EventName.SIGN_IN_SWITCH_DEVICE,r):i===e.WebsocketTypeEnum.LISTEN_INCOMING_CALL?(clearTimeout(lt.autoStateTimer),lt.sessionId=r.session_id,ut.updateIsCalling(!0),ut.updateDirection(e.DirectionEnum.INCOMING),this.inCallAutoAnswer(),ut.updateDisplayText(e.DisplayTextEnum.LISTENING),ut.updateActionConfigs(ps),dt.emit(e.CallSipCallEventEnum.LISTEN_INCOMING_CALL,{session_id:r.session_id}),lt.enableBrowserAlert&&ss.show("📞 监听来电","正在来电...",()=>{dt.emit(e.EventName.NOTIFICATION_CLICK,{customer_phone:r.customer_phone})},lt.browserAlertTime)):i===e.WebsocketTypeEnum.LISTEN_INCOMING_CALL_OFF_HOOK?(lt.monitoredAgentNo=r.monitored_agent_no,lt.earSpeakAgent="",ut.updateIncomingIsAnswer(!0),dt.emit(e.CallSipCallEventEnum.LISTEN_INCOMING_CALL_OFF_HOOK,{session_id:lt.sessionId,monitored_agent_no:r.monitored_agent_no}),ut.updateActionConfigs(ms),ut.updateDisplayText(e.DisplayTextEnum.CALLING)):i===e.WebsocketTypeEnum.LISTEN_CALL_FAILED?"failed"===r.status&&(dt.emit(e.CallSipCallEventEnum.LISTEN_CALL_FAILED),lt.monitoredAgentNo=""):i===e.WebsocketTypeEnum.EAR_SPEECH?"success"===r.status?(r.monitored_agent_no===lt.agentInfo.agent_no&&(ut.updateActionConfigs(_s),dt.emit(e.CallSipCallEventEnum.EAR_SPEECH_BE_SUCCESS)),r.monitor_agent_no===lt.agentInfo.agent_no&&(ut.updateActionConfigs(Es),dt.emit(e.CallSipCallEventEnum.EAR_SPEECH_SUCCESS,{monitored_agent_no:r.monitored_agent_no,monitor_agent_no:r.monitor_agent_no}),lt.earSpeakAgent=r.monitored_agent_no)):dt.emit(e.CallSipCallEventEnum.EAR_SPEECH_FAILED):i===e.WebsocketTypeEnum.STOP_EAR_SPEECH?"success"===r.status?(r.monitored_agent_no===lt.agentInfo.agent_no&&ut.updateActionConfigs(fs),r.monitor_agent_no===lt.agentInfo.agent_no&&ut.updateActionConfigs(ms),lt.earSpeakAgent="",dt.emit(e.CallSipCallEventEnum.STOP_EAR_SPEECH_SUCCESS)):dt.emit(e.CallSipCallEventEnum.STOP_EAR_SPEECH_FAILED):i===e.WebsocketTypeEnum.CALL_FORCE_INSERT?"success"===r.status?(r.monitored_agent_no===lt.agentInfo.agent_no&&(ut.updateActionConfigs(ws),dt.emit(e.CallSipCallEventEnum.CALL_FORCE_INSERT_SUCCESS,{monitored_agent_no:r.monitored_agent_no,monitor_agent_no:r.monitor_agent_no})),r.monitor_agent_no===lt.agentInfo.agent_no&&(ut.updateActionConfigs(Ts),dt.emit(e.CallSipCallEventEnum.CALL_FORCE_INSERT_SUCCESS_LISTENER,{monitored_agent_no:r.monitored_agent_no,monitor_agent_no:r.monitor_agent_no}))):dt.emit(e.CallSipCallEventEnum.CALL_FORCE_INSERT_FAILED):i===e.WebsocketTypeEnum.INTERNAL_CALL_START_CONSULT?r.agent_no===lt.agentInfo.agent_no?(ut.updateConsultIsAnswer(!0),ut.updateActionConfigs(ls),ut.updateDisplayText(e.DisplayTextEnum.CONSULTING)):(ut.updateDisplayText(e.DisplayTextEnum.OTHER_SIDE_CONSULTING),ut.updateActionConfigs([])):i===e.WebsocketTypeEnum.INTERNAL_CALL_END_CONSULT?(ut.updateActionConfigs(ds),ut.updateDisplayText(""),ut.updateConsultIsAnswer(!1)):i===e.WebsocketTypeEnum.CALL_SIP_INCOMING_CALL&&dt.emit(e.CallSipCallEventEnum.CALL_SIP_INCOMING_CALL)},this.ws.onclose=t=>{dt.emit(e.EventName.FAIL_NOTIFICATION,"链接已断开,请检查网络"),this.stopHeartbeat();const s=ut.get("isNextState");!this.manualClose&&s&&setTimeout(()=>this.initWebSocket(),this.reconnectDelay)},this.ws.onerror=t=>{dt.emit(e.EventName.FAIL_NOTIFICATION,"连接失败,请检查网络"),this.ws?.close()}}startHeartbeat(){const e=new Blob(["\n let timer;\n self.onmessage = function (e) {\n if (e.data === 'start') {\n timer = setInterval(() => {\n self.postMessage('heartbeat');\n }, 5000);\n } else if (e.data === 'stop') {\n clearInterval(timer);\n }\n };\n "],{type:"application/javascript"}),t=URL.createObjectURL(e);this.heartbeatWorker=new Worker(t),this.heartbeatWorker.onmessage=()=>{const e=(new Date).getTime();this.sendMessage({type:0,msg_id:e}),this.pendingMessages.set(e,performance.now())},this.heartbeatWorker.postMessage("start")}stopHeartbeat(){this.heartbeatWorker&&(this.heartbeatWorker.postMessage("stop"),this.heartbeatWorker.terminate(),this.heartbeatWorker=null)}sendMessage(e){this.ws?.readyState===WebSocket.OPEN?(this.ws.send(JSON.stringify(e)),0!==e.type&&Is("%cWebSocket 发送消息:","color: green; font-weight: bold;",e)):console.warn("WebSocket 未连接,消息未发送")}close(){this.manualClose=!0,this.stopHeartbeat(),this.ws?.close()}reconnect(){this.initWebSocket()}static __internalClose(){vs&&(vs.close(),vs=null)}static __internalSend(e){if(!vs)throw new Error("WebSocket 尚未初始化");vs.sendMessage(e)}}class As{constructor(e){this.sipClient=null,this.sipClient=e}roleMute(){const e=ut.get("isCalling"),t=lt.sessionId;if(!e)throw new Error(JSON.stringify({code:1,msg:"当前没有通话"}));if(!t)throw new Error(JSON.stringify({code:1,msg:"当前没有通话"}))}holdCall(){this.roleMute();const t=ut.get("isHold"),{sessionId:s}=lt;if(!s)return;if(!ut.get("actionConfigs").includes("hold"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿保持"}));if(t)throw new Error(JSON.stringify({code:1,msg:"当前已处于保持状态"}));ys.__internalSend({type:e.WebsocketTypeEnum.CALL_HOLD,data:{session_id:s}})}unholdCall(){this.roleMute();const{isHold:t}=ut.getState(),{sessionId:s}=lt;if(!ut.get("actionConfigs").includes("unhold"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿取消保持"}));if(s){if(!t)throw new Error(JSON.stringify({code:1,msg:"当前未处于保持状态"}));ys.__internalSend({type:e.WebsocketTypeEnum.CALL_UNHOLD,data:{session_id:s}})}}sendDTMF(e){if(1!==ut.get("answerDevice"))throw new Error(JSON.stringify({code:1,msg:"当前设备不支持此功能"}));if(!ut.get("actionConfigs").includes("dtmf"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿发送按键"}));const{isCalling:t}=ut.getState();if(!t)throw new Error(JSON.stringify({code:1,msg:"当前没有通话"}));this.sipClient.sendDTMF(e)}cancelCall(){if(!ut.get("isCalling"))throw new Error(JSON.stringify({code:1,msg:"当前没有通话"}));const t=lt.sessionId;dt.emit(e.CallSipCallEventEnum.REJECT,{session_id:t}),ys.__internalSend({type:e.WebsocketTypeEnum.AGENT_HANGUP,data:{session_id:t}})}async consultCall(t){this.roleMute();const{isCalling:s,outCallIsAnswer:i,consultIsAnswer:r,incomingIsAnswer:n}=ut.getState(),o=lt.sessionId;if(!ut.get("actionConfigs").includes("consult"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿调用咨询"}));if(r)throw new Error(JSON.stringify({code:1,msg:"当前正在咨询"}));if(!(s||i||n))throw new Error(JSON.stringify({code:1,msg:"当前没有通话"}));if(!o)throw new Error(JSON.stringify({code:1,msg:"sessionId不存在"}));ys.__internalSend({type:e.WebsocketTypeEnum.CONSULT_REQUEST,data:{session_id:o,consultation_agent_no:t}})}async answerCall(){if(1!==ut.get("answerDevice"))throw new Error(JSON.stringify({code:1,msg:"当前设备不支持此功能"}));await this.sipClient.answerCall()}makeCall(t){if("string"!=typeof t||""===t.trim())throw new Error(JSON.stringify({code:1,msg:"外呼号码非法"}));const s={};Jt(t)?s.trace_id=t:s.customer_phone=t.replace(/[\s\r\n-]+/g,"");const i=ut.get("isCalling"),r=ut.get("selectOutNumber")||"";if(i)throw new Error(JSON.stringify({code:1,msg:"正在呼叫中,请勿重复点击"}));ut.updateIsCalling(!0),ut.updateDirection(e.DirectionEnum.OUTGOING),ys.__internalSend({type:e.WebsocketTypeEnum.OUT_CALL,data:{...s,caller:r.replace(/[\s\r\n-]+/g,"")}})}previewCall(t,s){const i={};Jt(t)?i.trace_id=t:i.customer_phone=t.replace(/[\s\r\n-]+/g,"");const r=ut.get("isCalling"),n=ut.get("selectOutNumber")||"";if(r)throw new Error(JSON.stringify({code:1,msg:"正在呼叫中,请勿重复点击"}));if("string"!=typeof t||""===t.trim())throw new Error(JSON.stringify({code:1,msg:"外呼号码非法"}));ut.updateIsCalling(!0),ut.updateDirection(e.DirectionEnum.OUTGOING),ys.__internalSend({type:e.WebsocketTypeEnum.PREVIEW_OUT_CALL,data:{...i,caller:n,preview_task_id:s}})}async hangup(){if(!ut.get("isCalling"))throw new Error(JSON.stringify({code:1,msg:"当前没有通话"}));const t=lt.sessionId;ys.__internalSend({type:e.WebsocketTypeEnum.AGENT_HANGUP,data:{session_id:t}})}mute(){this.roleMute();const t=ut.get("actionConfigs"),s=ut.get("isMuted"),i=lt.sessionId;if(s)throw new Error(JSON.stringify({code:1,msg:"当前未处于静音状态"}));if(!t.includes("mute"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿调用静音"}));ys.__internalSend({type:e.WebsocketTypeEnum.MUTE,data:{session_id:i}})}unmute(){this.roleMute();const t=ut.get("actionConfigs"),s=ut.get("isMuted"),i=lt.sessionId;if(!s)throw new Error(JSON.stringify({code:1,msg:"当前未处于未静音状态"}));if(!t.includes("unmute"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿调用静音"}));ys.__internalSend({type:e.WebsocketTypeEnum.UNMUTE,data:{session_id:i}})}consultTransfer(){this.roleMute();const t=ut.get("consultIsAnswer"),s=lt.sessionId;if(!ut.get("actionConfigs").includes("consult_transfer"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿调用咨询转移"}));if(!t)throw new Error(JSON.stringify({code:1,msg:"当前未处于咨询中"}));ys.__internalSend({type:e.WebsocketTypeEnum.CONSULT_TRANSFER,data:{session_id:s}})}satisfactionEvaluation(){this.roleMute();const t=lt.sessionId;if(!ut.get("actionConfigs").includes("satisfaction"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿调用满意度评价"}));ys.__internalSend({type:e.WebsocketTypeEnum.SATISFACTION_EVALUATION,data:{session_id:t}})}startConference(){this.roleMute();if(!ut.get("actionConfigs").includes("conference"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿调用三方会议"}));const t=lt.sessionId;if(!ut.get("consultIsAnswer"))throw new Error(JSON.stringify({code:1,msg:"当前未处于咨询中"}));ys.__internalSend({type:e.WebsocketTypeEnum.CONSULT_THREE_WAY,data:{session_id:t}})}consultRetrieve(){this.roleMute();if(!ut.get("actionConfigs").includes("consult_retrieve"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿取回通话"}));const t=lt.sessionId;if(!ut.get("consultIsAnswer"))throw new Error(JSON.stringify({code:1,msg:"当前未处于咨询中"}));ys.__internalSend({type:e.WebsocketTypeEnum.CONSULT_RETURN_CALL,data:{session_id:t}})}async transferAgent(t){this.roleMute();if(!ut.get("actionConfigs").includes("transfer"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿转接"}));const{transferIsAnswer:s}=ut.getState(),i=lt.sessionId;if(s)throw new Error(JSON.stringify({code:1,msg:"当前正在转接"}));ys.__internalSend({type:e.WebsocketTypeEnum.TRANSFER,data:{session_id:i,transfer_type:0,transfer_dest:t}})}async transferOutline(t){this.roleMute();if(!ut.get("actionConfigs").includes("transfer"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿转接"}));if(!t)throw new Error(JSON.stringify({code:1,msg:"号码不能为空"}));if(!/^\d+$/.test(t))throw new Error(JSON.stringify({code:1,msg:"号码格式错误"}));const{transferIsAnswer:s}=ut.getState(),i=lt.sessionId;if(s)throw new Error(JSON.stringify({code:1,msg:"当前正在转接"}));if(s)throw new Error(JSON.stringify({code:1,msg:"当前正在转接"}));ys.__internalSend({type:e.WebsocketTypeEnum.TRANSFER,data:{session_id:i,transfer_type:2,transfer_dest:t}})}}var bs;class Rs{static{this._instance=null}#e;#t;#s;#i;#r;#n;#o;static{this._timer=null}constructor(){if(this.#e=null,this.#t=new Cs,this.#i=null,this.#o=!1,this.#a=()=>{},this.#c=()=>{},this.initWebRtc=async()=>{if(this.#e)return;const e=lt.agentInfo.sip_account_list.find(e=>1===e.device_type);if(!e)throw new Error(JSON.stringify({code:1,msg:"未找到 sip_account_list"}));{const t=e.sip_register_addr;this.#e=new ft({server:t.split(":")[0],user:e.sip_account,password:e.sip_password,webSocket:`wss://${t}`,callTimeout:3e4},this.#h),await this.#e.start()}},this.#h=e=>{const{type:t,data:s}=e;dt.emit(t,s)},!bs._creatingInstance)throw new Error("请使用 YSYTAgentSdk.getInstance() 获取实例");clearInterval(this.#i),this.#i=setInterval(async()=>{const e=await this.#d();pt.updateRttObject(e)},2e3),ss.requestMediaPermissions(),this.#n=ut.subscribeKey("isNextState",async t=>{if(t){1===ut.get("answerDevice")&&await this.#e.reconnect();let t="";const s=new URL(Zt).host;t=Zt.includes("https")?`wss://${s}`:`ws://${s}`;const{agent_no:i}=lt.agentInfo;ys.getInstance({url:`${t}/ccs-ws/api/v1/ws/call/${i}?Authorization=`,sipClient:this.#e}),setTimeout(()=>{this.#t._changeState({data:{state:e.AgentStatus.BUSY,state_name:"忙碌"},success:()=>{ut.updateDisplayText(""),dt.emit(e.CallSipCallEventEnum.AGENT_STATE,{state:e.AgentStatus.BUSY,state_name:"忙碌"})}},"d")},10)}else ys.__internalClose(),ut.updateDisplayText("离线")}),this.#r=ut.subscribeKey("answerDevice",async t=>{1===t?lt.stateObject.state===e.AgentStatus.UNREGISTERED&&await this.#t._changeState({data:{...lt.stateBeforeChange,state_name:lt.stateBeforeChange.state===e.AgentStatus.IDLE?"空闲":"忙碌"}},"qq"):await this.destroyRtc()}),this.on(e.EventName.KICK_OFF,()=>{this.destroy()}),window.addEventListener("beforeunload",e=>{e.returnValue="",this.destroy()}),window.addEventListener("online",this.#a),window.addEventListener("offline",this.#c)}#a;#c;async#l(){const t=ut.get("isNextState");try{await rs(),t||ut.updateIsNextState(!0)}catch(s){dt.emit(e.EventName.FAIL_NOTIFICATION,"网络断开,请检查网络"),t&&ut.updateIsNextState(!1)}}#g(){bs._timer||(bs._timer=setInterval(()=>this.#l(),3e3))}static get instance(){return this._instance}static async destroyInstance(){this._instance&&(await this._instance.destroy(),this._instance=null)}static getInstance(e){if(!this._instance){if(!e)throw new Error("首次调用必须传入配置参数");const{url:t,appKey:s,appSecret:i,agentNo:r}=e;Zt=t||"https://aicc-api.yescloudy.com",zt=s,Xt=i,Qt=r,bs._creatingInstance=!0,this._instance=new bs,delete bs._creatingInstance}return this._instance}getInit(){return this.#o}async init({enableBrowserAlert:t,logBuiltinEnabled:s,browserAlertTime:i}){try{let r="";const n=new URL(Zt).host;r=Zt.includes("https")?`wss://${n}`:`ws://${n}`;const o=ys.getInstance({url:`${r}/ccs-ws/api/v1/ws/call/${Qt}?Authorization=`,sipClient:null,onOpen:async()=>{lt.logBuiltinEnabled=s||!1,lt.browserAlertTime=i||5e3,await this.#t._agentLogin(Qt);const{current_answer_device:r,current_state:n,out_display_number:a,out_display_select_switch:c}=lt.agentInfo;n===e.AgentStatus.IDLE?(ut.updateActionConfigs(os),lt.stateObject={state:n,state_name:"空闲"},lt.stateBeforeChange=lt.stateObject):n===e.AgentStatus.BUSY?(ut.updateActionConfigs(as),lt.stateObject={state:n,state_name:"忙碌"},lt.stateBeforeChange=lt.stateObject):n===e.AgentStatus.UNREGISTERED&&(ut.updateActionConfigs(as),lt.stateObject={state:n,state_name:"未注册"}),1===c?ut.updateSelectOutNumber(a):ut.updateSelectOutNumber(""),ut.updateAnswerDevice(r),Cs.setInitRtcFn(this.initWebRtc),1===r&&(await this.initWebRtc(),o.setSipClient(this.#e)),this.#s=new As(this.#e),lt.enableBrowserAlert=t,t&&ss.requestPermission(),dt.emit(e.EventName.AGENT_INIT_STATUS,!0),this.#o=!0,clearInterval(bs._timer),bs._timer=null,this.#g()}})}catch(t){dt.emit(e.EventName.AGENT_INIT_STATUS,!1),this.#o=!1}}#h;on(e,t){return dt.on(e,t),this}off(e,t){dt.off(e,t)}offAll(){dt.clearAllListeners()}async destroyRtc(){await(this.#e?.destroy()),this.#e=null}async destroy(){bs._instance&&(await this.destroyRtc(),this.#r?.(),this.#n?.(),clearInterval(this.#i),ys.__internalClose(),dt.emit(e.EventName.DESTROY),this.offAll(),bs._instance=null,ut.reset(),ut.updateSelectOutNumber(""),clearInterval(bs._timer),bs._timer=null)}async#d(){return this.#e?this.#e.getNetworkStats():{}}get call_api(){const e=e=>(...t)=>e.apply(this,t);return{answerCall:e(()=>this.#s.answerCall()),makeCall:e=>this.#s.makeCall(e),previewMakeCall:(e,t)=>this.#s.previewCall(e,t),cancelCall:e(()=>this.#s.cancelCall()),hangup:e(()=>this.#s.hangup()),sendDTMF:e(e=>this.#s.sendDTMF(e)),holdCall:e(()=>this.#s.holdCall()),unholdCall:e(()=>this.#s.unholdCall()),consultCall:e(async e=>{try{await this.#s.consultCall(e)}catch(e){throw console.warn(e),e}}),consultRetrieve:e(()=>this.#s.consultRetrieve()),consultTransfer:e(()=>this.#s.consultTransfer()),mute:e(()=>this.#s.mute()),unmute:e(()=>this.#s.unmute()),satisfactionEvaluation:e(()=>this.#s.satisfactionEvaluation()),startConference:e(()=>this.#s.startConference()),transferAgent:e(e=>this.#s.transferAgent(e)),transferOutline:e(e=>this.#s.transferOutline(e)),earSpeakStart:e(e=>this.#t.earCall(e)),earSpeakStop:e(e=>this.#t.stopEarCall(e)),forceInsert:e(e=>this.#t.forceInsert(e)),forceDisconnect:e(e=>this.#t.forceDisconnect(e))}}get agent_api(){const e=e=>(...t)=>e.apply(this,t);return{changeDevice:e(e=>this.#t.changeDevice(e)),changeState:e(e=>this.#t.changeState(e,"c")),getIdleAgentList:e(e=>this.#t.getIdleAgentList(e)),getAgentState:e(e=>this.#t.getAgentState(e)),setAgentExplicit:e(e=>this.#t.setAgentExplicit(e)),checkAgentLogin:e=>this.#t.checkAgentLogin(e),getCallRecord:e=>this.#t.getCallRecord(e),agentLogout:async(e,t)=>{try{await this.#t.logout(e),await this.destroy(),t?.({code:0,msg:""})}catch(e){}},listenAgentCall:e=>this.#t.listenCall(e)}}getAgentData(){const{agent_no:e,agent_name:t,answer_devices:s,out_display_data:i,out_display_select_switch:r,current_state:n}=lt.agentInfo,{stateObject:o}=lt,a={1:"软电话",2:"手机模式",3:"SIP话机"};return{agent_no:e,agent_name:t,init_state:n,default_device:ut.get("answerDevice"),out_display_data:i,out_display_select_switch:r,answer_devices:(s||"").split(",").map(e=>({value:Number(e),label:a[Number(e)]})),stateObject:o}}async getRealTimeCustomerInfo(){return ut.get("customerObject")}setBrowserAlert(e){if("boolean"!=typeof e)throw new Error(JSON.stringify({code:1,msg:"参数类型错误"}));lt.logBuiltinEnabled=e||!1}setBrowserAlertTime(e){if("number"!=typeof e)throw new Error(JSON.stringify({code:1,msg:"参数类型错误"}));lt.browserAlertTime=e||3e3}}bs=Rs,e.default=Rs,Object.defineProperty(e,"__esModule",{value:!0})});
|
|
12
|
+
!function(e){!function(){var i="input is invalid type",r="object"==typeof window,n=r?window:{};n.JS_MD5_NO_WINDOW&&(r=!1);var o=!r&&"object"==typeof self,a=!n.JS_MD5_NO_NODE_JS&&"object"==typeof process&&process.versions&&process.versions.node;a?n=jt:o&&(n=self);var c,h=!n.JS_MD5_NO_COMMON_JS&&e.exports,d=!n.JS_MD5_NO_ARRAY_BUFFER&&"undefined"!=typeof ArrayBuffer,l="0123456789abcdef".split(""),g=[128,32768,8388608,-2147483648],u=[0,8,16,24],p=["hex","array","digest","buffer","arrayBuffer","base64"],f="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),m=[];if(d){var _=new ArrayBuffer(68);c=new Uint8Array(_),m=new Uint32Array(_)}var E=Array.isArray;!n.JS_MD5_NO_NODE_JS&&E||(E=function(e){return"[object Array]"===Object.prototype.toString.call(e)});var T=ArrayBuffer.isView;!d||!n.JS_MD5_NO_ARRAY_BUFFER_IS_VIEW&&T||(T=function(e){return"object"==typeof e&&e.buffer&&e.buffer.constructor===ArrayBuffer});var w=function(e){var t=typeof e;if("string"===t)return[e,!0];if("object"!==t||null===e)throw new Error(i);if(d&&e.constructor===ArrayBuffer)return[new Uint8Array(e),!1];if(!E(e)&&!T(e))throw new Error(i);return[e,!1]},C=function(e){return function(t){return new v(!0).update(t)[e]()}},S=function(e){var r,o=t,a=s.Buffer;r=a.from&&!n.JS_MD5_NO_BUFFER_FROM?a.from:function(e){return new a(e)};return function(t){if("string"==typeof t)return o.createHash("md5").update(t,"utf8").digest("hex");if(null==t)throw new Error(i);return t.constructor===ArrayBuffer&&(t=new Uint8Array(t)),E(t)||T(t)||t.constructor===a?o.createHash("md5").update(r(t)).digest("hex"):e(t)}},I=function(e){return function(t,s){return new y(t,!0).update(s)[e]()}};function v(e){if(e)m[0]=m[16]=m[1]=m[2]=m[3]=m[4]=m[5]=m[6]=m[7]=m[8]=m[9]=m[10]=m[11]=m[12]=m[13]=m[14]=m[15]=0,this.blocks=m,this.buffer8=c;else if(d){var t=new ArrayBuffer(68);this.buffer8=new Uint8Array(t),this.blocks=new Uint32Array(t)}else this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];this.h0=this.h1=this.h2=this.h3=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0}function y(e,t){var s,i=w(e);if(e=i[0],i[1]){var r,n=[],o=e.length,a=0;for(s=0;s<o;++s)(r=e.charCodeAt(s))<128?n[a++]=r:r<2048?(n[a++]=192|r>>>6,n[a++]=128|63&r):r<55296||r>=57344?(n[a++]=224|r>>>12,n[a++]=128|r>>>6&63,n[a++]=128|63&r):(r=65536+((1023&r)<<10|1023&e.charCodeAt(++s)),n[a++]=240|r>>>18,n[a++]=128|r>>>12&63,n[a++]=128|r>>>6&63,n[a++]=128|63&r);e=n}e.length>64&&(e=new v(!0).update(e).array());var c=[],h=[];for(s=0;s<64;++s){var d=e[s]||0;c[s]=92^d,h[s]=54^d}v.call(this,t),this.update(h),this.oKeyPad=c,this.inner=!0,this.sharedMemory=t}v.prototype.update=function(e){if(this.finalized)throw new Error("finalize already called");var t=w(e);e=t[0];for(var s,i,r=t[1],n=0,o=e.length,a=this.blocks,c=this.buffer8;n<o;){if(this.hashed&&(this.hashed=!1,a[0]=a[16],a[16]=a[1]=a[2]=a[3]=a[4]=a[5]=a[6]=a[7]=a[8]=a[9]=a[10]=a[11]=a[12]=a[13]=a[14]=a[15]=0),r)if(d)for(i=this.start;n<o&&i<64;++n)(s=e.charCodeAt(n))<128?c[i++]=s:s<2048?(c[i++]=192|s>>>6,c[i++]=128|63&s):s<55296||s>=57344?(c[i++]=224|s>>>12,c[i++]=128|s>>>6&63,c[i++]=128|63&s):(s=65536+((1023&s)<<10|1023&e.charCodeAt(++n)),c[i++]=240|s>>>18,c[i++]=128|s>>>12&63,c[i++]=128|s>>>6&63,c[i++]=128|63&s);else for(i=this.start;n<o&&i<64;++n)(s=e.charCodeAt(n))<128?a[i>>>2]|=s<<u[3&i++]:s<2048?(a[i>>>2]|=(192|s>>>6)<<u[3&i++],a[i>>>2]|=(128|63&s)<<u[3&i++]):s<55296||s>=57344?(a[i>>>2]|=(224|s>>>12)<<u[3&i++],a[i>>>2]|=(128|s>>>6&63)<<u[3&i++],a[i>>>2]|=(128|63&s)<<u[3&i++]):(s=65536+((1023&s)<<10|1023&e.charCodeAt(++n)),a[i>>>2]|=(240|s>>>18)<<u[3&i++],a[i>>>2]|=(128|s>>>12&63)<<u[3&i++],a[i>>>2]|=(128|s>>>6&63)<<u[3&i++],a[i>>>2]|=(128|63&s)<<u[3&i++]);else if(d)for(i=this.start;n<o&&i<64;++n)c[i++]=e[n];else for(i=this.start;n<o&&i<64;++n)a[i>>>2]|=e[n]<<u[3&i++];this.lastByteIndex=i,this.bytes+=i-this.start,i>=64?(this.start=i-64,this.hash(),this.hashed=!0):this.start=i}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296|0,this.bytes=this.bytes%4294967296),this},v.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex;e[t>>>2]|=g[3&t],t>=56&&(this.hashed||this.hash(),e[0]=e[16],e[16]=e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=e[7]=e[8]=e[9]=e[10]=e[11]=e[12]=e[13]=e[14]=e[15]=0),e[14]=this.bytes<<3,e[15]=this.hBytes<<3|this.bytes>>>29,this.hash()}},v.prototype.hash=function(){var e,t,s,i,r,n,o=this.blocks;this.first?t=((t=((e=((e=o[0]-680876937)<<7|e>>>25)-271733879|0)^(s=((s=(-271733879^(i=((i=(-1732584194^2004318071&e)+o[1]-117830708)<<12|i>>>20)+e|0)&(-271733879^e))+o[2]-1126478375)<<17|s>>>15)+i|0)&(i^e))+o[3]-1316259209)<<22|t>>>10)+s|0:(e=this.h0,t=this.h1,s=this.h2,t=((t+=((e=((e+=((i=this.h3)^t&(s^i))+o[0]-680876936)<<7|e>>>25)+t|0)^(s=((s+=(t^(i=((i+=(s^e&(t^s))+o[1]-389564586)<<12|i>>>20)+e|0)&(e^t))+o[2]+606105819)<<17|s>>>15)+i|0)&(i^e))+o[3]-1044525330)<<22|t>>>10)+s|0),t=((t+=((e=((e+=(i^t&(s^i))+o[4]-176418897)<<7|e>>>25)+t|0)^(s=((s+=(t^(i=((i+=(s^e&(t^s))+o[5]+1200080426)<<12|i>>>20)+e|0)&(e^t))+o[6]-1473231341)<<17|s>>>15)+i|0)&(i^e))+o[7]-45705983)<<22|t>>>10)+s|0,t=((t+=((e=((e+=(i^t&(s^i))+o[8]+1770035416)<<7|e>>>25)+t|0)^(s=((s+=(t^(i=((i+=(s^e&(t^s))+o[9]-1958414417)<<12|i>>>20)+e|0)&(e^t))+o[10]-42063)<<17|s>>>15)+i|0)&(i^e))+o[11]-1990404162)<<22|t>>>10)+s|0,t=((t+=((e=((e+=(i^t&(s^i))+o[12]+1804603682)<<7|e>>>25)+t|0)^(s=((s+=(t^(i=((i+=(s^e&(t^s))+o[13]-40341101)<<12|i>>>20)+e|0)&(e^t))+o[14]-1502002290)<<17|s>>>15)+i|0)&(i^e))+o[15]+1236535329)<<22|t>>>10)+s|0,t=((t+=((i=((i+=(t^s&((e=((e+=(s^i&(t^s))+o[1]-165796510)<<5|e>>>27)+t|0)^t))+o[6]-1069501632)<<9|i>>>23)+e|0)^e&((s=((s+=(e^t&(i^e))+o[11]+643717713)<<14|s>>>18)+i|0)^i))+o[0]-373897302)<<20|t>>>12)+s|0,t=((t+=((i=((i+=(t^s&((e=((e+=(s^i&(t^s))+o[5]-701558691)<<5|e>>>27)+t|0)^t))+o[10]+38016083)<<9|i>>>23)+e|0)^e&((s=((s+=(e^t&(i^e))+o[15]-660478335)<<14|s>>>18)+i|0)^i))+o[4]-405537848)<<20|t>>>12)+s|0,t=((t+=((i=((i+=(t^s&((e=((e+=(s^i&(t^s))+o[9]+568446438)<<5|e>>>27)+t|0)^t))+o[14]-1019803690)<<9|i>>>23)+e|0)^e&((s=((s+=(e^t&(i^e))+o[3]-187363961)<<14|s>>>18)+i|0)^i))+o[8]+1163531501)<<20|t>>>12)+s|0,t=((t+=((i=((i+=(t^s&((e=((e+=(s^i&(t^s))+o[13]-1444681467)<<5|e>>>27)+t|0)^t))+o[2]-51403784)<<9|i>>>23)+e|0)^e&((s=((s+=(e^t&(i^e))+o[7]+1735328473)<<14|s>>>18)+i|0)^i))+o[12]-1926607734)<<20|t>>>12)+s|0,t=((t+=((n=(i=((i+=((r=t^s)^(e=((e+=(r^i)+o[5]-378558)<<4|e>>>28)+t|0))+o[8]-2022574463)<<11|i>>>21)+e|0)^e)^(s=((s+=(n^t)+o[11]+1839030562)<<16|s>>>16)+i|0))+o[14]-35309556)<<23|t>>>9)+s|0,t=((t+=((n=(i=((i+=((r=t^s)^(e=((e+=(r^i)+o[1]-1530992060)<<4|e>>>28)+t|0))+o[4]+1272893353)<<11|i>>>21)+e|0)^e)^(s=((s+=(n^t)+o[7]-155497632)<<16|s>>>16)+i|0))+o[10]-1094730640)<<23|t>>>9)+s|0,t=((t+=((n=(i=((i+=((r=t^s)^(e=((e+=(r^i)+o[13]+681279174)<<4|e>>>28)+t|0))+o[0]-358537222)<<11|i>>>21)+e|0)^e)^(s=((s+=(n^t)+o[3]-722521979)<<16|s>>>16)+i|0))+o[6]+76029189)<<23|t>>>9)+s|0,t=((t+=((n=(i=((i+=((r=t^s)^(e=((e+=(r^i)+o[9]-640364487)<<4|e>>>28)+t|0))+o[12]-421815835)<<11|i>>>21)+e|0)^e)^(s=((s+=(n^t)+o[15]+530742520)<<16|s>>>16)+i|0))+o[2]-995338651)<<23|t>>>9)+s|0,t=((t+=((i=((i+=(t^((e=((e+=(s^(t|~i))+o[0]-198630844)<<6|e>>>26)+t|0)|~s))+o[7]+1126891415)<<10|i>>>22)+e|0)^((s=((s+=(e^(i|~t))+o[14]-1416354905)<<15|s>>>17)+i|0)|~e))+o[5]-57434055)<<21|t>>>11)+s|0,t=((t+=((i=((i+=(t^((e=((e+=(s^(t|~i))+o[12]+1700485571)<<6|e>>>26)+t|0)|~s))+o[3]-1894986606)<<10|i>>>22)+e|0)^((s=((s+=(e^(i|~t))+o[10]-1051523)<<15|s>>>17)+i|0)|~e))+o[1]-2054922799)<<21|t>>>11)+s|0,t=((t+=((i=((i+=(t^((e=((e+=(s^(t|~i))+o[8]+1873313359)<<6|e>>>26)+t|0)|~s))+o[15]-30611744)<<10|i>>>22)+e|0)^((s=((s+=(e^(i|~t))+o[6]-1560198380)<<15|s>>>17)+i|0)|~e))+o[13]+1309151649)<<21|t>>>11)+s|0,t=((t+=((i=((i+=(t^((e=((e+=(s^(t|~i))+o[4]-145523070)<<6|e>>>26)+t|0)|~s))+o[11]-1120210379)<<10|i>>>22)+e|0)^((s=((s+=(e^(i|~t))+o[2]+718787259)<<15|s>>>17)+i|0)|~e))+o[9]-343485551)<<21|t>>>11)+s|0,this.first?(this.h0=e+1732584193|0,this.h1=t-271733879|0,this.h2=s-1732584194|0,this.h3=i+271733878|0,this.first=!1):(this.h0=this.h0+e|0,this.h1=this.h1+t|0,this.h2=this.h2+s|0,this.h3=this.h3+i|0)},v.prototype.hex=function(){this.finalize();var e=this.h0,t=this.h1,s=this.h2,i=this.h3;return l[e>>>4&15]+l[15&e]+l[e>>>12&15]+l[e>>>8&15]+l[e>>>20&15]+l[e>>>16&15]+l[e>>>28&15]+l[e>>>24&15]+l[t>>>4&15]+l[15&t]+l[t>>>12&15]+l[t>>>8&15]+l[t>>>20&15]+l[t>>>16&15]+l[t>>>28&15]+l[t>>>24&15]+l[s>>>4&15]+l[15&s]+l[s>>>12&15]+l[s>>>8&15]+l[s>>>20&15]+l[s>>>16&15]+l[s>>>28&15]+l[s>>>24&15]+l[i>>>4&15]+l[15&i]+l[i>>>12&15]+l[i>>>8&15]+l[i>>>20&15]+l[i>>>16&15]+l[i>>>28&15]+l[i>>>24&15]},v.prototype.toString=v.prototype.hex,v.prototype.digest=function(){this.finalize();var e=this.h0,t=this.h1,s=this.h2,i=this.h3;return[255&e,e>>>8&255,e>>>16&255,e>>>24&255,255&t,t>>>8&255,t>>>16&255,t>>>24&255,255&s,s>>>8&255,s>>>16&255,s>>>24&255,255&i,i>>>8&255,i>>>16&255,i>>>24&255]},v.prototype.array=v.prototype.digest,v.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(16),t=new Uint32Array(e);return t[0]=this.h0,t[1]=this.h1,t[2]=this.h2,t[3]=this.h3,e},v.prototype.buffer=v.prototype.arrayBuffer,v.prototype.base64=function(){for(var e,t,s,i="",r=this.array(),n=0;n<15;)e=r[n++],t=r[n++],s=r[n++],i+=f[e>>>2]+f[63&(e<<4|t>>>4)]+f[63&(t<<2|s>>>6)]+f[63&s];return e=r[n],i+=f[e>>>2]+f[e<<4&63]+"=="},y.prototype=new v,y.prototype.finalize=function(){if(v.prototype.finalize.call(this),this.inner){this.inner=!1;var e=this.array();v.call(this,this.sharedMemory),this.update(this.oKeyPad),this.update(e),v.prototype.finalize.call(this)}};var A=function(){var e=C("hex");a&&(e=S(e)),e.create=function(){return new v},e.update=function(t){return e.create().update(t)};for(var t=0;t<p.length;++t){var s=p[t];e[s]=C(s)}return e}();A.md5=A,A.md5.hmac=function(){var e=I("hex");e.create=function(e){return new y(e)},e.update=function(t,s){return e.create(t).update(s)};for(var t=0;t<p.length;++t){var s=p[t];e[s]=I(s)}return e}(),h?e.exports=A:n.md5=A}()}(Bt);var Wt=Bt.exports;const Vt=(e,t)=>{const s=Date.now(),i=`${e}:${s}:${Wt.md5(`${t}${s}`)}`,r=(new TextEncoder).encode(i);return btoa(String.fromCharCode(...r))},Jt=e=>{if(/^\d+$/.test(e))return!1;if(!e||"string"!=typeof e||e.length%4!=0)return!1;if(!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e))return!1;try{const t=atob(e);return btoa(t)===e}catch(e){return!1}},Kt="/v1/aicc/bmserver",Yt="/v1/aicc/ccs";let Zt="",zt="",Xt="",Qt="";function es(e){const t=Vt(zt,Xt);return Gt.create({prefixUrl:`${Zt}`,timeout:!1,headers:{Authorization:t,...e},hooks:{afterResponse:[async(e,t,s)=>{if(-1!==s.url.indexOf("heartbeat"))return s;const i=await s.clone().json();if(0!==i.code)throw new Error(JSON.stringify(i)||"请求失败");return s.json=async()=>i,s}]}})}async function ts(e,t,s){const i=es(s),r="api/"+e.replace(/^\/+/,"");return i.post(r,{json:t}).json()}class ss{static requestPermission(){"Notification"in window&&"default"===Notification.permission&&Notification.requestPermission()}static async requestMediaPermissions(){try{const e=await navigator.mediaDevices.enumerateDevices();if(e.some(e=>"audioinput"===e.kind&&""!==e.label))return null;return await navigator.mediaDevices.getUserMedia({audio:!0})}catch(e){return console.warn("获取音频权限失败:",e),null}}static show(e,t,s,i){if("Notification"in window&&"granted"===Notification.permission){const r=new Notification(e,{body:t,tag:`xy-global-notification${(new Date).getTime()}`,renotify:!0});r.onclick=()=>{window.focus(),r.close(),s?.()},setTimeout(()=>r.close(),1e3*(i||3))}}static async checkMediaPermissions(){try{return(await navigator.mediaDevices.enumerateDevices()).some(e=>"audioinput"===e.kind&&""!==e.label)}catch(e){return console.warn("无法检查设备权限:",e),!1}}}const is=(e,t)=>ts(`${Yt}/state/change?h=${t}`,e,{h:t}),rs=()=>async function(e,t){const s=es(),i=e.replace(/^\/+/,"");return s.post(i,{json:t}).json()}("/heartbeat",{}),ns=[],os=["call_number"],as=["call_number"],cs=["hangup"],hs=["hold","hangup","mute","transfer","consult","satisfaction","dtmf"],ds=["hold","hangup","mute","transfer","consult"],ls=["consult_transfer","conference","consult_retrieve"],gs=["hangup"],us=["hangup"],ps=["answer","reject"],fs=["hangup","consult","transfer","hold","mute","satisfaction","dtmf"],ms=["hangup","whisper","force_insert","force_disconnect"],_s=["hangup"],Es=["hangup","cancel_whisper","force_insert"],Ts=["hangup"],ws=["hangup"];class Cs{constructor(){this.roleData={agentInfo:()=>{if(!lt.agentInfo?.agent_no)throw new Error(JSON.stringify({code:1,msg:"请先登录"}))},requestInfo:e=>{if(!e.data)throw new Error(JSON.stringify({code:1,msg:'Parameter "data" is required'}))},changeDevice:e=>{if(!e)throw new Error(JSON.stringify({code:1,msg:'Parameter "device" is required'}));const{answer_devices:t}=lt.agentInfo;if(!t.split(",").map(e=>Number(e)).includes(e))throw new Error(JSON.stringify({code:1,msg:"当前状态不支持"}))},changeState:(e,t)=>{if(!e)throw new Error(JSON.stringify({code:1,msg:'Parameter "state" is required'}));if(!t)throw new Error(JSON.stringify({code:1,msg:'Parameter "state_name" is required'}));if(2===e&&("通话中"===t||"整理"===t))throw new Error(JSON.stringify({code:1,msg:"当前状态不支持"}));if(![1,2].includes(e))throw new Error(JSON.stringify({code:1,msg:"当前状态不支持"}))},setAgentExplicit:e=>{const{out_display_select_switch:t,out_display_data:s}=lt.agentInfo;if(1!==t)throw new Error(JSON.stringify({code:1,msg:"当前坐席设置未开启允许指定外显"}));if(!e)throw new Error(JSON.stringify({code:1,msg:'Parameter "number" is required'}));if(!(s||"").split("#").includes(e))throw new Error(JSON.stringify({code:1,msg:"当前外显号码不存在"}))}},this.changeDevice=async t=>{try{if(ut.get("isCalling"))throw new Error(JSON.stringify({code:1,msg:"当前正在通话中,请勿切换设备"}));this.roleData.agentInfo(),this.roleData.requestInfo(t);const{data:s,success:i}=t,{device:r}=s;1===r&&await Cs.initRtcFn(),this.roleData.changeDevice(r);const{agent_no:n}=lt.agentInfo;await(e=>ts(`${Yt}/device/change`,e))({agent_no:n,answer_device:r}),ut.updateAnswerDevice(r);const o=ut.get("actionConfigs");ut.updateActionConfigs(o),2===r&<.stateObject.state===e.AgentStatus.UNREGISTERED&&await this._changeState({data:{...lt.stateBeforeChange,state_name:lt.stateBeforeChange.state===e.AgentStatus.IDLE?"空闲":"忙碌"}},"q"),i?.({code:0,msg:"请求成功"})}catch(t){throw dt.emit(e.EventName.FAIL_NOTIFICATION,JSON.parse(t.message).msg),t}}}formatDate(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")} ${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}:${String(e.getSeconds()).padStart(2,"0")}`}static setInitRtcFn(e){this.initRtcFn=e}async _agentLogin(t){try{const e=await(s={agent_no:t},ts(`${Yt}/agent/login`,s));lt.agentInfo=e.data}catch(t){throw dt.emit(e.EventName.FAIL_NOTIFICATION,JSON.parse(t.message).msg),t}var s}async _changeState(t,s){try{lt.autoStateTimer&&(clearTimeout(lt.autoStateTimer),lt.autoStateTimer=null),this.roleData.agentInfo(),this.roleData.requestInfo(t);const{data:i,success:r}=t,{state:n,state_name:o}=i,{agent_no:a}=lt.agentInfo;await is({agent_no:a,state_name:o,state:n},s),n===e.AgentStatus.IDLE?ut.updateActionConfigs(os):n===e.AgentStatus.BUSY&&ut.updateActionConfigs(as),lt.stateObject={state:n,state_name:o},r?.({code:0,msg:"请求成功"})}catch(t){throw dt.emit(e.EventName.FAIL_NOTIFICATION,JSON.parse(t.message).msg),t}}async _getInCallCrmDetail(t){try{const{phone:e}=t.data,s={};Jt(e)?s.trace_id=e:s.phone=e.replace(/[\s\r\n-]+/g,"");const i=await(e=>ts(`${Kt}/crm/popups`,e))({...s});t.success?.(i)}catch(t){throw dt.emit(e.EventName.FAIL_NOTIFICATION,JSON.parse(t.message).msg),t}}async changeState(t,s){try{if(ut.get("isCalling"))throw new Error(JSON.stringify({code:1,msg:"当前正在通话中,请勿切换设备"}));lt.autoStateTimer&&(clearTimeout(lt.autoStateTimer),lt.autoStateTimer=null),this.roleData.agentInfo(),this.roleData.requestInfo(t);const{data:i,success:r}=t,{state:n,state_name:o}=i;this.roleData.changeState(n,o);const{agent_no:a}=lt.agentInfo;await is({agent_no:a,state_name:o,state:n},s),(lt.stateObject.state===e.AgentStatus.IDLE||lt.stateObject.state===e.AgentStatus.BUSY&&"整理"!==o)&&(lt.stateBeforeChange=lt.stateObject),n===e.AgentStatus.IDLE?ut.updateActionConfigs(os):n===e.AgentStatus.BUSY&&ut.updateActionConfigs(as),lt.stateObject={state:n,state_name:o},r?.({code:0,msg:"请求成功"})}catch(t){throw dt.emit(e.EventName.FAIL_NOTIFICATION,JSON.parse(t.message).msg),t}}async getIdleAgentList(t){const{agent_no:s}=lt.agentInfo;try{this.roleData.agentInfo();const e=await(e=>ts(`${Yt}/agent/free`,e))({agent_no:s});t.success?.(e)}catch(t){throw dt.emit(e.EventName.FAIL_NOTIFICATION,JSON.parse(t.message).msg),t}}async getAgentState(t){try{const e=await ts(`${Kt}/agent/statecfg/list`,{}),s=(e.data||[]).filter(e=>0===e.enable).filter(e=>0!==e.state&&3!==e.state).filter(e=>"通话中"!==e.state_name&&"整理"!==e.state_name&&"未注册"!==e.state_name&&"离线接听"!==e.state_name).map(e=>({state:e.state,state_name:e.state_name})).reverse();t.success?.({...e,data:s})}catch(t){throw dt.emit(e.EventName.FAIL_NOTIFICATION,JSON.parse(t.message).msg),t}}async setAgentExplicit(t){try{this.roleData.agentInfo(),this.roleData.requestInfo(t),this.roleData.setAgentExplicit(t.data.number);const{agent_id:e}=lt.agentInfo;await(e=>ts(`${Kt}/agent/update`,e))({agent_id:e,out_display_number:t.data.number}),ut.updateSelectOutNumber(t.data.number),t.success?.({code:0,msg:"请求成功"})}catch(t){throw dt.emit(e.EventName.FAIL_NOTIFICATION,JSON.parse(t.message).msg),t}}async checkAgentLogin(t){try{this.roleData.requestInfo(t);const{agent_no:e}=t.data;if(!e)throw new Error(JSON.stringify({code:1,msg:'Parameter "agent_no" is required'}));const s=await(e=>ts(`${Yt}/agent/islogin`,e))({agent_no:e});t.success?.(s)}catch(t){throw dt.emit(e.EventName.FAIL_NOTIFICATION,JSON.parse(t.message).msg),t}}async getCallRecord(t){try{this.roleData.agentInfo();const{success:e}=t,s=new Date,i=new Date(s.getFullYear(),s.getMonth(),s.getDate(),0,0,0),r=new Date(s.getFullYear(),s.getMonth(),s.getDate(),23,59,59),n=[this.formatDate(i),this.formatDate(r)],{agent_no:o}=lt.agentInfo,a=await(e=>ts(`${Kt}/agent/recordpage`,e))({start_time:n[0],end_time:n[1],page_no:1,page_size:10,agent_no:o}),{code:c,msg:h,data:d}=a;e?.({code:c,msg:h,data:d})}catch(t){throw dt.emit(e.EventName.FAIL_NOTIFICATION,JSON.parse(t.message).msg),t}}async logout(t){this.roleData.agentInfo();try{const{agent_no:e}=lt.agentInfo,{data:s,success:i}=t;await(e=>ts(`${Yt}/agent/logout`,e))({...s,agent_no:e}),i?.({code:0,msg:""})}catch(t){throw dt.emit(e.EventName.FAIL_NOTIFICATION,JSON.parse(t.message).msg),t}}async listenCall(t){try{const{agent_no:e}=lt.agentInfo,{data:s,success:i}=t;if(this.roleData.agentInfo(),this.roleData.requestInfo(t),!s.monitored_agent_no)throw new Error(JSON.stringify({code:1,msg:'Parameter "monitored_agent_no" is required'}));await(e=>ts(`${Yt}/call/monitor`,e))({...s,monitor_agent_no:e}),lt.monitoredAgentNo=s.monitored_agent_no,i?.({code:0,msg:""})}catch(t){throw dt.emit(e.EventName.FAIL_NOTIFICATION,JSON.parse(t.message).msg),t}}async earCall(t){try{const{agentInfo:e,monitoredAgentNo:s}=lt,{agent_no:i}=e;this.roleData.agentInfo();const{success:r}=t;if(!s)throw new Error(JSON.stringify({code:1,msg:"当前未有监听坐席"}));await(e=>ts(`${Yt}/call/whisper`,e))({monitored_agent_no:s,monitor_agent_no:i}),r?.({code:0,msg:""})}catch(t){throw dt.emit(e.EventName.FAIL_NOTIFICATION,JSON.parse(t.message).msg),t}}async stopEarCall(t){try{const{agentInfo:e,earSpeakAgent:s}=lt;if(!s)throw new Error(JSON.stringify({code:1,msg:"当前没有正在耳语的坐席"}));const{agent_no:i}=e;this.roleData.agentInfo();const{success:r}=t;await(e=>ts(`${Yt}/call/stopwhisper`,e))({monitor_agent_no:i,monitored_agent_no:s}),r?.({code:0,msg:""})}catch(t){throw dt.emit(e.EventName.FAIL_NOTIFICATION,JSON.parse(t.message).msg),t}}async forceInsert(t){try{const{agentInfo:e,monitoredAgentNo:s}=lt,{agent_no:i}=e;this.roleData.agentInfo();const{success:r}=t;if(!s)throw new Error(JSON.stringify({code:1,msg:"当前未有监听坐席"}));await(e=>ts(`${Yt}/call/bargein`,e))({monitored_agent_no:s,monitor_agent_no:i}),r?.({code:0,msg:""})}catch(t){throw dt.emit(e.EventName.FAIL_NOTIFICATION,JSON.parse(t.message).msg),t}}async forceDisconnect(t){try{const{agentInfo:e,monitoredAgentNo:s}=lt,{agent_no:i}=e;this.roleData.agentInfo();const{success:r}=t;if(!s)throw new Error(JSON.stringify({code:1,msg:"当前未有监听坐席"}));await(e=>ts(`${Yt}/call/intercept`,e))({monitored_agent_no:s,monitor_agent_no:i}),r?.({code:0,msg:""})}catch(t){throw dt.emit(e.EventName.FAIL_NOTIFICATION,JSON.parse(t.message).msg),t}}}const Ss=console.log,Is=(...e)=>{lt.logBuiltinEnabled&&Ss(...e)};let vs=null;class ys{constructor(e,t){this.url=e,this.onOpenCallback=t,this.ws=null,this.heartbeatWorker=null,this.reconnectDelay=3e3,this.manualClose=!1,this.apiClient=new Cs,this.sipClient=null,this.pendingMessages=new Map,this.initWebSocket()}static getInstance({url:e,sipClient:t,onOpen:s}){if(!vs){if(!e)throw new Error("WebSocket 尚未初始化");vs=new ys(e,s),vs.sipClient=t}return vs}setSipClient(e){this.sipClient=e}stateIdleChange(t){const{state:s}=lt.stateObject;s!==e.AgentStatus.IDLE&&this.apiClient._changeState({data:{...lt.stateBeforeChange,state_name:lt.stateBeforeChange.state===e.AgentStatus.IDLE?"空闲":"忙碌"}},t)}inCallAutoAnswer(){const{soft_device_auto_answer:t,auto_answer_time:s}=lt.agentInfo,i=1===t,r=ut.get("direction");if(i&&r===e.DirectionEnum.INCOMING){const e=Number(s)||0;e>0&&(lt.autoAnswerTimer=setTimeout(()=>{this.sipClient?.answerCall(),lt.autoAnswerTimer=null},1e3*e-500))}}async getCustomerInfo(e){try{await this.apiClient._getInCallCrmDetail({data:{phone:e},success:e=>{ut.updateCustomerInfo(e.data||{phone:e.data.phone,is_vip:0,customer_name:"未知客户",city:"未知",province:"未知",contact_count:0,in_contact_count:0,trace_id:e.data.trace_id,contact_count_month:0,in_contact_count_month:0})}})}catch(e){}}putAgentState(t,s){if(!t)return;if(5===s)return void this.stateIdleChange("device_type5");lt.sessionId="";const{post_call_process_time:i}=lt.agentInfo,r=i||0;if(lt.autoStateTimer&&(clearTimeout(lt.autoStateTimer),lt.autoStateTimer=null),ut.updateCustomerInfo(void 0),r>0){const{state:t}=lt.stateObject;if(t===e.AgentStatus.IDLE)return;this.apiClient._changeState({data:{state:e.AgentStatus.BUSY,state_name:"整理"}},"ez"),lt.autoStateTimer=setTimeout(()=>{lt.autoStateTimer=null,this.stateIdleChange(`delay${r}`)},1e3*r)}else this.stateIdleChange("delay0")}stateBusyChange(){lt.sessionId="",clearTimeout(lt.autoStateTimer),ut.updateCustomerInfo(void 0),this.apiClient._changeState({data:{state:e.AgentStatus.BUSY,state_name:"忙碌"}},"dm")}initWebSocket(){if(1===this.ws?.readyState)return;if(!ut.get("isNextState")||this.manualClose)return;const t=Vt(zt,Xt);this.ws=new WebSocket(this.url+t),this.ws.onopen=()=>{const e=(new Date).getTime();this.sendMessage({type:0,msg_id:e}),this.pendingMessages.set(e,performance.now()),this.startHeartbeat(),this.manualClose=!1,this.onOpenCallback&&this.onOpenCallback()},this.ws.onmessage=async t=>{const s=JSON.parse(t.data),{type:i,data:r,code:n,msg:o,msg_id:a}=s;if(0===i&&a){const e=this.pendingMessages.get(a),t=performance.now()-e;lt.latency=parseFloat(t.toFixed(2)),this.pendingMessages.delete(a)}if(0!==i&&Is("%cWebSocket 收到消息:","color: blue; font-weight: bold;",s),i!==e.WebsocketTypeEnum.OUT_CALL&&i!==e.WebsocketTypeEnum.PREVIEW_OUT_CALL||(0!==n?(ut.reset(),dt.emit(e.CallSipCallEventEnum.OUT_FAILED,o),dt.emit(e.EventName.FAIL_NOTIFICATION,o),ut.updateActionConfigs(os),setTimeout(()=>{ut.updateCustomerInfo(void 0)},500),this.stateIdleChange("h")):0===n&&(dt.emit(e.CallSipCallEventEnum.OUT_SUCCESS),clearTimeout(lt.autoStateTimer))),i===e.WebsocketTypeEnum.AGENT_STATE){const{state:t,state_name:s}=r;lt.stateObject={state:t,state_name:s},lt.stateBeforeChange?.state||lt.stateObject.state!==e.AgentStatus.IDLE&&(lt.stateObject.state!==e.AgentStatus.BUSY||"整理"===s)||(lt.stateBeforeChange=lt.stateObject),"振铃中"===s&&ut.updateDisplayText(e.DisplayTextEnum.AGENT_RINGING);const i=ut.get("isCalling");t!==e.AgentStatus.UNREGISTERED||i||ut.updateActionConfigs(ns),t===e.AgentStatus.IDLE&<.stateObject.state===e.AgentStatus.UNREGISTERED&&ut.updateActionConfigs(os),dt.emit(e.CallSipCallEventEnum.AGENT_STATE,{state:t,state_name:s})}else if(i===e.WebsocketTypeEnum.OUT_CALL_INCOMING_CALL){try{await this.getCustomerInfo(r.trace_id||r.customer_phone)}catch(e){console.error(e)}r.preview_task_id?dt.emit(e.CallSipCallEventEnum.PREVIEW_OUT_INCOMING_CALL,{customer_phone:r.customer_phone,session_id:r.session_id,preview_task_id:r.preview_task_id,trace_id:r.trace_id}):0===r.direction?dt.emit(e.CallSipCallEventEnum.OUT_INCOMING_CALL,{customer_phone:r.customer_phone,session_id:r.session_id,trace_id:r.trace_id}):8===r.direction&&dt.emit(e.CallSipCallEventEnum.INTERNAL_OUT_INCOMING_CALL,{customer_phone:r.customer_phone,session_id:r.session_id,trace_id:r.trace_id}),lt.sessionId=r.session_id,ut.updateActionConfigs(cs,8!==r.direction)}else if(i===e.WebsocketTypeEnum.OUT_CALL_END){if(lt.sessionId!==r.session_id)return;if(ut.updateDisplayText(""),1===r.device_type&&r.agent_no===lt.agentInfo.agent_no)ut.reset(),dt.emit(e.CallSipCallEventEnum.OUT_HANGUP,{session_id:r.session_id}),ut.updateActionConfigs(os),this.putAgentState(!0);else if(2===r.device_type&&r.agent_no===lt.agentInfo.agent_no)ut.reset(),dt.emit(e.CallSipCallEventEnum.OUR_SIDE_CONSULT_HANGUP,{session_id:r.session_id}),ut.updateActionConfigs(os),this.putAgentState(!0);else if(2===r.device_type&&r.agent_no!==lt.agentInfo.agent_no){ut.get("isCalling")&&(ut.updateDisplayText(e.DisplayTextEnum.CALLING),dt.emit(e.CallSipCallEventEnum.OTHER_SIDE_CONSULT_HANGUP,{session_id:r.session_id}),ut.updateActionConfigs(hs))}else if(3===r.device_type&&r.agent_no===lt.agentInfo.agent_no)ut.reset(),dt.emit(e.CallSipCallEventEnum.THREE_WAY_OUR_SIDE_HANGUP,{session_id:r.session_id}),ut.updateActionConfigs(os),this.putAgentState(!0);else if(4===r.device_type&&r.agent_no===lt.agentInfo.agent_no)ut.reset(),dt.emit(e.CallSipCallEventEnum.TRANSFER_END,{session_id:r.session_id}),ut.updateActionConfigs(os),this.putAgentState(!0);else if(4===r.device_type&&r.agent_no!==lt.agentInfo.agent_no){dt.emit(e.CallSipCallEventEnum.TRANSFER_FAILED,"未知原因"),dt.emit(e.EventName.FAIL_NOTIFICATION,"转接失败");const t=ut.get("direction");t===e.DirectionEnum.OUTGOING?ut.updateActionConfigs(hs):t===e.DirectionEnum.INCOMING&&ut.updateActionConfigs(fs)}else 5===r.device_type&&r.agent_no===lt.agentInfo.agent_no&&(lt.monitoredAgentNo="",lt.earSpeakAgent="",ut.reset(),dt.emit(e.CallSipCallEventEnum.LISTEN_HANGUP,{session_id:r.session_id}),ut.updateActionConfigs(os),this.putAgentState(!0,5))}else if(i===e.WebsocketTypeEnum.OUT_CALL_RINGING)1===r.type&&(dt.emit(e.CallSipCallEventEnum.OUT_RINGING,{session_id:lt.sessionId,type:r.type}),ut.updateDisplayText(e.DisplayTextEnum.RINGING));else if(i===e.WebsocketTypeEnum.OUT_CALL_ANSWER)clearTimeout(lt.autoStateTimer),ut.updateIsCalling(!0),ut.updateOutCallIsAnswer(!0),ut.updateDisplayText(e.DisplayTextEnum.CALLING),8===r.direction?(dt.emit(e.CallSipCallEventEnum.INTERNAL_OUT_OFF_ANSWER,{session_id:lt.sessionId}),ut.updateActionConfigs(ds)):(dt.emit(e.CallSipCallEventEnum.OUT_OFF_ANSWER,{session_id:lt.sessionId}),ut.updateActionConfigs(hs));else if(i===e.WebsocketTypeEnum.CONSULT_RINGING)dt.emit(e.CallSipCallEventEnum.CONSULT_RINGING,{session_id:r.session_id}),ut.updateDisplayText(e.DisplayTextEnum.AGENT_RINGING),ut.updateActionConfigs([]),clearTimeout(lt.autoStateTimer);else if(i===e.WebsocketTypeEnum.CONSULT_ANSWER)dt.emit(e.CallSipCallEventEnum.CONSULT_OFF_HOOK,{session_id:r.session_id}),ut.updateConsultIsAnswer(!0),ut.updateDisplayText(e.DisplayTextEnum.CONSULTING),ut.updateActionConfigs(ls);else if(i===e.WebsocketTypeEnum.CONSULT_FAIL)dt.emit(e.CallSipCallEventEnum.CONSULT_FAILED,{custom_reason:r.custom_reason}),ut.updateDisplayText(e.DisplayTextEnum.CALLING),ut.updateActionConfigs(hs);else if(i===e.WebsocketTypeEnum.CONSULT_CALL_IN)dt.emit(e.CallSipCallEventEnum.CONSULT_INCOMING,{agent_no:r.agent_no,agent_mane:r.agent_name,session_id:r.session_id}),lt.sessionId=r.session_id,ut.updateIsCalling(!0),ut.updateDirection(e.DirectionEnum.CONSULT),ut.updateDisplayText(e.DisplayTextEnum.CONSULT_CALL_IN),ut.updateActionConfigs(ps),lt.enableBrowserAlert&&ss.show("📞 咨询来电",`坐席 [${r.agent_name}] 正在咨询...`,()=>{dt.emit(e.EventName.NOTIFICATION_CLICK,{agent_mane:r.agent_name,agent_no:r.agent_no})},lt.browserAlertTime);else if(i===e.WebsocketTypeEnum.CONSULT_CALL_IN_SUCCESS)dt.emit(e.CallSipCallEventEnum.CONSULT_CALL_IN_SUCCESS,{session_id:r.session_id}),ut.updateConsultIsAnswer(!0),ut.updateDisplayText(e.DisplayTextEnum.CALLING),ut.updateActionConfigs(gs);else if(i===e.WebsocketTypeEnum.CONSULT_RETURN_CALL_SUCCESS)"success"===r.status?(ut.updateConsultIsAnswer(!1),dt.emit(e.CallSipCallEventEnum.CONSULT_RETURN_CALL_SUCCESS),ut.updateDisplayText(e.DisplayTextEnum.CALLING),dt.emit(e.CallSipCallEventEnum.OTHER_SIDE_CONSULT_HANGUP),ut.updateActionConfigs(hs)):dt.emit(e.EventName.FAIL_NOTIFICATION,"媒体失败");else if(i===e.WebsocketTypeEnum.MUTE)0===n?(ut.updateIsMuted(!0),dt.emit(e.CallSipCallEventEnum.MUTE_SUCCESS),ut.updateDisplayText(e.DisplayTextEnum.MUTING)):(dt.emit(e.CallSipCallEventEnum.MUTE_FAILED,o),dt.emit(e.EventName.FAIL_NOTIFICATION,o));else if(i===e.WebsocketTypeEnum.UNMUTE)0===n?(ut.updateIsMuted(!1),dt.emit(e.CallSipCallEventEnum.UNMUTE_SUCCESS),ut.updateDisplayText(e.DisplayTextEnum.CALLING)):(dt.emit(e.CallSipCallEventEnum.UNMUTE_FAILED,o),dt.emit(e.EventName.FAIL_NOTIFICATION,o));else if(i===e.WebsocketTypeEnum.CALL_HOLD)0===n?(ut.updateIsHold(!0),ut.updateDisplayText(e.DisplayTextEnum.HOLDING),dt.emit(e.CallSipCallEventEnum.HOLD_SUCCESS)):(dt.emit(e.CallSipCallEventEnum.HOLD_FAILED,o),dt.emit(e.EventName.FAIL_NOTIFICATION,o));else if(i===e.WebsocketTypeEnum.CALL_UNHOLD)0===n?(ut.updateDisplayText(e.DisplayTextEnum.CALLING),ut.updateIsHold(!1),dt.emit(e.CallSipCallEventEnum.UNHOLD_SUCCESS)):(dt.emit(e.CallSipCallEventEnum.UNHOLD_FAILED,o),dt.emit(e.EventName.FAIL_NOTIFICATION,o));else if(i===e.WebsocketTypeEnum.CONSULT_TRANSFER)0===n?dt.emit(e.CallSipCallEventEnum.CONSULT_TRANSFER_SUCCESS):(dt.emit(e.CallSipCallEventEnum.CONSULT_TRANSFER_FAILED,o),dt.emit(e.EventName.FAIL_NOTIFICATION,o));else if(i===e.WebsocketTypeEnum.CONSULT_TRANSFER_FAILED)dt.emit(e.CallSipCallEventEnum.CONSULT_TRANSFER_FAILED,r.status);else if(i===e.WebsocketTypeEnum.CONSULT_TRANSFER_OFF_HOOK)ut.updateDirection(e.DirectionEnum.INCOMING),ut.updateDisplayText(e.DisplayTextEnum.CALLING),dt.emit(e.CallSipCallEventEnum.CONSULT_TRANSFER_OFF_HOOK),ut.updateActionConfigs(fs),ut.updateIncomingIsAnswer(!0),ut.updateConsultIsAnswer(!1);else if(i===e.WebsocketTypeEnum.INCOMING_CALL){clearTimeout(lt.autoStateTimer),lt.sessionId=r.session_id;try{await this.getCustomerInfo(r.trace_id||r.customer_phone)}catch(e){console.error(e)}ut.updateIsCalling(!0),ut.updateDirection(e.DirectionEnum.INCOMING),ut.updateDisplayText(e.DisplayTextEnum.INCOMING_CALL),this.inCallAutoAnswer(),1===r.direction&&dt.emit(e.CallSipCallEventEnum.INCOMING_CALL,{customer_phone:r.customer_phone,trace_id:r.trace_id,session_id:r.session_id}),8===r.direction&&dt.emit(e.CallSipCallEventEnum.INCOMING_CALL_IN,{customer_phone:r.customer_phone,trace_id:r.trace_id,session_id:r.session_id}),3===r.direction&&dt.emit(e.CallSipCallEventEnum.PREDICT_INCOMING_CALL,{customer_phone:r.customer_phone,trace_id:r.trace_id,session_id:r.session_id}),6===r.direction&&dt.emit(e.CallSipCallEventEnum.DUAL_CALL_INCOMING_CALL,{customer_phone:r.customer_phone,trace_id:r.trace_id,session_id:r.session_id}),ut.updateActionConfigs(ps),lt.enableBrowserAlert&&ss.show("📞 客户来电",`客户 [${r.customer_phone}] 正在呼入...`,()=>{dt.emit(e.EventName.NOTIFICATION_CLICK,{customer_phone:r.customer_phone})},lt.browserAlertTime)}else if(i===e.WebsocketTypeEnum.INCOMING_CALL_OFF_HOOK)ut.updateIncomingIsAnswer(!0),8===r.direction?(ut.updateActionConfigs(ds),dt.emit(e.CallSipCallEventEnum.INCOMING_CALL_IN_OFF_HOOK,{session_id:lt.sessionId})):(ut.updateActionConfigs(fs),dt.emit(e.CallSipCallEventEnum.INCOMING_CALL_OFF_HOOK,{session_id:lt.sessionId})),ut.updateDisplayText(e.DisplayTextEnum.CALLING);else if(i===e.WebsocketTypeEnum.INCOMING_CALL_END){if(lt.sessionId!==r.session_id)return;if(ut.updateDisplayText(""),1!==r.device_type&&7!==r.device_type||r.agent_no!==lt.agentInfo.agent_no)if(2===r.device_type&&r.agent_no===lt.agentInfo.agent_no)ut.reset(),dt.emit(e.CallSipCallEventEnum.OUR_SIDE_CONSULT_HANGUP,{session_id:r.session_id}),this.putAgentState(!0),ut.updateActionConfigs(os);else if(2===r.device_type&&r.agent_no!==lt.agentInfo.agent_no)ut.updateDisplayText(e.DisplayTextEnum.CALLING),dt.emit(e.CallSipCallEventEnum.OTHER_SIDE_CONSULT_HANGUP,{session_id:r.session_id}),ut.updateActionConfigs(hs);else if(3===r.device_type&&r.agent_no===lt.agentInfo.agent_no)this.putAgentState(!0),ut.reset(),dt.emit(e.CallSipCallEventEnum.THREE_WAY_OUR_SIDE_HANGUP,{session_id:r.session_id}),ut.updateActionConfigs(os);else if(4===r.device_type&&r.agent_no===lt.agentInfo.agent_no)this.putAgentState(!0),ut.reset(),dt.emit(e.CallSipCallEventEnum.TRANSFER_END,{session_id:r.session_id}),ut.updateActionConfigs(os);else if(4===r.device_type&&r.agent_no!==lt.agentInfo.agent_no){dt.emit(e.CallSipCallEventEnum.TRANSFER_FAILED,"未知原因"),dt.emit(e.EventName.FAIL_NOTIFICATION,"转接失败");const t=ut.get("direction");t===e.DirectionEnum.OUTGOING?ut.updateActionConfigs(hs):t===e.DirectionEnum.INCOMING&&ut.updateActionConfigs(fs)}else 5===r.device_type&&r.agent_no===lt.agentInfo.agent_no&&(this.putAgentState(!0,5),lt.monitoredAgentNo="",lt.earSpeakAgent="",ut.reset(),dt.emit(e.CallSipCallEventEnum.LISTEN_HANGUP,{session_id:r.session_id}),ut.updateActionConfigs(os));else this.putAgentState(!0),ut.reset(),dt.emit(e.CallSipCallEventEnum.INCOMING_CALL_END,{session_id:r.session_id}),ut.updateActionConfigs(os)}else if(i===e.WebsocketTypeEnum.SATISFACTION_EVALUATION)0===n?dt.emit(e.CallSipCallEventEnum.SATISFACTION_EVALUATION_SUCCESS):(dt.emit(e.CallSipCallEventEnum.SATISFACTION_EVALUATION_FAILED,o),dt.emit(e.EventName.FAIL_NOTIFICATION,o));else if(i===e.WebsocketTypeEnum.CONSULT_THREE_WAY)0!==n?(dt.emit(e.CallSipCallEventEnum.CONSULT_THREE_WAY_FAILED,o),dt.emit(e.EventName.FAIL_NOTIFICATION,o)):0===n&&ut.updateIsMeeting(!0);else if(i===e.WebsocketTypeEnum.CONSULT_THREE_WAY_RESULT)"success"===r.status?(ut.updateDirection(e.DirectionEnum.MEETING),ut.updateDisplayText(e.DisplayTextEnum.MEETING),ut.updateActionConfigs(us),dt.emit(e.CallSipCallEventEnum.CONSULT_THREE_WAY_SUCCESS)):(dt.emit(e.CallSipCallEventEnum.CONSULT_THREE_WAY_FAILED,{conf_name:r.conf_name}),ut.updateIsMeeting(!1));else if(i===e.WebsocketTypeEnum.TRANSFER_INCOMING_CALL)clearTimeout(lt.autoStateTimer),r.agent_no===lt.agentInfo.agent_no?(ut.updateDisplayText(e.DisplayTextEnum.TRANSFERRING),dt.emit(e.CallSipCallEventEnum.TRANSFER_PROGRESS),ut.updateActionConfigs([]),ut.updateTransferIsAnswer(!0)):(lt.sessionId=r.session_id,dt.emit(e.CallSipCallEventEnum.TRANSFER_INCOMING_CALL,{agent_no:r.agent_no,agent_name:r.agent_name,session_id:r.session_id}),ut.updateIsCalling(!0),ut.updateDirection(e.DirectionEnum.TRANSFER),ut.updateDisplayText(e.DisplayTextEnum.TRANSFER_INCOMING_CALL),ut.updateActionConfigs(ps),lt.enableBrowserAlert&&ss.show("📞 转接来电",`坐席 [${r.agent_no}] 正在转接...`,()=>{dt.emit(e.EventName.NOTIFICATION_CLICK,{agent_no:r.agent_no})},lt.browserAlertTime));else if(i===e.WebsocketTypeEnum.TRANSFER_OFF_HOOK)dt.emit(e.CallSipCallEventEnum.TRANSFER_OFF_HOOK,{session_id:lt.sessionId}),ut.updateTransferIsAnswer(!1),ut.updateDisplayText(e.DisplayTextEnum.CALLING),ut.updateActionConfigs(fs,8!==r.direction);else if(i===e.WebsocketTypeEnum.TRANSFER_FAILED){if("failed"===r.status){dt.emit(e.CallSipCallEventEnum.TRANSFER_FAILED,"未知原因"),dt.emit(e.EventName.FAIL_NOTIFICATION,"转接失败");const t=ut.get("direction");t===e.DirectionEnum.OUTGOING?ut.updateActionConfigs(hs):t===e.DirectionEnum.INCOMING&&ut.updateActionConfigs(fs)}}else i===e.WebsocketTypeEnum.KICK_OFFLINE?dt.emit(e.EventName.KICK_OFF):i===e.WebsocketTypeEnum.CONTINUOUS_NOT_ANSWER?(dt.emit(e.EventName.FAIL_NOTIFICATION,`已连续 ${r.miss_count} 次未接, 设置忙碌`),this.stateBusyChange()):i===e.WebsocketTypeEnum.SIGN_OUT?dt.emit(e.EventName.SIGN_OUT):i===e.WebsocketTypeEnum.SIGN_IN_SWITCH_DEVICE?dt.emit(e.EventName.SIGN_IN_SWITCH_DEVICE,r):i===e.WebsocketTypeEnum.LISTEN_INCOMING_CALL?(clearTimeout(lt.autoStateTimer),lt.sessionId=r.session_id,ut.updateIsCalling(!0),ut.updateDirection(e.DirectionEnum.INCOMING),this.inCallAutoAnswer(),ut.updateDisplayText(e.DisplayTextEnum.LISTENING),ut.updateActionConfigs(ps),dt.emit(e.CallSipCallEventEnum.LISTEN_INCOMING_CALL,{session_id:r.session_id}),lt.enableBrowserAlert&&ss.show("📞 监听来电","正在来电...",()=>{dt.emit(e.EventName.NOTIFICATION_CLICK,{customer_phone:r.customer_phone})},lt.browserAlertTime)):i===e.WebsocketTypeEnum.LISTEN_INCOMING_CALL_OFF_HOOK?(lt.monitoredAgentNo=r.monitored_agent_no,lt.earSpeakAgent="",ut.updateIncomingIsAnswer(!0),dt.emit(e.CallSipCallEventEnum.LISTEN_INCOMING_CALL_OFF_HOOK,{session_id:lt.sessionId,monitored_agent_no:r.monitored_agent_no}),ut.updateActionConfigs(ms),ut.updateDisplayText(e.DisplayTextEnum.CALLING)):i===e.WebsocketTypeEnum.LISTEN_CALL_FAILED?"failed"===r.status&&(dt.emit(e.CallSipCallEventEnum.LISTEN_CALL_FAILED),lt.monitoredAgentNo=""):i===e.WebsocketTypeEnum.EAR_SPEECH?"success"===r.status?(r.monitored_agent_no===lt.agentInfo.agent_no&&(ut.updateActionConfigs(_s),dt.emit(e.CallSipCallEventEnum.EAR_SPEECH_BE_SUCCESS)),r.monitor_agent_no===lt.agentInfo.agent_no&&(ut.updateActionConfigs(Es),dt.emit(e.CallSipCallEventEnum.EAR_SPEECH_SUCCESS,{monitored_agent_no:r.monitored_agent_no,monitor_agent_no:r.monitor_agent_no}),lt.earSpeakAgent=r.monitored_agent_no)):dt.emit(e.CallSipCallEventEnum.EAR_SPEECH_FAILED):i===e.WebsocketTypeEnum.STOP_EAR_SPEECH?"success"===r.status?(r.monitored_agent_no===lt.agentInfo.agent_no&&ut.updateActionConfigs(fs),r.monitor_agent_no===lt.agentInfo.agent_no&&ut.updateActionConfigs(ms),lt.earSpeakAgent="",dt.emit(e.CallSipCallEventEnum.STOP_EAR_SPEECH_SUCCESS)):dt.emit(e.CallSipCallEventEnum.STOP_EAR_SPEECH_FAILED):i===e.WebsocketTypeEnum.CALL_FORCE_INSERT?"success"===r.status?(r.monitored_agent_no===lt.agentInfo.agent_no&&(ut.updateActionConfigs(ws),dt.emit(e.CallSipCallEventEnum.CALL_FORCE_INSERT_SUCCESS,{monitored_agent_no:r.monitored_agent_no,monitor_agent_no:r.monitor_agent_no})),r.monitor_agent_no===lt.agentInfo.agent_no&&(ut.updateActionConfigs(Ts),dt.emit(e.CallSipCallEventEnum.CALL_FORCE_INSERT_SUCCESS_LISTENER,{monitored_agent_no:r.monitored_agent_no,monitor_agent_no:r.monitor_agent_no}))):dt.emit(e.CallSipCallEventEnum.CALL_FORCE_INSERT_FAILED):i===e.WebsocketTypeEnum.INTERNAL_CALL_START_CONSULT?r.agent_no===lt.agentInfo.agent_no?(ut.updateConsultIsAnswer(!0),ut.updateActionConfigs(ls),ut.updateDisplayText(e.DisplayTextEnum.CONSULTING)):(ut.updateDisplayText(e.DisplayTextEnum.OTHER_SIDE_CONSULTING),ut.updateActionConfigs([])):i===e.WebsocketTypeEnum.INTERNAL_CALL_END_CONSULT?(ut.updateActionConfigs(ds),ut.updateDisplayText(""),ut.updateConsultIsAnswer(!1)):i===e.WebsocketTypeEnum.CALL_SIP_INCOMING_CALL&&dt.emit(e.CallSipCallEventEnum.CALL_SIP_INCOMING_CALL)},this.ws.onclose=t=>{dt.emit(e.EventName.FAIL_NOTIFICATION,"链接已断开,请检查网络"),this.stopHeartbeat();const s=ut.get("isNextState");!this.manualClose&&s&&setTimeout(()=>this.initWebSocket(),this.reconnectDelay)},this.ws.onerror=t=>{dt.emit(e.EventName.FAIL_NOTIFICATION,"连接失败,请检查网络"),this.ws?.close()}}startHeartbeat(){const e=new Blob(["\n let timer;\n self.onmessage = function (e) {\n if (e.data === 'start') {\n timer = setInterval(() => {\n self.postMessage('heartbeat');\n }, 5000);\n } else if (e.data === 'stop') {\n clearInterval(timer);\n }\n };\n "],{type:"application/javascript"}),t=URL.createObjectURL(e);this.heartbeatWorker=new Worker(t),this.heartbeatWorker.onmessage=()=>{const e=(new Date).getTime();this.sendMessage({type:0,msg_id:e}),this.pendingMessages.set(e,performance.now())},this.heartbeatWorker.postMessage("start")}stopHeartbeat(){this.heartbeatWorker&&(this.heartbeatWorker.postMessage("stop"),this.heartbeatWorker.terminate(),this.heartbeatWorker=null)}sendMessage(e){this.ws?.readyState===WebSocket.OPEN?(this.ws.send(JSON.stringify(e)),0!==e.type&&Is("%cWebSocket 发送消息:","color: green; font-weight: bold;",e)):console.warn("WebSocket 未连接,消息未发送")}close(){this.manualClose=!0,this.stopHeartbeat(),this.ws?.close()}reconnect(){this.initWebSocket()}static __internalClose(){vs&&(vs.close(),vs=null)}static __internalSend(e){if(!vs)throw new Error("WebSocket 尚未初始化");vs.sendMessage(e)}}class As{constructor(e){this.sipClient=null,this.sipClient=e}roleMute(){const e=ut.get("isCalling"),t=lt.sessionId;if(!e)throw new Error(JSON.stringify({code:1,msg:"当前没有通话"}));if(!t)throw new Error(JSON.stringify({code:1,msg:"当前没有通话"}))}holdCall(){this.roleMute();const t=ut.get("isHold"),{sessionId:s}=lt;if(!s)return;if(!ut.get("actionConfigs").includes("hold"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿保持"}));if(t)throw new Error(JSON.stringify({code:1,msg:"当前已处于保持状态"}));ys.__internalSend({type:e.WebsocketTypeEnum.CALL_HOLD,data:{session_id:s}})}unholdCall(){this.roleMute();const{isHold:t}=ut.getState(),{sessionId:s}=lt;if(!ut.get("actionConfigs").includes("unhold"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿取消保持"}));if(s){if(!t)throw new Error(JSON.stringify({code:1,msg:"当前未处于保持状态"}));ys.__internalSend({type:e.WebsocketTypeEnum.CALL_UNHOLD,data:{session_id:s}})}}sendDTMF(e){if(1!==ut.get("answerDevice"))throw new Error(JSON.stringify({code:1,msg:"当前设备不支持此功能"}));if(!ut.get("actionConfigs").includes("dtmf"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿发送按键"}));const{isCalling:t}=ut.getState();if(!t)throw new Error(JSON.stringify({code:1,msg:"当前没有通话"}));this.sipClient.sendDTMF(e)}cancelCall(){if(!ut.get("isCalling"))throw new Error(JSON.stringify({code:1,msg:"当前没有通话"}));const t=lt.sessionId;dt.emit(e.CallSipCallEventEnum.REJECT,{session_id:t}),ys.__internalSend({type:e.WebsocketTypeEnum.AGENT_HANGUP,data:{session_id:t}})}async consultCall(t){this.roleMute();const{isCalling:s,outCallIsAnswer:i,consultIsAnswer:r,incomingIsAnswer:n}=ut.getState(),o=lt.sessionId;if(!ut.get("actionConfigs").includes("consult"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿调用咨询"}));if(r)throw new Error(JSON.stringify({code:1,msg:"当前正在咨询"}));if(!(s||i||n))throw new Error(JSON.stringify({code:1,msg:"当前没有通话"}));if(!o)throw new Error(JSON.stringify({code:1,msg:"sessionId不存在"}));ys.__internalSend({type:e.WebsocketTypeEnum.CONSULT_REQUEST,data:{session_id:o,consultation_agent_no:t}})}async answerCall(){if(1!==ut.get("answerDevice"))throw new Error(JSON.stringify({code:1,msg:"当前设备不支持此功能"}));await this.sipClient.answerCall()}makeCall(t){if("string"!=typeof t||""===t.trim())throw new Error(JSON.stringify({code:1,msg:"外呼号码非法"}));const s={};Jt(t)?s.trace_id=t:s.customer_phone=t.replace(/[\s\r\n-]+/g,"");const i=ut.get("isCalling"),r=ut.get("selectOutNumber")||"";if(i)throw new Error(JSON.stringify({code:1,msg:"正在呼叫中,请勿重复点击"}));ut.updateIsCalling(!0),ut.updateDirection(e.DirectionEnum.OUTGOING),ys.__internalSend({type:e.WebsocketTypeEnum.OUT_CALL,data:{...s,caller:r.replace(/[\s\r\n-]+/g,"")}})}previewCall(t,s){const i={};Jt(t)?i.trace_id=t:i.customer_phone=t.replace(/[\s\r\n-]+/g,"");const r=ut.get("isCalling"),n=ut.get("selectOutNumber")||"";if(r)throw new Error(JSON.stringify({code:1,msg:"正在呼叫中,请勿重复点击"}));if("string"!=typeof t||""===t.trim())throw new Error(JSON.stringify({code:1,msg:"外呼号码非法"}));ut.updateIsCalling(!0),ut.updateDirection(e.DirectionEnum.OUTGOING),ys.__internalSend({type:e.WebsocketTypeEnum.PREVIEW_OUT_CALL,data:{...i,caller:n,preview_task_id:s}})}async hangup(){if(!ut.get("isCalling"))throw new Error(JSON.stringify({code:1,msg:"当前没有通话"}));const t=lt.sessionId;ys.__internalSend({type:e.WebsocketTypeEnum.AGENT_HANGUP,data:{session_id:t}})}mute(){this.roleMute();const t=ut.get("actionConfigs"),s=ut.get("isMuted"),i=lt.sessionId;if(s)throw new Error(JSON.stringify({code:1,msg:"当前未处于静音状态"}));if(!t.includes("mute"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿调用静音"}));ys.__internalSend({type:e.WebsocketTypeEnum.MUTE,data:{session_id:i}})}unmute(){this.roleMute();const t=ut.get("actionConfigs"),s=ut.get("isMuted"),i=lt.sessionId;if(!s)throw new Error(JSON.stringify({code:1,msg:"当前未处于未静音状态"}));if(!t.includes("unmute"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿调用静音"}));ys.__internalSend({type:e.WebsocketTypeEnum.UNMUTE,data:{session_id:i}})}consultTransfer(){this.roleMute();const t=ut.get("consultIsAnswer"),s=lt.sessionId;if(!ut.get("actionConfigs").includes("consult_transfer"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿调用咨询转移"}));if(!t)throw new Error(JSON.stringify({code:1,msg:"当前未处于咨询中"}));ys.__internalSend({type:e.WebsocketTypeEnum.CONSULT_TRANSFER,data:{session_id:s}})}satisfactionEvaluation(){this.roleMute();const t=lt.sessionId;if(!ut.get("actionConfigs").includes("satisfaction"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿调用满意度评价"}));ys.__internalSend({type:e.WebsocketTypeEnum.SATISFACTION_EVALUATION,data:{session_id:t}})}startConference(){this.roleMute();if(!ut.get("actionConfigs").includes("conference"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿调用三方会议"}));const t=lt.sessionId;if(!ut.get("consultIsAnswer"))throw new Error(JSON.stringify({code:1,msg:"当前未处于咨询中"}));ys.__internalSend({type:e.WebsocketTypeEnum.CONSULT_THREE_WAY,data:{session_id:t}})}consultRetrieve(){this.roleMute();if(!ut.get("actionConfigs").includes("consult_retrieve"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿取回通话"}));const t=lt.sessionId;if(!ut.get("consultIsAnswer"))throw new Error(JSON.stringify({code:1,msg:"当前未处于咨询中"}));ys.__internalSend({type:e.WebsocketTypeEnum.CONSULT_RETURN_CALL,data:{session_id:t}})}async transferAgent(t){this.roleMute();if(!ut.get("actionConfigs").includes("transfer"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿转接"}));const{transferIsAnswer:s}=ut.getState(),i=lt.sessionId;if(s)throw new Error(JSON.stringify({code:1,msg:"当前正在转接"}));ys.__internalSend({type:e.WebsocketTypeEnum.TRANSFER,data:{session_id:i,transfer_type:0,transfer_dest:t}})}async transferOutline(t){this.roleMute();if(!ut.get("actionConfigs").includes("transfer"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿转接"}));if(!t)throw new Error(JSON.stringify({code:1,msg:"号码不能为空"}));if(!/^\d+$/.test(t))throw new Error(JSON.stringify({code:1,msg:"号码格式错误"}));const{transferIsAnswer:s}=ut.getState(),i=lt.sessionId;if(s)throw new Error(JSON.stringify({code:1,msg:"当前正在转接"}));if(s)throw new Error(JSON.stringify({code:1,msg:"当前正在转接"}));ys.__internalSend({type:e.WebsocketTypeEnum.TRANSFER,data:{session_id:i,transfer_type:2,transfer_dest:t}})}}var bs;class Rs{static{this._instance=null}#e;#t;#s;#i;#r;#n;#o;static{this._timer=null}constructor(){if(this.#e=null,this.#t=new Cs,this.#i=null,this.#o=!1,this.#a=()=>{},this.#c=()=>{},this.initWebRtc=async()=>{if(this.#e)return;const e=lt.agentInfo.sip_account_list.find(e=>1===e.device_type);if(!e)throw new Error(JSON.stringify({code:1,msg:"未找到 sip_account_list"}));{const t=e.sip_register_addr;this.#e=new ft({server:t.split(":")[0],user:e.sip_account,password:e.sip_password,webSocket:`wss://${t}`,callTimeout:3e4},this.#h),await this.#e.start()}},this.#h=e=>{const{type:t,data:s}=e;dt.emit(t,s)},!bs._creatingInstance)throw new Error("请使用 YSYTAgentSdk.getInstance() 获取实例");clearInterval(this.#i),this.#i=setInterval(async()=>{const e=await this.#d();pt.updateRttObject(e)},2e3),ss.requestMediaPermissions(),this.#n=ut.subscribeKey("isNextState",async t=>{if(t){1===ut.get("answerDevice")&&await this.#e.reconnect();let t="";const s=new URL(Zt).host;t=Zt.includes("https")?`wss://${s}`:`ws://${s}`;const{agent_no:i}=lt.agentInfo;ys.getInstance({url:`${t}/ccs-ws/api/v1/ws/call/${i}?Authorization=`,sipClient:this.#e}),setTimeout(()=>{this.#t._changeState({data:{state:e.AgentStatus.BUSY,state_name:"忙碌"},success:()=>{ut.updateDisplayText(""),dt.emit(e.CallSipCallEventEnum.AGENT_STATE,{state:e.AgentStatus.BUSY,state_name:"忙碌"})}},"d")},10)}else ys.__internalClose(),ut.updateIsCalling(!1),ut.updateOutCallIsAnswer(!1),ut.updateIncomingIsAnswer(!1),ut.updateIsMuted(!1),ut.updateConsultIsAnswer(!1),ut.updateIsHold(!1),ut.updateCustomerInfo(void 0),ut.updateDisplayText("离线")}),this.#r=ut.subscribeKey("answerDevice",async t=>{1===t?lt.stateObject.state===e.AgentStatus.UNREGISTERED&&await this.#t._changeState({data:{...lt.stateBeforeChange,state_name:lt.stateBeforeChange.state===e.AgentStatus.IDLE?"空闲":"忙碌"}},"qq"):await this.destroyRtc()}),this.on(e.EventName.KICK_OFF,()=>{this.destroy()}),window.addEventListener("beforeunload",e=>{e.returnValue="",this.destroy()}),window.addEventListener("online",this.#a),window.addEventListener("offline",this.#c)}#a;#c;async#l(){const t=ut.get("isNextState");try{await rs(),t||ut.updateIsNextState(!0)}catch(s){dt.emit(e.EventName.FAIL_NOTIFICATION,"网络断开,请检查网络"),t&&ut.updateIsNextState(!1)}}#g(){bs._timer||(bs._timer=setInterval(()=>this.#l(),3e3))}static get instance(){return this._instance}static async destroyInstance(){this._instance&&(await this._instance.destroy(),this._instance=null)}static getInstance(e){if(!this._instance){if(!e)throw new Error("首次调用必须传入配置参数");const{url:t,appKey:s,appSecret:i,agentNo:r}=e;Zt=t||"https://aicc-api.yescloudy.com",zt=s,Xt=i,Qt=r,bs._creatingInstance=!0,this._instance=new bs,delete bs._creatingInstance}return this._instance}getInit(){return this.#o}async init({enableBrowserAlert:t,logBuiltinEnabled:s,browserAlertTime:i}){try{let r="";const n=new URL(Zt).host;r=Zt.includes("https")?`wss://${n}`:`ws://${n}`;const o=ys.getInstance({url:`${r}/ccs-ws/api/v1/ws/call/${Qt}?Authorization=`,sipClient:null,onOpen:async()=>{lt.logBuiltinEnabled=s||!1,lt.browserAlertTime=i||5e3,await this.#t._agentLogin(Qt);const{current_answer_device:r,current_state:n,out_display_number:a,out_display_select_switch:c}=lt.agentInfo;n===e.AgentStatus.IDLE?(ut.updateActionConfigs(os),lt.stateObject={state:n,state_name:"空闲"},lt.stateBeforeChange=lt.stateObject):n===e.AgentStatus.BUSY?(ut.updateActionConfigs(as),lt.stateObject={state:n,state_name:"忙碌"},lt.stateBeforeChange=lt.stateObject):n===e.AgentStatus.UNREGISTERED&&(ut.updateActionConfigs(as),lt.stateObject={state:n,state_name:"未注册"}),1===c?ut.updateSelectOutNumber(a):ut.updateSelectOutNumber(""),ut.updateAnswerDevice(r),Cs.setInitRtcFn(this.initWebRtc),1===r&&(await this.initWebRtc(),o.setSipClient(this.#e)),this.#s=new As(this.#e),lt.enableBrowserAlert=t,t&&ss.requestPermission(),dt.emit(e.EventName.AGENT_INIT_STATUS,!0),this.#o=!0,clearInterval(bs._timer),bs._timer=null,this.#g()}})}catch(t){dt.emit(e.EventName.AGENT_INIT_STATUS,!1),this.#o=!1}}#h;on(e,t){return dt.on(e,t),this}off(e,t){dt.off(e,t)}offAll(){dt.clearAllListeners()}async destroyRtc(){await(this.#e?.destroy()),this.#e=null}async destroy(){bs._instance&&(await this.destroyRtc(),this.#r?.(),this.#n?.(),clearInterval(this.#i),ys.__internalClose(),dt.emit(e.EventName.DESTROY),this.offAll(),bs._instance=null,ut.reset(),ut.updateSelectOutNumber(""),clearInterval(bs._timer),bs._timer=null)}async#d(){return this.#e?this.#e.getNetworkStats():{}}get call_api(){const e=e=>(...t)=>e.apply(this,t);return{answerCall:e(()=>this.#s.answerCall()),makeCall:e=>this.#s.makeCall(e),previewMakeCall:(e,t)=>this.#s.previewCall(e,t),cancelCall:e(()=>this.#s.cancelCall()),hangup:e(()=>this.#s.hangup()),sendDTMF:e(e=>this.#s.sendDTMF(e)),holdCall:e(()=>this.#s.holdCall()),unholdCall:e(()=>this.#s.unholdCall()),consultCall:e(async e=>{try{await this.#s.consultCall(e)}catch(e){throw console.warn(e),e}}),consultRetrieve:e(()=>this.#s.consultRetrieve()),consultTransfer:e(()=>this.#s.consultTransfer()),mute:e(()=>this.#s.mute()),unmute:e(()=>this.#s.unmute()),satisfactionEvaluation:e(()=>this.#s.satisfactionEvaluation()),startConference:e(()=>this.#s.startConference()),transferAgent:e(e=>this.#s.transferAgent(e)),transferOutline:e(e=>this.#s.transferOutline(e)),earSpeakStart:e(e=>this.#t.earCall(e)),earSpeakStop:e(e=>this.#t.stopEarCall(e)),forceInsert:e(e=>this.#t.forceInsert(e)),forceDisconnect:e(e=>this.#t.forceDisconnect(e))}}get agent_api(){const t=e=>(...t)=>e.apply(this,t);return{changeDevice:t(e=>this.#t.changeDevice(e)),changeState:t(async t=>{const s=ut.get("answerDevice");if(lt.stateObject.state===e.AgentStatus.UNREGISTERED&&1===s){await this.#e.reconnect();let e="";const t=new URL(Zt).host;e=Zt.includes("https")?`wss://${t}`:`ws://${t}`;const{agent_no:s}=lt.agentInfo;ys.getInstance({url:`${e}/ccs-ws/api/v1/ws/call/${s}?Authorization=`,sipClient:this.#e})}await this.#t.changeState(t,"c")}),getIdleAgentList:t(e=>this.#t.getIdleAgentList(e)),getAgentState:t(e=>this.#t.getAgentState(e)),setAgentExplicit:t(e=>this.#t.setAgentExplicit(e)),checkAgentLogin:e=>this.#t.checkAgentLogin(e),getCallRecord:e=>this.#t.getCallRecord(e),agentLogout:async(e,t)=>{try{await this.#t.logout(e),await this.destroy(),t?.({code:0,msg:""})}catch(e){}},listenAgentCall:e=>this.#t.listenCall(e)}}getAgentData(){const{agent_no:e,agent_name:t,answer_devices:s,out_display_data:i,out_display_select_switch:r,current_state:n}=lt.agentInfo,{stateObject:o}=lt,a={1:"软电话",2:"手机模式",3:"SIP话机"};return{agent_no:e,agent_name:t,init_state:n,default_device:ut.get("answerDevice"),out_display_data:i,out_display_select_switch:r,answer_devices:(s||"").split(",").map(e=>({value:Number(e),label:a[Number(e)]})),stateObject:o}}async getRealTimeCustomerInfo(){return ut.get("customerObject")}setBrowserAlert(e){if("boolean"!=typeof e)throw new Error(JSON.stringify({code:1,msg:"参数类型错误"}));lt.logBuiltinEnabled=e||!1}setBrowserAlertTime(e){if("number"!=typeof e)throw new Error(JSON.stringify({code:1,msg:"参数类型错误"}));lt.browserAlertTime=e||3e3}}bs=Rs,e.default=Rs,Object.defineProperty(e,"__esModule",{value:!0})});
|