<template>
  <div class="pk-mini-workbench">
    <el-container class="pk-container">
      <!-- 左侧导航栏 -->
      <el-aside class="pk-aside" width="80px">
        <PkAppaside :active="activeTab" @navigate="handleNavigate" />
      </el-aside>
      <!-- 右侧主体内容 -->
      <el-main class="pk-main">
        <KeepAlive>
          <component :is="currentComponent" />
        </KeepAlive>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import PkAppaside from '@/components/pk-mini/PkAppaside.vue'
import PkHall from './PkHall.vue'
import Forum from './Forum.vue'
import Message from './Message.vue'
import Mine from './Mine.vue'
import { initPkGoEasy, goEasyLink, goEasyDisConnect } from '@/utils/pk-mini/goeasy'
import { getOtp } from '@/api/pk-mini'
import { getMainUserData } from '@/utils/pk-mini/storage'
import { ElMessage, ElNotification } from 'element-plus'

const activeTab = ref('pk')
let reconnectNotification = null

const componentMap = {
  pk: PkHall,
  forum: Forum,
  message: Message,
  mine: Mine
}

const currentComponent = computed(() => componentMap[activeTab.value])

const handleNavigate = (tab) => {
  activeTab.value = tab
}

// 自动连接 IM
async function autoLinkIM() {
  try {
    const userData = getMainUserData()
    if (!userData || !userData.id) {
      console.log('PK Mini: 用户未登录，跳过 IM 连接')
      return
    }

    const otp = await getOtp()
    const data = {
      id: String(userData.id),
      // avatar: userData.headerIcon || '',
      nickname: userData.username  || '',
      key: otp
    }

    await goEasyLink({
      ...data,
      onProgress: () => {
        if (!reconnectNotification) {
          reconnectNotification = ElNotification({
            title: 'IM 重连中',
            message: '聊天系统正在重新连接，请稍候...',
            type: 'warning',
            duration: 0
          })
        }
      },
      onSuccess: () => {
        if (reconnectNotification) {
          reconnectNotification.close()
          reconnectNotification = null
        }
      }
    })
    console.log('PK Mini: IM 连接成功')
  } catch (err) {
    console.error('PK Mini: IM 连接失败', err)
    if (reconnectNotification) {
      reconnectNotification.close()
      reconnectNotification = null
    }
    ElMessage.warning('PK工作台聊天系统连接失败')
  }
}

onMounted(() => {
  // 初始化 GoEasy
  initPkGoEasy()
  // 自动连接 IM
  autoLinkIM()
})

onUnmounted(() => {
  // 断开 IM 连接
  goEasyDisConnect().catch(() => {})
  // 清理重连通知
  if (reconnectNotification) {
    reconnectNotification.close()
    reconnectNotification = null
  }
})
</script>

<style scoped lang="less">
.pk-mini-workbench {
  width: 100%;
  height: 100%;
  background-color: #f9fafb; // gray-50
}

.pk-container {
  width: 100%;
  height: 100%;
}

.pk-aside {
  height: 100%;
  background-color: #ffffff;
  border-right: 1px solid #f1f5f9; // slate-100
}

.pk-main {
  height: 100%;
  padding: 0;
  overflow: hidden;
}
</style>
