<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 || !goeasy_appkey) 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) => {
        // 重连心跳：不要把 ready 置 false，否则上线按钮会卡死
        console.log('[KefuConnect] 重连中…', attempts)
      }
    })

    // 监听重连成功（GoEasy 2.x）
    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>
