import { handleUserData, ISsqChatImpl, SsqUser } from "./ISsqChatImpl"; import { HTML5 } from "cc/env"; interface SsqSDK { push(command: string, payload?: unknown): void; } type SsqWindow = Window & { ssq?: SsqSDK; __ssc?: { setting?: Record } }; export class SsqChatH5 implements ISsqChatImpl { private readyPromise: Promise | null = null; private script: HTMLScriptElement | null = null; private readonly src = 'https://plugin-code.salesmartly.com/js/project_607414_626816_1768878382.js'; private get browser(): SsqWindow { if (!HTML5 || typeof window === 'undefined' || typeof document === 'undefined') { throw new Error('当前平台暂不支持网页客服,请使用网页版联系客服。'); } return window as SsqWindow; } /** 单次加载、并发复用,等待 SDK onReady 而不是仅等待 script.onload。 */ ensureReady(): Promise { if (this.readyPromise) return this.readyPromise; this.readyPromise = this.load().catch(error => { this.readyPromise = null; throw error; }); return this.readyPromise; } init(): Promise { return this.ensureReady(); } private load(): Promise { return new Promise((resolve, reject) => { const browser = this.browser; browser.__ssc = browser.__ssc || {}; browser.__ssc.setting = { ...browser.__ssc.setting, hideIcon: true }; let settled = false; const finish = (error?: Error) => { if (settled) return; settled = true; clearTimeout(timer); if (this.script) { this.script.onload = null; this.script.onerror = null; } if (error) { if (!browser.ssq) { this.script?.remove(); this.script = null; } reject(error); } else resolve(); }; const timer = setTimeout(() => finish(new Error('客服初始化超时,请稍后重试。')), 15000); const waitReady = () => { try { if (!browser.ssq) throw new Error('客服脚本未正确初始化。'); browser.ssq.push('onReady', () => finish()); } catch (error) { finish(error instanceof Error ? error : new Error(String(error))); } }; if (browser.ssq) { waitReady(); return; } const script = document.createElement('script'); this.script = script; script.async = true; script.src = this.src; script.onload = waitReady; script.onerror = () => finish(new Error('客服加载失败,请检查网络后重试。')); (document.head || document.body).appendChild(script); }); } /** SDK 未提供此调用的完成回调,按 SDK 命令顺序先绑定再打开。 */ bindUser(user: SsqUser | null): void { const browser = this.browser; if (!browser.ssq) { console.error('客服尚未初始化。') return; }; const info = handleUserData(user, window.location.hostname); browser.ssq.push('setLoginInfo', info); } openChat(): void { const sdk = this.browser.ssq; if (!sdk) throw new Error('客服尚未初始化。'); sdk.push('chatOpen'); } closeChat(): void { this.browser.ssq?.push('chatClose'); } }