Files
zyt/server/public/admin/assets/index-BPQRtzHa.js
T
2026-07-05 08:59:47 +08:00

71 lines
62 KiB
JavaScript

var $n=Object.defineProperty;var Gn=(i,e,n)=>e in i?$n(i,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):i[e]=n;var E=(i,e,n)=>Gn(i,typeof e!="symbol"?e+"":e,n);import{i as nn,d as an,g as Wn,G as zn,F as Kn,am as Xn,Y as Yn,r as on,f as jn,K as qn}from"./element-plus-CXrrycLn.js";import{s as me,q as ze}from"./@vue/runtime-dom-DDAG46FW.js";import{ai as rt,c as lt,Q as Jn,r as Bt,Y as Zn,aj as Qn,ak as ea,l as ta,al as na,am as aa}from"./@element-plus/icons-vue-BAghejlR.js";import{u as sn,_ as ft,i as F}from"./index-CO3hhC4Q.js";import{Z as oa,S as sa}from"./@mediapipe/tasks-vision-dSeFstGv.js";import{f as mt,w as rn,ae as ia,ak as R,I as P,F as ra,J as y,aq as la,a as h,aN as S,G as X,T as ln,O as fe,aP as Ke,H as $,A as J,n as Xe,aB as ca,ab as ua,b as da,d as fa}from"./@vue/runtime-core-C6bnekPw.js";import{r as Ot,y as A,n as T}from"./@vue/reactivity-DiY1c2vO.js";import{p as ct,Q,o as ut}from"./@vue/shared-mAAVTE9n.js";import{u as ma,l as ha}from"./file-BdBRZBUu.js";import{a as pa}from"./patient-CXHiwyhn.js";import{O as ot,ac as va,ax as ga,ay as ya,az as _a}from"./tcm-ujpoSvdA.js";import{E as ba}from"./@tencentcloud/chat-uikit-vue3-CLQ__Wr9.js";import{p as wa}from"./im-business-message-parse-QKjFLn3X.js";import{g as Ea,G as Ta,C as Sa,M as Ca,a as Aa,O as ka,E as Ra,N as xa,S as Ia,A as La,b as Ma}from"./tuikit-atomicx-vue3-Dln8Zi6e.js";import{T as ye}from"./@tencentcloud/chat-AC2Y2r2A.js";import{X as Ht}from"./@tencentcloud/chat-uikit-engine-zx802ozq.js";import{u as Da,F as H,z as Pa,g as ae,a as oe,l as q}from"./@tencentcloud/call-uikit-vue-DB7vt9Ht.js";import{c as De}from"./@tencentcloud/call-engine-js-BX2W9Lhf.js";import{D as Ua}from"./@tencentcloud/uikit-base-component-vue3-YgTqL4da.js";import"./lodash-es-C2A-Pj28.js";import"./@popperjs/core-C5az9QE8.js";import"./dayjs-DG77mNTn.js";import"./lodash-D3kF6u-c.js";import"./@ctrl/tinycolor-BuyEbX8F.js";import"./async-validator-CFA_igpM.js";import"./normalize-wheel-es-BQoi3Ox2.js";import"./jspdf-BsthCvR5.js";import"./@babel/runtime-BanGtE2-.js";import"./fflate-_ayOYiT1.js";import"./vue-router-QlpZ4wdW.js";import"./pinia-B8cvXbiZ.js";import"./axios-C80V62Fs.js";import"./@vueuse/core-1S4fJlii.js";import"./@vueuse/shared-Cl3lVqjz.js";import"./css-color-function-DI01JAaZ.js";import"./balanced-match-BdS7OldZ.js";import"./color-B2zxaWkI.js";import"./clone-DBZ6_OiU.js";import"./color-convert-OrFsTA_V.js";import"./color-name-Dju3oUBS.js";import"./color-string-pUQDDJII.js";import"./ms-CzQ2E3wO.js";import"./vue-clipboard3-DByT_rEQ.js";import"./clipboard-CHgxszqY.js";import"./echarts-CNLwa9wG.js";import"./tslib-BDyQ-Jie.js";import"./zrender-DRNXw7y3.js";import"./highlight.js-Bxt7hFFy.js";import"./@highlightjs/vue-plugin-C4onkBvW.js";import"./@tencentcloud/tui-core-8M7p1XHw.js";import"./tim-upload-plugin-HO4N4AW9.js";import"./tim-profanity-filter-plugin-Dn_Cf-mP.js";import"./vue-BVs68q8v.js";import"./@vue/compiler-dom-CqayqxS7.js";import"./@vue/compiler-core-CvbQOXIO.js";import"./@tencentcloud/tuiroom-engine-js-Br9swJyU.js";import"./rtc-detect-Chu-fZvE.js";import"./tcplayer.js-qpFBCYzN.js";const Ee=0,qe=1,Ye=9,cn="tcm_call_beauty_settings",Va=()=>({enabled:!1,slimStrength:30,lipstickStrength:0,lipstickColor:"#c94f5e",blushStrength:0,blushColor:"#e88193"}),un=()=>({enabled:!1,style:qe,beautyLevel:5,whitenessLevel:3,ruddinessLevel:2,advanced:Va()}),be=i=>{const e=Math.round(Number(i));return Number.isFinite(e)?Math.min(Ye,Math.max(0,e)):0},st=(i,e)=>{const n=Math.round(Number(i));return Number.isFinite(n)?Math.min(100,Math.max(0,n)):e},$t=(i,e)=>typeof i=="string"&&/^#[0-9a-fA-F]{6}$/.test(i)?i:e;function Fa(i){return i.enabled&&(i.slimStrength>0||i.lipstickStrength>0||i.blushStrength>0)}function dn(i){return i.enabled&&(i.beautyLevel>0||i.whitenessLevel>0||i.ruddinessLevel>0)||Fa(i.advanced)}function ht(){const i=un();try{const e=localStorage.getItem(cn);if(!e)return i;const n=JSON.parse(e),a=i.advanced,t=(n==null?void 0:n.advanced)??{};return{enabled:!!(n!=null&&n.enabled),style:(n==null?void 0:n.style)===Ee?Ee:qe,beautyLevel:be((n==null?void 0:n.beautyLevel)??i.beautyLevel),whitenessLevel:be((n==null?void 0:n.whitenessLevel)??i.whitenessLevel),ruddinessLevel:be((n==null?void 0:n.ruddinessLevel)??i.ruddinessLevel),advanced:{enabled:!!(t!=null&&t.enabled),slimStrength:st(t==null?void 0:t.slimStrength,a.slimStrength),lipstickStrength:st(t==null?void 0:t.lipstickStrength,a.lipstickStrength),lipstickColor:$t(t==null?void 0:t.lipstickColor,a.lipstickColor),blushStrength:st(t==null?void 0:t.blushStrength,a.blushStrength),blushColor:$t(t==null?void 0:t.blushColor,a.blushColor)}}}catch{return i}}function Na(i){try{localStorage.setItem(cn,JSON.stringify(i))}catch{}}async function Ba(i,e){if(!i||typeof i.setBeautyLevel!="function")return!1;const n=e.enabled;try{return await i.setBeautyLevel({style:e.style===Ee?Ee:qe,beautyLevel:n?be(e.beautyLevel):0,whitenessLevel:n?be(e.whitenessLevel):0,ruddinessLevel:n?be(e.ruddinessLevel):0}),!0}catch(a){return console.warn("[call-beauty] 应用美颜设置失败",a),!1}}const Oa="0.10.35",Ha=`https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@${Oa}/wasm`,$a="https://storage.googleapis.com/mediapipe-models/face_landmarker/face_landmarker/float16/1/face_landmarker.task",Ga=()=>`${"/admin/".replace(/\/+$/,"")}/mediapipe`;let Pe=null;async function Gt(i,e){const n=await oa.forVisionTasks(i);return sa.createFromOptions(n,{baseOptions:{modelAssetPath:e,delegate:"GPU"},runningMode:"VIDEO",numFaces:1,outputFaceBlendshapes:!1,outputFacialTransformationMatrixes:!1})}function fn(){if(!Pe){const i=Ga();Pe=Gt(`${i}/wasm`,`${i}/face_landmarker.task`).catch(e=>(console.warn("[face-beauty] 本地模型加载失败,回退 CDN",e),Gt(Ha,$a))),Pe.catch(()=>{Pe=null})}return Pe}const Wa=[61,146,91,181,84,17,314,405,321,375,291,409,270,269,267,0,37,39,40,185],za=[78,95,88,178,87,14,317,402,318,324,308,415,310,311,312,13,82,81,80,191],Ka=50,Xa=280,Wt=4,zt=152,Ge=234,We=454,Ya=[132,172,136],ja=[361,397,365],se=6,qa=`
attribute vec2 a_pos;
uniform float u_flipY;
varying vec2 v_uv;
void main() {
float v = a_pos.y * 0.5;
v_uv = vec2(a_pos.x * 0.5 + 0.5, u_flipY > 0.5 ? 0.5 - v : 0.5 + v);
gl_Position = vec4(a_pos, 0.0, 1.0);
}
`,Ja=`
precision highp float;
uniform sampler2D u_tex;
uniform int u_warpCount;
uniform vec2 u_warpCenter[${se}];
uniform vec2 u_warpOffset[${se}];
uniform float u_warpRadius[${se}];
uniform vec2 u_aspect;
varying vec2 v_uv;
void main() {
vec2 uv = v_uv;
for (int i = 0; i < ${se}; i++) {
if (i >= u_warpCount) break;
vec2 d = (uv - u_warpCenter[i]) * u_aspect;
float dist = length(d);
float r = u_warpRadius[i];
if (dist < r) {
float x = dist / r;
float f = (1.0 - x * x);
f = f * f;
// 反向映射:目标位置向外采样,脸颊边缘被背景"挤"进来,视觉上变窄
uv -= u_warpOffset[i] * f;
}
}
gl_FragColor = texture2D(u_tex, clamp(uv, 0.001, 0.999));
}
`,Za=`
precision mediump float;
uniform sampler2D u_tex;
uniform vec2 u_dir;
varying vec2 v_uv;
void main() {
vec4 sum = texture2D(u_tex, v_uv) * 0.227027;
sum += (texture2D(u_tex, v_uv + u_dir * 1.3846) + texture2D(u_tex, v_uv - u_dir * 1.3846)) * 0.3162162;
sum += (texture2D(u_tex, v_uv + u_dir * 3.2308) + texture2D(u_tex, v_uv - u_dir * 3.2308)) * 0.0702703;
gl_FragColor = sum;
}
`,Qa=`
precision mediump float;
uniform sampler2D u_sharp;
uniform sampler2D u_blur;
uniform float u_smooth;
uniform float u_white;
uniform float u_ruddy;
uniform float u_edgeKeep;
varying vec2 v_uv;
void main() {
vec3 a = texture2D(u_sharp, v_uv).rgb;
vec3 b = texture2D(u_blur, v_uv).rgb;
// 亮度差大 = 五官/轮廓边缘,磨皮时予以保留
float lumDiff = abs(dot(a - b, vec3(0.299, 0.587, 0.114)));
float edge = smoothstep(0.05, 0.22, lumDiff) * u_edgeKeep;
vec3 c = mix(a, b, u_smooth * (1.0 - edge));
// 美白:提亮中间调,避免高光过曝
c = c + u_white * c * (vec3(1.0) - c) * 0.55;
// 红润:暖色偏移
c *= vec3(1.0) + u_ruddy * vec3(0.10, 0.0, -0.04);
gl_FragColor = vec4(clamp(c, 0.0, 1.0), 1.0);
}
`;class eo{constructor(e,n){E(this,"canvas");E(this,"gl");E(this,"videoTexture");E(this,"warpProg");E(this,"blurProg");E(this,"finalProg");E(this,"fboA");E(this,"fboB");E(this,"fboC");E(this,"lost",!1);this.canvas=document.createElement("canvas"),this.canvas.width=e,this.canvas.height=n;const a=this.canvas.getContext("webgl",{premultipliedAlpha:!1,preserveDrawingBuffer:!1});if(!a)throw new Error("WebGL 不可用");this.gl=a,this.canvas.addEventListener("webglcontextlost",()=>{this.lost=!0});const t=new Float32Array([-1,-1,1,-1,-1,1,1,1]),r=a.createBuffer();a.bindBuffer(a.ARRAY_BUFFER,r),a.bufferData(a.ARRAY_BUFFER,t,a.STATIC_DRAW),this.warpProg=this.buildProgram(Ja,["u_tex","u_warpCount","u_warpCenter","u_warpOffset","u_warpRadius","u_aspect"]),this.blurProg=this.buildProgram(Za,["u_tex","u_dir"]),this.finalProg=this.buildProgram(Qa,["u_sharp","u_blur","u_smooth","u_white","u_ruddy","u_edgeKeep"]),this.videoTexture=this.createTexture(),this.fboA=this.createFbo(e,n),this.fboB=this.createFbo(e,n),this.fboC=this.createFbo(e,n)}get isLost(){return this.lost}compile(e,n){const a=this.gl,t=a.createShader(e);if(a.shaderSource(t,n),a.compileShader(t),!a.getShaderParameter(t,a.COMPILE_STATUS))throw new Error(`着色器编译失败: ${a.getShaderInfoLog(t)}`);return t}buildProgram(e,n){const a=this.gl,t=a.createProgram();if(a.attachShader(t,this.compile(a.VERTEX_SHADER,qa)),a.attachShader(t,this.compile(a.FRAGMENT_SHADER,e)),a.linkProgram(t),!a.getProgramParameter(t,a.LINK_STATUS))throw new Error(`着色器链接失败: ${a.getProgramInfoLog(t)}`);const r={};for(const f of n)r[f]=a.getUniformLocation(t,f);return{program:t,aPos:a.getAttribLocation(t,"a_pos"),flipY:a.getUniformLocation(t,"u_flipY"),uniforms:r}}createTexture(){const e=this.gl,n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),n}createFbo(e,n){const a=this.gl,t=this.createTexture();a.bindTexture(a.TEXTURE_2D,t),a.texImage2D(a.TEXTURE_2D,0,a.RGBA,e,n,0,a.RGBA,a.UNSIGNED_BYTE,null);const r=a.createFramebuffer();return a.bindFramebuffer(a.FRAMEBUFFER,r),a.framebufferTexture2D(a.FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,t,0),a.bindFramebuffer(a.FRAMEBUFFER,null),{fb:r,tex:t}}usePass(e,n,a){const t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,n),t.viewport(0,0,this.canvas.width,this.canvas.height),t.useProgram(e.program),t.enableVertexAttribArray(e.aPos),t.vertexAttribPointer(e.aPos,2,t.FLOAT,!1,0,0),t.uniform1f(e.flipY,a?1:0)}bindTex(e,n,a){const t=this.gl;t.activeTexture(t.TEXTURE0+e),t.bindTexture(t.TEXTURE_2D,n),t.uniform1i(a,e)}render(e,n,a){const t=this.gl,{width:r,height:f}=this.canvas;t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,this.videoTexture),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e);const u=this.warpProg;this.usePass(u,this.fboA.fb,!1),this.bindTex(0,this.videoTexture,u.uniforms.u_tex);const p=Math.min(n.length,se),c=new Float32Array(se*2),v=new Float32Array(se*2),_=new Float32Array(se);for(let b=0;b<p;b++)c[b*2]=n[b][0],c[b*2+1]=n[b][1],v[b*2]=n[b][2],v[b*2+1]=n[b][3],_[b]=n[b][4];t.uniform1i(u.uniforms.u_warpCount,p),t.uniform2fv(u.uniforms.u_warpCenter,c),t.uniform2fv(u.uniforms.u_warpOffset,v),t.uniform1fv(u.uniforms.u_warpRadius,_),t.uniform2f(u.uniforms.u_aspect,r/f,1),t.drawArrays(t.TRIANGLE_STRIP,0,4);let x=this.fboA.tex;if(a.smooth>.001){const b=1+a.smooth*3,M=this.blurProg;this.usePass(M,this.fboB.fb,!1),this.bindTex(0,this.fboA.tex,M.uniforms.u_tex),t.uniform2f(M.uniforms.u_dir,b/r,0),t.drawArrays(t.TRIANGLE_STRIP,0,4),this.usePass(M,this.fboC.fb,!1),this.bindTex(0,this.fboB.tex,M.uniforms.u_tex),t.uniform2f(M.uniforms.u_dir,0,b/f),t.drawArrays(t.TRIANGLE_STRIP,0,4),x=this.fboC.tex}const g=this.finalProg;this.usePass(g,null,!0),this.bindTex(0,this.fboA.tex,g.uniforms.u_sharp),this.bindTex(1,x,g.uniforms.u_blur),t.uniform1f(g.uniforms.u_smooth,Math.min(.92,a.smooth)),t.uniform1f(g.uniforms.u_white,a.white),t.uniform1f(g.uniforms.u_ruddy,a.ruddy),t.uniform1f(g.uniforms.u_edgeKeep,a.edgeKeep),t.drawArrays(t.TRIANGLE_STRIP,0,4)}destroy(){const e=this.gl.getExtension("WEBGL_lose_context");e==null||e.loseContext()}}function pt(){try{const i=document.createElement("canvas");return typeof i.captureStream!="function"?!1:!!i.getContext("webgl")}catch{return!1}}const je=new Set;function to(i){je.forEach(e=>e.updateSettings(i))}function no(){for(const i of je)if(!i.isPreview)return!0;return!1}class mn{constructor(e,n,a){E(this,"isPreview");E(this,"sourceTrack");E(this,"settings");E(this,"video");E(this,"output");E(this,"ctx");E(this,"renderer",null);E(this,"landmarker",null);E(this,"outputStream",null);E(this,"destroyed",!1);E(this,"rafId",0);E(this,"vfcId",0);E(this,"watchdogTimer",null);E(this,"lastFrameAt",0);E(this,"lastDetectTs",-1);this.isPreview=!!(a!=null&&a.isPreview),this.sourceTrack=e,this.settings=this.cloneSettings(n),this.video=document.createElement("video"),this.video.muted=!0,this.video.playsInline=!0,this.output=document.createElement("canvas");const t=this.output.getContext("2d");if(!t)throw new Error("Canvas 2D 不可用");this.ctx=t}cloneSettings(e){return{...e,advanced:{...e.advanced}}}updateSettings(e){this.settings=this.cloneSettings(e)}async start(){this.video.srcObject=new MediaStream([this.sourceTrack]),await this.video.play(),this.video.videoWidth===0&&await new Promise(t=>{this.video.addEventListener("loadedmetadata",()=>t(),{once:!0}),setTimeout(t,1500)});const e=this.video.videoWidth||640,n=this.video.videoHeight||480;this.output.width=e,this.output.height=n;try{this.renderer=new eo(e,n)}catch(t){console.warn("[face-beauty] WebGL 初始化失败,瘦脸/磨皮/美白不可用",t)}fn().then(t=>{this.destroyed||(this.landmarker=t)}).catch(t=>{console.warn("[face-beauty] 人脸模型加载失败,瘦脸/口红/腮红退化为透传",t)}),this.drawFrame(),this.outputStream=this.output.captureStream(30);const a=this.outputStream.getVideoTracks()[0];return this.startFrameLoop(),this.sourceTrack.addEventListener("ended",()=>this.destroy()),je.add(this),a}startFrameLoop(){const e=this.video;if(typeof e.requestVideoFrameCallback=="function"){const n=()=>{this.destroyed||(this.drawFrame(),this.vfcId=e.requestVideoFrameCallback(n))};this.vfcId=e.requestVideoFrameCallback(n)}else{const n=()=>{this.destroyed||(this.drawFrame(),this.rafId=requestAnimationFrame(n))};this.rafId=requestAnimationFrame(n)}this.watchdogTimer=setInterval(()=>{this.destroyed||performance.now()-this.lastFrameAt>400&&this.drawFrame()},500)}detect(){var n;if(!this.landmarker)return null;let e=performance.now();e<=this.lastDetectTs&&(e=this.lastDetectTs+.01),this.lastDetectTs=e;try{const t=(n=this.landmarker.detectForVideo(this.video,e).faceLandmarks)==null?void 0:n[0];return t&&t.length>0?t:null}catch{return null}}drawFrame(){if(this.destroyed||this.video.readyState<HTMLMediaElement.HAVE_CURRENT_DATA)return;this.lastFrameAt=performance.now();const e=this.settings,n=e.advanced,a={smooth:e.enabled?e.beautyLevel/9:0,white:e.enabled?e.whitenessLevel/9*.8:0,ruddy:e.enabled?e.ruddinessLevel/9*.8:0,edgeKeep:e.style===Ee?.55:1},t=a.smooth>0||a.white>0||a.ruddy>0,r=n.enabled&&n.slimStrength>0,f=n.enabled&&(n.lipstickStrength>0||n.blushStrength>0),u=r||f?this.detect():null,{width:p,height:c}=this.output;this.renderer&&!this.renderer.isLost&&(t||r&&u)?(this.renderer.render(this.video,r&&u?this.buildWarps(u):[],a),this.ctx.drawImage(this.renderer.canvas,0,0,p,c)):this.ctx.drawImage(this.video,0,0,p,c),u&&f&&(n.lipstickStrength>0&&this.drawLipstick(u),n.blushStrength>0&&this.drawBlush(u))}buildWarps(e){const{width:n,height:a}=this.output,t=n/a,r=Math.hypot((e[We].x-e[Ge].x)*t,e[We].y-e[Ge].y),f={x:(e[Wt].x+e[zt].x)/2,y:(e[Wt].y+e[zt].y)/2},u=this.settings.advanced.slimStrength/100*.16,p=r*.42,c=[];for(const v of[...Ya,...ja]){const _=e[v],x=f.x-_.x,g=f.y-_.y,b=Math.hypot(x*t,g)||1,M=r*u/b;c.push([_.x,_.y,x*M,g*M,p])}return c}tracePath(e,n){const{width:a,height:t}=this.output;this.ctx.moveTo(e[n[0]].x*a,e[n[0]].y*t);for(let r=1;r<n.length;r++)this.ctx.lineTo(e[n[r]].x*a,e[n[r]].y*t);this.ctx.closePath()}drawLipstick(e){const n=this.settings.advanced,a=this.ctx;a.save(),a.globalCompositeOperation="multiply",a.globalAlpha=Math.min(.75,n.lipstickStrength/100*.75),a.filter="blur(2px)",a.fillStyle=n.lipstickColor,a.beginPath(),this.tracePath(e,Wa),this.tracePath(e,za),a.fill("evenodd"),a.restore()}drawBlush(e){const n=this.settings.advanced,a=this.ctx,{width:t,height:r}=this.output,f=t/r,u=Math.hypot((e[We].x-e[Ge].x)*f,e[We].y-e[Ge].y)*r,p=Math.max(8,u*.16);a.save(),a.globalCompositeOperation="soft-light",a.globalAlpha=Math.min(.9,n.blushStrength/100*.9);for(const c of[Ka,Xa]){const v=e[c].x*t,_=e[c].y*r,x=a.createRadialGradient(v,_,0,v,_,p);x.addColorStop(0,n.blushColor),x.addColorStop(1,`${n.blushColor}00`),a.fillStyle=x,a.beginPath(),a.arc(v,_,p,0,Math.PI*2),a.fill()}a.restore()}destroy(){var n,a;if(this.destroyed)return;this.destroyed=!0,je.delete(this);const e=this.video;this.vfcId&&typeof e.cancelVideoFrameCallback=="function"&&e.cancelVideoFrameCallback(this.vfcId),this.rafId&&cancelAnimationFrame(this.rafId),this.watchdogTimer&&clearInterval(this.watchdogTimer),(n=this.outputStream)==null||n.getTracks().forEach(t=>t.stop());try{this.sourceTrack.stop()}catch{}this.video.srcObject=null,(a=this.renderer)==null||a.destroy(),this.renderer=null}}function ao(){var i;try{return((i=sn().userInfo)==null?void 0:i.enable_beauty)!==0}catch{return!0}}let Kt=!1,dt=null;function oo(i){return dt?dt(i):navigator.mediaDevices.getUserMedia(i)}async function so(i){const e=i.getVideoTracks()[0];if(!e)return i;const n=ht(),a=new mn(e,n),t=await a.start(),r=t.stop.bind(t);return t.stop=()=>{r(),a.destroy(),i.getTracks().forEach(f=>f.stop())},new MediaStream([t,...i.getAudioTracks()])}function io(){var e;if(Kt||!((e=navigator.mediaDevices)!=null&&e.getUserMedia))return;Kt=!0;const i=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);dt=i,navigator.mediaDevices.getUserMedia=async n=>{const a=await i(n);if(!(n!=null&&n.video))return a;const t=ht();if(!ao()||!dn(t)||!pt())return a;try{return await so(a)}catch(r){return console.warn("[face-beauty] 美颜管线创建失败,使用原始摄像头画面",r),a}}}function Xt(){pt()&&fn().catch(()=>{})}const ro={class:"beauty-window-title"},lo={class:"beauty-window-body"},co={class:"beauty-preview-col"},uo={key:0,class:"beauty-preview-placeholder"},fo={key:0},mo={key:1,class:"beauty-preview-error-text"},ho={key:2},po={key:1,class:"beauty-preview-badge"},vo={class:"beauty-preview-toolbar"},go={class:"beauty-control-col"},yo={class:"beauty-section-header"},_o={class:"beauty-item"},bo={class:"beauty-item"},wo={class:"beauty-item"},Eo={class:"beauty-item"},To={class:"beauty-section-header"},So={class:"beauty-section-title"},Co={key:0,class:"beauty-unsupported"},Ao={class:"beauty-item"},ko={class:"beauty-item"},Ro={class:"beauty-item"},xo={key:2,class:"beauty-restart-hint"},Io={class:"beauty-window-footer"},Yt=780,Lo=mt({__name:"index",props:{getEngine:{},popperZIndex:{default:300001}},setup(i,{expose:e}){const n=["#c94f5e","#b03a48","#d96a76","#a52a3c","#e0788a","#8f2436"],a=["#e88193","#f0a3b0","#dd6b7f","#f2b8c0","#e5949e"],t=i;io();const r=Ot(ht()),f=pt();r.advanced.enabled&&Xt();const u=J(()=>dn(r)&&!no()),p=T(!1),c=Ot({x:0,y:0}),v=J(()=>({left:`${c.x}px`,top:`${c.y}px`,width:`${Yt}px`,zIndex:t.popperZIndex})),_={active:!1,offsetX:0,offsetY:0},x=k=>{_.active&&(c.x=Math.max(0,Math.min(window.innerWidth-120,k.clientX-_.offsetX)),c.y=Math.max(0,Math.min(window.innerHeight-60,k.clientY-_.offsetY)))},g=()=>{_.active=!1,document.removeEventListener("mousemove",x),document.removeEventListener("mouseup",g)},b=k=>{_.active=!0,_.offsetX=k.clientX-c.x,_.offsetY=k.clientY-c.y,document.addEventListener("mousemove",x),document.addEventListener("mouseup",g),k.preventDefault()},M=()=>{p.value||(c.x=Math.max(16,Math.floor((window.innerWidth-Yt)/2)),c.y=Math.max(16,Math.floor(window.innerHeight*.12)),p.value=!0,f&&N())},I=()=>{re(),p.value=!1};let ee=null;const Te=async()=>{f||await Ba(t.getEngine(),r)},Je=async()=>{r.enabled&&await Te()};rn(r,()=>{Na(r),to({...r,advanced:{...r.advanced}}),r.advanced.enabled&&Xt(),ee&&clearTimeout(ee),ee=setTimeout(()=>{ee=null,Te()},200)},{deep:!0});const W=T(!1),te=T(!1),ie=T(""),z=T(null),K=T(null);let V=null;const he=()=>{var k;document.fullscreenElement?document.exitFullscreen().catch(()=>{}):(k=K.value)==null||k.requestFullscreen().catch(()=>{})},N=async()=>{if(!(W.value||te.value)){ie.value="",te.value=!0;try{const m=(await oo({video:{width:{ideal:1280},height:{ideal:720}},audio:!1})).getVideoTracks()[0];if(!m)throw new Error("未获取到摄像头画面");V=new mn(m,{...r,advanced:{...r.advanced}},{isPreview:!0});const G=await V.start();W.value=!0,await Xe(),z.value&&(z.value.srcObject=new MediaStream([G]),await z.value.play().catch(()=>{}))}catch(k){console.warn("[call-beauty] 预览启动失败",k),V==null||V.destroy(),V=null,W.value=!1,ie.value=(k==null?void 0:k.name)==="NotAllowedError"?"摄像头权限被拒绝,请在浏览器地址栏允许摄像头访问":(k==null?void 0:k.name)==="NotReadableError"?"摄像头被其他程序占用,无法打开预览":"预览启动失败,请检查摄像头设备"}finally{te.value=!1}}},re=()=>{document.fullscreenElement&&document.fullscreenElement===K.value&&document.exitFullscreen().catch(()=>{}),z.value&&(z.value.srcObject=null),V==null||V.destroy(),V=null,W.value=!1,te.value=!1},le=()=>{W.value?re():N()},Se=()=>{const k=un();Object.assign(r.advanced,k.advanced,{enabled:r.advanced.enabled}),Object.assign(r,{style:k.style,beautyLevel:k.beautyLevel,whitenessLevel:k.whitenessLevel,ruddinessLevel:k.ruddinessLevel})};return ia(()=>{ee&&clearTimeout(ee),re(),g()}),e({applyNow:Te,applyIfEnabled:Je,openPanel:M}),(k,m)=>{const G=an,Y=nn,Z=Wn,pe=Kn,ve=zn,ne=Xn,Ze=Yn,Ce=on,ce=jn;return R(),P(ra,null,[y("span",{class:"beauty-trigger",onClick:M},[la(k.$slots,"reference",{},()=>[h(Y,{type:"primary",link:"",size:"small"},{default:S(()=>[h(G,null,{default:S(()=>[h(A(rt))]),_:1}),m[13]||(m[13]=y("span",{class:"beauty-btn-text"},"美颜",-1))]),_:1})],!0)]),(R(),X(ln,{to:"body"},[p.value?(R(),P("div",{key:0,class:"beauty-window",style:ct(v.value),onMousedown:m[12]||(m[12]=me(()=>{},["stop"]))},[y("div",{class:"beauty-window-header",onMousedown:b},[y("span",ro,[h(G,null,{default:S(()=>[h(A(rt))]),_:1}),m[14]||(m[14]=fe(" 美颜设置 ",-1))]),h(Y,{type:"danger",link:"",class:"beauty-window-close",onMousedown:m[0]||(m[0]=me(()=>{},["stop"])),onClick:I},{default:S(()=>[h(G,null,{default:S(()=>[h(A(lt))]),_:1})]),_:1})],32),y("div",lo,[y("div",co,[y("div",{ref_key:"previewStageRef",ref:K,class:"beauty-preview-stage"},[Ke(y("video",{ref_key:"previewVideoRef",ref:z,class:"beauty-preview-video",autoplay:"",muted:"",playsinline:""},null,512),[[ze,W.value]]),W.value?$("",!0):(R(),P("div",uo,[h(G,{size:36},{default:S(()=>[h(A(Jn))]),_:1}),te.value?(R(),P("span",fo,"正在打开摄像头...")):ie.value?(R(),P("span",mo,Q(ie.value),1)):(R(),P("span",ho,"摄像头预览未开启"))])),W.value?(R(),P("span",po,"对方看到的效果(镜像显示)")):$("",!0),W.value?(R(),X(Y,{key:2,class:"beauty-fullscreen-btn",circle:"",size:"small",title:"全屏预览(按 Esc 退出)",onClick:he},{default:S(()=>[h(G,null,{default:S(()=>[h(A(Bt))]),_:1})]),_:1})):$("",!0)],512),y("div",vo,[h(Y,{size:"small",loading:te.value,onClick:le},{default:S(()=>[fe(Q(W.value?"关闭预览":"打开预览"),1)]),_:1},8,["loading"]),W.value?(R(),X(Y,{key:0,size:"small",onClick:he},{default:S(()=>[h(G,null,{default:S(()=>[h(A(Bt))]),_:1}),m[15]||(m[15]=y("span",{style:{"margin-left":"2px"}},"全屏",-1))]),_:1})):$("",!0),m[16]||(m[16]=y("span",{class:"beauty-preview-note"},"预览效果即对方所见(画面镜像显示)",-1))])]),y("div",go,[y("div",yo,[m[17]||(m[17]=y("span",{class:"beauty-section-title"},"基础美颜",-1)),h(Z,{modelValue:r.enabled,"onUpdate:modelValue":m[1]||(m[1]=L=>r.enabled=L),size:"small"},null,8,["modelValue"])]),y("div",{class:ut(["beauty-section-body",{"is-disabled":!r.enabled}])},[y("div",_o,[m[20]||(m[20]=y("span",{class:"beauty-label"},"磨皮算法",-1)),h(ve,{modelValue:r.style,"onUpdate:modelValue":m[2]||(m[2]=L=>r.style=L),size:"small",disabled:!r.enabled},{default:S(()=>[h(pe,{value:A(qe)},{default:S(()=>[...m[18]||(m[18]=[fe("自然",-1)])]),_:1},8,["value"]),h(pe,{value:A(Ee)},{default:S(()=>[...m[19]||(m[19]=[fe("光滑",-1)])]),_:1},8,["value"])]),_:1},8,["modelValue","disabled"])]),y("div",bo,[m[21]||(m[21]=y("span",{class:"beauty-label"},"磨皮",-1)),h(ne,{modelValue:r.beautyLevel,"onUpdate:modelValue":m[3]||(m[3]=L=>r.beautyLevel=L),min:0,max:A(Ye),step:1,disabled:!r.enabled},null,8,["modelValue","max","disabled"])]),y("div",wo,[m[22]||(m[22]=y("span",{class:"beauty-label"},"美白",-1)),h(ne,{modelValue:r.whitenessLevel,"onUpdate:modelValue":m[4]||(m[4]=L=>r.whitenessLevel=L),min:0,max:A(Ye),step:1,disabled:!r.enabled},null,8,["modelValue","max","disabled"])]),y("div",Eo,[m[23]||(m[23]=y("span",{class:"beauty-label"},"红润",-1)),h(ne,{modelValue:r.ruddinessLevel,"onUpdate:modelValue":m[5]||(m[5]=L=>r.ruddinessLevel=L),min:0,max:A(Ye),step:1,disabled:!r.enabled},null,8,["modelValue","max","disabled"])])],2),h(Ze,{class:"beauty-divider"}),y("div",To,[y("span",So,[m[24]||(m[24]=fe(" 高级美颜 ",-1)),h(Ce,{placement:"top",content:"瘦脸/口红/腮红由本机 AI 实时处理(免费,无需腾讯付费特效)。开关在下次开启摄像头时生效,通话中可关闭摄像头再打开。"},{default:S(()=>[h(G,{class:"beauty-help-icon"},{default:S(()=>[h(A(Zn))]),_:1})]),_:1})]),h(Z,{modelValue:r.advanced.enabled,"onUpdate:modelValue":m[6]||(m[6]=L=>r.advanced.enabled=L),size:"small",disabled:!A(f)},null,8,["modelValue","disabled"])]),A(f)?(R(),P("div",{key:1,class:ut(["beauty-section-body",{"is-disabled":!r.advanced.enabled}])},[y("div",Ao,[m[25]||(m[25]=y("span",{class:"beauty-label"},"瘦脸",-1)),h(ne,{modelValue:r.advanced.slimStrength,"onUpdate:modelValue":m[7]||(m[7]=L=>r.advanced.slimStrength=L),min:0,max:100,step:1,disabled:!r.advanced.enabled},null,8,["modelValue","disabled"])]),y("div",ko,[m[26]||(m[26]=y("span",{class:"beauty-label"},"口红",-1)),h(ne,{modelValue:r.advanced.lipstickStrength,"onUpdate:modelValue":m[8]||(m[8]=L=>r.advanced.lipstickStrength=L),min:0,max:100,step:1,disabled:!r.advanced.enabled},null,8,["modelValue","disabled"]),h(ce,{modelValue:r.advanced.lipstickColor,"onUpdate:modelValue":m[9]||(m[9]=L=>r.advanced.lipstickColor=L),size:"small",predefine:n,disabled:!r.advanced.enabled},null,8,["modelValue","disabled"])]),y("div",Ro,[m[27]||(m[27]=y("span",{class:"beauty-label"},"腮红",-1)),h(ne,{modelValue:r.advanced.blushStrength,"onUpdate:modelValue":m[10]||(m[10]=L=>r.advanced.blushStrength=L),min:0,max:100,step:1,disabled:!r.advanced.enabled},null,8,["modelValue","disabled"]),h(ce,{modelValue:r.advanced.blushColor,"onUpdate:modelValue":m[11]||(m[11]=L=>r.advanced.blushColor=L),size:"small",predefine:a,disabled:!r.advanced.enabled},null,8,["modelValue","disabled"])])],2)):(R(),P("div",Co," 当前浏览器不支持高级美颜(需要 WebGL),请使用新版 Chrome / Edge ")),u.value?(R(),P("div",xo," 通话中如果摄像头已按原始画面开启,需关闭摄像头再打开才能生效 ")):$("",!0),y("div",Io,[m[29]||(m[29]=y("span",{class:"beauty-tip"},"全部为免费能力,通话中实时生效",-1)),h(Y,{link:"",type:"primary",size:"small",onClick:Se},{default:S(()=>[...m[28]||(m[28]=[fe(" 恢复默认 ",-1)])]),_:1})])])])],36)):$("",!0)]))],64)}}}),Mo=ft(Lo,[["__scopeId","data-v-42161d2a"]]);function Do(){const i=["video/webm;codecs=vp9,opus","video/webm;codecs=vp8,opus","video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm"];for(const e of i)if(MediaRecorder.isTypeSupported(e))return e;return""}function Po(){const i=window;return i.AudioContext||i.webkitAudioContext||null}function jt(i,e,n,a,t,r){const f=e.videoWidth||e.clientWidth||1,u=e.videoHeight||e.clientHeight||1,p=Math.max(t/f,r/u),c=f*p,v=u*p,_=n+(t-c)/2,x=a+(r-v)/2;try{i.drawImage(e,_,x,c,v)}catch{}}function Uo(i,e,n,a){i.fillStyle="#0b0b0b",i.fillRect(0,0,n,a);const t=e.filter(c=>c.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA);if(t.length===0)return;if(t.length===1){jt(i,t[0],0,0,n,a);return}const r=Math.ceil(Math.sqrt(t.length)),f=Math.ceil(t.length/r),u=n/r,p=a/f;t.forEach((c,v)=>{const _=v%r,x=Math.floor(v/r);jt(i,c,_*u,x*p,u,p)})}function Vo(i){const e=new Set,n=[];for(const a of i){const t=a.srcObject;if(t instanceof MediaStream)for(const r of t.getAudioTracks())r.kind!=="audio"||r.readyState==="ended"||!r.enabled||e.has(r.id)||(e.add(r.id),n.push(r))}return n}function Fo(i){var a;const e=new Set,n=[];for(const t of i){if(t.readyState<HTMLMediaElement.HAVE_CURRENT_DATA)continue;const r=(a=t.captureStream)==null?void 0:a.call(t);if(r)for(const f of r.getAudioTracks())f.kind!=="audio"||f.readyState==="ended"||!f.enabled||e.has(f.id)||(e.add(f.id),n.push(f))}return n}function No(i){const e=new Set,n=[],a=[...document.body.querySelectorAll("audio")];i&&a.push(...i.querySelectorAll("audio"));const t=document.getElementById("tuicallkit-id");t&&a.push(...t.querySelectorAll("audio"));const r=new Set;for(const f of a){if(r.has(f))continue;r.add(f);const u=f.srcObject;if(u instanceof MediaStream)for(const p of u.getAudioTracks())p.kind!=="audio"||p.readyState==="ended"||!p.enabled||e.has(p.id)||(e.add(p.id),n.push(p))}return n}function it(i){const e=new Set,n=u=>{const p=[];for(const c of u)e.has(c)||(e.add(c),p.push(c));return p},a=[...i.querySelectorAll("video")];if(a.length>0)return n(a);const t=document.getElementById("tuicallkit-id");if(t){const u=[...t.querySelectorAll("video")];if(u.length>0)return n(u)}const f=[...document.body.querySelectorAll("video")].filter(u=>{const p=u.srcObject;return p instanceof MediaStream?p.getVideoTracks().some(c=>c.readyState==="live"):!1});return n(f)}class Bo{constructor(){E(this,"canvas",null);E(this,"ctx",null);E(this,"rafId",0);E(this,"container",null);E(this,"mediaRecorder",null);E(this,"chunks",[]);E(this,"mimeType","");E(this,"audioCtx",null);E(this,"audioDestination",null);E(this,"wiredTrackIds",new Set);E(this,"canvasVideoTrack",null);E(this,"silentOsc",null);E(this,"silentGain",null);E(this,"micStream",null);E(this,"stopResultPromise",null)}isRecording(){return this.mediaRecorder!==null&&this.mediaRecorder.state==="recording"}beginStopNow(){if(this.stopResultPromise)return;cancelAnimationFrame(this.rafId),this.rafId=0;const e=this.mediaRecorder,n=this.mimeType;!e||e.state==="inactive"||(this.stopResultPromise=new Promise(a=>{var t;e.onstop=()=>{this.teardownAudioGraph();const r=e.mimeType||n||"video/webm",f=this.chunks.length>0?new Blob(this.chunks,{type:r}):null;this.chunks=[],this.mediaRecorder=null,this.container=null,this.canvas=null,this.ctx=null,this.canvasVideoTrack=null,a(f&&f.size>0?f:null)};try{const r=e;(t=r.requestData)==null||t.call(r),e.stop()}catch{this.teardownAudioGraph(),this.chunks=[],this.mediaRecorder=null,this.container=null,this.canvas=null,this.ctx=null,this.canvasVideoTrack=null,a(null)}}))}teardownAudioGraph(){var e;try{(e=this.silentOsc)==null||e.stop()}catch{}if(this.silentOsc=null,this.silentGain=null,this.micStream){for(const n of this.micStream.getTracks())try{n.stop()}catch{}this.micStream=null}this.wiredTrackIds.clear(),this.audioDestination=null,this.audioCtx&&(this.audioCtx.close().catch(()=>{}),this.audioCtx=null)}connectTrackToMixer(e){if(!(e.kind!=="audio"||e.readyState==="ended"||!e.enabled)&&!(!this.audioCtx||!this.audioDestination)&&!this.wiredTrackIds.has(e.id))try{const n=this.audioCtx.createMediaStreamSource(new MediaStream([e])),a=this.audioCtx.createGain();a.gain.value=1.25,n.connect(a),a.connect(this.audioDestination),this.wiredTrackIds.add(e.id)}catch{}}attachMicForMixer(){if(!this.audioCtx||!this.audioDestination)return;const e=navigator.mediaDevices;e!=null&&e.getUserMedia&&e.getUserMedia({audio:!0,video:!1}).then(n=>{if(!this.audioDestination||!this.audioCtx){n.getTracks().forEach(a=>a.stop());return}if(this.micStream){n.getTracks().forEach(a=>a.stop());return}this.micStream=n;for(const a of n.getAudioTracks())this.connectTrackToMixer(a)}).catch(()=>{})}wireIncomingAudio(){var f;if(!this.audioCtx||!this.audioDestination||!this.container)return;this.audioCtx.state==="suspended"&&this.audioCtx.resume().catch(()=>{});const e=it(this.container),n=document.getElementById("tuicallkit-id"),a=[...document.body.querySelectorAll("audio"),...this.container.querySelectorAll("audio"),...n?n.querySelectorAll("audio"):[]],t=new Set,r=[];for(const u of e)t.has(u)||(t.add(u),r.push(u));for(const u of a)t.has(u)||(t.add(u),r.push(u));for(const u of r){const p=u.srcObject;if(p instanceof MediaStream)for(const c of p.getAudioTracks())this.connectTrackToMixer(c);if(u instanceof HTMLVideoElement&&u.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA){const c=(f=u.captureStream)==null?void 0:f.call(u);if(c)for(const v of c.getAudioTracks())this.connectTrackToMixer(v)}}}reset(){if(cancelAnimationFrame(this.rafId),this.rafId=0,this.stopResultPromise=null,this.canvasVideoTrack=null,this.mediaRecorder&&this.mediaRecorder.state!=="inactive")try{this.mediaRecorder.stop()}catch{}this.mediaRecorder=null,this.chunks=[],this.canvas=null,this.ctx=null,this.container=null,this.mimeType="",this.teardownAudioGraph()}start(e){if(typeof MediaRecorder>"u")return!1;this.reset(),this.container=e;const n=Do();if(this.mimeType=n||"video/webm",this.canvas=document.createElement("canvas"),this.canvas.width=1280,this.canvas.height=720,this.ctx=this.canvas.getContext("2d",{alpha:!1}),!this.ctx)return!1;const t=this.canvas.captureStream(30).getVideoTracks();this.canvasVideoTrack=t[0]??null;const r=it(e),f=Po();let u;if(f)try{this.audioCtx=new f,this.audioDestination=this.audioCtx.createMediaStreamDestination(),this.audioCtx.resume().catch(()=>{}),this.wireIncomingAudio(),this.attachMicForMixer();const c=this.audioDestination.stream.getAudioTracks(),v=this.audioCtx.createOscillator(),_=this.audioCtx.createGain();_.gain.value=1e-5,v.frequency.value=20,v.connect(_),_.connect(this.audioDestination),v.start(),this.silentOsc=v,this.silentGain=_,u=new MediaStream([...t,...c])}catch{this.teardownAudioGraph(),u=this.buildStreamWithoutMixer(t,r)}else u=this.buildStreamWithoutMixer(t,r);try{this.mediaRecorder=n?new MediaRecorder(u,{mimeType:n}):new MediaRecorder(u)}catch{try{this.mediaRecorder=new MediaRecorder(u)}catch{return this.reset(),!1}}this.chunks=[],this.mediaRecorder.ondataavailable=c=>{c.data&&c.data.size>0&&this.chunks.push(c.data)},this.mediaRecorder.onerror=c=>{console.error("[call-local-recorder] MediaRecorder 错误",c)};const p=()=>{var v,_;if(!this.ctx||!this.canvas||!this.container)return;this.wireIncomingAudio();const c=it(this.container);Uo(this.ctx,c,this.canvas.width,this.canvas.height),(_=(v=this.canvasVideoTrack)==null?void 0:v.requestFrame)==null||_.call(v),this.rafId=requestAnimationFrame(p)};this.rafId=requestAnimationFrame(p);try{this.mediaRecorder.start(250)}catch{return this.reset(),!1}return!0}buildStreamWithoutMixer(e,n){const a=new Set,t=[],r=f=>{for(const u of f)a.has(u.id)||(a.add(u.id),t.push(u))};return r(Vo(n)),r(Fo(n)),r(No(this.container)),new MediaStream([...e,...t])}async stop(){this.beginStopNow();const e=this.stopResultPromise;return e||null}}function qt(i){const e=i.srcObject;return e instanceof MediaStream?e.getVideoTracks().some(n=>n.readyState==="live"):!1}function we(i){const e=i.getBoundingClientRect();return Math.max(0,e.width)*Math.max(0,e.height)}function Jt(i){const e=i.videoWidth||i.clientWidth,n=i.videoHeight||i.clientHeight;return e*n}function Oo(i){const e=new Map,n=new Map;for(const a of i){const t=a.srcObject;if(!(t instanceof MediaStream))continue;const r=t.getVideoTracks(),f=t.id&&String(t.id)||r.map(c=>c.id).filter(Boolean).join("|")||`${r.length}`,u=we(a),p=n.get(f)??0;u>=p&&(e.set(f,a),n.set(f,u))}return e.size===0?i:Array.from(e.values())}function Ho(i){if(i.length<2)return i;let e=0;for(const a of i)e=Math.max(e,we(a));return e<=1||Math.min(...i.map(a=>we(a)))/e>=.25?i:i.filter(a=>we(a)>=e*.25)}function $o(i){let e=i;for(let n=0;n<12&&e;n++){const a=getComputedStyle(e).transform;if(a&&a!=="none"&&(/matrix\(\s*-1\s*,/.test(a)||/scaleX\(\s*-1/.test(a)))return!0;e=e.parentElement}return!1}function Go(i){const e=/local|self|pusher|mini[_-]?stream|preview[_-]?self|own[_-]?camera|tui-local|tencent-local|stream-local|publisher|send|pip|picture[_-]?in[_-]?picture/i,n=/remote|subscriber|peer|other|tui-remote|stream-remote|big-stream|play[_-]?stream|receiver|pull|substream/i;let a=i;for(let t=0;t<20&&a;t++){const r=`${a.className||""} ${a.id||""} ${a.getAttribute("data-type")||""}`;if(n.test(r))return!1;if(e.test(r))return!0;a=a.parentElement}return!1}async function Wo(i,e){const n=(e==null?void 0:e.preferRemote)!==!1,a=[i,...(e==null?void 0:e.extraRoots)||[]].filter(g=>!!g),t=new Set;for(const g of a)for(const b of g.querySelectorAll("video"))b instanceof HTMLVideoElement&&t.add(b);if(t.size===0){const g=document.querySelector(".chat-dialog-call-kit-wrapper");if(g)for(const b of g.querySelectorAll("video"))b instanceof HTMLVideoElement&&t.add(b)}t.size===0&&document.body.querySelectorAll("video").forEach(g=>{g instanceof HTMLVideoElement&&qt(g)&&t.add(g)});let r=Array.from(t).filter(g=>g.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA&&qt(g));if(r.length===0&&(r=Array.from(t).filter(g=>g.readyState>=2)),r.length===0)return null;r=Oo(r);let f=null,u=0,p=0;if(n){const g=r.map(I=>({v:I,layout:we(I),pixel:Jt(I),localClass:Go(I),mirror:$o(I)}));let b=g.filter(I=>!I.localClass&&!I.mirror);b.length===0&&(b=g.filter(I=>!I.localClass)),b.length===0&&(b=g.filter(I=>!I.mirror)),b.length===0&&(b=g);let M=b.map(I=>I.v);M=Ho(M),b=b.filter(I=>M.includes(I.v));for(const I of b)(I.layout>u||I.layout===u&&I.pixel>p)&&(u=I.layout,p=I.pixel,f=I.v)}else for(const g of r){const b=we(g),M=Jt(g);(b>u||b===u&&M>p)&&(u=b,p=M,f=g)}if(!f)return null;const c=f.videoWidth||f.clientWidth,v=f.videoHeight||f.clientHeight;if(!c||!v)return null;const _=document.createElement("canvas");_.width=c,_.height=v;const x=_.getContext("2d");if(!x)return null;try{x.drawImage(f,0,0,c,v)}catch{return null}return new Promise(g=>{_.toBlob(b=>g(b),"image/jpeg",.92)})}function zo(i){const e=[];let n=i,a=0;for(;n!=null&&a<6;){if(typeof n=="string"){e.push(n);break}if(typeof n=="object"){const t=n;typeof t.message=="string"&&e.push(t.message),typeof t.name=="string"&&e.push(t.name),typeof t.code<"u"&&e.push(String(t.code)),n=t.cause}else{e.push(String(n));break}a++}return e.join(" ").toLowerCase()}const Zt=-1001;function _e(i){if(i&&typeof i=="object"){const n=i,a=n.code??n.error_code;if(a===Zt||a===String(Zt))return!0}const e=zo(i);return e.includes("does not support this ability")||e.includes("package you purchased")||e.includes("-1001")&&e.includes("does not support")}function hn(){return"套餐欠费或未开通该能力,请联系管理员在腾讯云续费或升级套餐。"}function Ko(i,e="通话操作失败"){return _e(i)?hn():i instanceof Error?i.message||e:typeof i=="string"&&i||e}const Xo={key:0,class:"chat-uikit-custom-msg"},Yo={key:0,class:"chat-uikit-custom-msg__tag"},jo={class:"chat-uikit-custom-msg__main"},qo={key:1,class:"chat-uikit-custom-msg__sub"},Jo={key:1,class:"chat-uikit-custom-msg chat-uikit-custom-msg--plain"},Zo={class:"chat-uikit-custom-msg__main"},Qo={key:2,class:"chat-uikit-custom-msg chat-uikit-custom-msg--plain"},es={key:0,class:"chat-uikit-custom-msg__sub"},ts=mt({inheritAttrs:!1,__name:"ChatMessageItem",props:{message:{}},setup(i){const e=i,n=ca();function a(c){if(!c||typeof c!="object")return null;const v=c,_=v.data;if(typeof _=="string")return _;if(_&&typeof _=="object")return JSON.stringify(_);const x=v.extension;return typeof x=="string"&&x.trim().startsWith("{")?x:null}const t=J(()=>{var v;const c=(v=e.message)==null?void 0:v.type;return!!(c===Ta.CUSTOM||typeof c=="string"&&/custom/i.test(c))}),r=J(()=>{var v;if(!t.value)return null;const c=(v=a(e.message.payload))==null?void 0:v.trim();return c?wa(c):null}),f=J(()=>t.value&&!!r.value),u=J(()=>{const c=e.message.payload,v=c==null?void 0:c.description;return typeof v=="string"&&v.trim()?v.trim():""}),p=J(()=>{var v;const c=(v=a(e.message.payload))==null?void 0:v.trim();return!c||c.length<2?"":c.length<=120?c:`${c.slice(0,117)}…`});return(c,v)=>f.value?(R(),P("div",Xo,[r.value.tag?(R(),P("span",Yo,Q(r.value.tag),1)):$("",!0),y("div",jo,Q(r.value.main),1),r.value.sub?(R(),P("div",qo,Q(r.value.sub),1)):$("",!0)])):t.value&&u.value?(R(),P("div",Jo,[y("div",Zo,Q(u.value),1)])):t.value?(R(),P("div",Qo,[v[0]||(v[0]=y("div",{class:"chat-uikit-custom-msg__main"},"系统消息",-1)),p.value?(R(),P("div",es,Q(p.value),1)):$("",!0)])):(R(),X(A(Ea),ua({key:3},A(n),{message:i.message}),null,16,["message"]))}}),ns=ft(ts,[["__scopeId","data-v-1c506f55"]]);function as(i){if(i==null)return null;if(typeof i=="object"&&!Array.isArray(i))return i;if(typeof i!="string")return null;const e=i.trim();if(!e.startsWith("{"))return null;try{return JSON.parse(e)}catch{return null}}function Qt(i){const e=i.toLowerCase();return["hangup","cancel","reject","timeout","linebusy","end"].includes(e)}function os(i){const e=i.trim();if(!e)return!1;if(/\bcall_end\b/i.test(e)&&(/call_engine|call_record|rtc/i.test(e)||/"reason"\s*:\s*\d/.test(e))||/call_engine_srv\.[a-z_]*call[a-z_]*/i.test(e)&&/hangup|end|leave|reject|cancel/i.test(e))return!0;if(!e.startsWith("{"))return!1;let n;try{n=JSON.parse(e)}catch{return!1}if(n.businessID===1||n.businessID==="1"){const t=as(n.data);if(t){const r=String(t.cmd??"");if(Qt(r))return!0}}if((n.businessID==="rtc_call"||typeof n.cmd=="string")&&Qt(String(n.cmd??"")))return!0;const a=JSON.stringify(n);return!!(a.includes("call_engine_srv")&&/hangup|call_end|CALL_END|reject|cancel/i.test(a))}const ss=["title"],is={class:"chat-container"},rs={key:0,class:"loading-container"},ls={key:1,class:"error-container"},cs={key:2,class:"chat-content"},us={class:"chat-layout"},ds={class:"message-toolbar"},fs={class:"call-kit-drag-handle-left"},ms={key:0,class:"call-local-recording-hint"},hs={class:"call-kit-drag-handle-actions"},Ue="idle",Ve="calling",de="connected",en=40,ps=100,vs=1500,gs=2600,ys=667,tn=16,_s=mt({__name:"index",setup(i,{expose:e}){const n=T(""),a=T(!1),t=T(!1),r=T(!1),f=T(""),u=T(""),p=T(null),c=T(null),v=T("正在初始化..."),_=T(""),x=T(""),g=T(!1),b=T(!1),M=T(null),I=J(()=>{var s;return((s=ie.userInfo)==null?void 0:s.enable_beauty)!==0}),ee=()=>{try{return H.getTUICallEngineInstance()}catch{return null}},{login:Te}=Ma(),{setActiveConversation:Je,createC2CConversation:W,activeConversation:te}=La(),ie=sn(),z=T("");let K=null,V=null,he=0;const N=new Bo,re=T(!1),le=T(!1);let Se=0,k=null,m=null,G=Promise.resolve(),Y=null;function Z(){k&&(clearTimeout(k),k=null)}function pe(s){re.value=!!(s!=null&&s.isLochostVod)}function ve(){return m||(m=(async()=>{if(Z(),le.value=!1,!re.value)return;N.beginStopNow();const s=Y??c.value;try{await G}catch{}const o=await N.stop();if(!o){console.warn("[chat-dialog] 本地录制无有效文件(若通话较长仍出现,请换 Chrome 并看控制台是否有 MediaRecorder 报错)");return}if(s==null){F.msgWarning("缺少诊单信息,本地录制无法保存到通话记录");return}try{const l=await ha(o,`call-rec-${s}-${Date.now()}.webm`),d=l.uri||l.url;if(!d){F.msgError("上传成功但未返回文件地址");return}await va({diagnosis_id:s,file_url:d}),F.msgSuccess("本地录制已上传并关联到通话记录")}catch(l){const d=l instanceof Error?l.message:String(l);console.warn("[chat-dialog] 本地录制上传/关联失败",l),F.msgError(d||"本地录制上传失败")}})().finally(()=>{m=null}),m)}function ne(){const s=ae.getData(oe.CALL,q.ROOM_ID);if(s==null)return"";if(typeof s=="number")return s===0?"":String(s);const o=String(s).trim();return!o||o==="0"?"":o}function Ze(){var s,o;try{const l=(o=(s=H).getTUICallEngineInstance)==null?void 0:o.call(s);if(!l)return"";const d=[l.roomId,l.roomID,l._roomId,l._roomID,l.strRoomID];for(const w of d){if(w==null||w==="")continue;const C=String(w).trim();if(C&&C!=="0")return C}}catch{}return""}function Ce(){return ne()||Ze()}function ce(s,o){if(o!=null&&String(o).trim()!==""&&String(o)!=="0")return String(o).trim();if(typeof s=="number"&&s>0)return String(s);if(typeof s=="string"){const l=s.trim();if(l&&l!=="0")return l}return""}function L(s){if(s==null||typeof s!="object")return"";const o=s,l=ce(o.roomID,o.strRoomID)||ce(o.roomId,o.strRoomId);if(l)return l;const d=o.data;if(d&&typeof d=="object"){const w=d,C=ce(w.roomID,w.strRoomID)||ce(w.roomId,w.strRoomId);if(C)return C}return""}function ge(){V&&(clearTimeout(V),V=null),he=0}function pn(){ge();const s=()=>{V=null;const o=ae.getData(oe.CALL,q.CALL_STATUS);if(o===Ue||o!==Ve&&o!==de)return;const l=Ce();if(l){Re(l);return}if(he++,he>=en){console.warn("[chat-dialog] 仍未解析到有效房间号(已重试",en,"次)");return}V=setTimeout(s,ps)};V=setTimeout(s,0)}async function vt(s){if(!(p.value==null||c.value==null)){await Xe();for(let o=0;o<40;o++){const l=Ce();if(l){await Re(l);return}await new Promise(d=>setTimeout(d,50))}console.warn("[chat-dialog] 发起通话后仍未解析到房间号(API:",s,")")}}function vn(){var d,w;const s=window;if(s.__zytEngineRoomCapture__)return;const o=(w=(d=H).getTUICallEngineInstance)==null?void 0:w.call(d);if(!o||typeof o.calls!="function")return;s.__zytEngineRoomCapture__=!0,o.__zytEngineRoomCapture__=!0;const l=C=>{const D=o[C];typeof D=="function"&&(o[C]=async function(...U){const O=await D.apply(o,U),j=L(O);return j&&Re(j),await vt("engine."+C),O})};l("calls"),l("call"),l("groupCall")}function gn(){const s=window;if(s.__zytHangupPreStop__)return;const o=H,l=o.hangup;typeof l=="function"&&(s.__zytHangupPreStop__=!0,o.hangup=function(...w){return N.beginStopNow(),l.apply(H,w)})}function gt(){var C,D;const s=window;if(s.__zytTrtcPreStop__)return;const o=(D=(C=H).getTUICallEngineInstance)==null?void 0:D.call(C),l=o==null?void 0:o.trtcCloud;if(!l||typeof l!="object")return;let d=0;const w=["stopLocalVideo","stopLocalAudio"];for(const B of w){const U=l[B];typeof U=="function"&&(l[B]=function(...j){return N.beginStopNow(),U.apply(l,j)},d++)}d>0&&(s.__zytTrtcPreStop__=!0)}let Ae=[],ke=null,yt=0;async function Fe(){const s=Y??c.value;if(s==null){console.warn("[chat-dialog] endCall 跳过:无诊单 ID(快照与当前均为空)");return}try{await ga({diagnosis_id:s}),console.log("[chat-dialog] endCall 已同步",{diagnosis_id:s})}catch(o){console.warn("[chat-dialog] endCall 失败",o)}}function _t(s){const o=Date.now();o-yt<vs||(yt=o,console.log("[chat-dialog] 挂断停合流:",s),N.isRecording()&&N.beginStopNow(),Fe())}function yn(){var s;Qe();try{const o=(s=Ht)==null?void 0:s.chat;if(!(o!=null&&o.on)){console.warn("[chat-dialog] TUIChatEngine.chat 不可用,无法监听 IM 视频挂断信令");return}ke=l=>{if(!t.value)return;const d=_.value;if(!d)return;const w=d.startsWith("C2C")?d:`C2C${d}`,C=Array.isArray(l.data)?l.data:[];for(const D of C){if(!D||D.conversationID!==w)continue;const B=D.type;if(!(B===ye.TYPES.MSG_CUSTOM||B==="TIMCustomElem"||typeof B=="string"&&/custom/i.test(B)))continue;const O=D.payload,j=typeof(O==null?void 0:O.data)=="string"?O.data:"";if(!(!j||!os(j))){_t("IM");break}}},o.on(ye.EVENT.MESSAGE_RECEIVED,ke)}catch(o){console.warn("[chat-dialog] 绑定 IM 挂断监听失败",o)}}function Qe(){var s,o;if(ke){try{const l=(s=Ht)==null?void 0:s.chat;(o=l==null?void 0:l.off)==null||o.call(l,ye.EVENT.MESSAGE_RECEIVED,ke)}catch{}ke=null}}function _n(){var s,o;try{const l=(o=(s=H).getTUICallEngineInstance)==null?void 0:o.call(s),d=l==null?void 0:l.on;if(!l||typeof d!="function"||l.__zytRoomEvents)return;l.__zytRoomEvents=!0;const w=U=>{const O=L(U);if(O){Re(O);return}et()},C=()=>{_t("TUICallEngine")},D=[De.TUICallEvent.CALL_END,De.TUICallEvent.USER_LEAVE,De.TUICallEvent.ON_CALL_NOT_CONNECTED];for(const U of D)d.call(l,U,C),Ae.push({event:U,fn:C});const B=[De.TUICallEvent.USER_ENTER,De.TUICallEvent.ON_CALL_BEGIN];for(const U of B)d.call(l,U,w),Ae.push({event:U,fn:w})}catch(l){console.warn("[chat-dialog] 绑定引擎房间事件失败",l)}}function bn(){var s,o;try{const l=(o=(s=H).getTUICallEngineInstance)==null?void 0:o.call(s);if(!(l!=null&&l.off)){Ae=[];return}for(const{event:d,fn:w}of Ae)l.off(d,w);l.__zytRoomEvents=!1}catch{}Ae=[]}function wn(){const s=window;if(s.__zytTUICallRoomHooks__)return;s.__zytTUICallRoomHooks__=!0;const o=H,l=d=>{const w=o[d];typeof w=="function"&&(o[d]=async function(...D){const B=await w.apply(o,D);return await vt(d),B})};l("calls"),l("call"),l("groupCall")}async function Re(s){try{await G}catch{}if(p.value==null||c.value==null)return;const o=`${c.value}:${s}`;if(o===z.value){ge();return}z.value=o;try{const l=await ya({diagnosis_id:c.value,room_id:s});ge(),console.log("[chat-dialog] bindCallRoom 成功",{room_id:s,bindRes:l});const d=l==null?void 0:l.cloud_recording;d&&d.started===!1&&d.message&&F.msgWarning(`云端合流录制未启动(关闭控制台全局录制后仅依赖 API):${d.message}`)}catch(l){console.warn("[chat-dialog] bindCallRoom 失败",l),z.value=""}}async function et(){if(p.value==null||c.value==null)return;const s=ae.getData(oe.CALL,q.CALL_STATUS);if(s===Ue){ge(),z.value="";return}if(s!==Ve&&s!==de)return;await Xe();const o=Ce();if(o){await Re(o);return}pn()}async function En(){if(!(p.value==null||c.value==null))try{await _a({diagnosis_id:c.value,patient_id:p.value,call_type:2})}catch(s){console.warn("[chat-dialog] startCall 记录失败",s)}}function Tn(){K==null||K();let s=ae.getData(oe.CALL,q.CALL_STATUS)??Ue;const o=d=>{var C;const w=d??Ue;if(w===Ue){(s===Ve||s===de)&&N.beginStopNow(),Z(),le.value=!1,(s===Ve||s===de)&&(async()=>(await Fe(),b.value=!1,await ve()))(),ge(),z.value="",s=w;return}if(w===de){if(et(),(C=M.value)==null||C.applyIfEnabled(),Z(),!re.value){s=w;return}const D=Se,B=(U=0)=>{if(D!==Se){console.log("[chat-dialog] 录制轮次已变化,取消启动");return}const O=nt.value,j=ae.getData(oe.CALL,q.CALL_STATUS);if(!O||j!==de){console.warn("[chat-dialog] 录制启动条件不满足",{root:!!O,status:j});return}console.log(`[chat-dialog] 尝试启动本地录制(第 ${U+1} 次)`);let Me=Array.from(O.querySelectorAll("video"));if(Me.length===0&&(Me=Array.from(document.body.querySelectorAll("video")).filter(On=>{const Nt=On.srcObject;return Nt instanceof MediaStream?Nt.getVideoTracks().some(Hn=>Hn.readyState==="live"):!1}),console.log("[chat-dialog] 在 body 中找到活跃视频:",Me.length)),Me.length===0){U<10?(console.warn("[chat-dialog] 未找到视频元素,300ms 后重试"),k=setTimeout(()=>B(U+1),300)):console.error("[chat-dialog] 重试 10 次后仍未找到视频元素,放弃录制");return}if(!Me.some(Ft=>Ft.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA)){U<10?(console.warn("[chat-dialog] 视频元素未就绪,300ms 后重试"),k=setTimeout(()=>B(U+1),300)):console.error("[chat-dialog] 重试 10 次后视频仍未就绪,放弃录制");return}console.log("[chat-dialog] 视频元素已就绪,立即启动录制");const Vt=N.start(O);le.value=Vt,Vt?console.log("[chat-dialog] ✅ 本地录制已成功启动"):console.error("[chat-dialog] 本地录制启动失败(MediaRecorder 或画布初始化失败)")};k=setTimeout(()=>B(0),500)}else Z();s=w},l=()=>{et()};ae.watch(oe.CALL,{[q.CALL_STATUS]:o,[q.ROOM_ID]:l}),K=()=>{try{ae.unwatch(oe.CALL,{[q.CALL_STATUS]:o,[q.ROOM_ID]:l})}catch{}ge(),K=null}}let bt=0;function xe(){const s=Date.now();s-bt<gs||(bt=s,F.msgError(hn()),b.value=!1)}let Ie=null,Ne=!1,ue=null;function Sn(){Ne||(Ie=console.error.bind(console),Ne=!0,console.error=(...s)=>{if(Ie(...s),!t.value||!g.value)return;const o=s.map(l=>{if(typeof l=="string")return l;if(l instanceof Error)return l.message;try{return JSON.stringify(l)}catch{return String(l)}}).join(" ");_e(o)&&xe()})}function Cn(){Ne&&Ie&&(console.error=Ie),Ne=!1,Ie=null}function An(){var s,o,l;try{const d=(o=(s=H).getTUICallEngineInstance)==null?void 0:o.call(s);if(!(d!=null&&d.on))return;ue&&((l=d.off)==null||l.call(d,"error",ue)),ue=w=>{!t.value||!g.value||_e(w)&&xe()},d.on("error",ue)}catch(d){console.warn("绑定 TUICallEngine error 监听失败:",d)}}function kn(){var s,o;try{const l=(o=(s=H).getTUICallEngineInstance)==null?void 0:o.call(s);l!=null&&l.off&&ue&&l.off("error",ue)}catch{}ue=null}async function Rn(s,o){try{const l=ye.create({SDKAppID:s}),d={businessID:"doctor_entered_consult_room",time:Date.now()},w=l.createCustomMessage({to:o,conversationType:ye.TYPES.CONV_C2C,payload:{data:JSON.stringify(d)}});await l.sendMessage(w),console.log("已发送医生进入诊室信令(患者端聊天列表不展示)")}catch(l){console.warn("发送医生进入诊室信令失败:",l)}}const wt=s=>{!t.value||!g.value||_e(s.reason)&&xe()};da(()=>{Sn(),window.addEventListener("unhandledrejection",wt)}),fa(()=>{Z(),N.reset(),K==null||K(),bn(),Qe(),Cn(),kn(),window.removeEventListener("unhandledrejection",wt)});const xn=async(s,o)=>{try{if(!s){console.warn("头像 URL 为空,跳过更新");return}console.log("开始更新头像到 IM:",s);const l=await new Promise((d,w)=>{setTimeout(async()=>{try{const D=await ye.create({SDKAppID:o}).updateMyProfile({avatar:s});console.log("IM 头像更新成功:",D),d(D)}catch(C){console.error("更新头像异常:",C),d(null)}},500)})}catch(l){console.error("IM 头像更新失败:",l.message||l)}};rn(()=>te.value,async s=>{if(s){if(u.value=s.getShowName()||u.value,console.log("会话切换:",s.conversationID,"名称:",u.value,s),s.userProfile.userID.includes("doctor"))console.log("当前会话是医生,跳过获取 assistant_id");else try{const o=await ot({patient_id:s.userProfile.userID.replace("patient_",""),diagnosis_id:c.value});pe(o),_.value=o.patientUserId,n.value=o.assistant_id,console.log("会话切换后获取到 assistant_id:",n.value,"完整响应:",o)}catch(o){console.error("获取 assistant_id 失败:",o)}console.log("会话切换完成,userID:",s.userProfile.userID)}});const In=async s=>{t.value=!0,a.value=!1,Be.value=100,Oe.value=80,kt(),u.value=s.patientName,p.value=s.patientId,c.value=s.diagnosisId||null,f.value="",r.value=!1,g.value=!1,b.value=!1,v.value="正在获取签名...";try{const o=await ot({patient_id:s.patientId,diagnosis_id:s.diagnosisId||0});if(pe(o),n.value=o.assistant_id,console.log("后端返回的签名数据:",o),console.log("assistant_id:",n.value),!o||!o.userSig)throw new Error("获取签名失败");o.assistant_id||console.warn("警告:后端未返回 assistant_id,群视频通话可能无法正常工作"),_.value=o.patientUserId||`patient_${s.patientId}`,v.value="正在登录聊天...",await Te({sdkAppId:Number(o.sdkAppId),userId:o.userId,userSig:o.userSig,useUploadPlugin:!0}),yn();const l=Number(o.sdkAppId);if(!window.__TUICallKitInited__){v.value="正在初始化通话能力...";try{await H.init({userID:o.userId,userSig:o.userSig,SDKAppID:l}),window.__TUICallKitInited__=!0}catch(d){console.warn("TUICallKit 初始化失败,聊天仍可用,音视频通话不可用:",(d==null?void 0:d.message)||d),_e(d)&&xe()}}g.value=!!window.__TUICallKitInited__,g.value&&(H.setCallback({beforeCalling:()=>{gt(),Z(),N.reset(),le.value=!1,Se++,Y=c.value,kt(),b.value=!0,G=En(),setTimeout(()=>{var d;(d=M.value)==null||d.applyIfEnabled()},1500)},afterCalling:()=>{N.beginStopNow(),(async()=>(await Fe(),b.value=!1,await ve()))()}}),wn(),vn(),gn(),gt(),_n(),Tn(),An()),console.log("Chat UIKit 登录成功,患者用户ID:",_.value),v.value="加载聊天界面...",setTimeout(async()=>{var w;r.value=!0,await Xe(),await new Promise(C=>setTimeout(C,1e3));const d=(w=ie.userInfo)==null?void 0:w.avatar;console.log("准备更新头像,avatar:",d),d&&await xn(d,l);try{const C=await W(_.value);x.value=C.conversationID,console.log("已创建/获取会话:",x.value),Je(x.value),console.log("已激活会话"),await Rn(l,_.value)}catch(C){console.error("创建/激活会话失败:",C)}},800)}catch(o){console.error("初始化聊天失败:",o),f.value=o.message||"初始化聊天失败",F.msgError(f.value)}},Ln=async()=>{if(!g.value){F.msgWarning("通话服务初始化中,请稍后再试");return}if(!_.value){F.msgWarning("未找到患者通话ID,无法发起群视频");return}try{if(!n.value){console.warn("assistant_id 为空,尝试重新获取");const o=await ot({patient_id:p.value,diagnosis_id:c.value});pe(o),n.value=o.assistant_id,console.log("重新获取 assistant_id:",n.value)}const s=[_.value,n.value].filter(o=>o);if(s.length<2){F.msgWarning("助理ID获取失败,无法发起群视频"),console.error("userIDList 不完整:",s,"assistant_ids:",n.value);return}console.log("发起群视频通话,参与者:",s),await H.calls({userIDList:s,type:Pa.VIDEO_CALL})}catch(s){console.error("发起群视频失败:",s),_e(s)?xe():F.msgError(Ko(s,"发起群视频失败"))}},Mn=T(),Be=T(100),Oe=T(80),tt=T(!1),Et=T(0),Tt=T(0),St=T(0),Ct=T(0),At=T(),nt=T(),Le=T(!1),He=T(0),$e=T(0);function kt(){He.value=tn,$e.value=Math.max(tn,Math.floor((window.innerHeight-ys)/2))}const at=T(!1),Rt=T(0),xt=T(0),It=T(0),Lt=T(0),Dn=J(()=>({left:`${He.value}px`,top:`${$e.value}px`})),Pn=s=>{at.value=!0,Rt.value=s.clientX,xt.value=s.clientY,It.value=He.value,Lt.value=$e.value,document.addEventListener("mousemove",Mt),document.addEventListener("mouseup",Dt)},Mt=s=>{at.value&&(He.value=Math.max(0,It.value+s.clientX-Rt.value),$e.value=Math.max(0,Lt.value+s.clientY-xt.value))},Dt=()=>{at.value=!1,document.removeEventListener("mousemove",Mt),document.removeEventListener("mouseup",Dt)},Un=async()=>{if(!Le.value){Le.value=!0;try{if(p.value==null){F.msgWarning("缺少患者信息,无法同步舌苔照片");return}const s=At.value,o=nt.value,l=s||o;if(!l)return;const d=await Wo(l,{extraRoots:[o].filter(Boolean)});if(!d){F.msgWarning("截屏失败,请确认视频画面已加载");return}const w=await ma(d,`callshot-${Date.now()}.jpg`),C=w.url||w.uri;if(!C){F.msgError("上传未返回图片路径");return}if(c.value==null){F.msgWarning("请先保存诊单后再从视频同步舌苔照片");return}await pa({diagnosis_id:c.value,tongue_images:[C]}),F.msgSuccess("舌苔照片已保存")}catch(s){const o=s;console.error(o),F.msgError((o==null?void 0:o.message)||"上传失败")}finally{Le.value=!1}}},Vn=async()=>{if(g.value)try{N.beginStopNow(),await ve(),await H.hangup()}catch(s){console.warn("关闭视频窗口时挂断失败:",s)}b.value=!1},Fn=J(()=>({left:`${Be.value}px`,top:`${Oe.value}px`})),Nn=s=>{const o=s.target;o.closest(".chat-close-btn")||o.closest(".chat-header-actions")||(tt.value=!0,Et.value=s.clientX,Tt.value=s.clientY,St.value=Be.value,Ct.value=Oe.value,document.addEventListener("mousemove",Pt),document.addEventListener("mouseup",Ut))},Pt=s=>{tt.value&&(Be.value=Math.max(0,St.value+s.clientX-Et.value),Oe.value=Math.max(0,Ct.value+s.clientY-Tt.value))},Ut=()=>{tt.value=!1,document.removeEventListener("mousemove",Pt),document.removeEventListener("mouseup",Ut)},Bn=async()=>{if(Qe(),g.value){const s=ae.getData(oe.CALL,q.CALL_STATUS);if(s===Ve||s===de)try{N.beginStopNow(),await ve(),await H.hangup()}catch(o){console.warn("挂断通话时出错:",o)}}c.value!=null&&await Fe(),t.value=!1,b.value=!1};return e({open:In}),(s,o)=>{const l=an,d=nn,w=on,C=qn;return R(),X(ln,{to:"body"},[Ke(y("div",{ref_key:"chatWindowRef",ref:Mn,class:ut(["chat-floating-window",{"chat-floating-window--minimized":a.value}]),style:ct(Fn.value)},[y("div",{class:"chat-window-header",onMousedown:Nn},[y("span",{class:"chat-window-title",title:u.value},"与 "+Q(u.value)+" 通讯",9,ss),y("div",{class:"chat-header-actions",onMousedown:o[2]||(o[2]=me(()=>{},["stop"]))},[h(d,{type:"danger",link:"",class:"chat-close-btn",onClick:Bn},{default:S(()=>[h(l,null,{default:S(()=>[h(A(lt))]),_:1})]),_:1}),a.value?(R(),X(w,{key:1,content:"展开聊天窗口",placement:"top"},{default:S(()=>[h(d,{type:"primary",link:"",class:"chat-expand-btn",onClick:o[1]||(o[1]=D=>a.value=!1)},{default:S(()=>[h(l,null,{default:S(()=>[h(A(ea))]),_:1}),o[6]||(o[6]=y("span",{class:"chat-header-btn-text"},"展开",-1))]),_:1})]),_:1})):(R(),X(w,{key:0,content:"缩小为标题条,不关闭会话",placement:"top"},{default:S(()=>[h(d,{type:"primary",link:"",class:"chat-minimize-btn",onClick:o[0]||(o[0]=D=>a.value=!0)},{default:S(()=>[h(l,null,{default:S(()=>[h(A(Qn))]),_:1}),o[5]||(o[5]=y("span",{class:"chat-header-btn-text"},"缩小",-1))]),_:1})]),_:1}))],32)],32),Ke(y("div",is,[r.value?f.value?(R(),P("div",ls,[h(C,{title:f.value,type:"error",closable:!1},null,8,["title"])])):(R(),P("div",cs,[h(A(Ua),{language:"zh-CN",theme:"light"},{default:S(()=>[y("div",us,[h(A(ba),{class:"chat-area"},{default:S(()=>[h(A(Sa),{conversationID:x.value,Message:ns},null,8,["conversationID"]),h(A(Ca),null,{headerToolbar:S(()=>[y("div",ds,[h(A(Aa)),h(A(ka)),h(A(Ra)),g.value?(R(),X(A(xa),{key:0})):$("",!0),g.value?(R(),X(A(Ia),{key:1})):$("",!0),g.value?(R(),X(d,{key:2,size:"small",type:"primary",onClick:Ln},{default:S(()=>[...o[7]||(o[7]=[fe(" 群视频 ",-1)])]),_:1})):$("",!0),g.value&&I.value?(R(),X(Mo,{key:3,ref_key:"beautyPanelRef",ref:M,"get-engine":ee,"popper-z-index":300002},{reference:S(()=>[h(d,{size:"small"},{default:S(()=>[h(l,null,{default:S(()=>[h(A(rt))]),_:1}),o[8]||(o[8]=y("span",{style:{"margin-left":"2px"}},"美颜",-1))]),_:1})]),_:1},512)):$("",!0)])]),_:1})]),_:1})])]),_:1})])):(R(),P("div",rs,[h(l,{class:"is-loading"},{default:S(()=>[h(A(ta))]),_:1}),y("span",null,Q(v.value),1)]))],512),[[ze,!a.value]]),g.value?Ke((R(),P("div",{key:0,ref_key:"callKitWrapperRef",ref:At,class:"chat-dialog-call-kit-wrapper",style:ct(Dn.value)},[y("div",{class:"call-kit-drag-handle",onMousedown:Pn},[y("div",fs,[o[9]||(o[9]=y("span",{class:"drag-handle-text"},"视频通话",-1)),le.value?(R(),P("span",ms,"本地录制中")):$("",!0)]),y("div",hs,[h(d,{type:"primary",link:"",class:"call-kit-screenshot-btn",loading:Le.value,disabled:Le.value,onMousedown:o[3]||(o[3]=me(()=>{},["stop"])),onClick:me(Un,["stop","prevent"])},{default:S(()=>[h(l,null,{default:S(()=>[h(A(na))]),_:1}),o[10]||(o[10]=y("span",{class:"call-kit-screenshot-text"},"截屏",-1))]),_:1},8,["loading","disabled"]),h(d,{type:"danger",link:"",class:"call-kit-close-btn",onMousedown:o[4]||(o[4]=me(()=>{},["stop"])),onClick:me(Vn,["stop"])},{default:S(()=>[h(l,null,{default:S(()=>[h(A(lt))]),_:1})]),_:1}),h(l,{class:"drag-handle-icon"},{default:S(()=>[h(A(aa))]),_:1})])],32),y("div",{ref_key:"callKitContentRef",ref:nt,class:"call-kit-content"},[h(A(Da),{allowedMinimized:!0,allowedFullScreen:!0,class:"chat-dialog-call-kit"})],512)],4)),[[ze,b.value]]):$("",!0)],6),[[ze,t.value]])])}}}),Ai=ft(_s,[["__scopeId","data-v-d1dcd64f"]]);export{Ai as default};