<template>
  <div style="display: none;"></div>
</template>

<script setup>
import { onMounted, onUnmounted, getCurrentInstance } from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'
import GoEasy from 'goeasy'

const { proxy } = getCurrentInstance()
const emit = defineEmits(['connected'])

// 每次进入页面都重新获取权限并建立连接
async function connect() {
  console.log('[KefuConnect] 开始获取客服权限...')
  const phone = localStorage.getItem('username')
  if (!phone) {
    console.error('[KefuConnect] 未找到手机号')
    return
  }

  try {
    const res = await request.post('/houtai/kfhqltqx', { phone })
    if (res.code !== 0) {
      console.warn('[KefuConnect] 接口返回非0:', res)
      return
    }
    const { permissions, goeasy_appkey } = res.data
    console.log('[KefuConnect] 权限码:', permissions)
    console.log('[KefuConnect] GoEasy appkey:', goeasy_appkey)

    if (!permissions || permissions.length === 0) {
      console.warn('[KefuConnect] 无聊天权限，不能连接')
      ElMessage.warning('您没有客服聊天权限')
      return
    }
    if (!goeasy_appkey) {
      console.warn('[KefuConnect] 未获取到 appkey')
      return
    }

    // 断开旧连接
    if (window.goeasy) {
      console.log('[KefuConnect] 断开旧连接...')
      try { window.goeasy.disconnect({}) } catch (e) {}
      window.goeasy = null
    }

    const agentId = 'KF' + phone
    console.log('[KefuConnect] 客服ID:', agentId)

    // 创建新实例
    const goeasy = GoEasy.getInstance({
      host: 'hangzhou.goeasy.io',      // 根据实际区域修改
      appkey: goeasy_appkey,
      modules: ['im']
    })
    console.log('[KefuConnect] GoEasy 实例创建成功，准备连接...')

    goeasy.connect({
      id: agentId,
      data: { name: phone, avatar: '' },
      onSuccess: () => {
        console.log('[KefuConnect] ✅ 连接成功！')
        window.goeasy = goeasy
        window.__kefuAgentId = agentId
        // 通知父组件（Agent.vue）可以进行上线操作
        emit('connected')
        proxy.$emitter.emit('goeasy-connected')
      },
      onFailed: (error) => {
        console.error('[KefuConnect] ❌ 连接失败:', error)
        ElMessage.error('消息服务连接失败，请重试')
      },
      onProgress: (attempts) => {
        console.log('[KefuConnect] 🔄 重连中... 第' + attempts + '次')
      }
    })
  } catch (e) {
    console.error('[KefuConnect] 连接异常:', e)
  }
}

onMounted(() => {
  console.log('[KefuConnect] 组件挂载，开始建立客服长连接')
  connect()
})

onUnmounted(() => {
  console.log('[KefuConnect] 组件卸载，但保持连接存活（可后续优化）')
})
</script>