ysyt-react-agent-lib 1.2.26 → 1.2.28

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.
@@ -152,7 +152,7 @@ React keys must be passed directly to JSX without using spread:
152
152
  `+i+`
153
153
  `);if(this.state===dt.Connected){if(this.onMessage)try{this.onMessage(i)}catch(o){throw this.logger.error(o.toString()),this.logger.error("Exception thrown by onMessage callback"),o}}else this.logger.warn("Received message while not connected, discarding...")}else this.logger.warn("Received empty message, discarding...")}onWebSocketOpen(e,n){n===this._ws&&this._state===dt.Connecting&&(this.logger.log(`WebSocket opened ${this.server}`),this.transitionState(dt.Connected))}transitionLoopDetectedError(e){let n="A state transition loop has been detected.";return n+=` An attempt to transition from ${this._state} to ${e} before the prior transition completed.`,n+=" Perhaps you are synchronously calling connect() or disconnect() from a callback or state change handler?",this.logger.error(n),new ca("Loop detected.")}transitionState(e,n){const r=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};if(this.transitioningState)throw this.transitionLoopDetectedError(e);switch(this.transitioningState=!0,this._state){case dt.Connecting:e!==dt.Connected&&e!==dt.Disconnecting&&e!==dt.Disconnected&&r();break;case dt.Connected:e!==dt.Disconnecting&&e!==dt.Disconnected&&r();break;case dt.Disconnecting:e!==dt.Connecting&&e!==dt.Disconnected&&r();break;case dt.Disconnected:e!==dt.Connecting&&r();break;default:throw new Error("Unknown state.")}const i=this._state;this._state=e;const o=this.connectResolve,a=this.connectReject;i===dt.Connecting&&(this.connectPromise=void 0,this.connectResolve=void 0,this.connectReject=void 0);const s=this.disconnectResolve,A=this.disconnectReject;if(i===dt.Disconnecting&&(this.disconnectPromise=void 0,this.disconnectResolve=void 0,this.disconnectReject=void 0),this.connectTimeout&&(clearTimeout(this.connectTimeout),this.connectTimeout=void 0),this.logger.log(`Transitioned from ${i} to ${this._state}`),this._stateEventEmitter.emit(this._state),e===dt.Connected&&(this.startSendingKeepAlives(),this.onConnect))try{this.onConnect()}catch(c){throw this.logger.error(c.toString()),this.logger.error("Exception thrown by onConnect callback"),c}if(i===dt.Connected&&(this.stopSendingKeepAlives(),this.onDisconnect))try{n?this.onDisconnect(n):this.onDisconnect()}catch(c){throw this.logger.error(c.toString()),this.logger.error("Exception thrown by onDisconnect callback"),c}if(i===dt.Connecting){if(!o)throw new Error("Connect resolve undefined.");if(!a)throw new Error("Connect reject undefined.");e===dt.Connected?o():a(n||new Error("Connect aborted."))}if(i===dt.Disconnecting){if(!s)throw new Error("Disconnect resolve undefined.");if(!A)throw new Error("Disconnect reject undefined.");e===dt.Disconnected?s():A(n||new Error("Disconnect aborted."))}this.transitioningState=!1}clearKeepAliveTimeout(){this.keepAliveDebounceTimeout&&clearTimeout(this.keepAliveDebounceTimeout),this.keepAliveDebounceTimeout=void 0}sendKeepAlive(){return this.keepAliveDebounceTimeout?Promise.resolve():(this.keepAliveDebounceTimeout=setTimeout(()=>{this.clearKeepAliveTimeout()},1e3*this.configuration.keepAliveDebounce),this.send(`\r
154
154
  \r
155
- `))}startSendingKeepAlives(){this.configuration.keepAliveInterval&&!this.keepAliveInterval&&(this.keepAliveInterval=setInterval(()=>{this.sendKeepAlive(),this.startSendingKeepAlives()},(e=>{const n=.8*e;return 1e3*(Math.random()*(e-n)+n)})(this.configuration.keepAliveInterval)))}stopSendingKeepAlives(){this.keepAliveInterval&&clearInterval(this.keepAliveInterval),this.keepAliveDebounceTimeout&&clearTimeout(this.keepAliveDebounceTimeout),this.keepAliveInterval=void 0,this.keepAliveDebounceTimeout=void 0}};R0.defaultOptions={server:"",connectionTimeout:5,keepAliveInterval:0,keepAliveDebounce:10,traceSip:!0};let Fg=class Js{constructor(e={}){if(this._publishers={},this._registerers={},this._sessions={},this._subscriptions={},this._state=Dn.Stopped,this._stateEventEmitter=new Pa,this.delegate=e.delegate,this.options=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},Js.defaultOptions()),{sipjsId:zi(5)}),{uri:new Ni("sip","anonymous."+zi(6),"anonymous.invalid")}),{viaHost:zi(12)+".invalid"}),Js.stripUndefinedProperties(e)),this.options.hackIpInContact)if(typeof this.options.hackIpInContact=="boolean"&&this.options.hackIpInContact){const i=Math.floor(Math.random()*254+1);this.options.viaHost="192.0.2."+i}else this.options.hackIpInContact&&(this.options.viaHost=this.options.hackIpInContact);switch(this.loggerFactory=new $S,this.logger=this.loggerFactory.getLogger("sip.UserAgent"),this.loggerFactory.builtinEnabled=this.options.logBuiltinEnabled,this.loggerFactory.connector=this.options.logConnector,this.options.logLevel){case"error":this.loggerFactory.level=On.error;break;case"warn":this.loggerFactory.level=On.warn;break;case"log":this.loggerFactory.level=On.log;break;case"debug":this.loggerFactory.level=On.debug}if(this.options.logConfiguration&&(this.logger.log("Configuration:"),Object.keys(this.options).forEach(n=>{const r=this.options[n];switch(n){case"uri":case"sessionDescriptionHandlerFactory":this.logger.log("· "+n+": "+r);break;case"authorizationPassword":this.logger.log("· "+n+": NOT SHOWN");break;case"transportConstructor":this.logger.log("· "+n+": "+r.name);break;default:this.logger.log("· "+n+": "+JSON.stringify(r))}})),this.options.transportOptions){const n=this.options.transportOptions,r=n.maxReconnectionAttempts,i=n.reconnectionTimeout;r!==void 0&&this.logger.warn('The transport option "maxReconnectionAttempts" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.'),i!==void 0&&this.logger.warn('The transport option "reconnectionTimeout" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.'),e.reconnectionDelay===void 0&&i!==void 0&&(this.options.reconnectionDelay=i),e.reconnectionAttempts===void 0&&r!==void 0&&(this.options.reconnectionAttempts=r)}if(e.reconnectionDelay!==void 0&&this.logger.warn('The user agent option "reconnectionDelay" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.'),e.reconnectionAttempts!==void 0&&this.logger.warn('The user agent option "reconnectionAttempts" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.'),this._transport=new this.options.transportConstructor(this.getLogger("sip.Transport"),this.options.transportOptions),this.initTransportCallbacks(),this._contact=this.initContact(),this._instanceId=this.options.instanceId?this.options.instanceId:Js.newUUID(),En.parse(this._instanceId,"uuid")===-1)throw new Error("Invalid instanceId.");this._userAgentCore=this.initCore()}static makeURI(e){return En.URIParse(e)}static defaultOptions(){return{allowLegacyNotifications:!1,authorizationHa1:"",authorizationPassword:"",authorizationUsername:"",delegate:{},contactName:"",contactParams:{transport:"ws"},displayName:"",forceRport:!1,gracefulShutdown:!0,hackAllowUnregisteredOptionTags:!1,hackIpInContact:!1,hackViaTcp:!1,instanceId:"",instanceIdAlwaysAdded:!1,logBuiltinEnabled:!0,logConfiguration:!0,logConnector:()=>{},logLevel:"log",noAnswerTimeout:60,preloadedRouteSet:[],reconnectionAttempts:0,reconnectionDelay:4,sendInitialProvisionalResponse:!0,sessionDescriptionHandlerFactory:mw(),sessionDescriptionHandlerFactoryOptions:{},sipExtension100rel:Nr.Unsupported,sipExtensionReplaces:Nr.Unsupported,sipExtensionExtraSupported:[],sipjsId:"",transportConstructor:R0,transportOptions:{},uri:new Ni("sip","anonymous","anonymous.invalid"),userAgentString:"SIP.js/0.21.1",viaHost:""}}static newUUID(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const n=Math.floor(16*Math.random());return(e==="x"?n:n%4+8).toString(16)})}static stripUndefinedProperties(e){return Object.keys(e).reduce((n,r)=>(e[r]!==void 0&&(n[r]=e[r]),n),{})}get configuration(){return this.options}get contact(){return this._contact}get instanceId(){return this._instanceId}get state(){return this._state}get stateChange(){return this._stateEventEmitter}get transport(){return this._transport}get userAgentCore(){return this._userAgentCore}getLogger(e,n){return this.loggerFactory.getLogger(e,n)}getLoggerFactory(){return this.loggerFactory}isConnected(){return this.transport.isConnected()}reconnect(){return this.state===Dn.Stopped?Promise.reject(new Error("User agent stopped.")):Promise.resolve().then(()=>this.transport.connect())}start(){return this.state===Dn.Started?(this.logger.warn("User agent already started"),Promise.resolve()):(this.logger.log(`Starting ${this.configuration.uri}`),this.transitionState(Dn.Started),this.transport.connect())}async stop(){if(this.state===Dn.Stopped)return this.logger.warn("User agent already stopped"),Promise.resolve();if(this.logger.log(`Stopping ${this.configuration.uri}`),!this.options.gracefulShutdown)return this.logger.log("Dispose of transport"),this.transport.dispose().catch(s=>{throw this.logger.error(s.message),s}),this.logger.log("Dispose of core"),this.userAgentCore.dispose(),this._publishers={},this._registerers={},this._sessions={},this._subscriptions={},this.transitionState(Dn.Stopped),Promise.resolve();const e=Object.assign({},this._publishers),n=Object.assign({},this._registerers),r=Object.assign({},this._sessions),i=Object.assign({},this._subscriptions),o=this.transport,a=this.userAgentCore;this.logger.log("Dispose of registerers");for(const s in n)n[s]&&await n[s].dispose().catch(A=>{throw this.logger.error(A.message),delete this._registerers[s],A});this.logger.log("Dispose of sessions");for(const s in r)r[s]&&await r[s].dispose().catch(A=>{throw this.logger.error(A.message),delete this._sessions[s],A});this.logger.log("Dispose of subscriptions");for(const s in i)i[s]&&await i[s].dispose().catch(A=>{throw this.logger.error(A.message),delete this._subscriptions[s],A});this.logger.log("Dispose of publishers");for(const s in e)e[s]&&await e[s].dispose().catch(A=>{throw this.logger.error(A.message),delete this._publishers[s],A});this.logger.log("Dispose of transport"),await o.dispose().catch(s=>{throw this.logger.error(s.message),s}),this.logger.log("Dispose of core"),a.dispose(),this.transitionState(Dn.Stopped)}_makeInviter(e,n){return new v0(this,e,n)}attemptReconnection(e=1){const n=this.options.reconnectionAttempts,r=this.options.reconnectionDelay;e>n?this.logger.log("Maximum reconnection attempts reached"):(this.logger.log(`Reconnection attempt ${e} of ${n} - trying`),setTimeout(()=>{this.reconnect().then(()=>{this.logger.log(`Reconnection attempt ${e} of ${n} - succeeded`)}).catch(i=>{this.logger.error(i.message),this.logger.log(`Reconnection attempt ${e} of ${n} - failed`),this.attemptReconnection(++e)})},e===1?0:1e3*r))}initContact(){const e=this.options.contactName!==""?this.options.contactName:zi(8),n=this.options.contactParams;return{pubGruu:void 0,tempGruu:void 0,uri:new Ni("sip",e,this.options.viaHost,void 0,n),toString:(r={})=>{const i=r.anonymous||!1,o=r.outbound||!1,a=r.register||!1;let s="<";return s+=i?this.contact.tempGruu||`sip:anonymous@anonymous.invalid;transport=${n.transport?n.transport:"ws"}`:a?this.contact.uri:this.contact.pubGruu||this.contact.uri,o&&(s+=";ob"),s+=">",this.options.instanceIdAlwaysAdded&&(s+=';+sip.instance="<urn:uuid:'+this._instanceId+'>"'),s}}}initCore(){let e=[];e.push("outbound"),this.options.sipExtension100rel===Nr.Supported&&e.push("100rel"),this.options.sipExtensionReplaces===Nr.Supported&&e.push("replaces"),this.options.sipExtensionExtraSupported&&e.push(...this.options.sipExtensionExtraSupported),this.options.hackAllowUnregisteredOptionTags||(e=e.filter(o=>JS[o])),e=Array.from(new Set(e));const n=e.slice();(this.contact.pubGruu||this.contact.tempGruu)&&n.push("gruu");const r={aor:this.options.uri,contact:this.contact,displayName:this.options.displayName,loggerFactory:this.loggerFactory,hackViaTcp:this.options.hackViaTcp,routeSet:this.options.preloadedRouteSet,supportedOptionTags:e,supportedOptionTagsResponse:n,sipjsId:this.options.sipjsId,userAgentHeaderFieldValue:this.options.userAgentString,viaForceRport:this.options.forceRport,viaHost:this.options.viaHost,authenticationFactory:()=>{const o=this.options.authorizationUsername?this.options.authorizationUsername:this.options.uri.user,a=this.options.authorizationPassword?this.options.authorizationPassword:void 0,s=this.options.authorizationHa1?this.options.authorizationHa1:void 0;return new _S(this.getLoggerFactory(),s,o,a)},transportAccessor:()=>this.transport},i={onInvite:o=>{var a;const s=new eu(this,o);if(o.delegate={onCancel:A=>{s._onCancel(A)},onTransportError:A=>{this.logger.error("A transport error has occurred while handling an incoming INVITE request.")}},o.trying(),this.options.sipExtensionReplaces!==Nr.Unsupported){const A=o.message.parseHeader("replaces");if(A){const c=A.call_id;if(typeof c!="string")throw new Error("Type of call id is not string");const u=A.replaces_to_tag;if(typeof u!="string")throw new Error("Type of to tag is not string");const d=A.replaces_from_tag;if(typeof d!="string")throw new Error("type of from tag is not string");const f=c+u+d,p=this.userAgentCore.dialogs.get(f);if(!p)return void s.reject({statusCode:481});if(!p.early&&A.early_only===!0)return void s.reject({statusCode:486});const v=this._sessions[c+d]||this._sessions[c+u]||void 0;if(!v)throw new Error("Session does not exist.");s._replacee=v}}if(!((a=this.delegate)===null||a===void 0)&&a.onInvite)return s.autoSendAnInitialProvisionalResponse?void s.progress().then(()=>{var A;if(((A=this.delegate)===null||A===void 0?void 0:A.onInvite)===void 0)throw new Error("onInvite undefined.");this.delegate.onInvite(s)}):void this.delegate.onInvite(s);s.reject({statusCode:486})},onMessage:o=>{if(this.delegate&&this.delegate.onMessage){const a=new p0(o);this.delegate.onMessage(a)}else o.accept()},onNotify:o=>{if(this.delegate&&this.delegate.onNotify){const a=new $l(o);this.delegate.onNotify(a)}else this.options.allowLegacyNotifications?o.accept():o.reject({statusCode:481})},onRefer:o=>{this.logger.warn("Received an out of dialog REFER request"),this.delegate&&this.delegate.onReferRequest?this.delegate.onReferRequest(o):o.reject({statusCode:405})},onRegister:o=>{this.logger.warn("Received an out of dialog REGISTER request"),this.delegate&&this.delegate.onRegisterRequest?this.delegate.onRegisterRequest(o):o.reject({statusCode:405})},onSubscribe:o=>{this.logger.warn("Received an out of dialog SUBSCRIBE request"),this.delegate&&this.delegate.onSubscribeRequest?this.delegate.onSubscribeRequest(o):o.reject({statusCode:405})}};return new pw(r,i)}initTransportCallbacks(){this.transport.onConnect=()=>this.onTransportConnect(),this.transport.onDisconnect=e=>this.onTransportDisconnect(e),this.transport.onMessage=e=>this.onTransportMessage(e)}onTransportConnect(){this.state!==Dn.Stopped&&this.delegate&&this.delegate.onConnect&&this.delegate.onConnect()}onTransportDisconnect(e){this.state!==Dn.Stopped&&(this.delegate&&this.delegate.onDisconnect&&this.delegate.onDisconnect(e),e&&this.options.reconnectionAttempts>0&&this.attemptReconnection())}onTransportMessage(e){const n=Ws.parseMessage(e,this.getLogger("sip.Parser"));if(!n)return void this.logger.warn("Failed to parse incoming message. Dropping.");if(this.state===Dn.Stopped&&n instanceof Bo)return void this.logger.warn(`Received ${n.method} request while stopped. Dropping.`);const r=()=>{const i=["from","to","call_id","cseq","via"];for(const o of i)if(!n.hasHeader(o))return this.logger.warn(`Missing mandatory header field : ${o}.`),!1;return!0};if(n instanceof Bo){if(!r())return void this.logger.warn("Request missing mandatory header field. Dropping.");if(!n.toTag&&n.callId.substr(0,5)===this.options.sipjsId)return void this.userAgentCore.replyStateless(n,{statusCode:482});const i=Qa(n.body),o=n.getHeader("content-length");if(o&&i<Number(o))return void this.userAgentCore.replyStateless(n,{statusCode:400})}if(n instanceof Fi){if(!r())return void this.logger.warn("Response missing mandatory header field. Dropping.");if(n.getHeaders("via").length>1)return void this.logger.warn("More than one Via header field present in the response. Dropping.");if(n.via.host!==this.options.viaHost||n.via.port!==void 0)return void this.logger.warn("Via sent-by in the response does not match UA Via host value. Dropping.");const i=Qa(n.body),o=n.getHeader("content-length");if(o&&i<Number(o))return void this.logger.warn("Message body length is lower than the value in Content-Length header field. Dropping.")}if(n instanceof Bo)this.userAgentCore.receiveIncomingRequestFromTransport(n);else{if(!(n instanceof Fi))throw new Error("Invalid message type.");this.userAgentCore.receiveIncomingResponseFromTransport(n)}}transitionState(e,n){const r=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case Dn.Started:e!==Dn.Stopped&&r();break;case Dn.Stopped:e!==Dn.Started&&r();break;default:throw new Error("Unknown state.")}this.logger.log(`Transitioned from ${this._state} to ${e}`),this._state=e,this._stateEventEmitter.emit(this._state)}},M0=class{constructor(e){this.listeners=[],this.keyListeners={},this.data={...e},this.proxy=new Proxy(this.data,{set:(n,r,i)=>(n[r]!==i&&(n[r]=i,this.notify(),this.notifyKey(r,i)),!0)})}getState(){return this.proxy}setState(e,n=!1){let r=!1;for(const i in e)if(Object.prototype.hasOwnProperty.call(e,i)){const o=this.data[i],a=e[i];(n||o!==a)&&(this.data[i]=a,r=!0,this.notifyKey(i,a))}(r||n)&&this.notify()}subscribe(e){return this.listeners.push(e),()=>{this.listeners=this.listeners.filter(n=>n!==e)}}subscribeKey(e,n){return this.keyListeners[e]||(this.keyListeners[e]=[]),this.keyListeners[e].push(n),()=>{this.keyListeners[e]=this.keyListeners[e].filter(r=>r!==n)}}notify(){const e=this.getState();for(const n of this.listeners)n(e)}notifyKey(e,n){const r=this.keyListeners[e];r&&r.forEach(i=>i(n))}};var Rt,xn,it,Ar,ie,He,Kt;(function(t){t[t.IDLE=1]="IDLE",t[t.BUSY=2]="BUSY",t[t.RINGING=3]="RINGING",t[t.OFFLINE=0]="OFFLINE",t[t.UNREGISTERED=4]="UNREGISTERED"})(Rt||(Rt={})),function(t){t.OUTGOING="outgoing",t.INCOMING="incoming",t.CONSULT="consult",t.MEETING="meeting",t.TRANSFER="transfer",t.PREDICT_OUT_CALL="predict_out_call"}(xn||(xn={})),function(t){t[t.OUT_CALL=100]="OUT_CALL",t[t.AGENT_STATE=101]="AGENT_STATE",t[t.OUT_CALL_INCOMING_CALL=102]="OUT_CALL_INCOMING_CALL",t[t.OUT_CALL_RINGING=103]="OUT_CALL_RINGING",t[t.OUT_CALL_ANSWER=104]="OUT_CALL_ANSWER",t[t.CALL_HOLD=105]="CALL_HOLD",t[t.CALL_UNHOLD=106]="CALL_UNHOLD",t[t.OUT_CALL_END=107]="OUT_CALL_END",t[t.CONSULT_REQUEST=108]="CONSULT_REQUEST",t[t.CONSULT_RINGING=109]="CONSULT_RINGING",t[t.CONSULT_ANSWER=110]="CONSULT_ANSWER",t[t.CONSULT_FAIL=111]="CONSULT_FAIL",t[t.MUTE=112]="MUTE",t[t.UNMUTE=113]="UNMUTE",t[t.CONSULT_CALL_IN=114]="CONSULT_CALL_IN",t[t.CONSULT_CALL_IN_SUCCESS=115]="CONSULT_CALL_IN_SUCCESS",t[t.CONSULT_RETURN_CALL=125]="CONSULT_RETURN_CALL",t[t.CONSULT_RETURN_CALL_SUCCESS=126]="CONSULT_RETURN_CALL_SUCCESS",t[t.CONSULT_TRANSFER=116]="CONSULT_TRANSFER",t[t.CONSULT_TRANSFER_FAILED=118]="CONSULT_TRANSFER_FAILED",t[t.CONSULT_TRANSFER_OFF_HOOK=117]="CONSULT_TRANSFER_OFF_HOOK",t[t.INCOMING_CALL=119]="INCOMING_CALL",t[t.INCOMING_CALL_OFF_HOOK=120]="INCOMING_CALL_OFF_HOOK",t[t.INCOMING_CALL_END=121]="INCOMING_CALL_END",t[t.SATISFACTION_EVALUATION=122]="SATISFACTION_EVALUATION",t[t.CONSULT_THREE_WAY=123]="CONSULT_THREE_WAY",t[t.CONSULT_THREE_WAY_RESULT=124]="CONSULT_THREE_WAY_RESULT",t[t.TRANSFER=127]="TRANSFER",t[t.TRANSFER_FAILED=128]="TRANSFER_FAILED",t[t.TRANSFER_INCOMING_CALL=129]="TRANSFER_INCOMING_CALL",t[t.TRANSFER_OFF_HOOK=130]="TRANSFER_OFF_HOOK",t[t.AGENT_HANGUP=131]="AGENT_HANGUP",t[t.KICK_OFFLINE=132]="KICK_OFFLINE",t[t.CONTINUOUS_NOT_ANSWER=133]="CONTINUOUS_NOT_ANSWER",t[t.PREVIEW_OUT_CALL=134]="PREVIEW_OUT_CALL",t[t.SIGN_OUT=135]="SIGN_OUT",t[t.SIGN_IN_SWITCH_DEVICE=136]="SIGN_IN_SWITCH_DEVICE",t[t.LISTEN_CALL_FAILED=137]="LISTEN_CALL_FAILED",t[t.LISTEN_INCOMING_CALL=138]="LISTEN_INCOMING_CALL",t[t.LISTEN_INCOMING_CALL_OFF_HOOK=139]="LISTEN_INCOMING_CALL_OFF_HOOK",t[t.EAR_SPEECH=140]="EAR_SPEECH",t[t.STOP_EAR_SPEECH=141]="STOP_EAR_SPEECH",t[t.CALL_FORCE_INSERT=142]="CALL_FORCE_INSERT",t[t.INTERNAL_CALL_START_CONSULT=145]="INTERNAL_CALL_START_CONSULT",t[t.INTERNAL_CALL_END_CONSULT=146]="INTERNAL_CALL_END_CONSULT",t[t.CALL_SIP_INCOMING_CALL=147]="CALL_SIP_INCOMING_CALL"}(it||(it={})),function(t){t.WEB_RTC_CONNECTING="connecting",t.WEB_RTC_CONNECTED="connected",t.WEB_RTC_DISCONNECTING="disconnecting",t.WEB_RTC_DISCONNECTED="disconnected",t.WEB_RTC_REGISTERED="registered",t.WEB_RTC_UNREGISTERED="unregistered",t.WEB_RTC_TERMINATED="terminated",t.WEB_RTC_REGISTER_FAILED="register_failed",t.WEB_RTC_ANSWER_FAILED="answer_failed",t.WEB_RTC_SEND_DTMF="send_dtmf"}(Ar||(Ar={})),function(t){t.CUSTOMER_INFO="customer_info",t.CALL_PROGRESS="call_progress",t.OUT_INCOMING_CALL="out_call_incoming_call",t.INTERNAL_OUT_INCOMING_CALL="internal_out_incoming_call",t.PREVIEW_OUT_INCOMING_CALL="preview_out_incoming_call",t.OUT_SUCCESS="out_call_success",t.OUT_FAILED="out_call_failed",t.OUT_RINGING="out_call_ringing",t.OUT_OFF_ANSWER="out_call_answer",t.INTERNAL_OUT_OFF_ANSWER="internal_out_call_answer",t.HOLD_SUCCESS="hold_success",t.HOLD_FAILED="hold_failed",t.UNHOLD_SUCCESS="unhold_success",t.UNHOLD_FAILED="unhold_failed",t.OUT_HANGUP="out_call_hangup",t.CONSULT_RINGING="consult_ringing",t.CONSULT_OFF_HOOK="consult_off_hook",t.CONSULT_FAILED="consult_failed",t.CONSULT_INCOMING="consult_incoming",t.CONSULT_CALL_IN_SUCCESS="consult_call_in_success",t.CONSULT_RETURN_CALL_SUCCESS="consult_return_call_success",t.OTHER_SIDE_CONSULT_HANGUP="other_side_consult_hangup",t.OUR_SIDE_CONSULT_HANGUP="our_side_consult_hangup",t.AGENT_STATE="agent_state",t.MUTE_SUCCESS="mute_success",t.MUTE_FAILED="mute_failed",t.UNMUTE_SUCCESS="unmute_success",t.UNMUTE_FAILED="unmute_failed",t.CONSULT_TRANSFER_SUCCESS="consult_transfer_success",t.CONSULT_TRANSFER_FAILED="consult_transfer_failed",t.CONSULT_TRANSFER_OFF_HOOK="consult_transfer_off_hook",t.INCOMING_CALL="incoming_call",t.INCOMING_CALL_IN="incoming_call_in",t.PREDICT_INCOMING_CALL="predict_incoming_call",t.DUAL_CALL_INCOMING_CALL="dual_call_incoming_call",t.INCOMING_CALL_OFF_HOOK="incoming_call_off_hook",t.INCOMING_CALL_IN_OFF_HOOK="incoming_call_in_off_hook",t.INCOMING_CALL_END="incoming_call_end",t.SATISFACTION_EVALUATION_SUCCESS="satisfaction_evaluation_success",t.SATISFACTION_EVALUATION_FAILED="satisfaction_evaluation_failed",t.CONSULT_THREE_WAY_SUCCESS="consult_three_way_success",t.CONSULT_THREE_WAY_FAILED="consult_three_way_failed",t.THREE_WAY_OUR_SIDE_HANGUP="three_way_our_side_hangup",t.TRANSFER_FAILED="transfer_failed",t.TRANSFER_PROGRESS="transfer_progress",t.TRANSFER_INCOMING_CALL="transfer_incoming_call",t.TRANSFER_OFF_HOOK="transfer_off_hook",t.TRANSFER_END="transfer_end",t.REJECT="reject",t.LISTEN_CALL_FAILED="listen_call_failed",t.LISTEN_INCOMING_CALL="listen_incoming_call",t.LISTEN_INCOMING_CALL_OFF_HOOK="listen_incoming_call_off_hook",t.LISTEN_HANGUP="listen_hangup",t.EAR_SPEECH_SUCCESS="ear_speech_success",t.EAR_SPEECH_BE_SUCCESS="ear_speech_be_success",t.EAR_SPEECH_FAILED="ear_speech_failed",t.STOP_EAR_SPEECH_SUCCESS="stop_ear_speech_success",t.STOP_EAR_SPEECH_FAILED="stop_ear_speech_failed",t.CALL_FORCE_INSERT_SUCCESS="call_force_insert_success",t.CALL_FORCE_INSERT_SUCCESS_LISTENER="call_force_insert_success_listener",t.CALL_FORCE_INSERT_FAILED="call_force_insert_failed",t.CALL_SIP_INCOMING_CALL="call_sip_incoming_call"}(ie||(ie={})),function(t){t.EVENT_ALL="event_all",t.NOTIFICATION_CLICK="notification_click",t.UPDATE_ANSWER_DEVICE="update_answer_device",t.PHONE_BAR_OPERATION="phone_bar_operation",t.AGENT_INIT_STATUS="agent_init_status",t.WEBSITE_DELAY="website_delay",t.SELECT_EXTERNAL_NUMBER="select_external_number",t.FAIL_NOTIFICATION="fail_notification",t.KICK_OFF="kick_off",t.DESTROY="destroy",t.NETWORK_OFFLINE="network_offline",t.NETWORK_ONLINE="network_online",t.SIGN_OUT="sign_out",t.SIGN_IN_SWITCH_DEVICE="sign_in_switch_device"}(He||(He={})),function(t){t.RINGING="客户振铃",t.AGENT_RINGING="振铃中",t.CALLING="通话中",t.CONSULTING="正在咨询",t.CONSULT_CALL_IN="咨询来电",t.INCOMING_CALL="客户来电",t.MEETING="会议中",t.TRANSFERRING="转接中",t.TRANSFER_INCOMING_CALL="转接来电",t.HOLDING="保持中",t.MUTING="静音中",t.LISTENING="监听来电",t.LINKING="正在链接",t.OTHER_SIDE_CONSULTING="对方正咨询"}(Kt||(Kt={}));const la={all:vi=vi||new Map,on:function(t,e){var n=vi.get(t);n?n.push(e):vi.set(t,[e])},off:function(t,e){var n=vi.get(t);n&&(e?n.splice(n.indexOf(e)>>>0,1):vi.set(t,[]))},emit:function(t,e){var n=vi.get(t);n&&n.slice().map(function(r){r(e)}),(n=vi.get("*"))&&n.slice().map(function(r){r(t,e)})}};var vi;const fe={on:(t,e)=>(la.on(t,e),fe),off(t,e){la.off(t,e)},emit(t,e){la.emit(t,e),la.emit(He.EVENT_ALL,{event:t,data:e})},clearAllListeners(){la.all.clear()}},K={agentInfo:{},isRtcReconnecting:!1,sessionId:"",enableBrowserAlert:!1,autoStateTimer:null,autoAnswerTimer:null,logBuiltinEnabled:!1,browserAlertTime:3e3,latency:0,monitoredAgentNo:"",earSpeakAgent:"",stateObject:{state:Rt.BUSY,state_name:"忙碌"},isAgentHangup:!1},vr={isCalling:!1,direction:null,outCallIsAnswer:!1,incomingIsAnswer:!1,transferIsAnswer:!1,isMeeting:!1,isHold:!1,displayText:"",isMuted:!1,consultIsAnswer:!1,actionConfigs:[],answerDevice:1,selectOutNumber:"",customerObject:void 0,isNextState:!0,isSipConnected:!1},G=new class extends M0{updateIsCalling(t){this.setState({isCalling:t})}updateDirection(t){this.setState({direction:t})}updateOutCallIsAnswer(t){this.setState({outCallIsAnswer:t})}updateIsHold(t){var n;if(((n=K.stateObject)==null?void 0:n.state)===Rt.UNREGISTERED)return;const e=this.get("actionConfigs");if(t){const r=[...e.filter(i=>i!=="hold")];r.push("unhold"),this.updateActionConfigs(r)}else{const r=[...e.filter(i=>i!=="unhold")];r.push("hold"),this.updateActionConfigs(r)}this.setState({isHold:t})}updateDisplayText(t){this.setState({displayText:t}),fe.emit(ie.CALL_PROGRESS,t)}updateActionConfigs(t,e=!0){const{show_satisfaction:n}=K.agentInfo||{},r=this.get("answerDevice"),i=t.filter(o=>(n!==0||o!=="satisfaction"||!e)&&(r!==2&&r!==3||o!=="answer"));this.setState({actionConfigs:i}),fe.emit(He.PHONE_BAR_OPERATION,i)}updateConsultIsAnswer(t){this.setState({consultIsAnswer:t})}updateIsMuted(t){var n;if(((n=K.stateObject)==null?void 0:n.state)===Rt.UNREGISTERED)return;const e=this.get("actionConfigs");if(t){const r=[...e.filter(i=>i!=="mute")];r.push("unmute"),this.updateActionConfigs(r)}else{const r=[...e.filter(i=>i!=="unmute")];r.push("mute"),this.updateActionConfigs(r)}this.setState({isMuted:t})}updateIncomingIsAnswer(t){this.setState({incomingIsAnswer:t})}updateAnswerDevice(t){this.setState({answerDevice:t}),fe.emit(He.UPDATE_ANSWER_DEVICE,t)}updateIsMeeting(t){this.setState({isMeeting:t})}updateTransferIsAnswer(t){this.setState({transferIsAnswer:t})}updateSelectOutNumber(t){fe.emit(He.SELECT_EXTERNAL_NUMBER,t),this.setState({selectOutNumber:t})}updateCustomerInfo(t){const e=this.get("displayText");if(t&&e){const{contact_count:n,customer_name:r,phone:i,city:o,province:a,is_vip:s,in_contact_count:A,trace_id:c,contact_count_month:u,in_contact_count_month:d}=t;fe.emit(ie.CUSTOMER_INFO,{customer_name:r||"未知客户",phone:i,city:o||"未知",province:a||"未知",contact_count:n||0,in_contact_count:A||0,is_vip:s,trace_id:c,contact_count_month:u||0,in_contact_count_month:d||0})}else fe.emit(ie.CUSTOMER_INFO,void 0);this.setState({customerObject:t})}updateIsNextState(t){this.setState({isNextState:t}),t?fe.emit(He.NETWORK_ONLINE):(K.stateObject={state:Rt.OFFLINE,state_name:"离线"},this.updateActionConfigs([]),fe.emit(ie.AGENT_STATE,K.stateObject),fe.emit(He.NETWORK_OFFLINE))}updateIsSipConnected(t){this.setState({isSipConnected:t})}reset(){this.updateAnswerDevice(1),this.updateIsCalling(vr.isCalling),this.updateDirection(vr.direction),this.updateOutCallIsAnswer(vr.outCallIsAnswer),this.updateIsHold(vr.isHold),this.updateDisplayText(vr.displayText),this.updateActionConfigs(vr.actionConfigs),this.updateConsultIsAnswer(vr.consultIsAnswer),this.updateIsMuted(vr.isMuted),this.updateIncomingIsAnswer(vr.incomingIsAnswer),this.updateIsMeeting(vr.isMeeting),this.updateTransferIsAnswer(vr.transferIsAnswer),this.updateCustomerInfo(void 0)}getCallInfo(){return this.getState()}get(t){return this.getState()[t]}}(vr),T0=new class extends M0{updateRttObject(t){this.setState({rttObject:t}),fe.emit(He.WEBSITE_DELAY,t)}}({rttObject:{rtt:null,jitter:null,packetsLost:null,packetsReceived:null,packetsSent:null,sendBitrate:null,recvBitrate:null,codec:null}});let kg=class extends Error{constructor(n,r,i){const o=`${n.status||n.status===0?n.status:""} ${n.statusText||""}`.trim();super(`Request failed with ${o?`status code ${o}`:"an unknown error"}: ${r.method} ${r.url}`);qr(this,"response");qr(this,"request");qr(this,"options");this.name="HTTPError",this.response=n,this.request=r,this.options=i}};class Pg extends Error{constructor(n){super(`Request timed out: ${n.method} ${n.url}`);qr(this,"request");this.name="TimeoutError",this.request=n}}const Qg=(()=>{let t=!1,e=!1;const n=typeof globalThis.ReadableStream=="function",r=typeof globalThis.Request=="function";if(n&&r)try{e=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return t=!0,"half"}}).headers.has("Content-Type")}catch(i){if(i instanceof Error&&i.message==="unsupported BodyInit type")return!1;throw i}return t&&!e})(),vw=typeof globalThis.AbortController=="function",Cw=typeof globalThis.AbortSignal=="function"&&typeof globalThis.AbortSignal.any=="function",yw=typeof globalThis.ReadableStream=="function",Ew=typeof globalThis.FormData=="function",N0=["get","post","put","patch","head","delete"],bw={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},jg=2147483647,Sw=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,D0=Symbol("stop"),ww={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0},Iw={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,dispatcher:!0,duplex:!0,priority:!0},xw=(t,e)=>{const n=(i=>{if(!i)return 0;if(i instanceof FormData){let o=0;for(const[a,s]of i)o+=Sw,o+=new TextEncoder().encode(`Content-Disposition: form-data; name="${a}"`).length,o+=typeof s=="string"?new TextEncoder().encode(s).length:s.size;return o}if(i instanceof Blob)return i.size;if(i instanceof ArrayBuffer)return i.byteLength;if(typeof i=="string")return new TextEncoder().encode(i).length;if(i instanceof URLSearchParams)return new TextEncoder().encode(i.toString()).length;if("byteLength"in i)return i.byteLength;if(typeof i=="object"&&i!==null)try{const o=JSON.stringify(i);return new TextEncoder().encode(o).length}catch{return 0}return 0})(t.body);let r=0;return new Request(t,{duplex:"half",body:new ReadableStream({async start(i){const o=t.body instanceof ReadableStream?t.body.getReader():new Response("").body.getReader();await async function a(){const{done:s,value:A}=await o.read();if(s)return e&&e({percent:1,transferredBytes:r,totalBytes:Math.max(n,r)},new Uint8Array),void i.close();r+=A.byteLength;let c=n===0?0:r/n;(n<r||c===1)&&(c=.99),e&&e({percent:Number(c.toFixed(2)),transferredBytes:r,totalBytes:n},A),i.enqueue(A),await a()}()}})})},pa=t=>t!==null&&typeof t=="object",xs=(...t)=>{for(const e of t)if((!pa(e)||Array.isArray(e))&&e!==void 0)throw new TypeError("The `options` argument must be an object");return Zd({},...t)},B0=(t={},e={})=>{const n=new globalThis.Headers(t),r=e instanceof globalThis.Headers,i=new globalThis.Headers(e);for(const[o,a]of i.entries())r&&a==="undefined"||a===void 0?n.delete(o):n.set(o,a);return n};function Rs(t,e,n){return Object.hasOwn(e,n)&&e[n]===void 0?[]:Zd(t[n]??[],e[n]??[])}const F0=(t={},e={})=>({beforeRequest:Rs(t,e,"beforeRequest"),beforeRetry:Rs(t,e,"beforeRetry"),afterResponse:Rs(t,e,"afterResponse"),beforeError:Rs(t,e,"beforeError")}),Zd=(...t)=>{let e={},n={},r={};for(const i of t)if(Array.isArray(i))Array.isArray(e)||(e=[]),e=[...e,...i];else if(pa(i)){for(let[o,a]of Object.entries(i))pa(a)&&o in e&&(a=Zd(e[o],a)),e={...e,[o]:a};pa(i.hooks)&&(r=F0(r,i.hooks),e.hooks=r),pa(i.headers)&&(n=B0(n,i.headers),e.headers=n)}return e},Rw=t=>N0.includes(t)?t.toUpperCase():t,Lg={limit:2,methods:["get","put","head","delete","options","trace"],statusCodes:[408,413,429,500,502,503,504],afterStatusCodes:[413,429,503],maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:t=>.3*2**(t-1)*1e3},Ow=(t={})=>{if(typeof t=="number")return{...Lg,limit:t};if(t.methods&&!Array.isArray(t.methods))throw new Error("retry.methods must be an array");if(t.statusCodes&&!Array.isArray(t.statusCodes))throw new Error("retry.statusCodes must be an array");return{...Lg,...t}};class fA{constructor(e,n={}){qr(this,"request");qr(this,"abortController");qr(this,"_retryCount",0);qr(this,"_input");qr(this,"_options");var r,i;if(this._input=e,this._options={...n,headers:B0(this._input.headers,n.headers),hooks:F0({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},n.hooks),method:Rw(n.method??this._input.method??"GET"),prefixUrl:String(n.prefixUrl||""),retry:Ow(n.retry),throwHttpErrors:n.throwHttpErrors!==!1,timeout:n.timeout??1e4,fetch:n.fetch??globalThis.fetch.bind(globalThis)},typeof this._input!="string"&&!(this._input instanceof URL||this._input instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(this._options.prefixUrl&&typeof this._input=="string"){if(this._input.startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");this._options.prefixUrl.endsWith("/")||(this._options.prefixUrl+="/"),this._input=this._options.prefixUrl+this._input}if(vw&&Cw){const o=this._options.signal??this._input.signal;this.abortController=new globalThis.AbortController,this._options.signal=o?AbortSignal.any([o,this.abortController.signal]):this.abortController.signal}if(Qg&&(this._options.duplex="half"),this._options.json!==void 0&&(this._options.body=((i=(r=this._options).stringifyJson)==null?void 0:i.call(r,this._options.json))??JSON.stringify(this._options.json),this._options.headers.set("content-type",this._options.headers.get("content-type")??"application/json")),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){const o="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,o);!(Ew&&this._options.body instanceof globalThis.FormData||this._options.body instanceof URLSearchParams)||this._options.headers&&this._options.headers["content-type"]||this.request.headers.delete("content-type"),this.request=new globalThis.Request(new globalThis.Request(a,{...this.request}),this._options)}if(this._options.onUploadProgress){if(typeof this._options.onUploadProgress!="function")throw new TypeError("The `onUploadProgress` option must be a function");if(!Qg)throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request.body&&(this.request=xw(this.request,this._options.onUploadProgress))}}static create(e,n){const r=new fA(e,n),i=async()=>{if(typeof r._options.timeout=="number"&&r._options.timeout>jg)throw new RangeError("The `timeout` option cannot be greater than 2147483647");await Promise.resolve();let a=await r._fetch();for(const s of r._options.hooks.afterResponse){const A=await s(r.request,r._options,r._decorateResponse(a.clone()));A instanceof globalThis.Response&&(a=A)}if(r._decorateResponse(a),!a.ok&&r._options.throwHttpErrors){let s=new kg(a,r.request,r._options);for(const A of r._options.hooks.beforeError)s=await A(s);throw s}if(r._options.onDownloadProgress){if(typeof r._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!yw)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return((s,A)=>{const c=Number(s.headers.get("content-length"))||0;let u=0;return s.status===204?(A&&A({percent:1,totalBytes:c,transferredBytes:u},new Uint8Array),new Response(null,{status:s.status,statusText:s.statusText,headers:s.headers})):new Response(new ReadableStream({async start(d){const f=s.body.getReader();A&&A({percent:0,transferredBytes:0,totalBytes:c},new Uint8Array),await async function p(){const{done:v,value:C}=await f.read();v?d.close():(A&&(u+=C.byteLength,A({percent:c===0?0:u/c,transferredBytes:u,totalBytes:c},C)),d.enqueue(C),await p())}()}}),{status:s.status,statusText:s.statusText,headers:s.headers})})(a.clone(),r._options.onDownloadProgress)}return a},o=(r._options.retry.methods.includes(r.request.method.toLowerCase())?r._retry(i):i()).finally(async()=>{var a;r.request.bodyUsed||await((a=r.request.body)==null?void 0:a.cancel())});for(const[a,s]of Object.entries(bw))o[a]=async()=>{r.request.headers.set("accept",r.request.headers.get("accept")||s);const A=await o;if(a==="json"){if(A.status===204||(await A.clone().arrayBuffer()).byteLength===0)return"";if(n.parseJson)return n.parseJson(await A.text())}return A[a]()};return o}_calculateRetryDelay(e){if(this._retryCount++,this._retryCount>this._options.retry.limit||e instanceof Pg)throw e;if(e instanceof kg){if(!this._options.retry.statusCodes.includes(e.response.status))throw e;const r=e.response.headers.get("Retry-After")??e.response.headers.get("RateLimit-Reset")??e.response.headers.get("X-RateLimit-Reset")??e.response.headers.get("X-Rate-Limit-Reset");if(r&&this._options.retry.afterStatusCodes.includes(e.response.status)){let i=1e3*Number(r);Number.isNaN(i)?i=Date.parse(r)-Date.now():i>=Date.parse("2024-01-01")&&(i-=Date.now());const o=this._options.retry.maxRetryAfter??i;return i<o?i:o}if(e.response.status===413)throw e}const n=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,n)}_decorateResponse(e){return this._options.parseJson&&(e.json=async()=>this._options.parseJson(await e.text())),e}async _retry(e){try{return await e()}catch(n){const r=Math.min(this._calculateRetryDelay(n),jg);if(this._retryCount<1)throw n;await async function(i,{signal:o}){return new Promise((a,s)=>{function A(){clearTimeout(c),s(o.reason)}o&&(o.throwIfAborted(),o.addEventListener("abort",A,{once:!0}));const c=setTimeout(()=>{o==null||o.removeEventListener("abort",A),a()},i)})}(r,{signal:this._options.signal});for(const i of this._options.hooks.beforeRetry)if(await i({request:this.request,options:this._options,error:n,retryCount:this._retryCount})===D0)return;return this._retry(e)}}async _fetch(){for(const r of this._options.hooks.beforeRequest){const i=await r(this.request,this._options);if(i instanceof Request){this.request=i;break}if(i instanceof Response)return i}const e=((r,i)=>{const o={};for(const a in i)a in Iw||a in ww||a in r||(o[a]=i[a]);return o})(this.request,this._options),n=this.request;return this.request=n.clone(),this._options.timeout===!1?this._options.fetch(n,e):async function(r,i,o,a){return new Promise((s,A)=>{const c=setTimeout(()=>{o&&o.abort(),A(new Pg(r))},a.timeout);a.fetch(r,i).then(s).catch(A).then(()=>{clearTimeout(c)})})}(n,e,this.abortController,this._options)}}/*! MIT License © Sindre Sorhus */const ru=t=>{const e=(n,r)=>fA.create(n,xs(t,r));for(const n of N0)e[n]=(r,i)=>fA.create(r,xs(t,i,{method:n}));return e.create=n=>ru(xs(n)),e.extend=n=>(typeof n=="function"&&(n=n(t??{})),ru(xs(t,n))),e.stop=D0,e};var Vc,Mw=ru(),Tw=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},k0={exports:{}};/**
155
+ `))}startSendingKeepAlives(){this.configuration.keepAliveInterval&&!this.keepAliveInterval&&(this.keepAliveInterval=setInterval(()=>{this.sendKeepAlive(),this.startSendingKeepAlives()},(e=>{const n=.8*e;return 1e3*(Math.random()*(e-n)+n)})(this.configuration.keepAliveInterval)))}stopSendingKeepAlives(){this.keepAliveInterval&&clearInterval(this.keepAliveInterval),this.keepAliveDebounceTimeout&&clearTimeout(this.keepAliveDebounceTimeout),this.keepAliveInterval=void 0,this.keepAliveDebounceTimeout=void 0}};R0.defaultOptions={server:"",connectionTimeout:5,keepAliveInterval:0,keepAliveDebounce:10,traceSip:!0};let Fg=class Js{constructor(e={}){if(this._publishers={},this._registerers={},this._sessions={},this._subscriptions={},this._state=Dn.Stopped,this._stateEventEmitter=new Pa,this.delegate=e.delegate,this.options=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},Js.defaultOptions()),{sipjsId:zi(5)}),{uri:new Ni("sip","anonymous."+zi(6),"anonymous.invalid")}),{viaHost:zi(12)+".invalid"}),Js.stripUndefinedProperties(e)),this.options.hackIpInContact)if(typeof this.options.hackIpInContact=="boolean"&&this.options.hackIpInContact){const i=Math.floor(Math.random()*254+1);this.options.viaHost="192.0.2."+i}else this.options.hackIpInContact&&(this.options.viaHost=this.options.hackIpInContact);switch(this.loggerFactory=new $S,this.logger=this.loggerFactory.getLogger("sip.UserAgent"),this.loggerFactory.builtinEnabled=this.options.logBuiltinEnabled,this.loggerFactory.connector=this.options.logConnector,this.options.logLevel){case"error":this.loggerFactory.level=On.error;break;case"warn":this.loggerFactory.level=On.warn;break;case"log":this.loggerFactory.level=On.log;break;case"debug":this.loggerFactory.level=On.debug}if(this.options.logConfiguration&&(this.logger.log("Configuration:"),Object.keys(this.options).forEach(n=>{const r=this.options[n];switch(n){case"uri":case"sessionDescriptionHandlerFactory":this.logger.log("· "+n+": "+r);break;case"authorizationPassword":this.logger.log("· "+n+": NOT SHOWN");break;case"transportConstructor":this.logger.log("· "+n+": "+r.name);break;default:this.logger.log("· "+n+": "+JSON.stringify(r))}})),this.options.transportOptions){const n=this.options.transportOptions,r=n.maxReconnectionAttempts,i=n.reconnectionTimeout;r!==void 0&&this.logger.warn('The transport option "maxReconnectionAttempts" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.'),i!==void 0&&this.logger.warn('The transport option "reconnectionTimeout" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.'),e.reconnectionDelay===void 0&&i!==void 0&&(this.options.reconnectionDelay=i),e.reconnectionAttempts===void 0&&r!==void 0&&(this.options.reconnectionAttempts=r)}if(e.reconnectionDelay!==void 0&&this.logger.warn('The user agent option "reconnectionDelay" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.'),e.reconnectionAttempts!==void 0&&this.logger.warn('The user agent option "reconnectionAttempts" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.'),this._transport=new this.options.transportConstructor(this.getLogger("sip.Transport"),this.options.transportOptions),this.initTransportCallbacks(),this._contact=this.initContact(),this._instanceId=this.options.instanceId?this.options.instanceId:Js.newUUID(),En.parse(this._instanceId,"uuid")===-1)throw new Error("Invalid instanceId.");this._userAgentCore=this.initCore()}static makeURI(e){return En.URIParse(e)}static defaultOptions(){return{allowLegacyNotifications:!1,authorizationHa1:"",authorizationPassword:"",authorizationUsername:"",delegate:{},contactName:"",contactParams:{transport:"ws"},displayName:"",forceRport:!1,gracefulShutdown:!0,hackAllowUnregisteredOptionTags:!1,hackIpInContact:!1,hackViaTcp:!1,instanceId:"",instanceIdAlwaysAdded:!1,logBuiltinEnabled:!0,logConfiguration:!0,logConnector:()=>{},logLevel:"log",noAnswerTimeout:60,preloadedRouteSet:[],reconnectionAttempts:0,reconnectionDelay:4,sendInitialProvisionalResponse:!0,sessionDescriptionHandlerFactory:mw(),sessionDescriptionHandlerFactoryOptions:{},sipExtension100rel:Nr.Unsupported,sipExtensionReplaces:Nr.Unsupported,sipExtensionExtraSupported:[],sipjsId:"",transportConstructor:R0,transportOptions:{},uri:new Ni("sip","anonymous","anonymous.invalid"),userAgentString:"SIP.js/0.21.1",viaHost:""}}static newUUID(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const n=Math.floor(16*Math.random());return(e==="x"?n:n%4+8).toString(16)})}static stripUndefinedProperties(e){return Object.keys(e).reduce((n,r)=>(e[r]!==void 0&&(n[r]=e[r]),n),{})}get configuration(){return this.options}get contact(){return this._contact}get instanceId(){return this._instanceId}get state(){return this._state}get stateChange(){return this._stateEventEmitter}get transport(){return this._transport}get userAgentCore(){return this._userAgentCore}getLogger(e,n){return this.loggerFactory.getLogger(e,n)}getLoggerFactory(){return this.loggerFactory}isConnected(){return this.transport.isConnected()}reconnect(){return this.state===Dn.Stopped?Promise.reject(new Error("User agent stopped.")):Promise.resolve().then(()=>this.transport.connect())}start(){return this.state===Dn.Started?(this.logger.warn("User agent already started"),Promise.resolve()):(this.logger.log(`Starting ${this.configuration.uri}`),this.transitionState(Dn.Started),this.transport.connect())}async stop(){if(this.state===Dn.Stopped)return this.logger.warn("User agent already stopped"),Promise.resolve();if(this.logger.log(`Stopping ${this.configuration.uri}`),!this.options.gracefulShutdown)return this.logger.log("Dispose of transport"),this.transport.dispose().catch(s=>{throw this.logger.error(s.message),s}),this.logger.log("Dispose of core"),this.userAgentCore.dispose(),this._publishers={},this._registerers={},this._sessions={},this._subscriptions={},this.transitionState(Dn.Stopped),Promise.resolve();const e=Object.assign({},this._publishers),n=Object.assign({},this._registerers),r=Object.assign({},this._sessions),i=Object.assign({},this._subscriptions),o=this.transport,a=this.userAgentCore;this.logger.log("Dispose of registerers");for(const s in n)n[s]&&await n[s].dispose().catch(A=>{throw this.logger.error(A.message),delete this._registerers[s],A});this.logger.log("Dispose of sessions");for(const s in r)r[s]&&await r[s].dispose().catch(A=>{throw this.logger.error(A.message),delete this._sessions[s],A});this.logger.log("Dispose of subscriptions");for(const s in i)i[s]&&await i[s].dispose().catch(A=>{throw this.logger.error(A.message),delete this._subscriptions[s],A});this.logger.log("Dispose of publishers");for(const s in e)e[s]&&await e[s].dispose().catch(A=>{throw this.logger.error(A.message),delete this._publishers[s],A});this.logger.log("Dispose of transport"),await o.dispose().catch(s=>{throw this.logger.error(s.message),s}),this.logger.log("Dispose of core"),a.dispose(),this.transitionState(Dn.Stopped)}_makeInviter(e,n){return new v0(this,e,n)}attemptReconnection(e=1){const n=this.options.reconnectionAttempts,r=this.options.reconnectionDelay;e>n?this.logger.log("Maximum reconnection attempts reached"):(this.logger.log(`Reconnection attempt ${e} of ${n} - trying`),setTimeout(()=>{this.reconnect().then(()=>{this.logger.log(`Reconnection attempt ${e} of ${n} - succeeded`)}).catch(i=>{this.logger.error(i.message),this.logger.log(`Reconnection attempt ${e} of ${n} - failed`),this.attemptReconnection(++e)})},e===1?0:1e3*r))}initContact(){const e=this.options.contactName!==""?this.options.contactName:zi(8),n=this.options.contactParams;return{pubGruu:void 0,tempGruu:void 0,uri:new Ni("sip",e,this.options.viaHost,void 0,n),toString:(r={})=>{const i=r.anonymous||!1,o=r.outbound||!1,a=r.register||!1;let s="<";return s+=i?this.contact.tempGruu||`sip:anonymous@anonymous.invalid;transport=${n.transport?n.transport:"ws"}`:a?this.contact.uri:this.contact.pubGruu||this.contact.uri,o&&(s+=";ob"),s+=">",this.options.instanceIdAlwaysAdded&&(s+=';+sip.instance="<urn:uuid:'+this._instanceId+'>"'),s}}}initCore(){let e=[];e.push("outbound"),this.options.sipExtension100rel===Nr.Supported&&e.push("100rel"),this.options.sipExtensionReplaces===Nr.Supported&&e.push("replaces"),this.options.sipExtensionExtraSupported&&e.push(...this.options.sipExtensionExtraSupported),this.options.hackAllowUnregisteredOptionTags||(e=e.filter(o=>JS[o])),e=Array.from(new Set(e));const n=e.slice();(this.contact.pubGruu||this.contact.tempGruu)&&n.push("gruu");const r={aor:this.options.uri,contact:this.contact,displayName:this.options.displayName,loggerFactory:this.loggerFactory,hackViaTcp:this.options.hackViaTcp,routeSet:this.options.preloadedRouteSet,supportedOptionTags:e,supportedOptionTagsResponse:n,sipjsId:this.options.sipjsId,userAgentHeaderFieldValue:this.options.userAgentString,viaForceRport:this.options.forceRport,viaHost:this.options.viaHost,authenticationFactory:()=>{const o=this.options.authorizationUsername?this.options.authorizationUsername:this.options.uri.user,a=this.options.authorizationPassword?this.options.authorizationPassword:void 0,s=this.options.authorizationHa1?this.options.authorizationHa1:void 0;return new _S(this.getLoggerFactory(),s,o,a)},transportAccessor:()=>this.transport},i={onInvite:o=>{var a;const s=new eu(this,o);if(o.delegate={onCancel:A=>{s._onCancel(A)},onTransportError:A=>{this.logger.error("A transport error has occurred while handling an incoming INVITE request.")}},o.trying(),this.options.sipExtensionReplaces!==Nr.Unsupported){const A=o.message.parseHeader("replaces");if(A){const c=A.call_id;if(typeof c!="string")throw new Error("Type of call id is not string");const u=A.replaces_to_tag;if(typeof u!="string")throw new Error("Type of to tag is not string");const d=A.replaces_from_tag;if(typeof d!="string")throw new Error("type of from tag is not string");const f=c+u+d,p=this.userAgentCore.dialogs.get(f);if(!p)return void s.reject({statusCode:481});if(!p.early&&A.early_only===!0)return void s.reject({statusCode:486});const v=this._sessions[c+d]||this._sessions[c+u]||void 0;if(!v)throw new Error("Session does not exist.");s._replacee=v}}if(!((a=this.delegate)===null||a===void 0)&&a.onInvite)return s.autoSendAnInitialProvisionalResponse?void s.progress().then(()=>{var A;if(((A=this.delegate)===null||A===void 0?void 0:A.onInvite)===void 0)throw new Error("onInvite undefined.");this.delegate.onInvite(s)}):void this.delegate.onInvite(s);s.reject({statusCode:486})},onMessage:o=>{if(this.delegate&&this.delegate.onMessage){const a=new p0(o);this.delegate.onMessage(a)}else o.accept()},onNotify:o=>{if(this.delegate&&this.delegate.onNotify){const a=new $l(o);this.delegate.onNotify(a)}else this.options.allowLegacyNotifications?o.accept():o.reject({statusCode:481})},onRefer:o=>{this.logger.warn("Received an out of dialog REFER request"),this.delegate&&this.delegate.onReferRequest?this.delegate.onReferRequest(o):o.reject({statusCode:405})},onRegister:o=>{this.logger.warn("Received an out of dialog REGISTER request"),this.delegate&&this.delegate.onRegisterRequest?this.delegate.onRegisterRequest(o):o.reject({statusCode:405})},onSubscribe:o=>{this.logger.warn("Received an out of dialog SUBSCRIBE request"),this.delegate&&this.delegate.onSubscribeRequest?this.delegate.onSubscribeRequest(o):o.reject({statusCode:405})}};return new pw(r,i)}initTransportCallbacks(){this.transport.onConnect=()=>this.onTransportConnect(),this.transport.onDisconnect=e=>this.onTransportDisconnect(e),this.transport.onMessage=e=>this.onTransportMessage(e)}onTransportConnect(){this.state!==Dn.Stopped&&this.delegate&&this.delegate.onConnect&&this.delegate.onConnect()}onTransportDisconnect(e){this.state!==Dn.Stopped&&(this.delegate&&this.delegate.onDisconnect&&this.delegate.onDisconnect(e),e&&this.options.reconnectionAttempts>0&&this.attemptReconnection())}onTransportMessage(e){const n=Ws.parseMessage(e,this.getLogger("sip.Parser"));if(!n)return void this.logger.warn("Failed to parse incoming message. Dropping.");if(this.state===Dn.Stopped&&n instanceof Bo)return void this.logger.warn(`Received ${n.method} request while stopped. Dropping.`);const r=()=>{const i=["from","to","call_id","cseq","via"];for(const o of i)if(!n.hasHeader(o))return this.logger.warn(`Missing mandatory header field : ${o}.`),!1;return!0};if(n instanceof Bo){if(!r())return void this.logger.warn("Request missing mandatory header field. Dropping.");if(!n.toTag&&n.callId.substr(0,5)===this.options.sipjsId)return void this.userAgentCore.replyStateless(n,{statusCode:482});const i=Qa(n.body),o=n.getHeader("content-length");if(o&&i<Number(o))return void this.userAgentCore.replyStateless(n,{statusCode:400})}if(n instanceof Fi){if(!r())return void this.logger.warn("Response missing mandatory header field. Dropping.");if(n.getHeaders("via").length>1)return void this.logger.warn("More than one Via header field present in the response. Dropping.");if(n.via.host!==this.options.viaHost||n.via.port!==void 0)return void this.logger.warn("Via sent-by in the response does not match UA Via host value. Dropping.");const i=Qa(n.body),o=n.getHeader("content-length");if(o&&i<Number(o))return void this.logger.warn("Message body length is lower than the value in Content-Length header field. Dropping.")}if(n instanceof Bo)this.userAgentCore.receiveIncomingRequestFromTransport(n);else{if(!(n instanceof Fi))throw new Error("Invalid message type.");this.userAgentCore.receiveIncomingResponseFromTransport(n)}}transitionState(e,n){const r=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case Dn.Started:e!==Dn.Stopped&&r();break;case Dn.Stopped:e!==Dn.Started&&r();break;default:throw new Error("Unknown state.")}this.logger.log(`Transitioned from ${this._state} to ${e}`),this._state=e,this._stateEventEmitter.emit(this._state)}},M0=class{constructor(e){this.listeners=[],this.keyListeners={},this.data={...e},this.proxy=new Proxy(this.data,{set:(n,r,i)=>(n[r]!==i&&(n[r]=i,this.notify(),this.notifyKey(r,i)),!0)})}getState(){return this.proxy}setState(e,n=!1){let r=!1;for(const i in e)if(Object.prototype.hasOwnProperty.call(e,i)){const o=this.data[i],a=e[i];(n||o!==a)&&(this.data[i]=a,r=!0,this.notifyKey(i,a))}(r||n)&&this.notify()}subscribe(e){return this.listeners.push(e),()=>{this.listeners=this.listeners.filter(n=>n!==e)}}subscribeKey(e,n){return this.keyListeners[e]||(this.keyListeners[e]=[]),this.keyListeners[e].push(n),()=>{this.keyListeners[e]=this.keyListeners[e].filter(r=>r!==n)}}notify(){const e=this.getState();for(const n of this.listeners)n(e)}notifyKey(e,n){const r=this.keyListeners[e];r&&r.forEach(i=>i(n))}};var Rt,xn,it,Ar,ie,He,Kt;(function(t){t[t.IDLE=1]="IDLE",t[t.BUSY=2]="BUSY",t[t.RINGING=3]="RINGING",t[t.OFFLINE=0]="OFFLINE",t[t.UNREGISTERED=4]="UNREGISTERED"})(Rt||(Rt={})),function(t){t.OUTGOING="outgoing",t.INCOMING="incoming",t.CONSULT="consult",t.MEETING="meeting",t.TRANSFER="transfer",t.PREDICT_OUT_CALL="predict_out_call"}(xn||(xn={})),function(t){t[t.OUT_CALL=100]="OUT_CALL",t[t.AGENT_STATE=101]="AGENT_STATE",t[t.OUT_CALL_INCOMING_CALL=102]="OUT_CALL_INCOMING_CALL",t[t.OUT_CALL_RINGING=103]="OUT_CALL_RINGING",t[t.OUT_CALL_ANSWER=104]="OUT_CALL_ANSWER",t[t.CALL_HOLD=105]="CALL_HOLD",t[t.CALL_UNHOLD=106]="CALL_UNHOLD",t[t.OUT_CALL_END=107]="OUT_CALL_END",t[t.CONSULT_REQUEST=108]="CONSULT_REQUEST",t[t.CONSULT_RINGING=109]="CONSULT_RINGING",t[t.CONSULT_ANSWER=110]="CONSULT_ANSWER",t[t.CONSULT_FAIL=111]="CONSULT_FAIL",t[t.MUTE=112]="MUTE",t[t.UNMUTE=113]="UNMUTE",t[t.CONSULT_CALL_IN=114]="CONSULT_CALL_IN",t[t.CONSULT_CALL_IN_SUCCESS=115]="CONSULT_CALL_IN_SUCCESS",t[t.CONSULT_RETURN_CALL=125]="CONSULT_RETURN_CALL",t[t.CONSULT_RETURN_CALL_SUCCESS=126]="CONSULT_RETURN_CALL_SUCCESS",t[t.CONSULT_TRANSFER=116]="CONSULT_TRANSFER",t[t.CONSULT_TRANSFER_FAILED=118]="CONSULT_TRANSFER_FAILED",t[t.CONSULT_TRANSFER_OFF_HOOK=117]="CONSULT_TRANSFER_OFF_HOOK",t[t.INCOMING_CALL=119]="INCOMING_CALL",t[t.INCOMING_CALL_OFF_HOOK=120]="INCOMING_CALL_OFF_HOOK",t[t.INCOMING_CALL_END=121]="INCOMING_CALL_END",t[t.SATISFACTION_EVALUATION=122]="SATISFACTION_EVALUATION",t[t.CONSULT_THREE_WAY=123]="CONSULT_THREE_WAY",t[t.CONSULT_THREE_WAY_RESULT=124]="CONSULT_THREE_WAY_RESULT",t[t.TRANSFER=127]="TRANSFER",t[t.TRANSFER_FAILED=128]="TRANSFER_FAILED",t[t.TRANSFER_INCOMING_CALL=129]="TRANSFER_INCOMING_CALL",t[t.TRANSFER_OFF_HOOK=130]="TRANSFER_OFF_HOOK",t[t.AGENT_HANGUP=131]="AGENT_HANGUP",t[t.KICK_OFFLINE=132]="KICK_OFFLINE",t[t.CONTINUOUS_NOT_ANSWER=133]="CONTINUOUS_NOT_ANSWER",t[t.PREVIEW_OUT_CALL=134]="PREVIEW_OUT_CALL",t[t.SIGN_OUT=135]="SIGN_OUT",t[t.SIGN_IN_SWITCH_DEVICE=136]="SIGN_IN_SWITCH_DEVICE",t[t.LISTEN_CALL_FAILED=137]="LISTEN_CALL_FAILED",t[t.LISTEN_INCOMING_CALL=138]="LISTEN_INCOMING_CALL",t[t.LISTEN_INCOMING_CALL_OFF_HOOK=139]="LISTEN_INCOMING_CALL_OFF_HOOK",t[t.EAR_SPEECH=140]="EAR_SPEECH",t[t.STOP_EAR_SPEECH=141]="STOP_EAR_SPEECH",t[t.CALL_FORCE_INSERT=142]="CALL_FORCE_INSERT",t[t.INTERNAL_CALL_START_CONSULT=145]="INTERNAL_CALL_START_CONSULT",t[t.INTERNAL_CALL_END_CONSULT=146]="INTERNAL_CALL_END_CONSULT",t[t.CALL_SIP_INCOMING_CALL=147]="CALL_SIP_INCOMING_CALL"}(it||(it={})),function(t){t.WEB_RTC_CONNECTING="connecting",t.WEB_RTC_CONNECTED="connected",t.WEB_RTC_DISCONNECTING="disconnecting",t.WEB_RTC_DISCONNECTED="disconnected",t.WEB_RTC_REGISTERED="registered",t.WEB_RTC_UNREGISTERED="unregistered",t.WEB_RTC_TERMINATED="terminated",t.WEB_RTC_REGISTER_FAILED="register_failed",t.WEB_RTC_ANSWER_FAILED="answer_failed",t.WEB_RTC_SEND_DTMF="send_dtmf"}(Ar||(Ar={})),function(t){t.CUSTOMER_INFO="customer_info",t.CALL_PROGRESS="call_progress",t.OUT_INCOMING_CALL="out_call_incoming_call",t.INTERNAL_OUT_INCOMING_CALL="internal_out_incoming_call",t.PREVIEW_OUT_INCOMING_CALL="preview_out_incoming_call",t.OUT_SUCCESS="out_call_success",t.OUT_FAILED="out_call_failed",t.OUT_RINGING="out_call_ringing",t.OUT_OFF_ANSWER="out_call_answer",t.INTERNAL_OUT_OFF_ANSWER="internal_out_call_answer",t.HOLD_SUCCESS="hold_success",t.HOLD_FAILED="hold_failed",t.UNHOLD_SUCCESS="unhold_success",t.UNHOLD_FAILED="unhold_failed",t.OUT_HANGUP="out_call_hangup",t.CONSULT_RINGING="consult_ringing",t.CONSULT_OFF_HOOK="consult_off_hook",t.CONSULT_FAILED="consult_failed",t.CONSULT_INCOMING="consult_incoming",t.CONSULT_CALL_IN_SUCCESS="consult_call_in_success",t.CONSULT_RETURN_CALL_SUCCESS="consult_return_call_success",t.OTHER_SIDE_CONSULT_HANGUP="other_side_consult_hangup",t.OUR_SIDE_CONSULT_HANGUP="our_side_consult_hangup",t.AGENT_STATE="agent_state",t.MUTE_SUCCESS="mute_success",t.MUTE_FAILED="mute_failed",t.UNMUTE_SUCCESS="unmute_success",t.UNMUTE_FAILED="unmute_failed",t.CONSULT_TRANSFER_SUCCESS="consult_transfer_success",t.CONSULT_TRANSFER_FAILED="consult_transfer_failed",t.CONSULT_TRANSFER_OFF_HOOK="consult_transfer_off_hook",t.INCOMING_CALL="incoming_call",t.INCOMING_CALL_IN="incoming_call_in",t.PREDICT_INCOMING_CALL="predict_incoming_call",t.DUAL_CALL_INCOMING_CALL="dual_call_incoming_call",t.INCOMING_CALL_OFF_HOOK="incoming_call_off_hook",t.INCOMING_CALL_IN_OFF_HOOK="incoming_call_in_off_hook",t.INCOMING_CALL_END="incoming_call_end",t.SATISFACTION_EVALUATION_SUCCESS="satisfaction_evaluation_success",t.SATISFACTION_EVALUATION_FAILED="satisfaction_evaluation_failed",t.CONSULT_THREE_WAY_SUCCESS="consult_three_way_success",t.CONSULT_THREE_WAY_FAILED="consult_three_way_failed",t.THREE_WAY_OUR_SIDE_HANGUP="three_way_our_side_hangup",t.TRANSFER_FAILED="transfer_failed",t.TRANSFER_PROGRESS="transfer_progress",t.TRANSFER_INCOMING_CALL="transfer_incoming_call",t.TRANSFER_OFF_HOOK="transfer_off_hook",t.TRANSFER_END="transfer_end",t.REJECT="reject",t.LISTEN_CALL_FAILED="listen_call_failed",t.LISTEN_INCOMING_CALL="listen_incoming_call",t.LISTEN_INCOMING_CALL_OFF_HOOK="listen_incoming_call_off_hook",t.LISTEN_HANGUP="listen_hangup",t.EAR_SPEECH_SUCCESS="ear_speech_success",t.EAR_SPEECH_BE_SUCCESS="ear_speech_be_success",t.EAR_SPEECH_FAILED="ear_speech_failed",t.STOP_EAR_SPEECH_SUCCESS="stop_ear_speech_success",t.STOP_EAR_SPEECH_FAILED="stop_ear_speech_failed",t.CALL_FORCE_INSERT_SUCCESS="call_force_insert_success",t.CALL_FORCE_INSERT_SUCCESS_LISTENER="call_force_insert_success_listener",t.CALL_FORCE_INSERT_FAILED="call_force_insert_failed",t.CALL_SIP_INCOMING_CALL="call_sip_incoming_call"}(ie||(ie={})),function(t){t.EVENT_ALL="event_all",t.NOTIFICATION_CLICK="notification_click",t.UPDATE_ANSWER_DEVICE="update_answer_device",t.PHONE_BAR_OPERATION="phone_bar_operation",t.AGENT_INIT_STATUS="agent_init_status",t.WEBSITE_DELAY="website_delay",t.SELECT_EXTERNAL_NUMBER="select_external_number",t.FAIL_NOTIFICATION="fail_notification",t.KICK_OFF="kick_off",t.DESTROY="destroy",t.NETWORK_OFFLINE="network_offline",t.NETWORK_ONLINE="network_online",t.SIGN_OUT="sign_out",t.SIGN_IN_SWITCH_DEVICE="sign_in_switch_device"}(He||(He={})),function(t){t.RINGING="客户振铃",t.AGENT_RINGING="振铃中",t.CALLING="通话中",t.CONSULTING="正在咨询",t.CONSULT_CALL_IN="咨询来电",t.INCOMING_CALL="客户来电",t.MEETING="会议中",t.TRANSFERRING="转接中",t.TRANSFER_INCOMING_CALL="转接来电",t.HOLDING="保持中",t.MUTING="静音中",t.LISTENING="监听来电",t.LINKING="正在链接",t.OTHER_SIDE_CONSULTING="对方正咨询"}(Kt||(Kt={}));const la={all:vi=vi||new Map,on:function(t,e){var n=vi.get(t);n?n.push(e):vi.set(t,[e])},off:function(t,e){var n=vi.get(t);n&&(e?n.splice(n.indexOf(e)>>>0,1):vi.set(t,[]))},emit:function(t,e){var n=vi.get(t);n&&n.slice().map(function(r){r(e)}),(n=vi.get("*"))&&n.slice().map(function(r){r(t,e)})}};var vi;const fe={on:(t,e)=>(la.on(t,e),fe),off(t,e){la.off(t,e)},emit(t,e){la.emit(t,e),la.emit(He.EVENT_ALL,{event:t,data:e})},clearAllListeners(){la.all.clear()}},K={agentInfo:{},isRtcReconnecting:!1,sessionId:"",enableBrowserAlert:!1,autoStateTimer:null,autoAnswerTimer:null,logBuiltinEnabled:!1,browserAlertTime:3e3,latency:0,monitoredAgentNo:"",earSpeakAgent:"",stateObject:{state:Rt.BUSY,state_name:"忙碌"},isAgentHangup:!1},vr={isCalling:!1,direction:null,outCallIsAnswer:!1,incomingIsAnswer:!1,transferIsAnswer:!1,isMeeting:!1,isHold:!1,displayText:"",isMuted:!1,consultIsAnswer:!1,actionConfigs:[],answerDevice:1,selectOutNumber:"",customerObject:void 0,isNextState:!0,isSipConnected:!1},G=new class extends M0{updateIsCalling(t){this.setState({isCalling:t})}updateDirection(t){this.setState({direction:t})}updateOutCallIsAnswer(t){this.setState({outCallIsAnswer:t})}updateIsHold(t){var n;if(((n=K.stateObject)==null?void 0:n.state)===Rt.UNREGISTERED)return;const e=this.get("actionConfigs");if(t){const r=[...e.filter(i=>i!=="hold")];r.push("unhold"),this.updateActionConfigs(r)}else{const r=[...e.filter(i=>i!=="unhold")];r.push("hold"),this.updateActionConfigs(r)}this.setState({isHold:t})}updateDisplayText(t){this.setState({displayText:t}),fe.emit(ie.CALL_PROGRESS,t)}updateActionConfigs(t,e=!0){const{show_satisfaction:n}=K.agentInfo||{},r=this.get("answerDevice"),i=t.filter(o=>(n!==0||o!=="satisfaction"||!e)&&(r!==2&&r!==3||o!=="answer"));this.setState({actionConfigs:i}),fe.emit(He.PHONE_BAR_OPERATION,i)}updateConsultIsAnswer(t){this.setState({consultIsAnswer:t})}updateIsMuted(t){var n;if(((n=K.stateObject)==null?void 0:n.state)===Rt.UNREGISTERED)return;const e=this.get("actionConfigs");if(t){const r=[...e.filter(i=>i!=="mute")];r.push("unmute"),this.updateActionConfigs(r)}else{const r=[...e.filter(i=>i!=="unmute")];r.push("mute"),this.updateActionConfigs(r)}this.setState({isMuted:t})}updateIncomingIsAnswer(t){this.setState({incomingIsAnswer:t})}updateAnswerDevice(t){this.setState({answerDevice:t}),fe.emit(He.UPDATE_ANSWER_DEVICE,t)}updateIsMeeting(t){this.setState({isMeeting:t})}updateTransferIsAnswer(t){this.setState({transferIsAnswer:t})}updateSelectOutNumber(t){fe.emit(He.SELECT_EXTERNAL_NUMBER,t),this.setState({selectOutNumber:t})}updateCustomerInfo(t){const e=this.get("displayText");if(t&&e){const{contact_count:n,customer_name:r,phone:i,city:o,province:a,is_vip:s,in_contact_count:A,trace_id:c,contact_count_month:u,in_contact_count_month:d,type:f}=t;fe.emit(ie.CUSTOMER_INFO,{customer_name:r||"未知客户",phone:i,city:o||"未知",province:a||"未知",contact_count:n||0,in_contact_count:A||0,is_vip:s,trace_id:c,contact_count_month:u||0,in_contact_count_month:d||0,type:f})}else fe.emit(ie.CUSTOMER_INFO,void 0);this.setState({customerObject:t})}updateIsNextState(t){this.setState({isNextState:t}),t?fe.emit(He.NETWORK_ONLINE):(K.stateObject={state:Rt.OFFLINE,state_name:"离线"},this.updateActionConfigs([]),fe.emit(ie.AGENT_STATE,K.stateObject),fe.emit(He.NETWORK_OFFLINE))}updateIsSipConnected(t){this.setState({isSipConnected:t})}reset(){this.updateAnswerDevice(1),this.updateIsCalling(vr.isCalling),this.updateDirection(vr.direction),this.updateOutCallIsAnswer(vr.outCallIsAnswer),this.updateIsHold(vr.isHold),this.updateDisplayText(vr.displayText),this.updateActionConfigs(vr.actionConfigs),this.updateConsultIsAnswer(vr.consultIsAnswer),this.updateIsMuted(vr.isMuted),this.updateIncomingIsAnswer(vr.incomingIsAnswer),this.updateIsMeeting(vr.isMeeting),this.updateTransferIsAnswer(vr.transferIsAnswer),this.updateCustomerInfo(void 0)}getCallInfo(){return this.getState()}get(t){return this.getState()[t]}}(vr),T0=new class extends M0{updateRttObject(t){this.setState({rttObject:t}),fe.emit(He.WEBSITE_DELAY,t)}}({rttObject:{rtt:null,jitter:null,packetsLost:null,packetsReceived:null,packetsSent:null,sendBitrate:null,recvBitrate:null,codec:null}});let kg=class extends Error{constructor(n,r,i){const o=`${n.status||n.status===0?n.status:""} ${n.statusText||""}`.trim();super(`Request failed with ${o?`status code ${o}`:"an unknown error"}: ${r.method} ${r.url}`);qr(this,"response");qr(this,"request");qr(this,"options");this.name="HTTPError",this.response=n,this.request=r,this.options=i}};class Pg extends Error{constructor(n){super(`Request timed out: ${n.method} ${n.url}`);qr(this,"request");this.name="TimeoutError",this.request=n}}const Qg=(()=>{let t=!1,e=!1;const n=typeof globalThis.ReadableStream=="function",r=typeof globalThis.Request=="function";if(n&&r)try{e=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return t=!0,"half"}}).headers.has("Content-Type")}catch(i){if(i instanceof Error&&i.message==="unsupported BodyInit type")return!1;throw i}return t&&!e})(),vw=typeof globalThis.AbortController=="function",Cw=typeof globalThis.AbortSignal=="function"&&typeof globalThis.AbortSignal.any=="function",yw=typeof globalThis.ReadableStream=="function",Ew=typeof globalThis.FormData=="function",N0=["get","post","put","patch","head","delete"],bw={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},jg=2147483647,Sw=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,D0=Symbol("stop"),ww={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0},Iw={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,dispatcher:!0,duplex:!0,priority:!0},xw=(t,e)=>{const n=(i=>{if(!i)return 0;if(i instanceof FormData){let o=0;for(const[a,s]of i)o+=Sw,o+=new TextEncoder().encode(`Content-Disposition: form-data; name="${a}"`).length,o+=typeof s=="string"?new TextEncoder().encode(s).length:s.size;return o}if(i instanceof Blob)return i.size;if(i instanceof ArrayBuffer)return i.byteLength;if(typeof i=="string")return new TextEncoder().encode(i).length;if(i instanceof URLSearchParams)return new TextEncoder().encode(i.toString()).length;if("byteLength"in i)return i.byteLength;if(typeof i=="object"&&i!==null)try{const o=JSON.stringify(i);return new TextEncoder().encode(o).length}catch{return 0}return 0})(t.body);let r=0;return new Request(t,{duplex:"half",body:new ReadableStream({async start(i){const o=t.body instanceof ReadableStream?t.body.getReader():new Response("").body.getReader();await async function a(){const{done:s,value:A}=await o.read();if(s)return e&&e({percent:1,transferredBytes:r,totalBytes:Math.max(n,r)},new Uint8Array),void i.close();r+=A.byteLength;let c=n===0?0:r/n;(n<r||c===1)&&(c=.99),e&&e({percent:Number(c.toFixed(2)),transferredBytes:r,totalBytes:n},A),i.enqueue(A),await a()}()}})})},pa=t=>t!==null&&typeof t=="object",xs=(...t)=>{for(const e of t)if((!pa(e)||Array.isArray(e))&&e!==void 0)throw new TypeError("The `options` argument must be an object");return Zd({},...t)},B0=(t={},e={})=>{const n=new globalThis.Headers(t),r=e instanceof globalThis.Headers,i=new globalThis.Headers(e);for(const[o,a]of i.entries())r&&a==="undefined"||a===void 0?n.delete(o):n.set(o,a);return n};function Rs(t,e,n){return Object.hasOwn(e,n)&&e[n]===void 0?[]:Zd(t[n]??[],e[n]??[])}const F0=(t={},e={})=>({beforeRequest:Rs(t,e,"beforeRequest"),beforeRetry:Rs(t,e,"beforeRetry"),afterResponse:Rs(t,e,"afterResponse"),beforeError:Rs(t,e,"beforeError")}),Zd=(...t)=>{let e={},n={},r={};for(const i of t)if(Array.isArray(i))Array.isArray(e)||(e=[]),e=[...e,...i];else if(pa(i)){for(let[o,a]of Object.entries(i))pa(a)&&o in e&&(a=Zd(e[o],a)),e={...e,[o]:a};pa(i.hooks)&&(r=F0(r,i.hooks),e.hooks=r),pa(i.headers)&&(n=B0(n,i.headers),e.headers=n)}return e},Rw=t=>N0.includes(t)?t.toUpperCase():t,Lg={limit:2,methods:["get","put","head","delete","options","trace"],statusCodes:[408,413,429,500,502,503,504],afterStatusCodes:[413,429,503],maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:t=>.3*2**(t-1)*1e3},Ow=(t={})=>{if(typeof t=="number")return{...Lg,limit:t};if(t.methods&&!Array.isArray(t.methods))throw new Error("retry.methods must be an array");if(t.statusCodes&&!Array.isArray(t.statusCodes))throw new Error("retry.statusCodes must be an array");return{...Lg,...t}};class fA{constructor(e,n={}){qr(this,"request");qr(this,"abortController");qr(this,"_retryCount",0);qr(this,"_input");qr(this,"_options");var r,i;if(this._input=e,this._options={...n,headers:B0(this._input.headers,n.headers),hooks:F0({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},n.hooks),method:Rw(n.method??this._input.method??"GET"),prefixUrl:String(n.prefixUrl||""),retry:Ow(n.retry),throwHttpErrors:n.throwHttpErrors!==!1,timeout:n.timeout??1e4,fetch:n.fetch??globalThis.fetch.bind(globalThis)},typeof this._input!="string"&&!(this._input instanceof URL||this._input instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(this._options.prefixUrl&&typeof this._input=="string"){if(this._input.startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");this._options.prefixUrl.endsWith("/")||(this._options.prefixUrl+="/"),this._input=this._options.prefixUrl+this._input}if(vw&&Cw){const o=this._options.signal??this._input.signal;this.abortController=new globalThis.AbortController,this._options.signal=o?AbortSignal.any([o,this.abortController.signal]):this.abortController.signal}if(Qg&&(this._options.duplex="half"),this._options.json!==void 0&&(this._options.body=((i=(r=this._options).stringifyJson)==null?void 0:i.call(r,this._options.json))??JSON.stringify(this._options.json),this._options.headers.set("content-type",this._options.headers.get("content-type")??"application/json")),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){const o="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,o);!(Ew&&this._options.body instanceof globalThis.FormData||this._options.body instanceof URLSearchParams)||this._options.headers&&this._options.headers["content-type"]||this.request.headers.delete("content-type"),this.request=new globalThis.Request(new globalThis.Request(a,{...this.request}),this._options)}if(this._options.onUploadProgress){if(typeof this._options.onUploadProgress!="function")throw new TypeError("The `onUploadProgress` option must be a function");if(!Qg)throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request.body&&(this.request=xw(this.request,this._options.onUploadProgress))}}static create(e,n){const r=new fA(e,n),i=async()=>{if(typeof r._options.timeout=="number"&&r._options.timeout>jg)throw new RangeError("The `timeout` option cannot be greater than 2147483647");await Promise.resolve();let a=await r._fetch();for(const s of r._options.hooks.afterResponse){const A=await s(r.request,r._options,r._decorateResponse(a.clone()));A instanceof globalThis.Response&&(a=A)}if(r._decorateResponse(a),!a.ok&&r._options.throwHttpErrors){let s=new kg(a,r.request,r._options);for(const A of r._options.hooks.beforeError)s=await A(s);throw s}if(r._options.onDownloadProgress){if(typeof r._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!yw)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return((s,A)=>{const c=Number(s.headers.get("content-length"))||0;let u=0;return s.status===204?(A&&A({percent:1,totalBytes:c,transferredBytes:u},new Uint8Array),new Response(null,{status:s.status,statusText:s.statusText,headers:s.headers})):new Response(new ReadableStream({async start(d){const f=s.body.getReader();A&&A({percent:0,transferredBytes:0,totalBytes:c},new Uint8Array),await async function p(){const{done:v,value:C}=await f.read();v?d.close():(A&&(u+=C.byteLength,A({percent:c===0?0:u/c,transferredBytes:u,totalBytes:c},C)),d.enqueue(C),await p())}()}}),{status:s.status,statusText:s.statusText,headers:s.headers})})(a.clone(),r._options.onDownloadProgress)}return a},o=(r._options.retry.methods.includes(r.request.method.toLowerCase())?r._retry(i):i()).finally(async()=>{var a;r.request.bodyUsed||await((a=r.request.body)==null?void 0:a.cancel())});for(const[a,s]of Object.entries(bw))o[a]=async()=>{r.request.headers.set("accept",r.request.headers.get("accept")||s);const A=await o;if(a==="json"){if(A.status===204||(await A.clone().arrayBuffer()).byteLength===0)return"";if(n.parseJson)return n.parseJson(await A.text())}return A[a]()};return o}_calculateRetryDelay(e){if(this._retryCount++,this._retryCount>this._options.retry.limit||e instanceof Pg)throw e;if(e instanceof kg){if(!this._options.retry.statusCodes.includes(e.response.status))throw e;const r=e.response.headers.get("Retry-After")??e.response.headers.get("RateLimit-Reset")??e.response.headers.get("X-RateLimit-Reset")??e.response.headers.get("X-Rate-Limit-Reset");if(r&&this._options.retry.afterStatusCodes.includes(e.response.status)){let i=1e3*Number(r);Number.isNaN(i)?i=Date.parse(r)-Date.now():i>=Date.parse("2024-01-01")&&(i-=Date.now());const o=this._options.retry.maxRetryAfter??i;return i<o?i:o}if(e.response.status===413)throw e}const n=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,n)}_decorateResponse(e){return this._options.parseJson&&(e.json=async()=>this._options.parseJson(await e.text())),e}async _retry(e){try{return await e()}catch(n){const r=Math.min(this._calculateRetryDelay(n),jg);if(this._retryCount<1)throw n;await async function(i,{signal:o}){return new Promise((a,s)=>{function A(){clearTimeout(c),s(o.reason)}o&&(o.throwIfAborted(),o.addEventListener("abort",A,{once:!0}));const c=setTimeout(()=>{o==null||o.removeEventListener("abort",A),a()},i)})}(r,{signal:this._options.signal});for(const i of this._options.hooks.beforeRetry)if(await i({request:this.request,options:this._options,error:n,retryCount:this._retryCount})===D0)return;return this._retry(e)}}async _fetch(){for(const r of this._options.hooks.beforeRequest){const i=await r(this.request,this._options);if(i instanceof Request){this.request=i;break}if(i instanceof Response)return i}const e=((r,i)=>{const o={};for(const a in i)a in Iw||a in ww||a in r||(o[a]=i[a]);return o})(this.request,this._options),n=this.request;return this.request=n.clone(),this._options.timeout===!1?this._options.fetch(n,e):async function(r,i,o,a){return new Promise((s,A)=>{const c=setTimeout(()=>{o&&o.abort(),A(new Pg(r))},a.timeout);a.fetch(r,i).then(s).catch(A).then(()=>{clearTimeout(c)})})}(n,e,this.abortController,this._options)}}/*! MIT License © Sindre Sorhus */const ru=t=>{const e=(n,r)=>fA.create(n,xs(t,r));for(const n of N0)e[n]=(r,i)=>fA.create(r,xs(t,i,{method:n}));return e.create=n=>ru(xs(n)),e.extend=n=>(typeof n=="function"&&(n=n(t??{})),ru(xs(t,n))),e.stop=D0,e};var Vc,Mw=ru(),Tw=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},k0={exports:{}};/**
156
156
  * [js-md5]{@link https://github.com/emn178/js-md5}
157
157
  *
158
158
  * @namespace md5
@@ -160,7 +160,7 @@ React keys must be passed directly to JSX without using spread:
160
160
  * @author Chen, Yi-Cyuan [emn178@gmail.com]
161
161
  * @copyright Chen, Yi-Cyuan 2014-2023
162
162
  * @license MIT
163
- */Vc=k0,function(){var t="input is invalid type",e=typeof window=="object",n=e?window:{};n.JS_MD5_NO_WINDOW&&(e=!1);var r=!e&&typeof self=="object",i=!n.JS_MD5_NO_NODE_JS&&typeof process=="object"&&process.versions&&process.versions.node;i?n=Tw:r&&(n=self);var o,a=!n.JS_MD5_NO_COMMON_JS&&Vc.exports,s=!n.JS_MD5_NO_ARRAY_BUFFER&&typeof ArrayBuffer<"u",A="0123456789abcdef".split(""),c=[128,32768,8388608,-2147483648],u=[0,8,16,24],d=["hex","array","digest","buffer","arrayBuffer","base64"],f="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),p=[];if(s){var v=new ArrayBuffer(68);o=new Uint8Array(v),p=new Uint32Array(v)}var C=Array.isArray;!n.JS_MD5_NO_NODE_JS&&C||(C=function(E){return Object.prototype.toString.call(E)==="[object Array]"});var m=ArrayBuffer.isView;!s||!n.JS_MD5_NO_ARRAY_BUFFER_IS_VIEW&&m||(m=function(E){return typeof E=="object"&&E.buffer&&E.buffer.constructor===ArrayBuffer});var y=function(E){var b=typeof E;if(b==="string")return[E,!0];if(b!=="object"||E===null)throw new Error(t);if(s&&E.constructor===ArrayBuffer)return[new Uint8Array(E),!1];if(!C(E)&&!m(E))throw new Error(t);return[E,!1]},w=function(E){return function(b){return new x(!0).update(b)[E]()}},I=function(E){var b,h=Og,S=Og.Buffer;return b=S.from&&!n.JS_MD5_NO_BUFFER_FROM?S.from:function(T){return new S(T)},function(T){if(typeof T=="string")return h.createHash("md5").update(T,"utf8").digest("hex");if(T==null)throw new Error(t);return T.constructor===ArrayBuffer&&(T=new Uint8Array(T)),C(T)||m(T)||T.constructor===S?h.createHash("md5").update(b(T)).digest("hex"):E(T)}},O=function(E){return function(b,h){return new g(b,!0).update(h)[E]()}};function x(E){if(E)p[0]=p[16]=p[1]=p[2]=p[3]=p[4]=p[5]=p[6]=p[7]=p[8]=p[9]=p[10]=p[11]=p[12]=p[13]=p[14]=p[15]=0,this.blocks=p,this.buffer8=o;else if(s){var b=new ArrayBuffer(68);this.buffer8=new Uint8Array(b),this.blocks=new Uint32Array(b)}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 g(E,b){var h,S=y(E);if(E=S[0],S[1]){var T,R=[],D=E.length,B=0;for(h=0;h<D;++h)(T=E.charCodeAt(h))<128?R[B++]=T:T<2048?(R[B++]=192|T>>>6,R[B++]=128|63&T):T<55296||T>=57344?(R[B++]=224|T>>>12,R[B++]=128|T>>>6&63,R[B++]=128|63&T):(T=65536+((1023&T)<<10|1023&E.charCodeAt(++h)),R[B++]=240|T>>>18,R[B++]=128|T>>>12&63,R[B++]=128|T>>>6&63,R[B++]=128|63&T);E=R}E.length>64&&(E=new x(!0).update(E).array());var k=[],P=[];for(h=0;h<64;++h){var H=E[h]||0;k[h]=92^H,P[h]=54^H}x.call(this,b),this.update(P),this.oKeyPad=k,this.inner=!0,this.sharedMemory=b}x.prototype.update=function(E){if(this.finalized)throw new Error("finalize already called");var b=y(E);E=b[0];for(var h,S,T=b[1],R=0,D=E.length,B=this.blocks,k=this.buffer8;R<D;){if(this.hashed&&(this.hashed=!1,B[0]=B[16],B[16]=B[1]=B[2]=B[3]=B[4]=B[5]=B[6]=B[7]=B[8]=B[9]=B[10]=B[11]=B[12]=B[13]=B[14]=B[15]=0),T)if(s)for(S=this.start;R<D&&S<64;++R)(h=E.charCodeAt(R))<128?k[S++]=h:h<2048?(k[S++]=192|h>>>6,k[S++]=128|63&h):h<55296||h>=57344?(k[S++]=224|h>>>12,k[S++]=128|h>>>6&63,k[S++]=128|63&h):(h=65536+((1023&h)<<10|1023&E.charCodeAt(++R)),k[S++]=240|h>>>18,k[S++]=128|h>>>12&63,k[S++]=128|h>>>6&63,k[S++]=128|63&h);else for(S=this.start;R<D&&S<64;++R)(h=E.charCodeAt(R))<128?B[S>>>2]|=h<<u[3&S++]:h<2048?(B[S>>>2]|=(192|h>>>6)<<u[3&S++],B[S>>>2]|=(128|63&h)<<u[3&S++]):h<55296||h>=57344?(B[S>>>2]|=(224|h>>>12)<<u[3&S++],B[S>>>2]|=(128|h>>>6&63)<<u[3&S++],B[S>>>2]|=(128|63&h)<<u[3&S++]):(h=65536+((1023&h)<<10|1023&E.charCodeAt(++R)),B[S>>>2]|=(240|h>>>18)<<u[3&S++],B[S>>>2]|=(128|h>>>12&63)<<u[3&S++],B[S>>>2]|=(128|h>>>6&63)<<u[3&S++],B[S>>>2]|=(128|63&h)<<u[3&S++]);else if(s)for(S=this.start;R<D&&S<64;++R)k[S++]=E[R];else for(S=this.start;R<D&&S<64;++R)B[S>>>2]|=E[R]<<u[3&S++];this.lastByteIndex=S,this.bytes+=S-this.start,S>=64?(this.start=S-64,this.hash(),this.hashed=!0):this.start=S}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296|0,this.bytes=this.bytes%4294967296),this},x.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var E=this.blocks,b=this.lastByteIndex;E[b>>>2]|=c[3&b],b>=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()}},x.prototype.hash=function(){var E,b,h,S,T,R,D=this.blocks;this.first?b=((b=((E=((E=D[0]-680876937)<<7|E>>>25)-271733879|0)^(h=((h=(-271733879^(S=((S=(-1732584194^2004318071&E)+D[1]-117830708)<<12|S>>>20)+E|0)&(-271733879^E))+D[2]-1126478375)<<17|h>>>15)+S|0)&(S^E))+D[3]-1316259209)<<22|b>>>10)+h|0:(E=this.h0,b=this.h1,h=this.h2,b=((b+=((E=((E+=((S=this.h3)^b&(h^S))+D[0]-680876936)<<7|E>>>25)+b|0)^(h=((h+=(b^(S=((S+=(h^E&(b^h))+D[1]-389564586)<<12|S>>>20)+E|0)&(E^b))+D[2]+606105819)<<17|h>>>15)+S|0)&(S^E))+D[3]-1044525330)<<22|b>>>10)+h|0),b=((b+=((E=((E+=(S^b&(h^S))+D[4]-176418897)<<7|E>>>25)+b|0)^(h=((h+=(b^(S=((S+=(h^E&(b^h))+D[5]+1200080426)<<12|S>>>20)+E|0)&(E^b))+D[6]-1473231341)<<17|h>>>15)+S|0)&(S^E))+D[7]-45705983)<<22|b>>>10)+h|0,b=((b+=((E=((E+=(S^b&(h^S))+D[8]+1770035416)<<7|E>>>25)+b|0)^(h=((h+=(b^(S=((S+=(h^E&(b^h))+D[9]-1958414417)<<12|S>>>20)+E|0)&(E^b))+D[10]-42063)<<17|h>>>15)+S|0)&(S^E))+D[11]-1990404162)<<22|b>>>10)+h|0,b=((b+=((E=((E+=(S^b&(h^S))+D[12]+1804603682)<<7|E>>>25)+b|0)^(h=((h+=(b^(S=((S+=(h^E&(b^h))+D[13]-40341101)<<12|S>>>20)+E|0)&(E^b))+D[14]-1502002290)<<17|h>>>15)+S|0)&(S^E))+D[15]+1236535329)<<22|b>>>10)+h|0,b=((b+=((S=((S+=(b^h&((E=((E+=(h^S&(b^h))+D[1]-165796510)<<5|E>>>27)+b|0)^b))+D[6]-1069501632)<<9|S>>>23)+E|0)^E&((h=((h+=(E^b&(S^E))+D[11]+643717713)<<14|h>>>18)+S|0)^S))+D[0]-373897302)<<20|b>>>12)+h|0,b=((b+=((S=((S+=(b^h&((E=((E+=(h^S&(b^h))+D[5]-701558691)<<5|E>>>27)+b|0)^b))+D[10]+38016083)<<9|S>>>23)+E|0)^E&((h=((h+=(E^b&(S^E))+D[15]-660478335)<<14|h>>>18)+S|0)^S))+D[4]-405537848)<<20|b>>>12)+h|0,b=((b+=((S=((S+=(b^h&((E=((E+=(h^S&(b^h))+D[9]+568446438)<<5|E>>>27)+b|0)^b))+D[14]-1019803690)<<9|S>>>23)+E|0)^E&((h=((h+=(E^b&(S^E))+D[3]-187363961)<<14|h>>>18)+S|0)^S))+D[8]+1163531501)<<20|b>>>12)+h|0,b=((b+=((S=((S+=(b^h&((E=((E+=(h^S&(b^h))+D[13]-1444681467)<<5|E>>>27)+b|0)^b))+D[2]-51403784)<<9|S>>>23)+E|0)^E&((h=((h+=(E^b&(S^E))+D[7]+1735328473)<<14|h>>>18)+S|0)^S))+D[12]-1926607734)<<20|b>>>12)+h|0,b=((b+=((R=(S=((S+=((T=b^h)^(E=((E+=(T^S)+D[5]-378558)<<4|E>>>28)+b|0))+D[8]-2022574463)<<11|S>>>21)+E|0)^E)^(h=((h+=(R^b)+D[11]+1839030562)<<16|h>>>16)+S|0))+D[14]-35309556)<<23|b>>>9)+h|0,b=((b+=((R=(S=((S+=((T=b^h)^(E=((E+=(T^S)+D[1]-1530992060)<<4|E>>>28)+b|0))+D[4]+1272893353)<<11|S>>>21)+E|0)^E)^(h=((h+=(R^b)+D[7]-155497632)<<16|h>>>16)+S|0))+D[10]-1094730640)<<23|b>>>9)+h|0,b=((b+=((R=(S=((S+=((T=b^h)^(E=((E+=(T^S)+D[13]+681279174)<<4|E>>>28)+b|0))+D[0]-358537222)<<11|S>>>21)+E|0)^E)^(h=((h+=(R^b)+D[3]-722521979)<<16|h>>>16)+S|0))+D[6]+76029189)<<23|b>>>9)+h|0,b=((b+=((R=(S=((S+=((T=b^h)^(E=((E+=(T^S)+D[9]-640364487)<<4|E>>>28)+b|0))+D[12]-421815835)<<11|S>>>21)+E|0)^E)^(h=((h+=(R^b)+D[15]+530742520)<<16|h>>>16)+S|0))+D[2]-995338651)<<23|b>>>9)+h|0,b=((b+=((S=((S+=(b^((E=((E+=(h^(b|~S))+D[0]-198630844)<<6|E>>>26)+b|0)|~h))+D[7]+1126891415)<<10|S>>>22)+E|0)^((h=((h+=(E^(S|~b))+D[14]-1416354905)<<15|h>>>17)+S|0)|~E))+D[5]-57434055)<<21|b>>>11)+h|0,b=((b+=((S=((S+=(b^((E=((E+=(h^(b|~S))+D[12]+1700485571)<<6|E>>>26)+b|0)|~h))+D[3]-1894986606)<<10|S>>>22)+E|0)^((h=((h+=(E^(S|~b))+D[10]-1051523)<<15|h>>>17)+S|0)|~E))+D[1]-2054922799)<<21|b>>>11)+h|0,b=((b+=((S=((S+=(b^((E=((E+=(h^(b|~S))+D[8]+1873313359)<<6|E>>>26)+b|0)|~h))+D[15]-30611744)<<10|S>>>22)+E|0)^((h=((h+=(E^(S|~b))+D[6]-1560198380)<<15|h>>>17)+S|0)|~E))+D[13]+1309151649)<<21|b>>>11)+h|0,b=((b+=((S=((S+=(b^((E=((E+=(h^(b|~S))+D[4]-145523070)<<6|E>>>26)+b|0)|~h))+D[11]-1120210379)<<10|S>>>22)+E|0)^((h=((h+=(E^(S|~b))+D[2]+718787259)<<15|h>>>17)+S|0)|~E))+D[9]-343485551)<<21|b>>>11)+h|0,this.first?(this.h0=E+1732584193|0,this.h1=b-271733879|0,this.h2=h-1732584194|0,this.h3=S+271733878|0,this.first=!1):(this.h0=this.h0+E|0,this.h1=this.h1+b|0,this.h2=this.h2+h|0,this.h3=this.h3+S|0)},x.prototype.hex=function(){this.finalize();var E=this.h0,b=this.h1,h=this.h2,S=this.h3;return A[E>>>4&15]+A[15&E]+A[E>>>12&15]+A[E>>>8&15]+A[E>>>20&15]+A[E>>>16&15]+A[E>>>28&15]+A[E>>>24&15]+A[b>>>4&15]+A[15&b]+A[b>>>12&15]+A[b>>>8&15]+A[b>>>20&15]+A[b>>>16&15]+A[b>>>28&15]+A[b>>>24&15]+A[h>>>4&15]+A[15&h]+A[h>>>12&15]+A[h>>>8&15]+A[h>>>20&15]+A[h>>>16&15]+A[h>>>28&15]+A[h>>>24&15]+A[S>>>4&15]+A[15&S]+A[S>>>12&15]+A[S>>>8&15]+A[S>>>20&15]+A[S>>>16&15]+A[S>>>28&15]+A[S>>>24&15]},x.prototype.toString=x.prototype.hex,x.prototype.digest=function(){this.finalize();var E=this.h0,b=this.h1,h=this.h2,S=this.h3;return[255&E,E>>>8&255,E>>>16&255,E>>>24&255,255&b,b>>>8&255,b>>>16&255,b>>>24&255,255&h,h>>>8&255,h>>>16&255,h>>>24&255,255&S,S>>>8&255,S>>>16&255,S>>>24&255]},x.prototype.array=x.prototype.digest,x.prototype.arrayBuffer=function(){this.finalize();var E=new ArrayBuffer(16),b=new Uint32Array(E);return b[0]=this.h0,b[1]=this.h1,b[2]=this.h2,b[3]=this.h3,E},x.prototype.buffer=x.prototype.arrayBuffer,x.prototype.base64=function(){for(var E,b,h,S="",T=this.array(),R=0;R<15;)E=T[R++],b=T[R++],h=T[R++],S+=f[E>>>2]+f[63&(E<<4|b>>>4)]+f[63&(b<<2|h>>>6)]+f[63&h];return E=T[R],S+=f[E>>>2]+f[E<<4&63]+"=="},g.prototype=new x,g.prototype.finalize=function(){if(x.prototype.finalize.call(this),this.inner){this.inner=!1;var E=this.array();x.call(this,this.sharedMemory),this.update(this.oKeyPad),this.update(E),x.prototype.finalize.call(this)}};var M=function(){var E=w("hex");i&&(E=I(E)),E.create=function(){return new x},E.update=function(S){return E.create().update(S)};for(var b=0;b<d.length;++b){var h=d[b];E[h]=w(h)}return E}();M.md5=M,M.md5.hmac=function(){var E=O("hex");E.create=function(S){return new g(S)},E.update=function(S,T){return E.create(S).update(T)};for(var b=0;b<d.length;++b){var h=d[b];E[h]=O(h)}return E}(),a?Vc.exports=M:n.md5=M}();var Nw=k0.exports;const P0=(t,e)=>{const n=Date.now(),r=`${t}:${n}:${Nw.md5(`${e}${n}`)}`,i=new TextEncoder().encode(r);return btoa(String.fromCharCode(...i))},iu=t=>{if(/^\d+$/.test(t)||!t||typeof t!="string"||t.length%4!=0||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t))return!1;try{const e=atob(t);return btoa(e)===t}catch{return!1}},Yi="/v1/aicc/bmserver",Or="/v1/aicc/ccs";let Si="",Kd="",Vd="",zc="";function Q0(t){const e=P0(Kd,Vd);return Mw.create({prefixUrl:`${Si}`,timeout:!1,headers:{Authorization:e,...t},hooks:{afterResponse:[async(n,r,i)=>{if(i.url.indexOf("heartbeat")!==-1)return i;const o=await i.clone().json();if(o.code!==0)throw new Error(JSON.stringify(o)||"请求失败");return i.json=async()=>o,i}]}})}async function yn(t,e,n){const r=Q0(n),i="api/"+t.replace(/^\/+/,"");return r.post(i,{json:e}).json()}const Ug=(t,e)=>yn(`${Or}/state/change?h=${e}`,t,{h:e}),Dw=()=>async function(t,e){const n=Q0(),r=t.replace(/^\/+/,"");return n.post(r,{json:e}).json()}("/heartbeat",{});class nn{static log(e,n={}){const{level:r="info",module:i="",timestamp:o=!0}=n;if(K.logBuiltinEnabled){const A=i?`[${i}]`:"",c=o?`[${new Date().toLocaleString()}]`:"";switch(r){case"debug":break;case"warn":console.warn(`${c}${A} ${e}`);break;case"error":console.error(`${c}${A} ${e}`)}}const a=K.agentInfo.agent_no;if(a){const A=JSON.stringify({level:r,module:i,content:e,timestamp:new Date().toISOString()});(s={agent_no:a,content:A},yn("/v1/aicc/ccs/softphone/log",s)).catch(()=>{})}var s}static debug(e,n){this.log(e,{level:"debug",module:n})}static info(e,n){this.log(e,{level:"info",module:n})}static warn(e,n){this.log(e,{level:"warn",module:n})}static error(e,n){this.log(e,{level:"error",module:n})}static errorObj(e,n){const r=JSON.stringify({message:e.message,stack:e.stack,name:e.name});this.log(r,{level:"error",module:n})}}class Bw{constructor(e,n){this.config=e,this.eventCallback=n,this.userAgent=null,this.registerer=null,this.activeSession=null,this.callTimeoutTimer=null,this.incomingInvitation=null,this.reconnectAttempts=0,this.maxReconnectAttempts=5,this.reconnectTimer=null,this.isOffline=!1,this.isManuallyStopped=!1,this.registerInterval=6e4,this.handleNetworkInfoChange=r=>{var i,o;if((i=r.rttObject)!=null&&i.rtt){const a=(o=r.rttObject)==null?void 0:o.rtt,s=a!=null&&a>0;s||this.isOffline?s&&this.isOffline&&(this.isOffline=!1,this.handleOnline()):(this.isOffline=!0,this.handleOffline())}},this.handleOffline=()=>{nn.warn("网络断开,准备销毁 SIP 客户端","sip-client.ts 75 handleOffline"),fe.emit(He.FAIL_NOTIFICATION,"网络断开,准备销毁 SIP 客户端"),this.destroy()},this.handleOnline=()=>{nn.warn("网络恢复,准备重新启动 SIP 客户端","sip-client.ts 82 handleOnline"),this.reconnect()},this.sleep=r=>new Promise(i=>setTimeout(i,r)),T0.subscribe(this.handleNetworkInfoChange)}async start(){const e=Fg.makeURI(`sip:${this.config.user}@${this.config.server}`);if(!e)throw new Error("无效的SIP配置");const n={uri:e,authorizationUsername:this.config.user,authorizationPassword:this.config.password,sendInitialProvisionalResponse:!1,transportOptions:{server:this.config.webSocket,connectionTimeout:10,keepAliveInterval:20,keepAliveDebounce:10},contactName:this.config.user,contactParams:{transport:"wss"},userAgentString:"SwiftSIP/2.0.21",sessionDescriptionHandlerFactoryOptions:{alwaysAcquireMediaFirst:!0,peerConnectionConfiguration:{iceServers:[{urls:"stun:stun.l.google.com:19302"}],iceCandidatePoolSize:0,iceTransportPolicy:"all",rtcpMuxPolicy:"require",bundlePolicy:"balanced",certificates:void 0,peerIdentity:void 0},iceGatheringTimeout:1e3},logBuiltinEnabled:K.logBuiltinEnabled};this.userAgent=new Fg(n),this.setupEventListeners(),await this.userAgent.start(),await this.register()}setupEventListeners(){this.userAgent&&(this.userAgent.transport.stateChange.addListener(e=>{var r;let n;switch(e){case dt.Connecting:n=Ar.WEB_RTC_CONNECTING;break;case dt.Connected:n=Ar.WEB_RTC_CONNECTED,this.reconnectAttempts=0,K.isRtcReconnecting=!1,G.updateIsSipConnected(!0),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null);break;case dt.Disconnecting:n=Ar.WEB_RTC_DISCONNECTING,G.updateIsSipConnected(!1);break;case dt.Disconnected:{if(G.updateIsSipConnected(!1),this.isManuallyStopped)return nn.warn("手动断开,不触发重连","sip-client.ts 204"),void console.warn("[SIP] 手动断开,不触发重连");fe.emit(He.FAIL_NOTIFICATION,"软电话链接失败"),n=Ar.WEB_RTC_DISCONNECTED;const i=G.get("answerDevice");if(!K.isRtcReconnecting&&this.reconnectAttempts<this.maxReconnectAttempts&&i===1){this.reconnectAttempts++;const o=1e3*this.reconnectAttempts;nn.warn(`SIP WebSocket 断开,第 ${this.reconnectAttempts} 次尝试重连,${o}ms 后重试...`,"sip-client.ts 219"),this.reconnectTimer=setTimeout(()=>{this.reconnect()},o)}else this.reconnectAttempts>=this.maxReconnectAttempts&&(nn.warn(`SIP 重连失败:已达到最大重试次数; reconnectAttempts: ${this.reconnectAttempts}; maxReconnectAttempts: ${this.maxReconnectAttempts}`,"sip-client.ts 228"),console.error("SIP 重连失败:已达到最大重试次数"),fe.emit(He.FAIL_NOTIFICATION,"SIP 重连失败:已达到最大重试次数"));break}default:G.updateIsSipConnected(!1),n="unknown"}(r=this.eventCallback)==null||r.call(this,{type:n})}),this.userAgent.delegate={onInvite:e=>{this.handleIncomingCall(e)}})}async refreshRegister(){if(this.registerer)try{await this.registerer.register(),new Date().toLocaleTimeString()}catch(e){console.error("[SIPClient] REGISTER刷新失败",e)}}async register(){var e,n;if(this.userAgent){this.registerer=new tu(this.userAgent,{expires:120,refreshFrequency:80}),(e=this.registerer)==null||e.stateChange.addListener(r=>{var o;let i;switch(r){case jt.Initial:G.updateDisplayText(Kt.LINKING),i="initial";break;case jt.Registered:G.updateDisplayText(""),i=Ar.WEB_RTC_REGISTERED;break;case jt.Unregistered:i=Ar.WEB_RTC_UNREGISTERED;break;case jt.Terminated:nn.warn(`注册流程已终止,无法再注册(如 UA 停止,或网络不可达);regStatus: ${Ar.WEB_RTC_TERMINATED}`,"sip-client.ts 299"),i=Ar.WEB_RTC_TERMINATED;break;default:i="unknown"}(o=this.eventCallback)==null||o.call(this,{type:i})});try{await this.registerer.register()}catch(r){(n=this.eventCallback)==null||n.call(this,{type:Ar.WEB_RTC_REGISTER_FAILED,data:r})}}}attachRemoteAudio(e){const n=e.sessionDescriptionHandler;if(n){const r=n.peerConnection;if(!r)return;const i=new MediaStream;r.getReceivers().forEach(a=>{a.track&&a.track.kind==="audio"&&i.addTrack(a.track)});let o=document.getElementById("sip-remote-audio");o||(o=document.createElement("audio"),o.id="sip-remote-audio",o.autoplay=!0,o.style.display="none",document.body.appendChild(o)),o.srcObject=i,o.play().catch(a=>{console.error("音频播放失败,需要用户交互触发",a)})}}handleSessionState(e,n,r){e.stateChange.addListener(i=>{switch(i){case he.Established:clearTimeout(this.callTimeoutTimer),this.activeSession=e,this.attachRemoteAudio(e);break;case he.Terminating:break;case he.Terminated:this.activeSession=null,clearTimeout(this.callTimeoutTimer);case he.Establishing:}})}handleIncomingCall(e){this.incomingInvitation=e,this.handleSessionState(e,!1),e.progress({statusCode:180,reasonPhrase:"Ringing"}).catch(n=>console.error("发送 180 失败",n)),G.get("direction")===xn.OUTGOING&&this.answerCall()}async answerCall(){var e;if(!this.incomingInvitation)throw new Error("无来电可接听");K.autoAnswerTimer&&(clearTimeout(K.autoAnswerTimer),K.autoAnswerTimer=null);try{await this.incomingInvitation.accept(),this.activeSession=this.incomingInvitation,this.incomingInvitation=null}catch(n){(e=this.eventCallback)==null||e.call(this,{type:Ar.WEB_RTC_ANSWER_FAILED,data:{detail:n}})}}async rejectInCall(){var e;if(this.incomingInvitation)try{await this.incomingInvitation.reject(),this.incomingInvitation=null,G.updateDirection(null),G.updateIsCalling(!1),clearTimeout(this.callTimeoutTimer)}catch(n){(e=this.eventCallback)==null||e.call(this,{type:"error",data:{message:"拒接失败",detail:n}})}}sendDTMF(e){var r;if(!this.activeSession)throw new Error("当前没有活跃的通话");const n=this.activeSession.sessionDescriptionHandler;n&&typeof n.sendDtmf=="function"?(n.sendDtmf(e),(r=this.eventCallback)==null||r.call(this,{type:Ar.WEB_RTC_SEND_DTMF,data:{tone:e}})):(console.warn("DTMF发送不支持或未初始化"),nn.warn("DTMF发送不支持或未初始化","sip-client.ts 490 sendDTMF"))}async hangup(){if(this.activeSession,this.activeSession){clearTimeout(this.callTimeoutTimer);const e=this.activeSession;if(!e)return;const n=e.state;try{n===he.Established?await e.bye():n===he.Establishing&&(e instanceof v0?await e.cancel():e instanceof eu&&await e.reject()),clearTimeout(this.callTimeoutTimer)}catch(r){nn.error("挂断失败","sip-client.ts 522 hangup"),console.error("挂断失败",r)}finally{this.activeSession=null}}}async rejectOutCall(){this.activeSession instanceof eu&&(await this.activeSession.reject(),this.activeSession=null)}async destroy(){if(this.isManuallyStopped=!0,clearTimeout(this.callTimeoutTimer),this.activeSession&&await this.hangup(),this.registerer){try{await this.registerer.unregister()}catch(e){console.warn("注销失败",e)}this.registerer=null}this.userAgent&&(await this.userAgent.stop(),this.userAgent=null)}async reconnect(){if(!K.isRtcReconnecting){K.isRtcReconnecting=!0;try{this.isManuallyStopped=!1,await this.destroy(),await this.start(),this.isOffline=!1,this.reconnectAttempts=0}catch(e){console.error("重连失败",e),K.isRtcReconnecting=!1}finally{K.isRtcReconnecting=!1}}}async getNetworkStats(){var e;if(this.activeSession){const n=(e=this.activeSession.sessionDescriptionHandler)==null?void 0:e.peerConnection;if(!n)return null;const r=await n.getStats(),i={};return r.forEach(o=>{o.type==="candidate-pair"&&o.state==="succeeded"&&o.currentRoundTripTime!=null&&(i.rtt=+(1e3*o.currentRoundTripTime).toFixed(2)),o.type==="inbound-rtp"&&o.kind==="audio"&&(i.jitter=+(1e3*o.jitter).toFixed(2),i.packetsLost=o.packetsLost,i.packetsReceived=o.packetsReceived,o.bytesReceived&&o.timestamp&&(i.recvBitrate=+(o.bytesReceived/1024).toFixed(2))),o.type==="outbound-rtp"&&o.kind==="audio"&&(i.packetsSent=o.packetsSent,o.bytesSent&&o.timestamp&&(i.sendBitrate=+(o.bytesSent/1024).toFixed(2))),o.type==="codec"&&o.mimeType&&(i.codec=o.mimeType)}),{...i,rtt:(i==null?void 0:i.rtt)||40}}return{rtt:K.latency||1}}}class To{static requestPermission(){"Notification"in window&&Notification.permission==="default"&&Notification.requestPermission()}static async requestMediaPermissions(){try{return(await navigator.mediaDevices.enumerateDevices()).some(n=>n.kind==="audioinput"&&n.label!=="")?null:await navigator.mediaDevices.getUserMedia({audio:!0})}catch(e){return console.warn("获取音频权限失败:",e),null}}static show(e,n,r,i){if("Notification"in window&&Notification.permission==="granted"){const o=new Notification(e,{body:n,tag:`xy-global-notification${new Date().getTime()}`,renotify:!0});o.onclick=()=>{window.focus(),o.close(),r==null||r()},setTimeout(()=>o.close(),1e3*(i||3))}}static async checkMediaPermissions(){try{return(await navigator.mediaDevices.enumerateDevices()).some(e=>e.kind==="audioinput"&&e.label!=="")}catch(e){return console.warn("无法检查设备权限:",e),!1}}}const Fw=[],Vn=["call_number"],gA=["call_number"],kw=["hangup"],Ci=["hold","hangup","mute","transfer","consult","satisfaction","dtmf"],Yc=["hold","hangup","mute","transfer","consult"],Hg=["consult_transfer","conference","consult_retrieve"],Pw=["hangup"],Qw=["hangup"],Os=["answer","reject"],Gi=["hangup","consult","transfer","hold","mute","satisfaction","dtmf"],Gg=["hangup","whisper","force_insert","force_disconnect"],jw=["hangup"],Lw=["hangup","cancel_whisper","force_insert"],Uw=["hangup"],Hw=["hangup"];class ja{constructor(){this.roleData={agentInfo:()=>{var e;if(!((e=K.agentInfo)!=null&&e.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:n}=K.agentInfo;if(!n.split(",").map(r=>Number(r)).includes(e))throw new Error(JSON.stringify({code:1,msg:"当前状态不支持"}))},changeState:(e,n)=>{if(!e)throw new Error(JSON.stringify({code:1,msg:'Parameter "state" is required'}));if(!n)throw new Error(JSON.stringify({code:1,msg:'Parameter "state_name" is required'}));if(e===2&&(n==="通话中"||n==="整理"))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:n,out_display_data:r}=K.agentInfo;if(n!==1)throw new Error(JSON.stringify({code:1,msg:"当前坐席设置未开启允许指定外显"}));if(!e)throw new Error(JSON.stringify({code:1,msg:'Parameter "number" is required'}));if(!(r||"").split("#").includes(e))throw new Error(JSON.stringify({code:1,msg:"当前外显号码不存在"}))}},this.changeDevice=async e=>{try{if(G.get("isCalling"))throw new Error(JSON.stringify({code:1,msg:"当前正在通话中,请勿切换设备"}));this.roleData.agentInfo(),this.roleData.requestInfo(e);const{data:n,success:r}=e,{device:i}=n;i===1&&await ja.initRtcFn(),this.roleData.changeDevice(i);const{agent_no:o}=K.agentInfo;await(s=>yn(`${Or}/device/change`,s))({agent_no:o,answer_device:i}),G.updateAnswerDevice(i);const a=G.get("actionConfigs");G.updateActionConfigs(a),i===2&&K.stateObject.state===Rt.UNREGISTERED&&await this._changeState({data:{...K.stateBeforeChange,state_name:K.stateBeforeChange.state===Rt.IDLE?"空闲":"忙碌"}},"q"),r==null||r({code:0,msg:"请求成功"})}catch(n){throw fe.emit(He.FAIL_NOTIFICATION,JSON.parse(n.message).msg),n}}}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 r=await(n={agent_no:e},yn(`${Or}/agent/login`,n));K.agentInfo=r.data}catch(r){throw fe.emit(He.FAIL_NOTIFICATION,JSON.parse(r.message).msg),r}var n}async _changeState(e,n){try{K.autoStateTimer&&(clearTimeout(K.autoStateTimer),K.autoStateTimer=null),this.roleData.agentInfo(),this.roleData.requestInfo(e);const{data:r,success:i}=e,{state:o,state_name:a}=r,{agent_no:s}=K.agentInfo;await Ug({agent_no:s,state_name:a,state:o},n),o===Rt.IDLE?G.updateActionConfigs(Vn):o===Rt.BUSY&&G.updateActionConfigs(gA),K.stateObject={state:o,state_name:a},i==null||i({code:0,msg:"请求成功"})}catch(r){throw fe.emit(He.FAIL_NOTIFICATION,JSON.parse(r.message).msg),r}}async _getInCallCrmDetail(e){var n;try{const{phone:r}=e.data,i={};iu(r)?i.trace_id=r:i.phone=r.replace(/[\s\r\n-]+/g,"");const o=await(a=>yn(`${Yi}/crm/popups`,a))({...i});(n=e.success)==null||n.call(e,o)}catch(r){throw fe.emit(He.FAIL_NOTIFICATION,JSON.parse(r.message).msg),r}}async changeState(e,n){try{if(G.get("isCalling"))throw new Error(JSON.stringify({code:1,msg:"当前正在通话中,请勿切换设备"}));K.autoStateTimer&&(clearTimeout(K.autoStateTimer),K.autoStateTimer=null),this.roleData.agentInfo(),this.roleData.requestInfo(e);const{data:r,success:i}=e,{state:o,state_name:a}=r;this.roleData.changeState(o,a);const{agent_no:s}=K.agentInfo;await Ug({agent_no:s,state_name:a,state:o},n),(K.stateObject.state===Rt.IDLE||K.stateObject.state===Rt.BUSY&&a!=="整理")&&(K.stateBeforeChange=K.stateObject),o===Rt.IDLE?G.updateActionConfigs(Vn):o===Rt.BUSY&&G.updateActionConfigs(gA),K.stateObject={state:o,state_name:a},i==null||i({code:0,msg:"请求成功"})}catch(r){throw fe.emit(He.FAIL_NOTIFICATION,JSON.parse(r.message).msg),r}}async getIdleAgentList(e){var r;const{agent_no:n}=K.agentInfo;try{this.roleData.agentInfo();const i=await(o=>yn(`${Or}/agent/free`,o))({agent_no:n});(r=e.success)==null||r.call(e,i)}catch(i){throw fe.emit(He.FAIL_NOTIFICATION,JSON.parse(i.message).msg),i}}async getAgentState(e){var n;try{const r=await yn(`${Yi}/agent/statecfg/list`,{}),i=(r.data||[]).filter(o=>o.enable===0).filter(o=>o.state!==0&&o.state!==3).filter(o=>o.state_name!=="通话中"&&o.state_name!=="整理"&&o.state_name!=="未注册"&&o.state_name!=="离线接听").map(o=>({state:o.state,state_name:o.state_name})).reverse();(n=e.success)==null||n.call(e,{...r,data:i})}catch(r){throw fe.emit(He.FAIL_NOTIFICATION,JSON.parse(r.message).msg),r}}async setAgentExplicit(e){var n;try{this.roleData.agentInfo(),this.roleData.requestInfo(e),this.roleData.setAgentExplicit(e.data.number);const{agent_id:r}=K.agentInfo;await(i=>yn(`${Yi}/agent/update`,i))({agent_id:r,out_display_number:e.data.number}),G.updateSelectOutNumber(e.data.number),(n=e.success)==null||n.call(e,{code:0,msg:"请求成功"})}catch(r){throw fe.emit(He.FAIL_NOTIFICATION,JSON.parse(r.message).msg),r}}async checkAgentLogin(e){var n;try{this.roleData.requestInfo(e);const{agent_no:r}=e.data;if(!r)throw new Error(JSON.stringify({code:1,msg:'Parameter "agent_no" is required'}));const i=await(o=>yn(`${Or}/agent/islogin`,o))({agent_no:r});(n=e.success)==null||n.call(e,i)}catch(r){throw fe.emit(He.FAIL_NOTIFICATION,JSON.parse(r.message).msg),r}}async getCallRecord(e){try{this.roleData.agentInfo();const{success:n}=e,r=new Date,i=new Date(r.getFullYear(),r.getMonth(),r.getDate(),0,0,0),o=new Date(r.getFullYear(),r.getMonth(),r.getDate(),23,59,59),a=[this.formatDate(i),this.formatDate(o)],{agent_no:s}=K.agentInfo,A=await(f=>yn(`${Yi}/agent/recordpage`,f))({start_time:a[0],end_time:a[1],page_no:1,page_size:10,agent_no:s}),{code:c,msg:u,data:d}=A;n==null||n({code:c,msg:u,data:d})}catch(n){throw fe.emit(He.FAIL_NOTIFICATION,JSON.parse(n.message).msg),n}}async logout(e){this.roleData.agentInfo();try{const{agent_no:n}=K.agentInfo,{data:r,success:i}=e;await(o=>yn(`${Or}/agent/logout`,o))({...r,agent_no:n}),i==null||i({code:0,msg:""})}catch(n){throw fe.emit(He.FAIL_NOTIFICATION,JSON.parse(n.message).msg),n}}async listenCall(e){try{const{agent_no:n}=K.agentInfo,{data:r,success:i}=e;if(this.roleData.agentInfo(),this.roleData.requestInfo(e),!r.monitored_agent_no)throw new Error(JSON.stringify({code:1,msg:'Parameter "monitored_agent_no" is required'}));await(o=>yn(`${Or}/call/monitor`,o))({...r,monitor_agent_no:n}),K.monitoredAgentNo=r.monitored_agent_no,i==null||i({code:0,msg:""})}catch(n){throw fe.emit(He.FAIL_NOTIFICATION,JSON.parse(n.message).msg),n}}async earCall(e){try{const{agentInfo:n,monitoredAgentNo:r}=K,{agent_no:i}=n;this.roleData.agentInfo();const{success:o}=e;if(!r)throw new Error(JSON.stringify({code:1,msg:"当前未有监听坐席"}));await(a=>yn(`${Or}/call/whisper`,a))({monitored_agent_no:r,monitor_agent_no:i}),o==null||o({code:0,msg:""})}catch(n){throw fe.emit(He.FAIL_NOTIFICATION,JSON.parse(n.message).msg),n}}async stopEarCall(e){try{const{agentInfo:n,earSpeakAgent:r}=K;if(!r)throw new Error(JSON.stringify({code:1,msg:"当前没有正在耳语的坐席"}));const{agent_no:i}=n;this.roleData.agentInfo();const{success:o}=e;await(a=>yn(`${Or}/call/stopwhisper`,a))({monitor_agent_no:i,monitored_agent_no:r}),o==null||o({code:0,msg:""})}catch(n){throw fe.emit(He.FAIL_NOTIFICATION,JSON.parse(n.message).msg),n}}async forceInsert(e){try{const{agentInfo:n,monitoredAgentNo:r}=K,{agent_no:i}=n;this.roleData.agentInfo();const{success:o}=e;if(!r)throw new Error(JSON.stringify({code:1,msg:"当前未有监听坐席"}));await(a=>yn(`${Or}/call/bargein`,a))({monitored_agent_no:r,monitor_agent_no:i}),o==null||o({code:0,msg:""})}catch(n){throw fe.emit(He.FAIL_NOTIFICATION,JSON.parse(n.message).msg),n}}async forceDisconnect(e){try{const{agentInfo:n,monitoredAgentNo:r}=K,{agent_no:i}=n;this.roleData.agentInfo();const{success:o}=e;if(!r)throw new Error(JSON.stringify({code:1,msg:"当前未有监听坐席"}));await(a=>yn(`${Or}/call/intercept`,a))({monitored_agent_no:r,monitor_agent_no:i}),o==null||o({code:0,msg:""})}catch(n){throw fe.emit(He.FAIL_NOTIFICATION,JSON.parse(n.message).msg),n}}}const Gw=console.log,qg=(...t)=>{K.logBuiltinEnabled&&Gw(...t)};let ni=null;class An{constructor(e,n){this.url=e,this.onOpenCallback=n,this.ws=null,this.heartbeatWorker=null,this.reconnectDelay=3e3,this.manualClose=!1,this.apiClient=new ja,this.sipClient=null,this.pendingMessages=new Map,this.initWebSocket()}static getInstance({url:e,sipClient:n,onOpen:r}){if(!ni){if(!e)throw new Error("WebSocket 尚未初始化");ni=new An(e,r),ni.sipClient=n}return ni}setSipClient(e){this.sipClient=e}stateIdleChange(e){const{state:n}=K.stateObject;n!==Rt.IDLE&&this.apiClient._changeState({data:{...K.stateBeforeChange,state_name:K.stateBeforeChange.state===Rt.IDLE?"空闲":"忙碌"}},e)}inCallAutoAnswer(){const{soft_device_auto_answer:e,auto_answer_time:n}=K.agentInfo,r=e===1,i=G.get("direction");if(r&&i===xn.INCOMING){const o=Number(n)||0;o>0&&(K.autoAnswerTimer=setTimeout(()=>{var a;(a=this.sipClient)==null||a.answerCall(),K.autoAnswerTimer=null},o>0?1e3*o-500:0))}}async getCustomerInfo(e){try{await this.apiClient._getInCallCrmDetail({data:{phone:e},success:n=>{G.updateCustomerInfo(n.data||{phone:n.data.phone,is_vip:0,customer_name:"未知客户",city:"未知",province:"未知",contact_count:0,in_contact_count:0,trace_id:n.data.trace_id,contact_count_month:0,in_contact_count_month:0})}})}catch{}}putAgentState(e,n){if(!e)return;if(n===5)return void this.stateIdleChange("device_type5");K.sessionId="";const{post_call_process_time:r}=K.agentInfo,i=r||0;if(K.autoStateTimer&&(clearTimeout(K.autoStateTimer),K.autoStateTimer=null),G.updateCustomerInfo(void 0),i>0){const{state:o}=K.stateObject;if(o===Rt.IDLE)return;this.apiClient._changeState({data:{state:Rt.BUSY,state_name:"整理"}},"ez"),K.autoStateTimer=setTimeout(()=>{K.autoStateTimer=null,this.stateIdleChange(`delay${i}`)},1e3*i)}else this.stateIdleChange("delay0")}stateBusyChange(){K.sessionId="",clearTimeout(K.autoStateTimer),G.updateCustomerInfo(void 0),this.apiClient._changeState({data:{state:Rt.BUSY,state_name:"忙碌"}},"dm")}initWebSocket(){var n;if(((n=this.ws)==null?void 0:n.readyState)===1||!G.get("isNextState")||this.manualClose)return;const e=P0(Kd,Vd);this.ws=new WebSocket(this.url+e),this.ws.onopen=()=>{const r=new Date().getTime();this.sendMessage({type:0,msg_id:r}),this.pendingMessages.set(r,performance.now()),this.startHeartbeat(),this.manualClose=!1,this.onOpenCallback&&this.onOpenCallback()},this.ws.onmessage=async r=>{var u;const i=JSON.parse(r.data),{type:o,data:a,code:s,msg:A,msg_id:c}=i;if(o===0&&c){const d=this.pendingMessages.get(c),f=performance.now()-d;K.latency=parseFloat(f.toFixed(2)),this.pendingMessages.delete(c)}if(o!==0&&qg("%cWebSocket 收到消息:","color: blue; font-weight: bold;",i),o!==it.OUT_CALL&&o!==it.PREVIEW_OUT_CALL||(K.isAgentHangup=!1,s!==0?(G.reset(),fe.emit(ie.OUT_FAILED,A),fe.emit(He.FAIL_NOTIFICATION,A),G.updateActionConfigs(Vn),setTimeout(()=>{G.updateCustomerInfo(void 0)},500),this.stateIdleChange("h")):s===0&&(fe.emit(ie.OUT_SUCCESS),K.sessionId=a.session_id,G.updateIsCalling(!0),clearTimeout(K.autoStateTimer))),o===it.AGENT_STATE){const{state:d,state_name:f}=a;K.stateObject={state:d,state_name:f},(u=K.stateBeforeChange)!=null&&u.state||K.stateObject.state!==Rt.IDLE&&(K.stateObject.state!==Rt.BUSY||f==="整理")||(K.stateBeforeChange=K.stateObject),f==="振铃中"&&G.updateDisplayText(Kt.AGENT_RINGING);const p=G.get("isCalling");d!==Rt.UNREGISTERED||p||G.updateActionConfigs(Fw),d===Rt.IDLE&&K.stateObject.state===Rt.UNREGISTERED&&G.updateActionConfigs(Vn),fe.emit(ie.AGENT_STATE,{state:d,state_name:f})}else if(o===it.OUT_CALL_INCOMING_CALL){K.isAgentHangup=!1;try{await this.getCustomerInfo(a.trace_id||a.customer_phone)}catch(d){console.error(d)}a.preview_task_id?fe.emit(ie.PREVIEW_OUT_INCOMING_CALL,{customer_phone:a.customer_phone,session_id:a.session_id,preview_task_id:a.preview_task_id,trace_id:a.trace_id}):a.direction===0?fe.emit(ie.OUT_INCOMING_CALL,{customer_phone:a.customer_phone,session_id:a.session_id,trace_id:a.trace_id}):a.direction===8&&fe.emit(ie.INTERNAL_OUT_INCOMING_CALL,{customer_phone:a.customer_phone,session_id:a.session_id,trace_id:a.trace_id}),K.sessionId=a.session_id,G.updateActionConfigs(kw,a.direction!==8)}else if(o===it.OUT_CALL_END){if(K.sessionId!==a.session_id)return;if(G.updateDisplayText(""),a.device_type===1&&a.agent_no===K.agentInfo.agent_no)G.reset(),fe.emit(ie.OUT_HANGUP,{session_id:a.session_id,isAgentHangup:K.isAgentHangup}),G.updateActionConfigs(Vn),this.putAgentState(!0);else if(a.device_type===2&&a.agent_no===K.agentInfo.agent_no)G.reset(),fe.emit(ie.OUR_SIDE_CONSULT_HANGUP,{session_id:a.session_id}),G.updateActionConfigs(Vn),this.putAgentState(!0);else if(a.device_type===2&&a.agent_no!==K.agentInfo.agent_no)G.get("isCalling")&&(G.updateDisplayText(Kt.CALLING),fe.emit(ie.OTHER_SIDE_CONSULT_HANGUP,{session_id:a.session_id,isAgentHangup:K.isAgentHangup}),G.updateActionConfigs(Ci));else if(a.device_type===3&&a.agent_no===K.agentInfo.agent_no)G.reset(),fe.emit(ie.THREE_WAY_OUR_SIDE_HANGUP,{session_id:a.session_id}),G.updateActionConfigs(Vn),this.putAgentState(!0);else if(a.device_type===4&&a.agent_no===K.agentInfo.agent_no)G.reset(),fe.emit(ie.TRANSFER_END,{session_id:a.session_id}),G.updateActionConfigs(Vn),this.putAgentState(!0);else if(a.device_type===4&&a.agent_no!==K.agentInfo.agent_no){fe.emit(ie.TRANSFER_FAILED,"未知原因"),fe.emit(He.FAIL_NOTIFICATION,"转接失败");const d=G.get("direction");d===xn.OUTGOING?G.updateActionConfigs(Ci):d===xn.INCOMING&&G.updateActionConfigs(Gi)}else a.device_type===5&&a.agent_no===K.agentInfo.agent_no&&(K.monitoredAgentNo="",K.earSpeakAgent="",G.reset(),fe.emit(ie.LISTEN_HANGUP,{session_id:a.session_id}),G.updateActionConfigs(Vn),this.putAgentState(!0,5))}else if(o===it.OUT_CALL_RINGING)a.type===1&&(K.isAgentHangup=!1,fe.emit(ie.OUT_RINGING,{session_id:K.sessionId,type:a.type}),G.updateDisplayText(Kt.RINGING));else if(o===it.OUT_CALL_ANSWER)K.isAgentHangup=!1,clearTimeout(K.autoStateTimer),G.updateIsCalling(!0),G.updateOutCallIsAnswer(!0),G.updateDisplayText(Kt.CALLING),a.direction===8?(fe.emit(ie.INTERNAL_OUT_OFF_ANSWER,{session_id:K.sessionId}),G.updateActionConfigs(Yc)):(fe.emit(ie.OUT_OFF_ANSWER,{session_id:K.sessionId}),G.updateActionConfigs(Ci));else if(o===it.CONSULT_RINGING)K.isAgentHangup=!1,fe.emit(ie.CONSULT_RINGING,{session_id:a.session_id}),G.updateDisplayText(Kt.AGENT_RINGING),G.updateActionConfigs([]),clearTimeout(K.autoStateTimer);else if(o===it.CONSULT_ANSWER)K.isAgentHangup=!1,fe.emit(ie.CONSULT_OFF_HOOK,{session_id:a.session_id}),G.updateConsultIsAnswer(!0),G.updateDisplayText(Kt.CONSULTING),G.updateActionConfigs(Hg);else if(o===it.CONSULT_FAIL)fe.emit(ie.CONSULT_FAILED,{custom_reason:a.custom_reason}),G.updateDisplayText(Kt.CALLING),G.updateActionConfigs(Ci);else if(o===it.CONSULT_CALL_IN)K.isAgentHangup=!1,fe.emit(ie.CONSULT_INCOMING,{agent_no:a.agent_no,agent_mane:a.agent_name,session_id:a.session_id}),K.sessionId=a.session_id,G.updateIsCalling(!0),G.updateDirection(xn.CONSULT),G.updateDisplayText(Kt.CONSULT_CALL_IN),G.updateActionConfigs(Os),K.enableBrowserAlert&&To.show("📞 咨询来电",`坐席 [${a.agent_name}] 正在咨询...`,()=>{fe.emit(He.NOTIFICATION_CLICK,{agent_mane:a.agent_name,agent_no:a.agent_no})},K.browserAlertTime);else if(o===it.CONSULT_CALL_IN_SUCCESS)fe.emit(ie.CONSULT_CALL_IN_SUCCESS,{session_id:a.session_id}),G.updateConsultIsAnswer(!0),G.updateDisplayText(Kt.CALLING),G.updateActionConfigs(Pw);else if(o===it.CONSULT_RETURN_CALL_SUCCESS)a.status==="success"?(G.updateConsultIsAnswer(!1),fe.emit(ie.CONSULT_RETURN_CALL_SUCCESS),G.updateDisplayText(Kt.CALLING),fe.emit(ie.OTHER_SIDE_CONSULT_HANGUP),G.updateActionConfigs(Ci)):fe.emit(He.FAIL_NOTIFICATION,"媒体失败");else if(o===it.MUTE)s===0?(G.updateIsMuted(!0),fe.emit(ie.MUTE_SUCCESS),G.updateDisplayText(Kt.MUTING)):(fe.emit(ie.MUTE_FAILED,A),fe.emit(He.FAIL_NOTIFICATION,A));else if(o===it.UNMUTE)s===0?(G.updateIsMuted(!1),fe.emit(ie.UNMUTE_SUCCESS),G.updateDisplayText(Kt.CALLING)):(fe.emit(ie.UNMUTE_FAILED,A),fe.emit(He.FAIL_NOTIFICATION,A));else if(o===it.CALL_HOLD)s===0?(G.updateIsHold(!0),G.updateDisplayText(Kt.HOLDING),fe.emit(ie.HOLD_SUCCESS)):(fe.emit(ie.HOLD_FAILED,A),fe.emit(He.FAIL_NOTIFICATION,A));else if(o===it.CALL_UNHOLD)s===0?(G.updateDisplayText(Kt.CALLING),G.updateIsHold(!1),fe.emit(ie.UNHOLD_SUCCESS)):(fe.emit(ie.UNHOLD_FAILED,A),fe.emit(He.FAIL_NOTIFICATION,A));else if(o===it.CONSULT_TRANSFER)K.isAgentHangup=!1,s===0?fe.emit(ie.CONSULT_TRANSFER_SUCCESS):(fe.emit(ie.CONSULT_TRANSFER_FAILED,A),fe.emit(He.FAIL_NOTIFICATION,A));else if(o===it.CONSULT_TRANSFER_FAILED)fe.emit(ie.CONSULT_TRANSFER_FAILED,a.status);else if(o===it.CONSULT_TRANSFER_OFF_HOOK)G.updateDirection(xn.INCOMING),G.updateDisplayText(Kt.CALLING),fe.emit(ie.CONSULT_TRANSFER_OFF_HOOK),G.updateActionConfigs(Gi),G.updateIncomingIsAnswer(!0),G.updateConsultIsAnswer(!1);else if(o===it.INCOMING_CALL){K.isAgentHangup=!1,clearTimeout(K.autoStateTimer),K.sessionId=a.session_id;try{await this.getCustomerInfo(a.trace_id||a.customer_phone)}catch(d){console.error(d)}G.updateIsCalling(!0),G.updateDirection(xn.INCOMING),G.updateDisplayText(Kt.INCOMING_CALL),this.inCallAutoAnswer(),a.direction===1&&fe.emit(ie.INCOMING_CALL,{customer_phone:a.customer_phone,trace_id:a.trace_id,session_id:a.session_id}),a.direction===8&&fe.emit(ie.INCOMING_CALL_IN,{customer_phone:a.customer_phone,trace_id:a.trace_id,session_id:a.session_id}),a.direction===3&&fe.emit(ie.PREDICT_INCOMING_CALL,{customer_phone:a.customer_phone,trace_id:a.trace_id,session_id:a.session_id}),a.direction===6&&fe.emit(ie.DUAL_CALL_INCOMING_CALL,{customer_phone:a.customer_phone,trace_id:a.trace_id,session_id:a.session_id}),G.updateActionConfigs(Os),K.enableBrowserAlert&&To.show("📞 客户来电",`客户 [${a.customer_phone}] 正在呼入...`,()=>{fe.emit(He.NOTIFICATION_CLICK,{customer_phone:a.customer_phone})},K.browserAlertTime)}else if(o===it.INCOMING_CALL_OFF_HOOK)G.updateIncomingIsAnswer(!0),a.direction===8?(G.updateActionConfigs(Yc),fe.emit(ie.INCOMING_CALL_IN_OFF_HOOK,{session_id:K.sessionId})):(G.updateActionConfigs(Gi),fe.emit(ie.INCOMING_CALL_OFF_HOOK,{session_id:K.sessionId})),G.updateDisplayText(Kt.CALLING);else if(o===it.INCOMING_CALL_END){if(K.sessionId!==a.session_id)return;if(G.updateDisplayText(""),a.device_type!==1&&a.device_type!==7||a.agent_no!==K.agentInfo.agent_no)if(a.device_type===2&&a.agent_no===K.agentInfo.agent_no)G.reset(),fe.emit(ie.OUR_SIDE_CONSULT_HANGUP,{session_id:a.session_id}),this.putAgentState(!0),G.updateActionConfigs(Vn);else if(a.device_type===2&&a.agent_no!==K.agentInfo.agent_no)G.updateDisplayText(Kt.CALLING),fe.emit(ie.OTHER_SIDE_CONSULT_HANGUP,{session_id:a.session_id,isAgentHangup:K.isAgentHangup}),G.updateActionConfigs(Ci);else if(a.device_type===3&&a.agent_no===K.agentInfo.agent_no)this.putAgentState(!0),G.reset(),fe.emit(ie.THREE_WAY_OUR_SIDE_HANGUP,{session_id:a.session_id}),G.updateActionConfigs(Vn);else if(a.device_type===4&&a.agent_no===K.agentInfo.agent_no)this.putAgentState(!0),G.reset(),fe.emit(ie.TRANSFER_END,{session_id:a.session_id}),G.updateActionConfigs(Vn);else if(a.device_type===4&&a.agent_no!==K.agentInfo.agent_no){fe.emit(ie.TRANSFER_FAILED,"未知原因"),fe.emit(He.FAIL_NOTIFICATION,"转接失败");const d=G.get("direction");d===xn.OUTGOING?G.updateActionConfigs(Ci):d===xn.INCOMING&&G.updateActionConfigs(Gi)}else a.device_type===5&&a.agent_no===K.agentInfo.agent_no&&(this.putAgentState(!0,5),K.monitoredAgentNo="",K.earSpeakAgent="",G.reset(),fe.emit(ie.LISTEN_HANGUP,{session_id:a.session_id}),G.updateActionConfigs(Vn));else this.putAgentState(!0),G.reset(),fe.emit(ie.INCOMING_CALL_END,{session_id:a.session_id,isAgentHangup:K.isAgentHangup}),G.updateActionConfigs(Vn)}else if(o===it.SATISFACTION_EVALUATION)s===0?fe.emit(ie.SATISFACTION_EVALUATION_SUCCESS):(fe.emit(ie.SATISFACTION_EVALUATION_FAILED,A),fe.emit(He.FAIL_NOTIFICATION,A));else if(o===it.CONSULT_THREE_WAY)s!==0?(fe.emit(ie.CONSULT_THREE_WAY_FAILED,A),fe.emit(He.FAIL_NOTIFICATION,A)):s===0&&G.updateIsMeeting(!0);else if(o===it.CONSULT_THREE_WAY_RESULT)a.status==="success"?(G.updateDirection(xn.MEETING),G.updateDisplayText(Kt.MEETING),G.updateActionConfigs(Qw),fe.emit(ie.CONSULT_THREE_WAY_SUCCESS)):(fe.emit(ie.CONSULT_THREE_WAY_FAILED,{conf_name:a.conf_name}),G.updateIsMeeting(!1));else if(o===it.TRANSFER_INCOMING_CALL)K.isAgentHangup=!1,clearTimeout(K.autoStateTimer),a.agent_no===K.agentInfo.agent_no?(G.updateDisplayText(Kt.TRANSFERRING),fe.emit(ie.TRANSFER_PROGRESS),G.updateActionConfigs([]),G.updateTransferIsAnswer(!0)):(K.sessionId=a.session_id,fe.emit(ie.TRANSFER_INCOMING_CALL,{agent_no:a.agent_no,agent_name:a.agent_name,session_id:a.session_id}),G.updateIsCalling(!0),G.updateDirection(xn.TRANSFER),G.updateDisplayText(Kt.TRANSFER_INCOMING_CALL),G.updateActionConfigs(Os),K.enableBrowserAlert&&To.show("📞 转接来电",`坐席 [${a.agent_no}] 正在转接...`,()=>{fe.emit(He.NOTIFICATION_CLICK,{agent_no:a.agent_no})},K.browserAlertTime));else if(o===it.TRANSFER_OFF_HOOK)fe.emit(ie.TRANSFER_OFF_HOOK,{session_id:K.sessionId}),G.updateTransferIsAnswer(!1),G.updateDisplayText(Kt.CALLING),G.updateActionConfigs(Gi,a.direction!==8);else if(o===it.TRANSFER_FAILED){if(a.status==="failed"){fe.emit(ie.TRANSFER_FAILED,"未知原因"),fe.emit(He.FAIL_NOTIFICATION,"转接失败");const d=G.get("direction");d===xn.OUTGOING?G.updateActionConfigs(Ci):d===xn.INCOMING&&G.updateActionConfigs(Gi)}}else o===it.KICK_OFFLINE?fe.emit(He.KICK_OFF):o===it.CONTINUOUS_NOT_ANSWER?(fe.emit(He.FAIL_NOTIFICATION,`已连续 ${a.miss_count} 次未接, 设置忙碌`),this.stateBusyChange()):o===it.SIGN_OUT?fe.emit(He.SIGN_OUT):o===it.SIGN_IN_SWITCH_DEVICE?fe.emit(He.SIGN_IN_SWITCH_DEVICE,a):o===it.LISTEN_INCOMING_CALL?(clearTimeout(K.autoStateTimer),K.sessionId=a.session_id,G.updateIsCalling(!0),G.updateDirection(xn.INCOMING),this.inCallAutoAnswer(),G.updateDisplayText(Kt.LISTENING),G.updateActionConfigs(Os),fe.emit(ie.LISTEN_INCOMING_CALL,{session_id:a.session_id}),K.enableBrowserAlert&&To.show("📞 监听来电","正在来电...",()=>{fe.emit(He.NOTIFICATION_CLICK,{customer_phone:a.customer_phone})},K.browserAlertTime)):o===it.LISTEN_INCOMING_CALL_OFF_HOOK?(K.monitoredAgentNo=a.monitored_agent_no,K.earSpeakAgent="",G.updateIncomingIsAnswer(!0),fe.emit(ie.LISTEN_INCOMING_CALL_OFF_HOOK,{session_id:K.sessionId,monitored_agent_no:a.monitored_agent_no}),G.updateActionConfigs(Gg),G.updateDisplayText(Kt.CALLING)):o===it.LISTEN_CALL_FAILED?a.status==="failed"&&(fe.emit(ie.LISTEN_CALL_FAILED),K.monitoredAgentNo=""):o===it.EAR_SPEECH?a.status==="success"?(a.monitored_agent_no===K.agentInfo.agent_no&&(G.updateActionConfigs(jw),fe.emit(ie.EAR_SPEECH_BE_SUCCESS)),a.monitor_agent_no===K.agentInfo.agent_no&&(G.updateActionConfigs(Lw),fe.emit(ie.EAR_SPEECH_SUCCESS,{monitored_agent_no:a.monitored_agent_no,monitor_agent_no:a.monitor_agent_no}),K.earSpeakAgent=a.monitored_agent_no)):fe.emit(ie.EAR_SPEECH_FAILED):o===it.STOP_EAR_SPEECH?a.status==="success"?(a.monitored_agent_no===K.agentInfo.agent_no&&G.updateActionConfigs(Gi),a.monitor_agent_no===K.agentInfo.agent_no&&G.updateActionConfigs(Gg),K.earSpeakAgent="",fe.emit(ie.STOP_EAR_SPEECH_SUCCESS)):fe.emit(ie.STOP_EAR_SPEECH_FAILED):o===it.CALL_FORCE_INSERT?a.status==="success"?(a.monitored_agent_no===K.agentInfo.agent_no&&(G.updateActionConfigs(Hw),fe.emit(ie.CALL_FORCE_INSERT_SUCCESS,{monitored_agent_no:a.monitored_agent_no,monitor_agent_no:a.monitor_agent_no})),a.monitor_agent_no===K.agentInfo.agent_no&&(G.updateActionConfigs(Uw),fe.emit(ie.CALL_FORCE_INSERT_SUCCESS_LISTENER,{monitored_agent_no:a.monitored_agent_no,monitor_agent_no:a.monitor_agent_no}))):fe.emit(ie.CALL_FORCE_INSERT_FAILED):o===it.INTERNAL_CALL_START_CONSULT?a.agent_no===K.agentInfo.agent_no?(G.updateConsultIsAnswer(!0),G.updateActionConfigs(Hg),G.updateDisplayText(Kt.CONSULTING)):(G.updateDisplayText(Kt.OTHER_SIDE_CONSULTING),G.updateActionConfigs([])):o===it.INTERNAL_CALL_END_CONSULT?(G.updateActionConfigs(Yc),G.updateDisplayText(""),G.updateConsultIsAnswer(!1)):o===it.CALL_SIP_INCOMING_CALL&&fe.emit(ie.CALL_SIP_INCOMING_CALL)},this.ws.onclose=r=>{fe.emit(He.FAIL_NOTIFICATION,"链接已断开,请检查网络"),this.stopHeartbeat();const i=G.get("isNextState");!this.manualClose&&i&&setTimeout(()=>this.initWebSocket(),this.reconnectDelay)},this.ws.onerror=r=>{var i;fe.emit(He.FAIL_NOTIFICATION,"连接失败,请检查网络"),(i=this.ws)==null||i.close()}}startHeartbeat(){const e=new Blob([`
163
+ */Vc=k0,function(){var t="input is invalid type",e=typeof window=="object",n=e?window:{};n.JS_MD5_NO_WINDOW&&(e=!1);var r=!e&&typeof self=="object",i=!n.JS_MD5_NO_NODE_JS&&typeof process=="object"&&process.versions&&process.versions.node;i?n=Tw:r&&(n=self);var o,a=!n.JS_MD5_NO_COMMON_JS&&Vc.exports,s=!n.JS_MD5_NO_ARRAY_BUFFER&&typeof ArrayBuffer<"u",A="0123456789abcdef".split(""),c=[128,32768,8388608,-2147483648],u=[0,8,16,24],d=["hex","array","digest","buffer","arrayBuffer","base64"],f="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),p=[];if(s){var v=new ArrayBuffer(68);o=new Uint8Array(v),p=new Uint32Array(v)}var C=Array.isArray;!n.JS_MD5_NO_NODE_JS&&C||(C=function(E){return Object.prototype.toString.call(E)==="[object Array]"});var m=ArrayBuffer.isView;!s||!n.JS_MD5_NO_ARRAY_BUFFER_IS_VIEW&&m||(m=function(E){return typeof E=="object"&&E.buffer&&E.buffer.constructor===ArrayBuffer});var y=function(E){var b=typeof E;if(b==="string")return[E,!0];if(b!=="object"||E===null)throw new Error(t);if(s&&E.constructor===ArrayBuffer)return[new Uint8Array(E),!1];if(!C(E)&&!m(E))throw new Error(t);return[E,!1]},w=function(E){return function(b){return new x(!0).update(b)[E]()}},I=function(E){var b,h=Og,S=Og.Buffer;return b=S.from&&!n.JS_MD5_NO_BUFFER_FROM?S.from:function(T){return new S(T)},function(T){if(typeof T=="string")return h.createHash("md5").update(T,"utf8").digest("hex");if(T==null)throw new Error(t);return T.constructor===ArrayBuffer&&(T=new Uint8Array(T)),C(T)||m(T)||T.constructor===S?h.createHash("md5").update(b(T)).digest("hex"):E(T)}},O=function(E){return function(b,h){return new g(b,!0).update(h)[E]()}};function x(E){if(E)p[0]=p[16]=p[1]=p[2]=p[3]=p[4]=p[5]=p[6]=p[7]=p[8]=p[9]=p[10]=p[11]=p[12]=p[13]=p[14]=p[15]=0,this.blocks=p,this.buffer8=o;else if(s){var b=new ArrayBuffer(68);this.buffer8=new Uint8Array(b),this.blocks=new Uint32Array(b)}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 g(E,b){var h,S=y(E);if(E=S[0],S[1]){var T,R=[],D=E.length,B=0;for(h=0;h<D;++h)(T=E.charCodeAt(h))<128?R[B++]=T:T<2048?(R[B++]=192|T>>>6,R[B++]=128|63&T):T<55296||T>=57344?(R[B++]=224|T>>>12,R[B++]=128|T>>>6&63,R[B++]=128|63&T):(T=65536+((1023&T)<<10|1023&E.charCodeAt(++h)),R[B++]=240|T>>>18,R[B++]=128|T>>>12&63,R[B++]=128|T>>>6&63,R[B++]=128|63&T);E=R}E.length>64&&(E=new x(!0).update(E).array());var k=[],P=[];for(h=0;h<64;++h){var H=E[h]||0;k[h]=92^H,P[h]=54^H}x.call(this,b),this.update(P),this.oKeyPad=k,this.inner=!0,this.sharedMemory=b}x.prototype.update=function(E){if(this.finalized)throw new Error("finalize already called");var b=y(E);E=b[0];for(var h,S,T=b[1],R=0,D=E.length,B=this.blocks,k=this.buffer8;R<D;){if(this.hashed&&(this.hashed=!1,B[0]=B[16],B[16]=B[1]=B[2]=B[3]=B[4]=B[5]=B[6]=B[7]=B[8]=B[9]=B[10]=B[11]=B[12]=B[13]=B[14]=B[15]=0),T)if(s)for(S=this.start;R<D&&S<64;++R)(h=E.charCodeAt(R))<128?k[S++]=h:h<2048?(k[S++]=192|h>>>6,k[S++]=128|63&h):h<55296||h>=57344?(k[S++]=224|h>>>12,k[S++]=128|h>>>6&63,k[S++]=128|63&h):(h=65536+((1023&h)<<10|1023&E.charCodeAt(++R)),k[S++]=240|h>>>18,k[S++]=128|h>>>12&63,k[S++]=128|h>>>6&63,k[S++]=128|63&h);else for(S=this.start;R<D&&S<64;++R)(h=E.charCodeAt(R))<128?B[S>>>2]|=h<<u[3&S++]:h<2048?(B[S>>>2]|=(192|h>>>6)<<u[3&S++],B[S>>>2]|=(128|63&h)<<u[3&S++]):h<55296||h>=57344?(B[S>>>2]|=(224|h>>>12)<<u[3&S++],B[S>>>2]|=(128|h>>>6&63)<<u[3&S++],B[S>>>2]|=(128|63&h)<<u[3&S++]):(h=65536+((1023&h)<<10|1023&E.charCodeAt(++R)),B[S>>>2]|=(240|h>>>18)<<u[3&S++],B[S>>>2]|=(128|h>>>12&63)<<u[3&S++],B[S>>>2]|=(128|h>>>6&63)<<u[3&S++],B[S>>>2]|=(128|63&h)<<u[3&S++]);else if(s)for(S=this.start;R<D&&S<64;++R)k[S++]=E[R];else for(S=this.start;R<D&&S<64;++R)B[S>>>2]|=E[R]<<u[3&S++];this.lastByteIndex=S,this.bytes+=S-this.start,S>=64?(this.start=S-64,this.hash(),this.hashed=!0):this.start=S}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296|0,this.bytes=this.bytes%4294967296),this},x.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var E=this.blocks,b=this.lastByteIndex;E[b>>>2]|=c[3&b],b>=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()}},x.prototype.hash=function(){var E,b,h,S,T,R,D=this.blocks;this.first?b=((b=((E=((E=D[0]-680876937)<<7|E>>>25)-271733879|0)^(h=((h=(-271733879^(S=((S=(-1732584194^2004318071&E)+D[1]-117830708)<<12|S>>>20)+E|0)&(-271733879^E))+D[2]-1126478375)<<17|h>>>15)+S|0)&(S^E))+D[3]-1316259209)<<22|b>>>10)+h|0:(E=this.h0,b=this.h1,h=this.h2,b=((b+=((E=((E+=((S=this.h3)^b&(h^S))+D[0]-680876936)<<7|E>>>25)+b|0)^(h=((h+=(b^(S=((S+=(h^E&(b^h))+D[1]-389564586)<<12|S>>>20)+E|0)&(E^b))+D[2]+606105819)<<17|h>>>15)+S|0)&(S^E))+D[3]-1044525330)<<22|b>>>10)+h|0),b=((b+=((E=((E+=(S^b&(h^S))+D[4]-176418897)<<7|E>>>25)+b|0)^(h=((h+=(b^(S=((S+=(h^E&(b^h))+D[5]+1200080426)<<12|S>>>20)+E|0)&(E^b))+D[6]-1473231341)<<17|h>>>15)+S|0)&(S^E))+D[7]-45705983)<<22|b>>>10)+h|0,b=((b+=((E=((E+=(S^b&(h^S))+D[8]+1770035416)<<7|E>>>25)+b|0)^(h=((h+=(b^(S=((S+=(h^E&(b^h))+D[9]-1958414417)<<12|S>>>20)+E|0)&(E^b))+D[10]-42063)<<17|h>>>15)+S|0)&(S^E))+D[11]-1990404162)<<22|b>>>10)+h|0,b=((b+=((E=((E+=(S^b&(h^S))+D[12]+1804603682)<<7|E>>>25)+b|0)^(h=((h+=(b^(S=((S+=(h^E&(b^h))+D[13]-40341101)<<12|S>>>20)+E|0)&(E^b))+D[14]-1502002290)<<17|h>>>15)+S|0)&(S^E))+D[15]+1236535329)<<22|b>>>10)+h|0,b=((b+=((S=((S+=(b^h&((E=((E+=(h^S&(b^h))+D[1]-165796510)<<5|E>>>27)+b|0)^b))+D[6]-1069501632)<<9|S>>>23)+E|0)^E&((h=((h+=(E^b&(S^E))+D[11]+643717713)<<14|h>>>18)+S|0)^S))+D[0]-373897302)<<20|b>>>12)+h|0,b=((b+=((S=((S+=(b^h&((E=((E+=(h^S&(b^h))+D[5]-701558691)<<5|E>>>27)+b|0)^b))+D[10]+38016083)<<9|S>>>23)+E|0)^E&((h=((h+=(E^b&(S^E))+D[15]-660478335)<<14|h>>>18)+S|0)^S))+D[4]-405537848)<<20|b>>>12)+h|0,b=((b+=((S=((S+=(b^h&((E=((E+=(h^S&(b^h))+D[9]+568446438)<<5|E>>>27)+b|0)^b))+D[14]-1019803690)<<9|S>>>23)+E|0)^E&((h=((h+=(E^b&(S^E))+D[3]-187363961)<<14|h>>>18)+S|0)^S))+D[8]+1163531501)<<20|b>>>12)+h|0,b=((b+=((S=((S+=(b^h&((E=((E+=(h^S&(b^h))+D[13]-1444681467)<<5|E>>>27)+b|0)^b))+D[2]-51403784)<<9|S>>>23)+E|0)^E&((h=((h+=(E^b&(S^E))+D[7]+1735328473)<<14|h>>>18)+S|0)^S))+D[12]-1926607734)<<20|b>>>12)+h|0,b=((b+=((R=(S=((S+=((T=b^h)^(E=((E+=(T^S)+D[5]-378558)<<4|E>>>28)+b|0))+D[8]-2022574463)<<11|S>>>21)+E|0)^E)^(h=((h+=(R^b)+D[11]+1839030562)<<16|h>>>16)+S|0))+D[14]-35309556)<<23|b>>>9)+h|0,b=((b+=((R=(S=((S+=((T=b^h)^(E=((E+=(T^S)+D[1]-1530992060)<<4|E>>>28)+b|0))+D[4]+1272893353)<<11|S>>>21)+E|0)^E)^(h=((h+=(R^b)+D[7]-155497632)<<16|h>>>16)+S|0))+D[10]-1094730640)<<23|b>>>9)+h|0,b=((b+=((R=(S=((S+=((T=b^h)^(E=((E+=(T^S)+D[13]+681279174)<<4|E>>>28)+b|0))+D[0]-358537222)<<11|S>>>21)+E|0)^E)^(h=((h+=(R^b)+D[3]-722521979)<<16|h>>>16)+S|0))+D[6]+76029189)<<23|b>>>9)+h|0,b=((b+=((R=(S=((S+=((T=b^h)^(E=((E+=(T^S)+D[9]-640364487)<<4|E>>>28)+b|0))+D[12]-421815835)<<11|S>>>21)+E|0)^E)^(h=((h+=(R^b)+D[15]+530742520)<<16|h>>>16)+S|0))+D[2]-995338651)<<23|b>>>9)+h|0,b=((b+=((S=((S+=(b^((E=((E+=(h^(b|~S))+D[0]-198630844)<<6|E>>>26)+b|0)|~h))+D[7]+1126891415)<<10|S>>>22)+E|0)^((h=((h+=(E^(S|~b))+D[14]-1416354905)<<15|h>>>17)+S|0)|~E))+D[5]-57434055)<<21|b>>>11)+h|0,b=((b+=((S=((S+=(b^((E=((E+=(h^(b|~S))+D[12]+1700485571)<<6|E>>>26)+b|0)|~h))+D[3]-1894986606)<<10|S>>>22)+E|0)^((h=((h+=(E^(S|~b))+D[10]-1051523)<<15|h>>>17)+S|0)|~E))+D[1]-2054922799)<<21|b>>>11)+h|0,b=((b+=((S=((S+=(b^((E=((E+=(h^(b|~S))+D[8]+1873313359)<<6|E>>>26)+b|0)|~h))+D[15]-30611744)<<10|S>>>22)+E|0)^((h=((h+=(E^(S|~b))+D[6]-1560198380)<<15|h>>>17)+S|0)|~E))+D[13]+1309151649)<<21|b>>>11)+h|0,b=((b+=((S=((S+=(b^((E=((E+=(h^(b|~S))+D[4]-145523070)<<6|E>>>26)+b|0)|~h))+D[11]-1120210379)<<10|S>>>22)+E|0)^((h=((h+=(E^(S|~b))+D[2]+718787259)<<15|h>>>17)+S|0)|~E))+D[9]-343485551)<<21|b>>>11)+h|0,this.first?(this.h0=E+1732584193|0,this.h1=b-271733879|0,this.h2=h-1732584194|0,this.h3=S+271733878|0,this.first=!1):(this.h0=this.h0+E|0,this.h1=this.h1+b|0,this.h2=this.h2+h|0,this.h3=this.h3+S|0)},x.prototype.hex=function(){this.finalize();var E=this.h0,b=this.h1,h=this.h2,S=this.h3;return A[E>>>4&15]+A[15&E]+A[E>>>12&15]+A[E>>>8&15]+A[E>>>20&15]+A[E>>>16&15]+A[E>>>28&15]+A[E>>>24&15]+A[b>>>4&15]+A[15&b]+A[b>>>12&15]+A[b>>>8&15]+A[b>>>20&15]+A[b>>>16&15]+A[b>>>28&15]+A[b>>>24&15]+A[h>>>4&15]+A[15&h]+A[h>>>12&15]+A[h>>>8&15]+A[h>>>20&15]+A[h>>>16&15]+A[h>>>28&15]+A[h>>>24&15]+A[S>>>4&15]+A[15&S]+A[S>>>12&15]+A[S>>>8&15]+A[S>>>20&15]+A[S>>>16&15]+A[S>>>28&15]+A[S>>>24&15]},x.prototype.toString=x.prototype.hex,x.prototype.digest=function(){this.finalize();var E=this.h0,b=this.h1,h=this.h2,S=this.h3;return[255&E,E>>>8&255,E>>>16&255,E>>>24&255,255&b,b>>>8&255,b>>>16&255,b>>>24&255,255&h,h>>>8&255,h>>>16&255,h>>>24&255,255&S,S>>>8&255,S>>>16&255,S>>>24&255]},x.prototype.array=x.prototype.digest,x.prototype.arrayBuffer=function(){this.finalize();var E=new ArrayBuffer(16),b=new Uint32Array(E);return b[0]=this.h0,b[1]=this.h1,b[2]=this.h2,b[3]=this.h3,E},x.prototype.buffer=x.prototype.arrayBuffer,x.prototype.base64=function(){for(var E,b,h,S="",T=this.array(),R=0;R<15;)E=T[R++],b=T[R++],h=T[R++],S+=f[E>>>2]+f[63&(E<<4|b>>>4)]+f[63&(b<<2|h>>>6)]+f[63&h];return E=T[R],S+=f[E>>>2]+f[E<<4&63]+"=="},g.prototype=new x,g.prototype.finalize=function(){if(x.prototype.finalize.call(this),this.inner){this.inner=!1;var E=this.array();x.call(this,this.sharedMemory),this.update(this.oKeyPad),this.update(E),x.prototype.finalize.call(this)}};var M=function(){var E=w("hex");i&&(E=I(E)),E.create=function(){return new x},E.update=function(S){return E.create().update(S)};for(var b=0;b<d.length;++b){var h=d[b];E[h]=w(h)}return E}();M.md5=M,M.md5.hmac=function(){var E=O("hex");E.create=function(S){return new g(S)},E.update=function(S,T){return E.create(S).update(T)};for(var b=0;b<d.length;++b){var h=d[b];E[h]=O(h)}return E}(),a?Vc.exports=M:n.md5=M}();var Nw=k0.exports;const P0=(t,e)=>{const n=Date.now(),r=`${t}:${n}:${Nw.md5(`${e}${n}`)}`,i=new TextEncoder().encode(r);return btoa(String.fromCharCode(...i))},iu=t=>{if(/^\d+$/.test(t)||!t||typeof t!="string"||t.length%4!=0||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t))return!1;try{const e=atob(t);return btoa(e)===t}catch{return!1}},Yi="/v1/aicc/bmserver",Or="/v1/aicc/ccs";let Si="",Kd="",Vd="",zc="";function Q0(t){const e=P0(Kd,Vd);return Mw.create({prefixUrl:`${Si}`,timeout:!1,headers:{Authorization:e,...t},hooks:{afterResponse:[async(n,r,i)=>{if(i.url.indexOf("heartbeat")!==-1)return i;const o=await i.clone().json();if(o.code!==0)throw new Error(JSON.stringify(o)||"请求失败");return i.json=async()=>o,i}]}})}async function yn(t,e,n){const r=Q0(n),i="api/"+t.replace(/^\/+/,"");return r.post(i,{json:e}).json()}const Ug=(t,e)=>yn(`${Or}/state/change?h=${e}`,t,{h:e}),Dw=()=>async function(t,e){const n=Q0(),r=t.replace(/^\/+/,"");return n.post(r,{json:e}).json()}("/heartbeat",{});class nn{static log(e,n={}){const{level:r="info",module:i="",timestamp:o=!0}=n;if(K.logBuiltinEnabled){const A=i?`[${i}]`:"",c=o?`[${new Date().toLocaleString()}]`:"";switch(r){case"debug":break;case"warn":console.warn(`${c}${A} ${e}`);break;case"error":console.error(`${c}${A} ${e}`)}}const a=K.agentInfo.agent_no;if(a){const A=JSON.stringify({level:r,module:i,content:e,timestamp:new Date().toISOString()});(s={agent_no:a,content:A},yn("/v1/aicc/ccs/softphone/log",s)).catch(()=>{})}var s}static debug(e,n){this.log(e,{level:"debug",module:n})}static info(e,n){this.log(e,{level:"info",module:n})}static warn(e,n){this.log(e,{level:"warn",module:n})}static error(e,n){this.log(e,{level:"error",module:n})}static errorObj(e,n){const r=JSON.stringify({message:e.message,stack:e.stack,name:e.name});this.log(r,{level:"error",module:n})}}class Bw{constructor(e,n){this.config=e,this.eventCallback=n,this.userAgent=null,this.registerer=null,this.activeSession=null,this.callTimeoutTimer=null,this.incomingInvitation=null,this.reconnectAttempts=0,this.maxReconnectAttempts=5,this.reconnectTimer=null,this.isOffline=!1,this.isManuallyStopped=!1,this.registerInterval=6e4,this.handleNetworkInfoChange=r=>{var i,o;if((i=r.rttObject)!=null&&i.rtt){const a=(o=r.rttObject)==null?void 0:o.rtt,s=a!=null&&a>0;s||this.isOffline?s&&this.isOffline&&(this.isOffline=!1,this.handleOnline()):(this.isOffline=!0,this.handleOffline())}},this.handleOffline=()=>{nn.warn("网络断开,准备销毁 SIP 客户端","sip-client.ts 75 handleOffline"),fe.emit(He.FAIL_NOTIFICATION,"网络断开,准备销毁 SIP 客户端"),this.destroy()},this.handleOnline=()=>{nn.warn("网络恢复,准备重新启动 SIP 客户端","sip-client.ts 82 handleOnline"),this.reconnect()},this.sleep=r=>new Promise(i=>setTimeout(i,r)),T0.subscribe(this.handleNetworkInfoChange)}async start(){const e=Fg.makeURI(`sip:${this.config.user}@${this.config.server}`);if(!e)throw new Error("无效的SIP配置");const n={uri:e,authorizationUsername:this.config.user,authorizationPassword:this.config.password,sendInitialProvisionalResponse:!1,transportOptions:{server:this.config.webSocket,connectionTimeout:10,keepAliveInterval:20,keepAliveDebounce:10},contactName:this.config.user,contactParams:{transport:"wss"},userAgentString:"SwiftSIP/2.0.21",sessionDescriptionHandlerFactoryOptions:{alwaysAcquireMediaFirst:!0,peerConnectionConfiguration:{iceServers:[{urls:"stun:stun.l.google.com:19302"}],iceCandidatePoolSize:0,iceTransportPolicy:"all",rtcpMuxPolicy:"require",bundlePolicy:"balanced",certificates:void 0,peerIdentity:void 0},iceGatheringTimeout:1e3},logBuiltinEnabled:K.logBuiltinEnabled};this.userAgent=new Fg(n),this.setupEventListeners(),await this.userAgent.start(),await this.register()}setupEventListeners(){this.userAgent&&(this.userAgent.transport.stateChange.addListener(e=>{var r;let n;switch(e){case dt.Connecting:n=Ar.WEB_RTC_CONNECTING;break;case dt.Connected:n=Ar.WEB_RTC_CONNECTED,this.reconnectAttempts=0,K.isRtcReconnecting=!1,G.updateIsSipConnected(!0),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null);break;case dt.Disconnecting:n=Ar.WEB_RTC_DISCONNECTING,G.updateIsSipConnected(!1);break;case dt.Disconnected:{if(G.updateIsSipConnected(!1),this.isManuallyStopped)return nn.warn("手动断开,不触发重连","sip-client.ts 204"),void console.warn("[SIP] 手动断开,不触发重连");fe.emit(He.FAIL_NOTIFICATION,"软电话链接失败"),n=Ar.WEB_RTC_DISCONNECTED;const i=G.get("answerDevice");if(!K.isRtcReconnecting&&this.reconnectAttempts<this.maxReconnectAttempts&&i===1){this.reconnectAttempts++;const o=1e3*this.reconnectAttempts;nn.warn(`SIP WebSocket 断开,第 ${this.reconnectAttempts} 次尝试重连,${o}ms 后重试...`,"sip-client.ts 219"),this.reconnectTimer=setTimeout(()=>{this.reconnect()},o)}else this.reconnectAttempts>=this.maxReconnectAttempts&&(nn.warn(`SIP 重连失败:已达到最大重试次数; reconnectAttempts: ${this.reconnectAttempts}; maxReconnectAttempts: ${this.maxReconnectAttempts}`,"sip-client.ts 228"),console.error("SIP 重连失败:已达到最大重试次数"),fe.emit(He.FAIL_NOTIFICATION,"SIP 重连失败:已达到最大重试次数"));break}default:G.updateIsSipConnected(!1),n="unknown"}(r=this.eventCallback)==null||r.call(this,{type:n})}),this.userAgent.delegate={onInvite:e=>{this.handleIncomingCall(e)}})}async refreshRegister(){if(this.registerer)try{await this.registerer.register(),new Date().toLocaleTimeString()}catch(e){console.error("[SIPClient] REGISTER刷新失败",e)}}async register(){var e,n;if(this.userAgent){this.registerer=new tu(this.userAgent,{expires:120,refreshFrequency:80}),(e=this.registerer)==null||e.stateChange.addListener(r=>{var o;let i;switch(r){case jt.Initial:G.updateDisplayText(Kt.LINKING),i="initial";break;case jt.Registered:G.updateDisplayText(""),i=Ar.WEB_RTC_REGISTERED;break;case jt.Unregistered:i=Ar.WEB_RTC_UNREGISTERED;break;case jt.Terminated:nn.warn(`注册流程已终止,无法再注册(如 UA 停止,或网络不可达);regStatus: ${Ar.WEB_RTC_TERMINATED}`,"sip-client.ts 299"),i=Ar.WEB_RTC_TERMINATED;break;default:i="unknown"}(o=this.eventCallback)==null||o.call(this,{type:i})});try{await this.registerer.register()}catch(r){(n=this.eventCallback)==null||n.call(this,{type:Ar.WEB_RTC_REGISTER_FAILED,data:r})}}}attachRemoteAudio(e){const n=e.sessionDescriptionHandler;if(n){const r=n.peerConnection;if(!r)return;const i=new MediaStream;r.getReceivers().forEach(a=>{a.track&&a.track.kind==="audio"&&i.addTrack(a.track)});let o=document.getElementById("sip-remote-audio");o||(o=document.createElement("audio"),o.id="sip-remote-audio",o.autoplay=!0,o.style.display="none",document.body.appendChild(o)),o.srcObject=i,o.play().catch(a=>{console.error("音频播放失败,需要用户交互触发",a)})}}handleSessionState(e,n,r){e.stateChange.addListener(i=>{switch(i){case he.Established:clearTimeout(this.callTimeoutTimer),this.activeSession=e,this.attachRemoteAudio(e);break;case he.Terminating:break;case he.Terminated:this.activeSession=null,clearTimeout(this.callTimeoutTimer);case he.Establishing:}})}handleIncomingCall(e){this.incomingInvitation=e,this.handleSessionState(e,!1),e.progress({statusCode:180,reasonPhrase:"Ringing"}).catch(n=>console.error("发送 180 失败",n)),G.get("direction")===xn.OUTGOING&&this.answerCall()}async answerCall(){var e;if(!this.incomingInvitation)throw new Error("无来电可接听");K.autoAnswerTimer&&(clearTimeout(K.autoAnswerTimer),K.autoAnswerTimer=null);try{await this.incomingInvitation.accept(),this.activeSession=this.incomingInvitation,this.incomingInvitation=null}catch(n){(e=this.eventCallback)==null||e.call(this,{type:Ar.WEB_RTC_ANSWER_FAILED,data:{detail:n}})}}async rejectInCall(){var e;if(this.incomingInvitation)try{await this.incomingInvitation.reject(),this.incomingInvitation=null,G.updateDirection(null),G.updateIsCalling(!1),clearTimeout(this.callTimeoutTimer)}catch(n){(e=this.eventCallback)==null||e.call(this,{type:"error",data:{message:"拒接失败",detail:n}})}}sendDTMF(e){var r;if(!this.activeSession)throw new Error("当前没有活跃的通话");const n=this.activeSession.sessionDescriptionHandler;n&&typeof n.sendDtmf=="function"?(n.sendDtmf(e),(r=this.eventCallback)==null||r.call(this,{type:Ar.WEB_RTC_SEND_DTMF,data:{tone:e}})):(console.warn("DTMF发送不支持或未初始化"),nn.warn("DTMF发送不支持或未初始化","sip-client.ts 490 sendDTMF"))}async hangup(){if(this.activeSession,this.activeSession){clearTimeout(this.callTimeoutTimer);const e=this.activeSession;if(!e)return;const n=e.state;try{n===he.Established?await e.bye():n===he.Establishing&&(e instanceof v0?await e.cancel():e instanceof eu&&await e.reject()),clearTimeout(this.callTimeoutTimer)}catch(r){nn.error("挂断失败","sip-client.ts 522 hangup"),console.error("挂断失败",r)}finally{this.activeSession=null}}}async rejectOutCall(){this.activeSession instanceof eu&&(await this.activeSession.reject(),this.activeSession=null)}async destroy(){if(this.isManuallyStopped=!0,clearTimeout(this.callTimeoutTimer),this.activeSession&&await this.hangup(),this.registerer){try{await this.registerer.unregister()}catch(e){console.warn("注销失败",e)}this.registerer=null}this.userAgent&&(await this.userAgent.stop(),this.userAgent=null)}async reconnect(){if(!K.isRtcReconnecting){K.isRtcReconnecting=!0;try{this.isManuallyStopped=!1,await this.destroy(),await this.start(),this.isOffline=!1,this.reconnectAttempts=0}catch(e){console.error("重连失败",e),K.isRtcReconnecting=!1}finally{K.isRtcReconnecting=!1}}}async getNetworkStats(){var e;if(this.activeSession){const n=(e=this.activeSession.sessionDescriptionHandler)==null?void 0:e.peerConnection;if(!n)return null;const r=await n.getStats(),i={};return r.forEach(o=>{o.type==="candidate-pair"&&o.state==="succeeded"&&o.currentRoundTripTime!=null&&(i.rtt=+(1e3*o.currentRoundTripTime).toFixed(2)),o.type==="inbound-rtp"&&o.kind==="audio"&&(i.jitter=+(1e3*o.jitter).toFixed(2),i.packetsLost=o.packetsLost,i.packetsReceived=o.packetsReceived,o.bytesReceived&&o.timestamp&&(i.recvBitrate=+(o.bytesReceived/1024).toFixed(2))),o.type==="outbound-rtp"&&o.kind==="audio"&&(i.packetsSent=o.packetsSent,o.bytesSent&&o.timestamp&&(i.sendBitrate=+(o.bytesSent/1024).toFixed(2))),o.type==="codec"&&o.mimeType&&(i.codec=o.mimeType)}),{...i,rtt:(i==null?void 0:i.rtt)||40}}return{rtt:K.latency||1}}}class To{static requestPermission(){"Notification"in window&&Notification.permission==="default"&&Notification.requestPermission()}static async requestMediaPermissions(){try{return(await navigator.mediaDevices.enumerateDevices()).some(n=>n.kind==="audioinput"&&n.label!=="")?null:await navigator.mediaDevices.getUserMedia({audio:!0})}catch(e){return console.warn("获取音频权限失败:",e),null}}static show(e,n,r,i){if("Notification"in window&&Notification.permission==="granted"){const o=new Notification(e,{body:n,tag:`xy-global-notification${new Date().getTime()}`,renotify:!0});o.onclick=()=>{window.focus(),o.close(),r==null||r()},setTimeout(()=>o.close(),1e3*(i||3))}}static async checkMediaPermissions(){try{return(await navigator.mediaDevices.enumerateDevices()).some(e=>e.kind==="audioinput"&&e.label!=="")}catch(e){return console.warn("无法检查设备权限:",e),!1}}}const Fw=[],Vn=["call_number"],gA=["call_number"],kw=["hangup"],Ci=["hold","hangup","mute","transfer","consult","satisfaction","dtmf"],Yc=["hold","hangup","mute","transfer","consult"],Hg=["consult_transfer","conference","consult_retrieve"],Pw=["hangup"],Qw=["hangup"],Os=["answer","reject"],Gi=["hangup","consult","transfer","hold","mute","satisfaction","dtmf"],Gg=["hangup","whisper","force_insert","force_disconnect"],jw=["hangup"],Lw=["hangup","cancel_whisper","force_insert"],Uw=["hangup"],Hw=["hangup"];class ja{constructor(){this.roleData={agentInfo:()=>{var e;if(!((e=K.agentInfo)!=null&&e.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:n}=K.agentInfo;if(!n.split(",").map(r=>Number(r)).includes(e))throw new Error(JSON.stringify({code:1,msg:"当前状态不支持"}))},changeState:(e,n)=>{if(!e)throw new Error(JSON.stringify({code:1,msg:'Parameter "state" is required'}));if(!n)throw new Error(JSON.stringify({code:1,msg:'Parameter "state_name" is required'}));if(e===2&&(n==="通话中"||n==="整理"))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:n,out_display_data:r}=K.agentInfo;if(n!==1)throw new Error(JSON.stringify({code:1,msg:"当前坐席设置未开启允许指定外显"}));if(!e)throw new Error(JSON.stringify({code:1,msg:'Parameter "number" is required'}));if(!(r||"").split("#").includes(e))throw new Error(JSON.stringify({code:1,msg:"当前外显号码不存在"}))}},this.changeDevice=async e=>{try{if(G.get("isCalling"))throw new Error(JSON.stringify({code:1,msg:"当前正在通话中,请勿切换设备"}));this.roleData.agentInfo(),this.roleData.requestInfo(e);const{data:n,success:r}=e,{device:i}=n;i===1&&await ja.initRtcFn(),this.roleData.changeDevice(i);const{agent_no:o}=K.agentInfo;await(s=>yn(`${Or}/device/change`,s))({agent_no:o,answer_device:i}),G.updateAnswerDevice(i);const a=G.get("actionConfigs");G.updateActionConfigs(a),i===2&&K.stateObject.state===Rt.UNREGISTERED&&await this._changeState({data:{...K.stateBeforeChange,state_name:K.stateBeforeChange.state===Rt.IDLE?"空闲":"忙碌"}},"q"),r==null||r({code:0,msg:"请求成功"})}catch(n){throw fe.emit(He.FAIL_NOTIFICATION,JSON.parse(n.message).msg),n}}}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 r=await(n={agent_no:e},yn(`${Or}/agent/login`,n));K.agentInfo=r.data}catch(r){throw fe.emit(He.FAIL_NOTIFICATION,JSON.parse(r.message).msg),r}var n}async _changeState(e,n){try{K.autoStateTimer&&(clearTimeout(K.autoStateTimer),K.autoStateTimer=null),this.roleData.agentInfo(),this.roleData.requestInfo(e);const{data:r,success:i}=e,{state:o,state_name:a}=r,{agent_no:s}=K.agentInfo;await Ug({agent_no:s,state_name:a,state:o},n),o===Rt.IDLE?G.updateActionConfigs(Vn):o===Rt.BUSY&&G.updateActionConfigs(gA),K.stateObject={state:o,state_name:a},i==null||i({code:0,msg:"请求成功"})}catch(r){throw fe.emit(He.FAIL_NOTIFICATION,JSON.parse(r.message).msg),r}}async _getInCallCrmDetail(e){var n;try{const{phone:r}=e.data,i={};iu(r)?i.trace_id=r:i.phone=r.replace(/[\s\r\n-]+/g,"");const o=await(a=>yn(`${Yi}/crm/popups`,a))({...i});(n=e.success)==null||n.call(e,o)}catch(r){throw fe.emit(He.FAIL_NOTIFICATION,JSON.parse(r.message).msg),r}}async changeState(e,n){try{if(G.get("isCalling"))throw new Error(JSON.stringify({code:1,msg:"当前正在通话中,请勿切换设备"}));K.autoStateTimer&&(clearTimeout(K.autoStateTimer),K.autoStateTimer=null),this.roleData.agentInfo(),this.roleData.requestInfo(e);const{data:r,success:i}=e,{state:o,state_name:a}=r;this.roleData.changeState(o,a);const{agent_no:s}=K.agentInfo;await Ug({agent_no:s,state_name:a,state:o},n),(K.stateObject.state===Rt.IDLE||K.stateObject.state===Rt.BUSY&&a!=="整理")&&(K.stateBeforeChange=K.stateObject),o===Rt.IDLE?G.updateActionConfigs(Vn):o===Rt.BUSY&&G.updateActionConfigs(gA),K.stateObject={state:o,state_name:a},i==null||i({code:0,msg:"请求成功"})}catch(r){throw fe.emit(He.FAIL_NOTIFICATION,JSON.parse(r.message).msg),r}}async getIdleAgentList(e){var r;const{agent_no:n}=K.agentInfo;try{this.roleData.agentInfo();const i=await(o=>yn(`${Or}/agent/free`,o))({agent_no:n});(r=e.success)==null||r.call(e,i)}catch(i){throw fe.emit(He.FAIL_NOTIFICATION,JSON.parse(i.message).msg),i}}async getAgentState(e){var n;try{const r=await yn(`${Yi}/agent/statecfg/list`,{}),i=(r.data||[]).filter(o=>o.enable===0).filter(o=>o.state!==0&&o.state!==3).filter(o=>o.state_name!=="通话中"&&o.state_name!=="整理"&&o.state_name!=="未注册"&&o.state_name!=="离线接听").map(o=>({state:o.state,state_name:o.state_name})).reverse();(n=e.success)==null||n.call(e,{...r,data:i})}catch(r){throw fe.emit(He.FAIL_NOTIFICATION,JSON.parse(r.message).msg),r}}async setAgentExplicit(e){var n;try{this.roleData.agentInfo(),this.roleData.requestInfo(e),this.roleData.setAgentExplicit(e.data.number);const{agent_id:r}=K.agentInfo;await(i=>yn(`${Yi}/agent/update`,i))({agent_id:r,out_display_number:e.data.number}),G.updateSelectOutNumber(e.data.number),(n=e.success)==null||n.call(e,{code:0,msg:"请求成功"})}catch(r){throw fe.emit(He.FAIL_NOTIFICATION,JSON.parse(r.message).msg),r}}async checkAgentLogin(e){var n;try{this.roleData.requestInfo(e);const{agent_no:r}=e.data;if(!r)throw new Error(JSON.stringify({code:1,msg:'Parameter "agent_no" is required'}));const i=await(o=>yn(`${Or}/agent/islogin`,o))({agent_no:r});(n=e.success)==null||n.call(e,i)}catch(r){throw fe.emit(He.FAIL_NOTIFICATION,JSON.parse(r.message).msg),r}}async getCallRecord(e){try{this.roleData.agentInfo();const{success:n}=e,r=new Date,i=new Date(r.getFullYear(),r.getMonth(),r.getDate(),0,0,0),o=new Date(r.getFullYear(),r.getMonth(),r.getDate(),23,59,59),a=[this.formatDate(i),this.formatDate(o)],{agent_no:s}=K.agentInfo,A=await(f=>yn(`${Yi}/agent/recordpage`,f))({start_time:a[0],end_time:a[1],page_no:1,page_size:10,agent_no:s}),{code:c,msg:u,data:d}=A;n==null||n({code:c,msg:u,data:d})}catch(n){throw fe.emit(He.FAIL_NOTIFICATION,JSON.parse(n.message).msg),n}}async logout(e){this.roleData.agentInfo();try{const{agent_no:n}=K.agentInfo,{data:r,success:i}=e;await(o=>yn(`${Or}/agent/logout`,o))({...r,agent_no:n}),i==null||i({code:0,msg:""})}catch(n){throw fe.emit(He.FAIL_NOTIFICATION,JSON.parse(n.message).msg),n}}async listenCall(e){try{const{agent_no:n}=K.agentInfo,{data:r,success:i}=e;if(this.roleData.agentInfo(),this.roleData.requestInfo(e),!r.monitored_agent_no)throw new Error(JSON.stringify({code:1,msg:'Parameter "monitored_agent_no" is required'}));await(o=>yn(`${Or}/call/monitor`,o))({...r,monitor_agent_no:n}),K.monitoredAgentNo=r.monitored_agent_no,i==null||i({code:0,msg:""})}catch(n){throw fe.emit(He.FAIL_NOTIFICATION,JSON.parse(n.message).msg),n}}async earCall(e){try{const{agentInfo:n,monitoredAgentNo:r}=K,{agent_no:i}=n;this.roleData.agentInfo();const{success:o}=e;if(!r)throw new Error(JSON.stringify({code:1,msg:"当前未有监听坐席"}));await(a=>yn(`${Or}/call/whisper`,a))({monitored_agent_no:r,monitor_agent_no:i}),o==null||o({code:0,msg:""})}catch(n){throw fe.emit(He.FAIL_NOTIFICATION,JSON.parse(n.message).msg),n}}async stopEarCall(e){try{const{agentInfo:n,earSpeakAgent:r}=K;if(!r)throw new Error(JSON.stringify({code:1,msg:"当前没有正在耳语的坐席"}));const{agent_no:i}=n;this.roleData.agentInfo();const{success:o}=e;await(a=>yn(`${Or}/call/stopwhisper`,a))({monitor_agent_no:i,monitored_agent_no:r}),o==null||o({code:0,msg:""})}catch(n){throw fe.emit(He.FAIL_NOTIFICATION,JSON.parse(n.message).msg),n}}async forceInsert(e){try{const{agentInfo:n,monitoredAgentNo:r}=K,{agent_no:i}=n;this.roleData.agentInfo();const{success:o}=e;if(!r)throw new Error(JSON.stringify({code:1,msg:"当前未有监听坐席"}));await(a=>yn(`${Or}/call/bargein`,a))({monitored_agent_no:r,monitor_agent_no:i}),o==null||o({code:0,msg:""})}catch(n){throw fe.emit(He.FAIL_NOTIFICATION,JSON.parse(n.message).msg),n}}async forceDisconnect(e){try{const{agentInfo:n,monitoredAgentNo:r}=K,{agent_no:i}=n;this.roleData.agentInfo();const{success:o}=e;if(!r)throw new Error(JSON.stringify({code:1,msg:"当前未有监听坐席"}));await(a=>yn(`${Or}/call/intercept`,a))({monitored_agent_no:r,monitor_agent_no:i}),o==null||o({code:0,msg:""})}catch(n){throw fe.emit(He.FAIL_NOTIFICATION,JSON.parse(n.message).msg),n}}}const Gw=console.log,qg=(...t)=>{K.logBuiltinEnabled&&Gw(...t)};let ni=null;class An{constructor(e,n){this.url=e,this.onOpenCallback=n,this.ws=null,this.heartbeatWorker=null,this.reconnectDelay=3e3,this.manualClose=!1,this.apiClient=new ja,this.sipClient=null,this.pendingMessages=new Map,this.initWebSocket()}static getInstance({url:e,sipClient:n,onOpen:r}){if(!ni){if(!e)throw new Error("WebSocket 尚未初始化");ni=new An(e,r),ni.sipClient=n}return ni}setSipClient(e){this.sipClient=e}stateIdleChange(e){const{state:n}=K.stateObject;n!==Rt.IDLE&&this.apiClient._changeState({data:{...K.stateBeforeChange,state_name:K.stateBeforeChange.state===Rt.IDLE?"空闲":"忙碌"}},e)}inCallAutoAnswer(){const{soft_device_auto_answer:e,auto_answer_time:n}=K.agentInfo,r=e===1,i=G.get("direction");if(r&&i===xn.INCOMING){const o=Number(n)||0;o>0&&(K.autoAnswerTimer=setTimeout(()=>{var a;(a=this.sipClient)==null||a.answerCall(),K.autoAnswerTimer=null},o>0?1e3*o-500:0))}}async getCustomerInfo(e,n){try{await this.apiClient._getInCallCrmDetail({data:{phone:e},success:r=>{const i=r.data?{...r.data,type:n}:{phone:r.data.phone,is_vip:0,customer_name:"未知客户",city:"未知",province:"未知",contact_count:0,in_contact_count:0,trace_id:r.data.trace_id,contact_count_month:0,in_contact_count_month:0,type:n};G.updateCustomerInfo(i)}})}catch{}}putAgentState(e,n){if(!e)return;if(n===5)return void this.stateIdleChange("device_type5");K.sessionId="";const{post_call_process_time:r}=K.agentInfo,i=r||0;if(K.autoStateTimer&&(clearTimeout(K.autoStateTimer),K.autoStateTimer=null),G.updateCustomerInfo(void 0),i>0){const{state:o}=K.stateObject;if(o===Rt.IDLE)return;this.apiClient._changeState({data:{state:Rt.BUSY,state_name:"整理"}},"ez"),K.autoStateTimer=setTimeout(()=>{K.autoStateTimer=null,this.stateIdleChange(`delay${i}`)},1e3*i)}else this.stateIdleChange("delay0")}stateBusyChange(){K.sessionId="",clearTimeout(K.autoStateTimer),G.updateCustomerInfo(void 0),this.apiClient._changeState({data:{state:Rt.BUSY,state_name:"忙碌"}},"dm")}initWebSocket(){var n;if(((n=this.ws)==null?void 0:n.readyState)===1||!G.get("isNextState")||this.manualClose)return;const e=P0(Kd,Vd);this.ws=new WebSocket(this.url+e),this.ws.onopen=()=>{const r=new Date().getTime();this.sendMessage({type:0,msg_id:r}),this.pendingMessages.set(r,performance.now()),this.startHeartbeat(),this.manualClose=!1,this.onOpenCallback&&this.onOpenCallback()},this.ws.onmessage=async r=>{var u;const i=JSON.parse(r.data),{type:o,data:a,code:s,msg:A,msg_id:c}=i;if(o===0&&c){const d=this.pendingMessages.get(c),f=performance.now()-d;K.latency=parseFloat(f.toFixed(2)),this.pendingMessages.delete(c)}if(o!==0&&qg("%cWebSocket 收到消息:","color: blue; font-weight: bold;",i),o!==it.OUT_CALL&&o!==it.PREVIEW_OUT_CALL||(K.isAgentHangup=!1,s!==0?(G.reset(),fe.emit(ie.OUT_FAILED,A),fe.emit(He.FAIL_NOTIFICATION,A),G.updateActionConfigs(Vn),setTimeout(()=>{G.updateCustomerInfo(void 0)},500),this.stateIdleChange("h")):s===0&&(fe.emit(ie.OUT_SUCCESS),K.sessionId=a.session_id,G.updateIsCalling(!0),clearTimeout(K.autoStateTimer))),o===it.AGENT_STATE){const{state:d,state_name:f}=a;K.stateObject={state:d,state_name:f},(u=K.stateBeforeChange)!=null&&u.state||K.stateObject.state!==Rt.IDLE&&(K.stateObject.state!==Rt.BUSY||f==="整理")||(K.stateBeforeChange=K.stateObject),f==="振铃中"&&G.updateDisplayText(Kt.AGENT_RINGING);const p=G.get("isCalling");d!==Rt.UNREGISTERED||p||G.updateActionConfigs(Fw),d===Rt.IDLE&&K.stateObject.state===Rt.UNREGISTERED&&G.updateActionConfigs(Vn),fe.emit(ie.AGENT_STATE,{state:d,state_name:f})}else if(o===it.OUT_CALL_INCOMING_CALL)K.isAgentHangup=!1,a.preview_task_id?(this.getCustomerInfo(a.trace_id||a.customer_phone,"preview_out_incoming_call"),fe.emit(ie.PREVIEW_OUT_INCOMING_CALL,{customer_phone:a.customer_phone,session_id:a.session_id,preview_task_id:a.preview_task_id,trace_id:a.trace_id})):a.direction===0?(this.getCustomerInfo(a.trace_id||a.customer_phone,"out_call_incoming_call"),fe.emit(ie.OUT_INCOMING_CALL,{customer_phone:a.customer_phone,session_id:a.session_id,trace_id:a.trace_id})):a.direction===8&&(this.getCustomerInfo(a.trace_id||a.customer_phone,"internal_out_incoming_call"),fe.emit(ie.INTERNAL_OUT_INCOMING_CALL,{customer_phone:a.customer_phone,session_id:a.session_id,trace_id:a.trace_id})),K.sessionId=a.session_id,G.updateActionConfigs(kw,a.direction!==8);else if(o===it.OUT_CALL_END){if(K.sessionId!==a.session_id)return;if(G.updateDisplayText(""),a.device_type===1&&a.agent_no===K.agentInfo.agent_no)G.reset(),fe.emit(ie.OUT_HANGUP,{session_id:a.session_id,isAgentHangup:K.isAgentHangup}),G.updateActionConfigs(Vn),this.putAgentState(!0);else if(a.device_type===2&&a.agent_no===K.agentInfo.agent_no)G.reset(),fe.emit(ie.OUR_SIDE_CONSULT_HANGUP,{session_id:a.session_id}),G.updateActionConfigs(Vn),this.putAgentState(!0);else if(a.device_type===2&&a.agent_no!==K.agentInfo.agent_no)G.get("isCalling")&&(G.updateDisplayText(Kt.CALLING),fe.emit(ie.OTHER_SIDE_CONSULT_HANGUP,{session_id:a.session_id,isAgentHangup:K.isAgentHangup}),G.updateActionConfigs(Ci));else if(a.device_type===3&&a.agent_no===K.agentInfo.agent_no)G.reset(),fe.emit(ie.THREE_WAY_OUR_SIDE_HANGUP,{session_id:a.session_id}),G.updateActionConfigs(Vn),this.putAgentState(!0);else if(a.device_type===4&&a.agent_no===K.agentInfo.agent_no)G.reset(),fe.emit(ie.TRANSFER_END,{session_id:a.session_id}),G.updateActionConfigs(Vn),this.putAgentState(!0);else if(a.device_type===4&&a.agent_no!==K.agentInfo.agent_no){fe.emit(ie.TRANSFER_FAILED,"未知原因"),fe.emit(He.FAIL_NOTIFICATION,"转接失败");const d=G.get("direction");d===xn.OUTGOING?G.updateActionConfigs(Ci):d===xn.INCOMING&&G.updateActionConfigs(Gi)}else a.device_type===5&&a.agent_no===K.agentInfo.agent_no&&(K.monitoredAgentNo="",K.earSpeakAgent="",G.reset(),fe.emit(ie.LISTEN_HANGUP,{session_id:a.session_id}),G.updateActionConfigs(Vn),this.putAgentState(!0,5))}else if(o===it.OUT_CALL_RINGING)a.type===1&&(K.isAgentHangup=!1,fe.emit(ie.OUT_RINGING,{session_id:K.sessionId,type:a.type}),G.updateDisplayText(Kt.RINGING));else if(o===it.OUT_CALL_ANSWER)K.isAgentHangup=!1,clearTimeout(K.autoStateTimer),G.updateIsCalling(!0),G.updateOutCallIsAnswer(!0),G.updateDisplayText(Kt.CALLING),a.direction===8?(fe.emit(ie.INTERNAL_OUT_OFF_ANSWER,{session_id:K.sessionId}),G.updateActionConfigs(Yc)):(fe.emit(ie.OUT_OFF_ANSWER,{session_id:K.sessionId}),G.updateActionConfigs(Ci));else if(o===it.CONSULT_RINGING)K.isAgentHangup=!1,fe.emit(ie.CONSULT_RINGING,{session_id:a.session_id}),G.updateDisplayText(Kt.AGENT_RINGING),G.updateActionConfigs([]),clearTimeout(K.autoStateTimer);else if(o===it.CONSULT_ANSWER)K.isAgentHangup=!1,fe.emit(ie.CONSULT_OFF_HOOK,{session_id:a.session_id}),G.updateConsultIsAnswer(!0),G.updateDisplayText(Kt.CONSULTING),G.updateActionConfigs(Hg);else if(o===it.CONSULT_FAIL)fe.emit(ie.CONSULT_FAILED,{custom_reason:a.custom_reason}),G.updateDisplayText(Kt.CALLING),G.updateActionConfigs(Ci);else if(o===it.CONSULT_CALL_IN)K.isAgentHangup=!1,fe.emit(ie.CONSULT_INCOMING,{agent_no:a.agent_no,agent_mane:a.agent_name,session_id:a.session_id}),K.sessionId=a.session_id,G.updateIsCalling(!0),G.updateDirection(xn.CONSULT),G.updateDisplayText(Kt.CONSULT_CALL_IN),G.updateActionConfigs(Os),K.enableBrowserAlert&&To.show("📞 咨询来电",`坐席 [${a.agent_name}] 正在咨询...`,()=>{fe.emit(He.NOTIFICATION_CLICK,{agent_mane:a.agent_name,agent_no:a.agent_no})},K.browserAlertTime);else if(o===it.CONSULT_CALL_IN_SUCCESS)fe.emit(ie.CONSULT_CALL_IN_SUCCESS,{session_id:a.session_id}),G.updateConsultIsAnswer(!0),G.updateDisplayText(Kt.CALLING),G.updateActionConfigs(Pw);else if(o===it.CONSULT_RETURN_CALL_SUCCESS)a.status==="success"?(G.updateConsultIsAnswer(!1),fe.emit(ie.CONSULT_RETURN_CALL_SUCCESS),G.updateDisplayText(Kt.CALLING),fe.emit(ie.OTHER_SIDE_CONSULT_HANGUP),G.updateActionConfigs(Ci)):fe.emit(He.FAIL_NOTIFICATION,"媒体失败");else if(o===it.MUTE)s===0?(G.updateIsMuted(!0),fe.emit(ie.MUTE_SUCCESS),G.updateDisplayText(Kt.MUTING)):(fe.emit(ie.MUTE_FAILED,A),fe.emit(He.FAIL_NOTIFICATION,A));else if(o===it.UNMUTE)s===0?(G.updateIsMuted(!1),fe.emit(ie.UNMUTE_SUCCESS),G.updateDisplayText(Kt.CALLING)):(fe.emit(ie.UNMUTE_FAILED,A),fe.emit(He.FAIL_NOTIFICATION,A));else if(o===it.CALL_HOLD)s===0?(G.updateIsHold(!0),G.updateDisplayText(Kt.HOLDING),fe.emit(ie.HOLD_SUCCESS)):(fe.emit(ie.HOLD_FAILED,A),fe.emit(He.FAIL_NOTIFICATION,A));else if(o===it.CALL_UNHOLD)s===0?(G.updateDisplayText(Kt.CALLING),G.updateIsHold(!1),fe.emit(ie.UNHOLD_SUCCESS)):(fe.emit(ie.UNHOLD_FAILED,A),fe.emit(He.FAIL_NOTIFICATION,A));else if(o===it.CONSULT_TRANSFER)K.isAgentHangup=!1,s===0?fe.emit(ie.CONSULT_TRANSFER_SUCCESS):(fe.emit(ie.CONSULT_TRANSFER_FAILED,A),fe.emit(He.FAIL_NOTIFICATION,A));else if(o===it.CONSULT_TRANSFER_FAILED)fe.emit(ie.CONSULT_TRANSFER_FAILED,a.status);else if(o===it.CONSULT_TRANSFER_OFF_HOOK)G.updateDirection(xn.INCOMING),G.updateDisplayText(Kt.CALLING),fe.emit(ie.CONSULT_TRANSFER_OFF_HOOK),G.updateActionConfigs(Gi),G.updateIncomingIsAnswer(!0),G.updateConsultIsAnswer(!1);else if(o===it.INCOMING_CALL)K.isAgentHangup=!1,clearTimeout(K.autoStateTimer),K.sessionId=a.session_id,G.updateIsCalling(!0),G.updateDirection(xn.INCOMING),G.updateDisplayText(Kt.INCOMING_CALL),this.inCallAutoAnswer(),a.direction===1&&(this.getCustomerInfo(a.trace_id||a.customer_phone,"incoming_call"),fe.emit(ie.INCOMING_CALL,{customer_phone:a.customer_phone,trace_id:a.trace_id,session_id:a.session_id})),a.direction===8&&(this.getCustomerInfo(a.trace_id||a.customer_phone,"incoming_call_in"),fe.emit(ie.INCOMING_CALL_IN,{customer_phone:a.customer_phone,trace_id:a.trace_id,session_id:a.session_id})),a.direction===3&&(this.getCustomerInfo(a.trace_id||a.customer_phone,"predict_incoming_call"),fe.emit(ie.PREDICT_INCOMING_CALL,{customer_phone:a.customer_phone,trace_id:a.trace_id,session_id:a.session_id})),a.direction===6&&(this.getCustomerInfo(a.trace_id||a.customer_phone,"out_call_incoming_call"),fe.emit(ie.DUAL_CALL_INCOMING_CALL,{customer_phone:a.customer_phone,trace_id:a.trace_id,session_id:a.session_id})),G.updateActionConfigs(Os),K.enableBrowserAlert&&To.show("📞 客户来电",`客户 [${a.customer_phone}] 正在呼入...`,()=>{fe.emit(He.NOTIFICATION_CLICK,{customer_phone:a.customer_phone})},K.browserAlertTime);else if(o===it.INCOMING_CALL_OFF_HOOK)G.updateIncomingIsAnswer(!0),a.direction===8?(G.updateActionConfigs(Yc),fe.emit(ie.INCOMING_CALL_IN_OFF_HOOK,{session_id:K.sessionId})):(G.updateActionConfigs(Gi),fe.emit(ie.INCOMING_CALL_OFF_HOOK,{session_id:K.sessionId})),G.updateDisplayText(Kt.CALLING);else if(o===it.INCOMING_CALL_END){if(K.sessionId!==a.session_id)return;if(G.updateDisplayText(""),a.device_type!==1&&a.device_type!==7||a.agent_no!==K.agentInfo.agent_no)if(a.device_type===2&&a.agent_no===K.agentInfo.agent_no)G.reset(),fe.emit(ie.OUR_SIDE_CONSULT_HANGUP,{session_id:a.session_id}),this.putAgentState(!0),G.updateActionConfigs(Vn);else if(a.device_type===2&&a.agent_no!==K.agentInfo.agent_no)G.updateDisplayText(Kt.CALLING),fe.emit(ie.OTHER_SIDE_CONSULT_HANGUP,{session_id:a.session_id,isAgentHangup:K.isAgentHangup}),G.updateActionConfigs(Ci);else if(a.device_type===3&&a.agent_no===K.agentInfo.agent_no)this.putAgentState(!0),G.reset(),fe.emit(ie.THREE_WAY_OUR_SIDE_HANGUP,{session_id:a.session_id}),G.updateActionConfigs(Vn);else if(a.device_type===4&&a.agent_no===K.agentInfo.agent_no)this.putAgentState(!0),G.reset(),fe.emit(ie.TRANSFER_END,{session_id:a.session_id}),G.updateActionConfigs(Vn);else if(a.device_type===4&&a.agent_no!==K.agentInfo.agent_no){fe.emit(ie.TRANSFER_FAILED,"未知原因"),fe.emit(He.FAIL_NOTIFICATION,"转接失败");const d=G.get("direction");d===xn.OUTGOING?G.updateActionConfigs(Ci):d===xn.INCOMING&&G.updateActionConfigs(Gi)}else a.device_type===5&&a.agent_no===K.agentInfo.agent_no&&(this.putAgentState(!0,5),K.monitoredAgentNo="",K.earSpeakAgent="",G.reset(),fe.emit(ie.LISTEN_HANGUP,{session_id:a.session_id}),G.updateActionConfigs(Vn));else this.putAgentState(!0),G.reset(),fe.emit(ie.INCOMING_CALL_END,{session_id:a.session_id,isAgentHangup:K.isAgentHangup}),G.updateActionConfigs(Vn)}else if(o===it.SATISFACTION_EVALUATION)s===0?fe.emit(ie.SATISFACTION_EVALUATION_SUCCESS):(fe.emit(ie.SATISFACTION_EVALUATION_FAILED,A),fe.emit(He.FAIL_NOTIFICATION,A));else if(o===it.CONSULT_THREE_WAY)s!==0?(fe.emit(ie.CONSULT_THREE_WAY_FAILED,A),fe.emit(He.FAIL_NOTIFICATION,A)):s===0&&G.updateIsMeeting(!0);else if(o===it.CONSULT_THREE_WAY_RESULT)a.status==="success"?(G.updateDirection(xn.MEETING),G.updateDisplayText(Kt.MEETING),G.updateActionConfigs(Qw),fe.emit(ie.CONSULT_THREE_WAY_SUCCESS)):(fe.emit(ie.CONSULT_THREE_WAY_FAILED,{conf_name:a.conf_name}),G.updateIsMeeting(!1));else if(o===it.TRANSFER_INCOMING_CALL)K.isAgentHangup=!1,clearTimeout(K.autoStateTimer),a.agent_no===K.agentInfo.agent_no?(G.updateDisplayText(Kt.TRANSFERRING),fe.emit(ie.TRANSFER_PROGRESS),G.updateActionConfigs([]),G.updateTransferIsAnswer(!0)):(K.sessionId=a.session_id,fe.emit(ie.TRANSFER_INCOMING_CALL,{agent_no:a.agent_no,agent_name:a.agent_name,session_id:a.session_id}),G.updateIsCalling(!0),G.updateDirection(xn.TRANSFER),G.updateDisplayText(Kt.TRANSFER_INCOMING_CALL),G.updateActionConfigs(Os),K.enableBrowserAlert&&To.show("📞 转接来电",`坐席 [${a.agent_no}] 正在转接...`,()=>{fe.emit(He.NOTIFICATION_CLICK,{agent_no:a.agent_no})},K.browserAlertTime));else if(o===it.TRANSFER_OFF_HOOK)fe.emit(ie.TRANSFER_OFF_HOOK,{session_id:K.sessionId}),G.updateTransferIsAnswer(!1),G.updateDisplayText(Kt.CALLING),G.updateActionConfigs(Gi,a.direction!==8);else if(o===it.TRANSFER_FAILED){if(a.status==="failed"){fe.emit(ie.TRANSFER_FAILED,"未知原因"),fe.emit(He.FAIL_NOTIFICATION,"转接失败");const d=G.get("direction");d===xn.OUTGOING?G.updateActionConfigs(Ci):d===xn.INCOMING&&G.updateActionConfigs(Gi)}}else o===it.KICK_OFFLINE?fe.emit(He.KICK_OFF):o===it.CONTINUOUS_NOT_ANSWER?(fe.emit(He.FAIL_NOTIFICATION,`已连续 ${a.miss_count} 次未接, 设置忙碌`),this.stateBusyChange()):o===it.SIGN_OUT?fe.emit(He.SIGN_OUT):o===it.SIGN_IN_SWITCH_DEVICE?fe.emit(He.SIGN_IN_SWITCH_DEVICE,a):o===it.LISTEN_INCOMING_CALL?(clearTimeout(K.autoStateTimer),K.sessionId=a.session_id,G.updateIsCalling(!0),G.updateDirection(xn.INCOMING),this.inCallAutoAnswer(),G.updateDisplayText(Kt.LISTENING),G.updateActionConfigs(Os),fe.emit(ie.LISTEN_INCOMING_CALL,{session_id:a.session_id}),K.enableBrowserAlert&&To.show("📞 监听来电","正在来电...",()=>{fe.emit(He.NOTIFICATION_CLICK,{customer_phone:a.customer_phone})},K.browserAlertTime)):o===it.LISTEN_INCOMING_CALL_OFF_HOOK?(K.monitoredAgentNo=a.monitored_agent_no,K.earSpeakAgent="",G.updateIncomingIsAnswer(!0),fe.emit(ie.LISTEN_INCOMING_CALL_OFF_HOOK,{session_id:K.sessionId,monitored_agent_no:a.monitored_agent_no}),G.updateActionConfigs(Gg),G.updateDisplayText(Kt.CALLING)):o===it.LISTEN_CALL_FAILED?a.status==="failed"&&(fe.emit(ie.LISTEN_CALL_FAILED),K.monitoredAgentNo=""):o===it.EAR_SPEECH?a.status==="success"?(a.monitored_agent_no===K.agentInfo.agent_no&&(G.updateActionConfigs(jw),fe.emit(ie.EAR_SPEECH_BE_SUCCESS)),a.monitor_agent_no===K.agentInfo.agent_no&&(G.updateActionConfigs(Lw),fe.emit(ie.EAR_SPEECH_SUCCESS,{monitored_agent_no:a.monitored_agent_no,monitor_agent_no:a.monitor_agent_no}),K.earSpeakAgent=a.monitored_agent_no)):fe.emit(ie.EAR_SPEECH_FAILED):o===it.STOP_EAR_SPEECH?a.status==="success"?(a.monitored_agent_no===K.agentInfo.agent_no&&G.updateActionConfigs(Gi),a.monitor_agent_no===K.agentInfo.agent_no&&G.updateActionConfigs(Gg),K.earSpeakAgent="",fe.emit(ie.STOP_EAR_SPEECH_SUCCESS)):fe.emit(ie.STOP_EAR_SPEECH_FAILED):o===it.CALL_FORCE_INSERT?a.status==="success"?(a.monitored_agent_no===K.agentInfo.agent_no&&(G.updateActionConfigs(Hw),fe.emit(ie.CALL_FORCE_INSERT_SUCCESS,{monitored_agent_no:a.monitored_agent_no,monitor_agent_no:a.monitor_agent_no})),a.monitor_agent_no===K.agentInfo.agent_no&&(G.updateActionConfigs(Uw),fe.emit(ie.CALL_FORCE_INSERT_SUCCESS_LISTENER,{monitored_agent_no:a.monitored_agent_no,monitor_agent_no:a.monitor_agent_no}))):fe.emit(ie.CALL_FORCE_INSERT_FAILED):o===it.INTERNAL_CALL_START_CONSULT?a.agent_no===K.agentInfo.agent_no?(G.updateConsultIsAnswer(!0),G.updateActionConfigs(Hg),G.updateDisplayText(Kt.CONSULTING)):(G.updateDisplayText(Kt.OTHER_SIDE_CONSULTING),G.updateActionConfigs([])):o===it.INTERNAL_CALL_END_CONSULT?(G.updateActionConfigs(Yc),G.updateDisplayText(""),G.updateConsultIsAnswer(!1)):o===it.CALL_SIP_INCOMING_CALL&&fe.emit(ie.CALL_SIP_INCOMING_CALL)},this.ws.onclose=r=>{fe.emit(He.FAIL_NOTIFICATION,"链接已断开,请检查网络"),this.stopHeartbeat();const i=G.get("isNextState");!this.manualClose&&i&&setTimeout(()=>this.initWebSocket(),this.reconnectDelay)},this.ws.onerror=r=>{var i;fe.emit(He.FAIL_NOTIFICATION,"连接失败,请检查网络"),(i=this.ws)==null||i.close()}}startHeartbeat(){const e=new Blob([`
164
164
  let timer;
165
165
  self.onmessage = function (e) {
166
166
  if (e.data === 'start') {
@@ -683,7 +683,7 @@ html body {
683
683
  &:hover {
684
684
  opacity: 0.9;
685
685
  }
686
- `;function bN({title:t,content:e,icon:n,onOk:r,onCancel:i}){const o=document.createElement("div");document.body.appendChild(o);const a=hN.createRoot(o),s=()=>{a.unmount(),o.remove()},A=async()=>{r&&await r(),s()},c=()=>{i==null||i(),s()};a.render(ae.jsx(pN,{children:ae.jsxs(mN,{children:[ae.jsxs(vN,{children:[n&&ae.jsx(CN,{children:n}),t]}),ae.jsx(yN,{children:e}),ae.jsxs(EN,{children:[ae.jsx(Ym,{onClick:c,children:"取消"}),ae.jsx(Ym,{primary:!0,onClick:A,children:"确定"})]})]})}))}const SN={1:ae.jsx(vt,{name:"ruandianhua"}),2:ae.jsx(vt,{name:"pnhone"}),3:ae.jsx(vt,{name:"sip-phone"})},wN={call_number:"",answer:"接听",reject:"拒接",hangup:"挂机",dtmf:"DTMF",unhold:"取消保持",hold:"保持",mute:"静音",unmute:"取消静音",satisfaction:"满意度",consult:"咨询",consult_transfer:"咨询转接",consult_retrieve:"取回通话",conference:"三方会议",whisper:"耳语",cancel_whisper:"取消耳语",force_insert:"强插",force_disconnect:"强拆",transfer:"转接"},IN={空闲:1,离线:0,未注册:4},xN=N.lazy(()=>Promise.resolve().then(()=>require("./ConsultModel-CwPWnbDX.js"))),RN=N.lazy(()=>Promise.resolve().then(()=>require("./TransferModel-BQN0vfjr.js"))),Cl=on.div`
686
+ `;function bN({title:t,content:e,icon:n,onOk:r,onCancel:i}){const o=document.createElement("div");document.body.appendChild(o);const a=hN.createRoot(o),s=()=>{a.unmount(),o.remove()},A=async()=>{r&&await r(),s()},c=()=>{i==null||i(),s()};a.render(ae.jsx(pN,{children:ae.jsxs(mN,{children:[ae.jsxs(vN,{children:[n&&ae.jsx(CN,{children:n}),t]}),ae.jsx(yN,{children:e}),ae.jsxs(EN,{children:[ae.jsx(Ym,{onClick:c,children:"取消"}),ae.jsx(Ym,{primary:!0,onClick:A,children:"确定"})]})]})}))}const SN={1:ae.jsx(vt,{name:"ruandianhua"}),2:ae.jsx(vt,{name:"pnhone"}),3:ae.jsx(vt,{name:"sip-phone"})},wN={call_number:"",answer:"接听",reject:"拒接",hangup:"挂机",dtmf:"DTMF",unhold:"取消保持",hold:"保持",mute:"静音",unmute:"取消静音",satisfaction:"满意度",consult:"咨询",consult_transfer:"咨询转接",consult_retrieve:"取回通话",conference:"三方会议",whisper:"耳语",cancel_whisper:"取消耳语",force_insert:"强插",force_disconnect:"强拆",transfer:"转接"},IN={空闲:1,离线:0,未注册:4},xN=N.lazy(()=>Promise.resolve().then(()=>require("./ConsultModel-4NfviEp_.js"))),RN=N.lazy(()=>Promise.resolve().then(()=>require("./TransferModel-IInPSlPH.js"))),Cl=on.div`
687
687
  width: 25px;
688
688
  height: 25px;
689
689
  background: ${({bg:t})=>t};
@@ -691,4 +691,4 @@ html body {
691
691
  display: flex;
692
692
  justify-content: center;
693
693
  align-items: center;
694
- `,ON=t=>{var Ue,F,ge;const{style:e,logBuiltinEnabled:n,browserAlertTime:r,enableBrowserAlert:i,agentNo:o,appKey:a,appSecret:s,url:A,onCallBack:c,ringingCardShow:u=!0,onLoginCancel:d,isCheckLogin:f,...p}=t,{height:v,busy:C,idle:m,unavailable:y,selectOutNumberColor:w}=e||{},I=N.useRef(),O=N.useRef(),[x,g]=N.useState(new Audio(fN)),M=N.useRef(),E=N.useRef(),[b,h]=N.useState(),[S,T]=N.useState(),[R,D]=N.useState(!1),[B,k]=N.useState(new Date().getTime()),[P,H]=N.useState(),[Z,V]=N.useState(),[q,U]=N.useState([]),[$,z]=N.useState([]),[J,W]=N.useState(""),[te,_]=N.useState(!1),[se,ce]=N.useState([]),[ue,ne]=N.useState(""),[me,Y]=N.useState(""),[de,le]=N.useState(!1),[Se,xe]=N.useState(!1),[ve,De]=N.useState(),[je,Le]=N.useState(new Date().getTime()),[Ie,pe]=N.useState(!0),[Oe,Ze]=N.useState(""),tt=j=>{switch(j){case Rt.IDLE:return m||"#1D92E9";case Rt.BUSY:return C||"#F5212D";case Rt.UNREGISTERED:return y||"#faad14";case Rt.OFFLINE:return y||"#8c8c8c";default:return"#1D92E9"}};N.useEffect(()=>((async()=>(D(!0),I.current=kn.getInstance({agentNo:o,appKey:a,appSecret:s,url:A}),rt(),I.current.on(He.PHONE_BAR_OPERATION,j=>{console.log(j),U(j)}),f?await I.current.agent_api.checkAgentLogin({data:{agent_no:o},success:async j=>{j.data.is_login?bN({title:"当前账号已登录!",icon:ae.jsx(vt,{name:"wing",size:20}),content:"是否继续登录",onOk:async()=>{await I.current.init({...p,logBuiltinEnabled:n,browserAlertTime:r,enableBrowserAlert:i,onCallBack:()=>{const re=I.current.getEarSpeakAgent();M.current=new Audio(re);const X=I.current.getEndSpeakAgent();E.current=new Audio(X)}}),O.current=I.current.getAgentData()},onCancel:()=>{d==null||d()}}):(await I.current.init({...p,logBuiltinEnabled:n,browserAlertTime:r,enableBrowserAlert:i,onCallBack:()=>{const re=I.current.getEarSpeakAgent();M.current=new Audio(re);const X=I.current.getEndSpeakAgent();E.current=new Audio(X)}}),O.current=I.current.getAgentData())}}):(await I.current.init({...p,logBuiltinEnabled:n,browserAlertTime:r,enableBrowserAlert:i,onCallBack:()=>{const j=I.current.getEarSpeakAgent();M.current=new Audio(j);const re=I.current.getEndSpeakAgent();E.current=new Audio(re)}}),O.current=I.current.getAgentData()),k(new Date().getTime()),D(!1)))(),()=>{var j;be(x),be(M.current),(j=I.current)==null||j.destroy()}),[]);const rt=()=>{var j,re;(j=I.current)==null||j.on(He.EVENT_ALL,({event:X,data:Ce})=>{switch(X){case ie.OUT_SUCCESS:case ie.CONSULT_RINGING:{Ge(x),De("out"),be(E.current);return}case ie.OUT_INCOMING_CALL:case ie.INTERNAL_OUT_INCOMING_CALL:{c==null||c(X,{customer_phone:Ce.customer_phone,session_id:Ce.session_id});return}case ie.PREVIEW_OUT_INCOMING_CALL:{c==null||c(ie.PREVIEW_OUT_INCOMING_CALL,{customer_phone:Ce.customer_phone,session_id:Ce.session_id,preview_task_id:Ce.preview_task_id});return}case ie.OUT_OFF_ANSWER:case ie.INTERNAL_OUT_OFF_ANSWER:case ie.OUT_FAILED:case ie.CONSULT_FAILED:case ie.OUT_RINGING:case ie.CONSULT_OFF_HOOK:{X===ie.OUT_OFF_ANSWER&&(c==null||c(X,{session_id:Ce.session_id})),be(x);return}case ie.CONSULT_INCOMING:case ie.TRANSFER_INCOMING_CALL:case ie.LISTEN_INCOMING_CALL:case ie.INCOMING_CALL_IN:case ie.INCOMING_CALL:{De("in"),be(E.current),(X===ie.CONSULT_INCOMING||X===ie.TRANSFER_INCOMING_CALL)&&(c==null||c(X,{agent_no:Ce.agent_no,agent_name:Ce.agent_name,session_id:Ce.session_id})),X===ie.INCOMING_CALL?c==null||c(ie.INCOMING_CALL,{customer_phone:Ce.customer_phone,session_id:Ce.session_id}):X===ie.INCOMING_CALL_IN?c==null||c(ie.INCOMING_CALL_IN,{customer_phone:Ce.customer_phone,session_id:Ce.session_id}):X===ie.LISTEN_INCOMING_CALL&&(c==null||c(ie.LISTEN_INCOMING_CALL,{session_id:Ce.session_id}));const{soft_device_ring_switch:ke}=I.current.getAgentData();if(!ke)return;Ge(M.current);return}case ie.PREDICT_INCOMING_CALL:{De("out"),be(E.current),X===ie.PREDICT_INCOMING_CALL&&(c==null||c(ie.PREDICT_INCOMING_CALL,{customer_phone:Ce.customer_phone,session_id:Ce.session_id}));const{soft_device_ring_switch:ke}=I.current.getAgentData();if(!ke)return;Ge(M.current);return}case ie.DUAL_CALL_INCOMING_CALL:{De("out"),be(E.current),X===ie.DUAL_CALL_INCOMING_CALL&&(c==null||c(ie.DUAL_CALL_INCOMING_CALL,{customer_phone:Ce.customer_phone,session_id:Ce.session_id}));const{soft_device_ring_switch:ke}=I.current.getAgentData();if(!ke)return;Ge(M.current);return}case ie.TRANSFER_OFF_HOOK:case ie.LISTEN_INCOMING_CALL_OFF_HOOK:case ie.CONSULT_CALL_IN_SUCCESS:case ie.INCOMING_CALL_IN_OFF_HOOK:case ie.INCOMING_CALL_OFF_HOOK:{X===ie.LISTEN_INCOMING_CALL_OFF_HOOK?c==null||c(X,{session_id:Ce.session_id,monitored_agent_no:Ce.monitored_agent_no}):c==null||c(X,{session_id:Ce.session_id}),be(M.current);return}case ie.OUT_HANGUP:case ie.LISTEN_HANGUP:case ie.LISTEN_CALL_FAILED:case ie.TRANSFER_END:case ie.THREE_WAY_OUR_SIDE_HANGUP:case ie.OUR_SIDE_CONSULT_HANGUP:case ie.OTHER_SIDE_CONSULT_HANGUP:case ie.INCOMING_CALL_END:{if(c==null||c(X,{session_id:Ce.session_id}),be(M.current),be(x),De(void 0),le(!1),xe(!1),X===ie.OUT_HANGUP||X===ie.INCOMING_CALL_END){const{isAgentHangup:ke}=Ce,{agent_hangup_ring_switch:Xe}=I.current.getAgentData();!ke&&Xe&&Ge(E.current,!1)}return}case ie.REJECT:c==null||c(X,{session_id:Ce.session_id});return;default:return null}}),(re=I.current)==null||re.on(ie.AGENT_STATE,X=>{if(V(X.state_name),k(new Date().getTime()),c==null||c(ie.AGENT_STATE,X),X.state===Rt.UNREGISTERED){It.warning("当前已掉线,自动重连中,请检查网络"),be(x);const{soft_device_ring_switch:Ce}=I.current.getAgentData();if(!Ce)return;be(M.current)}}).on(ie.CALL_PROGRESS,X=>{W(X)}).on(He.WEBSITE_DELAY,X=>{h(X)}).on(ie.CUSTOMER_INFO,X=>{T(X),X&&pe(!0)}).on(He.AGENT_INIT_STATUS,X=>{if(X){const{default_device:Ce,out_display_select_switch:ke,out_display_data:Xe,stateObject:{state_name:Ft}}=I.current.getAgentData();_(ke===1),ke===1&&ce((Xe||"").split("#")),H(Ce),V(Ft),Be()}}).on(He.SELECT_EXTERNAL_NUMBER,X=>{ne(X)}).on(He.FAIL_NOTIFICATION,X=>{be(x),be(M.current),It.error(X)}).on(He.KICK_OFF,()=>{be(x),be(M.current),c?c==null||c(He.KICK_OFF):It.warning("您的座席账号已在别处登录,请重新登录。如非您本人操作,请及时修改密码。"),V("")}).on(He.DESTROY,()=>{c==null||c(He.DESTROY),It.success("已离线"),be(x),be(M.current)}).on(He.NETWORK_OFFLINE,()=>{It.warning("网络已断开,请检查网络设置。"),be(x),be(M.current)}).on(He.NETWORK_ONLINE,()=>{It.success("网络已恢复")}).on(He.SIGN_OUT,()=>{c==null||c(He.SIGN_OUT),It.success("已被签出"),be(x),be(M.current)}).on(ie.LISTEN_CALL_FAILED,()=>{c==null||c(ie.LISTEN_CALL_FAILED),It.error("监听失败")}).on(ie.EAR_SPEECH_SUCCESS,({monitored_agent_no:X})=>{c==null||c(ie.EAR_SPEECH_SUCCESS,{monitored_agent_no:X}),It.success("正在耳语")}).on(ie.EAR_SPEECH_BE_SUCCESS,({monitor_agent_no:X})=>{c==null||c(ie.EAR_SPEECH_BE_SUCCESS,{monitor_agent_no:X}),It.success(`${X}正在与你耳语`)}).on(ie.EAR_SPEECH_FAILED,()=>{c==null||c(ie.EAR_SPEECH_FAILED),It.error("耳语失败")}).on(ie.STOP_EAR_SPEECH_SUCCESS,()=>{c==null||c(ie.STOP_EAR_SPEECH_SUCCESS),It.success("停止耳语")}).on(ie.CALL_FORCE_INSERT_SUCCESS,({monitored_agent_no:X,monitor_agent_no:Ce})=>{c==null||c(ie.CALL_FORCE_INSERT_SUCCESS,{monitored_agent_no:X,monitor_agent_no:Ce}),It.success("强插成功")}).on(ie.CALL_FORCE_INSERT_SUCCESS_LISTENER,({monitored_agent_no:X,monitor_agent_no:Ce})=>{c==null||c(ie.CALL_FORCE_INSERT_SUCCESS_LISTENER,{monitored_agent_no:X,monitor_agent_no:Ce}),It.success(`${Ce}强插`)}).on(He.SIGN_IN_SWITCH_DEVICE,X=>{c==null||c(He.SIGN_IN_SWITCH_DEVICE),It.success(`已被切换${X.answer_device===2?"手机模式":"SIP 话机"}设备`)}).on(ie.CALL_SIP_INCOMING_CALL,()=>{It.success("SIP话机有新的呼入")})};N.useEffect(()=>{var j;(j=I.current)==null||j.setBrowserAlertTime(r||3)},[r]),N.useEffect(()=>{var j;(j=I.current)==null||j.setBrowserAlert(i||!1)},[i]);const Ge=(j,re=!0)=>{j&&(j.currentTime=0,j.loop=re,j.play())},be=j=>{j&&j.pause()},Je=async j=>{var re;try{await((re=I.current)==null?void 0:re.agent_api.changeDevice({data:{device:j},success:()=>{H(j),It.success("切换设备成功")}}))}catch{}},lt=async(j,re)=>{var X;try{await((X=I.current)==null?void 0:X.agent_api.changeState({data:{state:j,state_name:re},success:()=>{V(re),It.success("切换状态成功")}}))}catch{}},$e=async j=>{var re;try{await((re=I.current)==null?void 0:re.agent_api.setAgentExplicit({data:{number:j},success:()=>{It.success(`切换[${j}]外显号码成功`)}}))}catch{}},Be=async()=>{var j;try{await((j=I.current)==null?void 0:j.agent_api.getAgentState({success:re=>{z(re.data)}}))}catch{}},Me=async j=>{var re;try{await((re=I.current)==null?void 0:re.call_api.makeCall(j))}catch(X){const{msg:Ce}=JSON.parse(X.message);It.warning(Ce)}},st=async()=>{var j;try{await((j=I.current)==null?void 0:j.call_api.answerCall())}catch(re){const{msg:X}=JSON.parse(re.message);It.warning(X)}},At=async()=>{var j;try{(j=I.current)==null||j.call_api.cancelCall()}catch(re){const{msg:X}=JSON.parse(re.message);It.warning(X)}},Ct=async()=>{var j;try{await((j=I.current)==null?void 0:j.call_api.hangup())}catch(re){const{msg:X}=JSON.parse(re.message);It.warning(X)}},Nt=async()=>{var j;try{(j=I.current)==null||j.call_api.holdCall()}catch(re){const{msg:X}=JSON.parse(re.message);It.warning(X)}},Jt=()=>{var j;(j=I.current)==null||j.call_api.unholdCall()},Wt=async j=>{var re;try{await((re=I.current)==null?void 0:re.call_api.consultCall(j))}catch(X){const{msg:Ce}=JSON.parse(X.message);It.warning(Ce)}},en=async()=>{var j;try{(j=I.current)==null||j.call_api.consultRetrieve()}catch(re){const{msg:X}=JSON.parse(re.message);It.warning(X)}},_t=async()=>{var j;try{(j=I.current)==null||j.call_api.consultTransfer()}catch(re){const{msg:X}=JSON.parse(re.message);It.warning(X)}},Zt=()=>{var j;try{(j=I.current)==null||j.call_api.mute()}catch(re){const{msg:X}=JSON.parse(re.message);It.warning(X)}},Ot=()=>{var j;try{(j=I.current)==null||j.call_api.unmute()}catch(re){const{msg:X}=JSON.parse(re.message);It.warning(X)}},pt=()=>{var j;try{(j=I.current)==null||j.call_api.satisfactionEvaluation()}catch(re){const{msg:X}=JSON.parse(re.message);It.warning(X)}},Ve=()=>{var j;try{(j=I.current)==null||j.call_api.startConference()}catch(re){const{msg:X}=JSON.parse(re.message);It.warning(X)}},_e=async j=>{var re;try{await((re=I.current)==null?void 0:re.call_api.transferAgent(j))}catch(X){const{msg:Ce}=JSON.parse(X.message);It.warning(Ce)}},Te=async j=>{var re;try{await((re=I.current)==null?void 0:re.call_api.transferOutline(j))}catch(X){const{msg:Ce}=JSON.parse(X.message);It.warning(Ce)}},ot=async()=>{var j;try{await((j=I.current)==null?void 0:j.call_api.earSpeakStart({success:()=>{}}))}catch(re){const{msg:X}=JSON.parse(re.message);It.warning(X)}},mt=async()=>{var j;try{await((j=I.current)==null?void 0:j.call_api.earSpeakStop({success:()=>{}}))}catch(re){const{msg:X}=JSON.parse(re.message);It.warning(X)}},Fe=async()=>{var j;try{await((j=I.current)==null?void 0:j.call_api.forceInsert({}))}catch(re){const{msg:X}=JSON.parse(re.message);It.warning(X)}},we=async()=>{var j;try{await((j=I.current)==null?void 0:j.call_api.forceDisconnect({}))}catch(re){const{msg:X}=JSON.parse(re.message);It.warning(X)}},Ke=ae.jsx(cN,{onPressEnter:j=>{j&&Me(j)}},je),ze=N.useMemo(()=>[{name:"call_number",icon:ae.jsx(No,{trigger:"click",rootClassName:"call-number-popover",destroyTooltipOnHide:!0,onOpenChange:re=>{Le(new Date().getTime())},content:Ke,children:ae.jsx(vt,{name:"boda",color:"#48D866",size:25})})},{name:"answer",icon:ae.jsx(vt,{name:"jieting",onClick:st,size:25})},{name:"hold",icon:ae.jsx(vt,{name:"baochi",color:"#1D92E9",onClick:Nt,size:25})},{name:"unhold",icon:ae.jsx(vt,{name:"quxiaobaochi",color:"#1D92E9",onClick:Jt,size:25})},{name:"mute",icon:ae.jsx(vt,{name:"mk",onClick:Zt,color:"#1D92E9",size:25})},{name:"unmute",icon:ae.jsx(vt,{name:"guanbimk",onClick:Ot,color:"#1D92E9",size:25})},{name:"satisfaction",icon:ae.jsx(vt,{name:"manyidu",onClick:pt,size:25})},{name:"consult",icon:ae.jsx(vt,{name:"zixun",onClick:()=>{le(!0)},size:25})},{name:"consult_transfer",icon:ae.jsx(vt,{name:"zhuanjie",onClick:_t,size:25})},{name:"transfer",icon:ae.jsx(vt,{size:25,name:"zhuanjie",onClick:()=>{xe(!0)}})},{name:"consult_retrieve",icon:ae.jsx(vt,{name:"fanhui",color:"#ffc53d",size:25,onClick:en})},{name:"conference",icon:ae.jsx(vt,{name:"huiyi",onClick:Ve,size:25})},{name:"whisper",icon:ae.jsx(Cl,{bg:"#1D92E9",children:ae.jsx(vt,{name:"whisper",size:15,color:"#fff",onClick:ot})})},{name:"cancel_whisper",icon:ae.jsx(Cl,{bg:"red",children:ae.jsx(vt,{name:"cancel_whisper",size:15,color:"#fff",onClick:mt})})},{name:"force_insert",icon:ae.jsx(Cl,{bg:"#1D92E9",children:ae.jsx(vt,{name:"force_insert",size:15,color:"#fff",onClick:Fe})})},{name:"force_disconnect",icon:ae.jsx(vt,{name:"force_disconnect",onClick:we,size:25})},{name:"reject",icon:ae.jsx(vt,{name:"jujie",color:"red",onClick:At,size:25})},{name:"hangup",icon:ae.jsx(vt,{name:"guaji",color:"red",onClick:Ct,size:25})},{name:"dtmf",icon:ae.jsx(No,{trigger:"click",onOpenChange:()=>{Ze("")},title:ae.jsx(di,{style:{borderRadius:20,textAlign:"center"},placeholder:"点击进行发送按键",value:Oe}),content:ae.jsx("div",{style:{width:300},children:ae.jsx(Dy,{onCallBack:re=>{var Ce;const X=Oe+re;Ze(X),(Ce=I.current)==null||Ce.call_api.sendDTMF(re)}})}),children:ae.jsx(vt,{name:"dtmf",size:25})})}].filter(({name:re})=>q.includes(re)),[q,Oe]);return ae.jsx(ae.Fragment,{children:ae.jsxs(_r,{prefixCls:"ysyt",theme:{components:{Select:{selectorBg:"none"}}},children:[Z?ae.jsx(Sc,{spinning:R,children:ae.jsxs(WI,{height:v,children:[ae.jsx(JI,{children:ae.jsx(go,{variant:"underlined",value:P,onChange:j=>{Je(j)},options:(((Ue=I.current.getAgentData())==null?void 0:Ue.answer_devices)||[]).map(j=>({...j,label:ae.jsxs("div",{style:{display:"flex",alignItems:"center"},children:[SN[j.value],ae.jsx("span",{style:{marginLeft:5},children:j.label})]})})),style:{width:140}})}),ae.jsxs(_I,{background:tt(IN[Z]??2),children:[ae.jsxs("div",{className:"ysyt-strip",children:[ae.jsx("div",{children:J?ae.jsx("span",{className:"ysyt-strip-state-name",children:J}):ae.jsx(ty,{trigger:["click"],menu:{items:$.map(j=>({label:ae.jsxs("div",{style:{display:"flex",alignItems:"center"},children:[j.state===1?ae.jsx(vt,{name:"kongxian",color:"#7cb305",size:16}):ae.jsx(vt,{name:"manglu",color:"#f5222d",size:16}),ae.jsx("span",{style:{marginLeft:10},children:j.state_name})]}),key:j.state_name,onClick:()=>{lt(j.state,j.state_name)}}))},children:ae.jsxs("div",{style:{color:"#fff",cursor:"pointer",display:"flex",alignItems:"center"},children:[Z==="空闲"?ae.jsx(vt,{name:"kongxian",color:"#fff",size:20}):ae.jsx(ae.Fragment,{children:Z==="未注册"?ae.jsx(vt,{name:"unregistered",size:20}):ae.jsx(vt,{name:"manglu2",size:20})}),ae.jsx("span",{style:{margin:"0 10px"},children:Z}),ae.jsx(vt,{name:"xia",color:"#fff"})]})})}),ae.jsx("div",{className:"ysyt-strip-time",children:ae.jsx(dN,{},B)}),u&&S&&ae.jsx("div",{className:"ysyt-strip-call-card",onClick:()=>pe(!Ie),children:Ie?ae.jsx(vt,{name:"unopen",color:"#fff"}):ae.jsx(vt,{name:"open",color:"#fff"})})]}),ae.jsx("div",{className:"ysyt-action",children:ze.map(({name:j,icon:re})=>ae.jsx(us,{title:wN[j],children:re},j))}),te&&ae.jsx(s2,{children:ae.jsx("div",{children:ae.jsx(No,{trigger:"click",title:"外显号码池",onOpenChange:j=>{j||Y("")},content:ae.jsxs(A2,{children:[ae.jsx("div",{children:ae.jsx(di,{value:me,placeholder:"请输入外显号码",onChange:j=>Y(j.target.value)})}),ae.jsx("div",{className:"ysyt-number-content",children:ae.jsx(os.Group,{value:ue,onChange:j=>{$e(j.target.value)},options:se.filter(j=>j.includes(me)).map(j=>({label:ae.jsx(c2,{style:{color:ue===j?"#1D92E9":""},children:j},j),value:j}))})})]}),children:ae.jsxs("div",{style:{fontSize:14,cursor:"pointer",color:w||"#333",display:"flex",alignItems:"center"},children:[ae.jsx(vt,{name:"external",color:w||"#333"}),ae.jsx("span",{style:{margin:"0 5px"},children:"外显号码"}),ae.jsx(vt,{name:"xia",color:w||"#333"})]})})})})]}),ae.jsx(r2,{children:b&&b.rtt&&ae.jsx("div",{children:ae.jsx(No,{content:ae.jsxs("div",{children:[ae.jsxs("div",{children:["延迟: ",b.rtt,"ms"]}),b.jitter&&ae.jsxs("div",{children:["抖动: ",b.jitter,"ms"]}),ae.jsxs("div",{children:["丢包: ",b.packetsLost||0]}),b.packetsReceived?ae.jsxs("div",{children:["接收: ",b.packetsReceived]}):null,b.packetsSent?ae.jsxs("div",{children:["发送: ",b.packetsSent]}):null,b.sendBitrate?ae.jsxs("div",{children:["发送码率: ",b.sendBitrate,"KB/s"]}):null,b.recvBitrate?ae.jsxs("div",{children:["接收码率: ",b.recvBitrate,"KB/s"]}):null]}),placement:"bottomLeft",children:ae.jsxs("div",{style:{padding:"0 10px"},children:[b.rtt>=250?ae.jsx(vt,{name:"wifi1"}):"",b.rtt>=121&&b.rtt<250?ae.jsx(vt,{name:"wifi2"}):"",b.rtt<=120?ae.jsx(vt,{name:"wifi3"}):""]})})})}),u&&ae.jsxs(a2,{height:v,show:!!S&&Ie,children:[ae.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:10},children:[ae.jsxs("div",{style:{display:"flex",alignItems:"center"},children:[(S==null?void 0:S.is_vip)===1&&ae.jsx(vt,{name:"vip"}),ae.jsx("span",{style:{marginLeft:5},children:S==null?void 0:S.customer_name})]}),ae.jsx("b",{children:S==null?void 0:S.phone})]}),ae.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[ae.jsxs("span",{children:[S==null?void 0:S.province,"-",S==null?void 0:S.city]}),ve&&ae.jsxs("span",{children:["当月",ve==="out"?"呼出次数:":"呼入次数:",ae.jsx("span",{style:{color:"#1D92E9"},children:ve==="out"?S==null?void 0:S.contact_count_month:S==null?void 0:S.in_contact_count_month})]})]}),ae.jsx("div",{style:{display:"flex",justifyContent:"flex-end",alignItems:"center"},children:ve&&ae.jsxs("span",{children:["总",ve==="out"?"呼出次数:":"呼入次数:",ae.jsx("span",{style:{color:"#1D92E9"},children:ve==="out"?(S==null?void 0:S.contact_count)||0:(S==null?void 0:S.in_contact_count)||0})]})})]})]})}):ae.jsx(ae.Fragment,{}),ae.jsx(N.Suspense,{children:de&&((F=I.current)==null?void 0:F.agent_api)&&ae.jsx(xN,{open:de,queryFetch:I.current.agent_api.getIdleAgentList,onCallBack:j=>{le(!1),j&&Wt(j)}})}),ae.jsx(N.Suspense,{children:Se&&((ge=I.current)==null?void 0:ge.agent_api)&&ae.jsx(RN,{open:Se,queryFetch:I.current.agent_api.getIdleAgentList,onCallBack:(j,re)=>{xe(!1),j&&(re===0?_e(j):re===1&&Te(j))}})})]})})},MN=t=>{var e;return(e=kn.getInstance())==null?void 0:e.call_api.makeCall(t)},TN=()=>{var t;return(t=kn.getInstance())==null?void 0:t.getRealTimeCustomerInfo()},NN=async t=>{var e,n;if(t!==Rt.IDLE&&t!==Rt.BUSY)throw new Error("Invalid agent state");try{await((n=(e=kn.getInstance())==null?void 0:e.agent_api)==null?void 0:n.changeState({data:{state:t,state_name:t===Rt.IDLE?"空闲":"忙碌"}}))}catch(r){console.error(r)}},DN=async t=>{var e,n;try{await((n=(e=kn.getInstance())==null?void 0:e.agent_api)==null?void 0:n.changeDevice({data:{device:t}}))}catch(r){console.error(r)}},BN=async(t=!1,e)=>{var n,r;try{await((r=(n=kn.getInstance())==null?void 0:n.agent_api)==null?void 0:r.agentLogout({data:{offline_answer:t},success:()=>{e==null||e()}}))}catch(i){console.log(i)}},FN=async(t,e)=>{var n,r;(r=(n=kn.getInstance())==null?void 0:n.call_api)==null||r.previewMakeCall(t,e)},kN=async t=>{var e,n;try{await((n=(e=kn.getInstance())==null?void 0:e.agent_api)==null?void 0:n.listenAgentCall({data:{monitored_agent_no:t},success:()=>{It.success("监听坐席通话成功")}}))}catch(r){console.error(r)}},PN=async()=>{var t,e;try{await((e=(t=kn.getInstance())==null?void 0:t.call_api)==null?void 0:e.earSpeakStart({}))}catch(n){console.log(n)}},QN=async()=>{var t,e;try{await((e=(t=kn.getInstance())==null?void 0:t.call_api)==null?void 0:e.earSpeakStop({}))}catch(n){console.log(n)}},jN=async()=>{var t,e;try{await((e=(t=kn.getInstance())==null?void 0:t.call_api)==null?void 0:e.forceInsert({}))}catch(n){console.log(n)}},LN=async()=>{var t,e;try{await((e=(t=kn.getInstance())==null?void 0:t.call_api)==null?void 0:e.forceDisconnect({}))}catch(n){console.log(n)}};exports.Button=Ao;exports.CONTAINER_MAX_OFFSET=sf;exports.CSSMotion=lo;exports.ConfigContext=Qt;exports.ConfigProvider=_r;exports.ContextIsolator=Ua;exports.DisabledContextProvider=Vv;exports.Empty=si;exports.FastColor=Gt;exports.Input=di;exports.KeyCode=at;exports.Keyframe=Pt;exports.ModelBody=n2;exports.Portal=gc;exports.Radio=os;exports.RefIcon=yc;exports.RefIcon$1=Rf;exports.RefIcon$2=as;exports.RefIcon$3=xf;exports.RefIcon$4=Of;exports.Space=Cc;exports.Spin=Sc;exports.Wave=nc;exports.YsytBarPhone=ON;exports.YsytIconSvg=vt;exports._extends=Qe;exports._objectSpread2=L;exports._slicedToArray=ee;exports._toConsumableArray=Re;exports._typeof=et;exports.agentLogout=BN;exports.callForceInsert=jN;exports.callForceSplit=LN;exports.canUseDom=Ln;exports.classNames=Ae;exports.clearFix=sA;exports.contains=tv;exports.convertLegacyProps=eR;exports.devUseWarning=cn;exports.genFocusStyle=AA;exports.genPresetColor=Uv;exports.genStyleHooks=Tn;exports.genSubStyleComponent=Lv;exports.getConfirmLocale=Wb;exports.getCustomerInfo=TN;exports.getReactRender=uf;exports.getTransitionName=sc;exports.globalConfig=Gd;exports.initMotion=XA;exports.initZoomMotion=Xa;exports.isPresetColor=WC;exports.isPresetStatusColor=OM;exports.jsxRuntimeExports=ae;exports.listenCall=kN;exports.localeValues=oo;exports.makeCall=MN;exports.merge=zt;exports.omit=tr;exports.pickAttrs=ki;exports.previewMakeCall=FN;exports.replaceElement=k1;exports.resetComponent=zn;exports.setAgentDevice=DN;exports.setAgentInitState=NN;exports.startEarSpeak=PN;exports.stopEarSpeak=QN;exports.unit=ye;exports.useCSSVarCls=Ur;exports.useComponentConfig=Jr;exports.useComposeRef=ji;exports.useEvent=rn;exports.useId=rc;exports.useLocale=HA;exports.useSafeState=Lo;exports.useToken=dr;exports.useZIndex=ts;exports.warnContext=s0;exports.warning=Di;exports.withPureRenderTheme=MC;exports.zIndexContext=es;
694
+ `,ON=t=>{var Ue,F,ge;const{style:e,logBuiltinEnabled:n,browserAlertTime:r,enableBrowserAlert:i,agentNo:o,appKey:a,appSecret:s,url:A,onCallBack:c,ringingCardShow:u=!0,onLoginCancel:d,isCheckLogin:f,...p}=t,{height:v,busy:C,idle:m,unavailable:y,selectOutNumberColor:w}=e||{},I=N.useRef(),O=N.useRef(),[x,g]=N.useState(new Audio(fN)),M=N.useRef(),E=N.useRef(),[b,h]=N.useState(),[S,T]=N.useState(),[R,D]=N.useState(!1),[B,k]=N.useState(new Date().getTime()),[P,H]=N.useState(),[Z,V]=N.useState(),[q,U]=N.useState([]),[$,z]=N.useState([]),[J,W]=N.useState(""),[te,_]=N.useState(!1),[se,ce]=N.useState([]),[ue,ne]=N.useState(""),[me,Y]=N.useState(""),[de,le]=N.useState(!1),[Se,xe]=N.useState(!1),[ve,De]=N.useState(),[je,Le]=N.useState(new Date().getTime()),[Ie,pe]=N.useState(!0),[Oe,Ze]=N.useState(""),tt=j=>{switch(j){case Rt.IDLE:return m||"#1D92E9";case Rt.BUSY:return C||"#F5212D";case Rt.UNREGISTERED:return y||"#faad14";case Rt.OFFLINE:return y||"#8c8c8c";default:return"#1D92E9"}};N.useEffect(()=>((async()=>(D(!0),I.current=kn.getInstance({agentNo:o,appKey:a,appSecret:s,url:A}),rt(),I.current.on(He.PHONE_BAR_OPERATION,j=>{console.log(j),U(j)}),f?await I.current.agent_api.checkAgentLogin({data:{agent_no:o},success:async j=>{j.data.is_login?bN({title:"当前账号已登录!",icon:ae.jsx(vt,{name:"wing",size:20}),content:"是否继续登录",onOk:async()=>{await I.current.init({...p,logBuiltinEnabled:n,browserAlertTime:r,enableBrowserAlert:i,onCallBack:()=>{const re=I.current.getEarSpeakAgent();M.current=new Audio(re);const X=I.current.getEndSpeakAgent();E.current=new Audio(X)}}),O.current=I.current.getAgentData()},onCancel:()=>{d==null||d()}}):(await I.current.init({...p,logBuiltinEnabled:n,browserAlertTime:r,enableBrowserAlert:i,onCallBack:()=>{const re=I.current.getEarSpeakAgent();M.current=new Audio(re);const X=I.current.getEndSpeakAgent();E.current=new Audio(X)}}),O.current=I.current.getAgentData())}}):(await I.current.init({...p,logBuiltinEnabled:n,browserAlertTime:r,enableBrowserAlert:i,onCallBack:()=>{const j=I.current.getEarSpeakAgent();M.current=new Audio(j);const re=I.current.getEndSpeakAgent();E.current=new Audio(re)}}),O.current=I.current.getAgentData()),k(new Date().getTime()),D(!1)))(),()=>{var j;be(x),be(M.current),(j=I.current)==null||j.destroy()}),[]);const rt=()=>{var j,re;(j=I.current)==null||j.on(He.EVENT_ALL,({event:X,data:Ce})=>{switch(console.log(X),X){case ie.OUT_SUCCESS:case ie.CONSULT_RINGING:{Ge(x),De("out"),be(E.current);return}case ie.OUT_INCOMING_CALL:case ie.INTERNAL_OUT_INCOMING_CALL:{c==null||c(X,{customer_phone:Ce.customer_phone,session_id:Ce.session_id});return}case ie.PREVIEW_OUT_INCOMING_CALL:{c==null||c(ie.PREVIEW_OUT_INCOMING_CALL,{customer_phone:Ce.customer_phone,session_id:Ce.session_id,preview_task_id:Ce.preview_task_id});return}case ie.OUT_OFF_ANSWER:case ie.INTERNAL_OUT_OFF_ANSWER:case ie.OUT_FAILED:case ie.CONSULT_FAILED:case ie.OUT_RINGING:case ie.CONSULT_OFF_HOOK:{X===ie.OUT_OFF_ANSWER&&(c==null||c(X,{session_id:Ce.session_id})),be(x);return}case ie.CONSULT_INCOMING:case ie.TRANSFER_INCOMING_CALL:case ie.LISTEN_INCOMING_CALL:case ie.INCOMING_CALL_IN:case ie.INCOMING_CALL:{De("in"),be(E.current),(X===ie.CONSULT_INCOMING||X===ie.TRANSFER_INCOMING_CALL)&&(c==null||c(X,{agent_no:Ce.agent_no,agent_name:Ce.agent_name,session_id:Ce.session_id})),X===ie.INCOMING_CALL?c==null||c(ie.INCOMING_CALL,{customer_phone:Ce.customer_phone,session_id:Ce.session_id}):X===ie.INCOMING_CALL_IN?c==null||c(ie.INCOMING_CALL_IN,{customer_phone:Ce.customer_phone,session_id:Ce.session_id}):X===ie.LISTEN_INCOMING_CALL&&(c==null||c(ie.LISTEN_INCOMING_CALL,{session_id:Ce.session_id}));const{soft_device_ring_switch:ke}=I.current.getAgentData();if(!ke)return;Ge(M.current);return}case ie.PREDICT_INCOMING_CALL:{De("out"),be(E.current),X===ie.PREDICT_INCOMING_CALL&&(c==null||c(ie.PREDICT_INCOMING_CALL,{customer_phone:Ce.customer_phone,session_id:Ce.session_id}));const{soft_device_ring_switch:ke}=I.current.getAgentData();if(!ke)return;Ge(M.current);return}case ie.DUAL_CALL_INCOMING_CALL:{De("out"),be(E.current),X===ie.DUAL_CALL_INCOMING_CALL&&(c==null||c(ie.DUAL_CALL_INCOMING_CALL,{customer_phone:Ce.customer_phone,session_id:Ce.session_id}));const{soft_device_ring_switch:ke}=I.current.getAgentData();if(!ke)return;Ge(M.current);return}case ie.TRANSFER_OFF_HOOK:case ie.LISTEN_INCOMING_CALL_OFF_HOOK:case ie.CONSULT_CALL_IN_SUCCESS:case ie.INCOMING_CALL_IN_OFF_HOOK:case ie.INCOMING_CALL_OFF_HOOK:{X===ie.LISTEN_INCOMING_CALL_OFF_HOOK?c==null||c(X,{session_id:Ce.session_id,monitored_agent_no:Ce.monitored_agent_no}):c==null||c(X,{session_id:Ce.session_id}),be(M.current);return}case ie.OUT_HANGUP:case ie.LISTEN_HANGUP:case ie.LISTEN_CALL_FAILED:case ie.TRANSFER_END:case ie.THREE_WAY_OUR_SIDE_HANGUP:case ie.OUR_SIDE_CONSULT_HANGUP:case ie.OTHER_SIDE_CONSULT_HANGUP:case ie.INCOMING_CALL_END:{if(c==null||c(X,{session_id:Ce.session_id}),be(M.current),be(x),De(void 0),le(!1),xe(!1),X===ie.OUT_HANGUP||X===ie.INCOMING_CALL_END){const{isAgentHangup:ke}=Ce,{agent_hangup_ring_switch:Xe}=I.current.getAgentData();!ke&&Xe&&Ge(E.current,!1)}return}case ie.REJECT:c==null||c(X,{session_id:Ce.session_id});return;case ie.CUSTOMER_INFO:c(X,Ce);return;default:return null}}),(re=I.current)==null||re.on(ie.AGENT_STATE,X=>{if(V(X.state_name),k(new Date().getTime()),c==null||c(ie.AGENT_STATE,X),X.state===Rt.UNREGISTERED){It.warning("当前已掉线,自动重连中,请检查网络"),be(x);const{soft_device_ring_switch:Ce}=I.current.getAgentData();if(!Ce)return;be(M.current)}}).on(ie.CALL_PROGRESS,X=>{W(X)}).on(He.WEBSITE_DELAY,X=>{h(X)}).on(ie.CUSTOMER_INFO,X=>{T(X),X&&pe(!0)}).on(He.AGENT_INIT_STATUS,X=>{if(X){const{default_device:Ce,out_display_select_switch:ke,out_display_data:Xe,stateObject:{state_name:Ft}}=I.current.getAgentData();_(ke===1),ke===1&&ce((Xe||"").split("#")),H(Ce),V(Ft),Be()}}).on(He.SELECT_EXTERNAL_NUMBER,X=>{ne(X)}).on(He.FAIL_NOTIFICATION,X=>{be(x),be(M.current),It.error(X)}).on(He.KICK_OFF,()=>{be(x),be(M.current),c?c==null||c(He.KICK_OFF):It.warning("您的座席账号已在别处登录,请重新登录。如非您本人操作,请及时修改密码。"),V("")}).on(He.DESTROY,()=>{c==null||c(He.DESTROY),It.success("已离线"),be(x),be(M.current)}).on(He.NETWORK_OFFLINE,()=>{It.warning("网络已断开,请检查网络设置。"),be(x),be(M.current)}).on(He.NETWORK_ONLINE,()=>{It.success("网络已恢复")}).on(He.SIGN_OUT,()=>{c==null||c(He.SIGN_OUT),It.success("已被签出"),be(x),be(M.current)}).on(ie.LISTEN_CALL_FAILED,()=>{c==null||c(ie.LISTEN_CALL_FAILED),It.error("监听失败")}).on(ie.EAR_SPEECH_SUCCESS,({monitored_agent_no:X})=>{c==null||c(ie.EAR_SPEECH_SUCCESS,{monitored_agent_no:X}),It.success("正在耳语")}).on(ie.EAR_SPEECH_BE_SUCCESS,({monitor_agent_no:X})=>{c==null||c(ie.EAR_SPEECH_BE_SUCCESS,{monitor_agent_no:X}),It.success(`${X}正在与你耳语`)}).on(ie.EAR_SPEECH_FAILED,()=>{c==null||c(ie.EAR_SPEECH_FAILED),It.error("耳语失败")}).on(ie.STOP_EAR_SPEECH_SUCCESS,()=>{c==null||c(ie.STOP_EAR_SPEECH_SUCCESS),It.success("停止耳语")}).on(ie.CALL_FORCE_INSERT_SUCCESS,({monitored_agent_no:X,monitor_agent_no:Ce})=>{c==null||c(ie.CALL_FORCE_INSERT_SUCCESS,{monitored_agent_no:X,monitor_agent_no:Ce}),It.success("强插成功")}).on(ie.CALL_FORCE_INSERT_SUCCESS_LISTENER,({monitored_agent_no:X,monitor_agent_no:Ce})=>{c==null||c(ie.CALL_FORCE_INSERT_SUCCESS_LISTENER,{monitored_agent_no:X,monitor_agent_no:Ce}),It.success(`${Ce}强插`)}).on(He.SIGN_IN_SWITCH_DEVICE,X=>{c==null||c(He.SIGN_IN_SWITCH_DEVICE),It.success(`已被切换${X.answer_device===2?"手机模式":"SIP 话机"}设备`)}).on(ie.CALL_SIP_INCOMING_CALL,()=>{It.success("SIP话机有新的呼入")})};N.useEffect(()=>{var j;(j=I.current)==null||j.setBrowserAlertTime(r||3)},[r]),N.useEffect(()=>{var j;(j=I.current)==null||j.setBrowserAlert(i||!1)},[i]);const Ge=(j,re=!0)=>{j&&(j.currentTime=0,j.loop=re,j.play())},be=j=>{j&&j.pause()},Je=async j=>{var re;try{await((re=I.current)==null?void 0:re.agent_api.changeDevice({data:{device:j},success:()=>{H(j),It.success("切换设备成功")}}))}catch{}},lt=async(j,re)=>{var X;try{await((X=I.current)==null?void 0:X.agent_api.changeState({data:{state:j,state_name:re},success:()=>{V(re),It.success("切换状态成功")}}))}catch{}},$e=async j=>{var re;try{await((re=I.current)==null?void 0:re.agent_api.setAgentExplicit({data:{number:j},success:()=>{It.success(`切换[${j}]外显号码成功`)}}))}catch{}},Be=async()=>{var j;try{await((j=I.current)==null?void 0:j.agent_api.getAgentState({success:re=>{z(re.data)}}))}catch{}},Me=async j=>{var re;try{await((re=I.current)==null?void 0:re.call_api.makeCall(j))}catch(X){const{msg:Ce}=JSON.parse(X.message);It.warning(Ce)}},st=async()=>{var j;try{await((j=I.current)==null?void 0:j.call_api.answerCall())}catch(re){const{msg:X}=JSON.parse(re.message);It.warning(X)}},At=async()=>{var j;try{(j=I.current)==null||j.call_api.cancelCall()}catch(re){const{msg:X}=JSON.parse(re.message);It.warning(X)}},Ct=async()=>{var j;try{await((j=I.current)==null?void 0:j.call_api.hangup())}catch(re){const{msg:X}=JSON.parse(re.message);It.warning(X)}},Nt=async()=>{var j;try{(j=I.current)==null||j.call_api.holdCall()}catch(re){const{msg:X}=JSON.parse(re.message);It.warning(X)}},Jt=()=>{var j;(j=I.current)==null||j.call_api.unholdCall()},Wt=async j=>{var re;try{await((re=I.current)==null?void 0:re.call_api.consultCall(j))}catch(X){const{msg:Ce}=JSON.parse(X.message);It.warning(Ce)}},en=async()=>{var j;try{(j=I.current)==null||j.call_api.consultRetrieve()}catch(re){const{msg:X}=JSON.parse(re.message);It.warning(X)}},_t=async()=>{var j;try{(j=I.current)==null||j.call_api.consultTransfer()}catch(re){const{msg:X}=JSON.parse(re.message);It.warning(X)}},Zt=()=>{var j;try{(j=I.current)==null||j.call_api.mute()}catch(re){const{msg:X}=JSON.parse(re.message);It.warning(X)}},Ot=()=>{var j;try{(j=I.current)==null||j.call_api.unmute()}catch(re){const{msg:X}=JSON.parse(re.message);It.warning(X)}},pt=()=>{var j;try{(j=I.current)==null||j.call_api.satisfactionEvaluation()}catch(re){const{msg:X}=JSON.parse(re.message);It.warning(X)}},Ve=()=>{var j;try{(j=I.current)==null||j.call_api.startConference()}catch(re){const{msg:X}=JSON.parse(re.message);It.warning(X)}},_e=async j=>{var re;try{await((re=I.current)==null?void 0:re.call_api.transferAgent(j))}catch(X){const{msg:Ce}=JSON.parse(X.message);It.warning(Ce)}},Te=async j=>{var re;try{await((re=I.current)==null?void 0:re.call_api.transferOutline(j))}catch(X){const{msg:Ce}=JSON.parse(X.message);It.warning(Ce)}},ot=async()=>{var j;try{await((j=I.current)==null?void 0:j.call_api.earSpeakStart({success:()=>{}}))}catch(re){const{msg:X}=JSON.parse(re.message);It.warning(X)}},mt=async()=>{var j;try{await((j=I.current)==null?void 0:j.call_api.earSpeakStop({success:()=>{}}))}catch(re){const{msg:X}=JSON.parse(re.message);It.warning(X)}},Fe=async()=>{var j;try{await((j=I.current)==null?void 0:j.call_api.forceInsert({}))}catch(re){const{msg:X}=JSON.parse(re.message);It.warning(X)}},we=async()=>{var j;try{await((j=I.current)==null?void 0:j.call_api.forceDisconnect({}))}catch(re){const{msg:X}=JSON.parse(re.message);It.warning(X)}},Ke=ae.jsx(cN,{onPressEnter:j=>{j&&Me(j)}},je),ze=N.useMemo(()=>[{name:"call_number",icon:ae.jsx(No,{trigger:"click",rootClassName:"call-number-popover",destroyTooltipOnHide:!0,onOpenChange:re=>{Le(new Date().getTime())},content:Ke,children:ae.jsx(vt,{name:"boda",color:"#48D866",size:25})})},{name:"answer",icon:ae.jsx(vt,{name:"jieting",onClick:st,size:25})},{name:"hold",icon:ae.jsx(vt,{name:"baochi",color:"#1D92E9",onClick:Nt,size:25})},{name:"unhold",icon:ae.jsx(vt,{name:"quxiaobaochi",color:"#1D92E9",onClick:Jt,size:25})},{name:"mute",icon:ae.jsx(vt,{name:"mk",onClick:Zt,color:"#1D92E9",size:25})},{name:"unmute",icon:ae.jsx(vt,{name:"guanbimk",onClick:Ot,color:"#1D92E9",size:25})},{name:"satisfaction",icon:ae.jsx(vt,{name:"manyidu",onClick:pt,size:25})},{name:"consult",icon:ae.jsx(vt,{name:"zixun",onClick:()=>{le(!0)},size:25})},{name:"consult_transfer",icon:ae.jsx(vt,{name:"zhuanjie",onClick:_t,size:25})},{name:"transfer",icon:ae.jsx(vt,{size:25,name:"zhuanjie",onClick:()=>{xe(!0)}})},{name:"consult_retrieve",icon:ae.jsx(vt,{name:"fanhui",color:"#ffc53d",size:25,onClick:en})},{name:"conference",icon:ae.jsx(vt,{name:"huiyi",onClick:Ve,size:25})},{name:"whisper",icon:ae.jsx(Cl,{bg:"#1D92E9",children:ae.jsx(vt,{name:"whisper",size:15,color:"#fff",onClick:ot})})},{name:"cancel_whisper",icon:ae.jsx(Cl,{bg:"red",children:ae.jsx(vt,{name:"cancel_whisper",size:15,color:"#fff",onClick:mt})})},{name:"force_insert",icon:ae.jsx(Cl,{bg:"#1D92E9",children:ae.jsx(vt,{name:"force_insert",size:15,color:"#fff",onClick:Fe})})},{name:"force_disconnect",icon:ae.jsx(vt,{name:"force_disconnect",onClick:we,size:25})},{name:"reject",icon:ae.jsx(vt,{name:"jujie",color:"red",onClick:At,size:25})},{name:"hangup",icon:ae.jsx(vt,{name:"guaji",color:"red",onClick:Ct,size:25})},{name:"dtmf",icon:ae.jsx(No,{trigger:"click",onOpenChange:()=>{Ze("")},title:ae.jsx(di,{style:{borderRadius:20,textAlign:"center"},placeholder:"点击进行发送按键",value:Oe}),content:ae.jsx("div",{style:{width:300},children:ae.jsx(Dy,{onCallBack:re=>{var Ce;const X=Oe+re;Ze(X),(Ce=I.current)==null||Ce.call_api.sendDTMF(re)}})}),children:ae.jsx(vt,{name:"dtmf",size:25})})}].filter(({name:re})=>q.includes(re)),[q,Oe]);return ae.jsx(ae.Fragment,{children:ae.jsxs(_r,{prefixCls:"ysyt",theme:{components:{Select:{selectorBg:"none"}}},children:[Z?ae.jsx(Sc,{spinning:R,children:ae.jsxs(WI,{height:v,children:[ae.jsx(JI,{children:ae.jsx(go,{variant:"underlined",value:P,onChange:j=>{Je(j)},options:(((Ue=I.current.getAgentData())==null?void 0:Ue.answer_devices)||[]).map(j=>({...j,label:ae.jsxs("div",{style:{display:"flex",alignItems:"center"},children:[SN[j.value],ae.jsx("span",{style:{marginLeft:5},children:j.label})]})})),style:{width:140}})}),ae.jsxs(_I,{background:tt(IN[Z]??2),children:[ae.jsxs("div",{className:"ysyt-strip",children:[ae.jsx("div",{children:J?ae.jsx("span",{className:"ysyt-strip-state-name",children:J}):ae.jsx(ty,{trigger:["click"],menu:{items:$.map(j=>({label:ae.jsxs("div",{style:{display:"flex",alignItems:"center"},children:[j.state===1?ae.jsx(vt,{name:"kongxian",color:"#7cb305",size:16}):ae.jsx(vt,{name:"manglu",color:"#f5222d",size:16}),ae.jsx("span",{style:{marginLeft:10},children:j.state_name})]}),key:j.state_name,onClick:()=>{lt(j.state,j.state_name)}}))},children:ae.jsxs("div",{style:{color:"#fff",cursor:"pointer",display:"flex",alignItems:"center"},children:[Z==="空闲"?ae.jsx(vt,{name:"kongxian",color:"#fff",size:20}):ae.jsx(ae.Fragment,{children:Z==="未注册"?ae.jsx(vt,{name:"unregistered",size:20}):ae.jsx(vt,{name:"manglu2",size:20})}),ae.jsx("span",{style:{margin:"0 10px"},children:Z}),ae.jsx(vt,{name:"xia",color:"#fff"})]})})}),ae.jsx("div",{className:"ysyt-strip-time",children:ae.jsx(dN,{},B)}),u&&S&&ae.jsx("div",{className:"ysyt-strip-call-card",onClick:()=>pe(!Ie),children:Ie?ae.jsx(vt,{name:"unopen",color:"#fff"}):ae.jsx(vt,{name:"open",color:"#fff"})})]}),ae.jsx("div",{className:"ysyt-action",children:ze.map(({name:j,icon:re})=>ae.jsx(us,{title:wN[j],children:re},j))}),te&&ae.jsx(s2,{children:ae.jsx("div",{children:ae.jsx(No,{trigger:"click",title:"外显号码池",onOpenChange:j=>{j||Y("")},content:ae.jsxs(A2,{children:[ae.jsx("div",{children:ae.jsx(di,{value:me,placeholder:"请输入外显号码",onChange:j=>Y(j.target.value)})}),ae.jsx("div",{className:"ysyt-number-content",children:ae.jsx(os.Group,{value:ue,onChange:j=>{$e(j.target.value)},options:se.filter(j=>j.includes(me)).map(j=>({label:ae.jsx(c2,{style:{color:ue===j?"#1D92E9":""},children:j},j),value:j}))})})]}),children:ae.jsxs("div",{style:{fontSize:14,cursor:"pointer",color:w||"#333",display:"flex",alignItems:"center"},children:[ae.jsx(vt,{name:"external",color:w||"#333"}),ae.jsx("span",{style:{margin:"0 5px"},children:"外显号码"}),ae.jsx(vt,{name:"xia",color:w||"#333"})]})})})})]}),ae.jsx(r2,{children:b&&b.rtt&&ae.jsx("div",{children:ae.jsx(No,{content:ae.jsxs("div",{children:[ae.jsxs("div",{children:["延迟: ",b.rtt,"ms"]}),b.jitter&&ae.jsxs("div",{children:["抖动: ",b.jitter,"ms"]}),ae.jsxs("div",{children:["丢包: ",b.packetsLost||0]}),b.packetsReceived?ae.jsxs("div",{children:["接收: ",b.packetsReceived]}):null,b.packetsSent?ae.jsxs("div",{children:["发送: ",b.packetsSent]}):null,b.sendBitrate?ae.jsxs("div",{children:["发送码率: ",b.sendBitrate,"KB/s"]}):null,b.recvBitrate?ae.jsxs("div",{children:["接收码率: ",b.recvBitrate,"KB/s"]}):null]}),placement:"bottomLeft",children:ae.jsxs("div",{style:{padding:"0 10px"},children:[b.rtt>=250?ae.jsx(vt,{name:"wifi1"}):"",b.rtt>=121&&b.rtt<250?ae.jsx(vt,{name:"wifi2"}):"",b.rtt<=120?ae.jsx(vt,{name:"wifi3"}):""]})})})}),u&&ae.jsxs(a2,{height:v,show:!!S&&Ie,children:[ae.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:10},children:[ae.jsxs("div",{style:{display:"flex",alignItems:"center"},children:[(S==null?void 0:S.is_vip)===1&&ae.jsx(vt,{name:"vip"}),ae.jsx("span",{style:{marginLeft:5},children:S==null?void 0:S.customer_name})]}),ae.jsx("b",{children:S==null?void 0:S.phone})]}),ae.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[ae.jsxs("span",{children:[S==null?void 0:S.province,"-",S==null?void 0:S.city]}),ve&&ae.jsxs("span",{children:["当月",ve==="out"?"呼出次数:":"呼入次数:",ae.jsx("span",{style:{color:"#1D92E9"},children:ve==="out"?S==null?void 0:S.contact_count_month:S==null?void 0:S.in_contact_count_month})]})]}),ae.jsx("div",{style:{display:"flex",justifyContent:"flex-end",alignItems:"center"},children:ve&&ae.jsxs("span",{children:["总",ve==="out"?"呼出次数:":"呼入次数:",ae.jsx("span",{style:{color:"#1D92E9"},children:ve==="out"?(S==null?void 0:S.contact_count)||0:(S==null?void 0:S.in_contact_count)||0})]})})]})]})}):ae.jsx(ae.Fragment,{}),ae.jsx(N.Suspense,{children:de&&((F=I.current)==null?void 0:F.agent_api)&&ae.jsx(xN,{open:de,queryFetch:I.current.agent_api.getIdleAgentList,onCallBack:j=>{le(!1),j&&Wt(j)}})}),ae.jsx(N.Suspense,{children:Se&&((ge=I.current)==null?void 0:ge.agent_api)&&ae.jsx(RN,{open:Se,queryFetch:I.current.agent_api.getIdleAgentList,onCallBack:(j,re)=>{xe(!1),j&&(re===0?_e(j):re===1&&Te(j))}})})]})})},MN=t=>{var e;return(e=kn.getInstance())==null?void 0:e.call_api.makeCall(t)},TN=()=>{var t;return(t=kn.getInstance())==null?void 0:t.getRealTimeCustomerInfo()},NN=async t=>{var e,n;if(t!==Rt.IDLE&&t!==Rt.BUSY)throw new Error("Invalid agent state");try{await((n=(e=kn.getInstance())==null?void 0:e.agent_api)==null?void 0:n.changeState({data:{state:t,state_name:t===Rt.IDLE?"空闲":"忙碌"}}))}catch(r){console.error(r)}},DN=async t=>{var e,n;try{await((n=(e=kn.getInstance())==null?void 0:e.agent_api)==null?void 0:n.changeDevice({data:{device:t}}))}catch(r){console.error(r)}},BN=async(t=!1,e)=>{var n,r;try{await((r=(n=kn.getInstance())==null?void 0:n.agent_api)==null?void 0:r.agentLogout({data:{offline_answer:t},success:()=>{e==null||e()}}))}catch(i){console.log(i)}},FN=async(t,e)=>{var n,r;(r=(n=kn.getInstance())==null?void 0:n.call_api)==null||r.previewMakeCall(t,e)},kN=async t=>{var e,n;try{await((n=(e=kn.getInstance())==null?void 0:e.agent_api)==null?void 0:n.listenAgentCall({data:{monitored_agent_no:t},success:()=>{It.success("监听坐席通话成功")}}))}catch(r){console.error(r)}},PN=async()=>{var t,e;try{await((e=(t=kn.getInstance())==null?void 0:t.call_api)==null?void 0:e.earSpeakStart({}))}catch(n){console.log(n)}},QN=async()=>{var t,e;try{await((e=(t=kn.getInstance())==null?void 0:t.call_api)==null?void 0:e.earSpeakStop({}))}catch(n){console.log(n)}},jN=async()=>{var t,e;try{await((e=(t=kn.getInstance())==null?void 0:t.call_api)==null?void 0:e.forceInsert({}))}catch(n){console.log(n)}},LN=async()=>{var t,e;try{await((e=(t=kn.getInstance())==null?void 0:t.call_api)==null?void 0:e.forceDisconnect({}))}catch(n){console.log(n)}};exports.Button=Ao;exports.CONTAINER_MAX_OFFSET=sf;exports.CSSMotion=lo;exports.ConfigContext=Qt;exports.ConfigProvider=_r;exports.ContextIsolator=Ua;exports.DisabledContextProvider=Vv;exports.Empty=si;exports.FastColor=Gt;exports.Input=di;exports.KeyCode=at;exports.Keyframe=Pt;exports.ModelBody=n2;exports.Portal=gc;exports.Radio=os;exports.RefIcon=yc;exports.RefIcon$1=Rf;exports.RefIcon$2=as;exports.RefIcon$3=xf;exports.RefIcon$4=Of;exports.Space=Cc;exports.Spin=Sc;exports.Wave=nc;exports.YsytBarPhone=ON;exports.YsytIconSvg=vt;exports._extends=Qe;exports._objectSpread2=L;exports._slicedToArray=ee;exports._toConsumableArray=Re;exports._typeof=et;exports.agentLogout=BN;exports.callForceInsert=jN;exports.callForceSplit=LN;exports.canUseDom=Ln;exports.classNames=Ae;exports.clearFix=sA;exports.contains=tv;exports.convertLegacyProps=eR;exports.devUseWarning=cn;exports.genFocusStyle=AA;exports.genPresetColor=Uv;exports.genStyleHooks=Tn;exports.genSubStyleComponent=Lv;exports.getConfirmLocale=Wb;exports.getCustomerInfo=TN;exports.getReactRender=uf;exports.getTransitionName=sc;exports.globalConfig=Gd;exports.initMotion=XA;exports.initZoomMotion=Xa;exports.isPresetColor=WC;exports.isPresetStatusColor=OM;exports.jsxRuntimeExports=ae;exports.listenCall=kN;exports.localeValues=oo;exports.makeCall=MN;exports.merge=zt;exports.omit=tr;exports.pickAttrs=ki;exports.previewMakeCall=FN;exports.replaceElement=k1;exports.resetComponent=zn;exports.setAgentDevice=DN;exports.setAgentInitState=NN;exports.startEarSpeak=PN;exports.stopEarSpeak=QN;exports.unit=ye;exports.useCSSVarCls=Ur;exports.useComponentConfig=Jr;exports.useComposeRef=ji;exports.useEvent=rn;exports.useId=rc;exports.useLocale=HA;exports.useSafeState=Lo;exports.useToken=dr;exports.useZIndex=ts;exports.warnContext=s0;exports.warning=Di;exports.withPureRenderTheme=MC;exports.zIndexContext=es;