Files
Vue3/src/components/KefuConnect.vue
2026-06-28 00:31:26 +08:00

111 lines
2.9 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<template>
<div style="display: none;"></div>
</template>
<script setup>
import { onMounted, getCurrentInstance } from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'
import GoEasy from 'goeasy'
import {
afterGoeasyConnected,
resumeKefuSession,
onGoeasyReconnected,
isGoeasyConnected
} from '@/utils/kefuChat'
const { proxy } = getCurrentInstance()
const emit = defineEmits(['connected'])
async function connect() {
const phone = localStorage.getItem('username')
if (!phone) return
try {
const res = await request.post('/houtai/kfhqltqx', { phone })
if (res.code !== 0) return
const { permissions, goeasy_appkey } = res.data
if (!permissions?.length) {
console.warn('[KefuConnect] 无聊天权限')
return
}
if (!goeasy_appkey) {
console.error('[KefuConnect] 后端未返回 goeasy_appkey')
ElMessage.error('消息服务未配置 AppKey请联系管理员')
proxy.$emitter.emit('kefu-goeasy-ready', false)
return
}
const agentId = 'KF' + phone
if (
window.goeasy &&
window.__kefuAgentId === agentId &&
window.__kefuAppkey === goeasy_appkey &&
isGoeasyConnected()
) {
resumeKefuSession(proxy.$emitter, phone)
emit('connected')
proxy.$emitter.emit('goeasy-connected')
return
}
if (window.goeasy) {
try { window.goeasy.disconnect({}) } catch (e) {}
window.goeasy = null
window.__kefuCsOnline = false
}
window.__kefuAppkey = goeasy_appkey
if (window.__kefuUserWantsOffline === undefined) {
window.__kefuUserWantsOffline = false
}
const goeasy = GoEasy.getInstance({
host: 'hangzhou.goeasy.io',
appkey: goeasy_appkey,
modules: ['im']
})
goeasy.connect({
id: agentId,
data: { name: phone, avatar: '' },
onSuccess: () => {
window.goeasy = goeasy
window.__kefuAgentId = agentId
proxy.$emitter.emit('kefu-goeasy-ready', true)
afterGoeasyConnected(proxy.$emitter, phone)
emit('connected')
proxy.$emitter.emit('goeasy-connected')
},
onFailed: (error) => {
console.error('[KefuConnect] 连接失败:', error)
proxy.$emitter.emit('kefu-goeasy-ready', false)
ElMessage.error('消息服务连接失败,请刷新重试')
},
onProgress: (attempts) => {
console.log('[KefuConnect] 重连中…', attempts)
}
})
try {
goeasy.on && goeasy.on('reconnected', () => {
console.log('[KefuConnect] 重连成功')
onGoeasyReconnected(proxy.$emitter, phone)
proxy.$emitter.emit('goeasy-connected')
})
} catch (e) {
// ignore
}
} catch (e) {
console.error('[KefuConnect] 连接异常:', e)
proxy.$emitter.emit('kefu-goeasy-ready', false)
}
}
onMounted(() => {
connect()
})
</script>