<template>
  <view class="callback-page">
    <view class="callback-card">
      <view class="loading-dot"></view>
      <text class="callback-title">正在完成登录</text>
      <text class="callback-desc">请稍候，正在同步账号信息…</text>
    </view>
  </view>
</template>

<script>
import { useUserStore } from '@/store/user'
import { useWebSocketStore } from '@/store/websocket'
import { useChatStore } from '@/store/chat'
import { useContactStore } from '@/store/contact'
import { useNotifyStore } from '@/store/notify'

function decodePayload(payload) {
  const normalized = String(payload || '').replace(/-/g, '+').replace(/_/g, '/')
  const padded = normalized + '='.repeat((4 - normalized.length % 4) % 4)
  const binary = atob(padded)
  return decodeURIComponent(Array.prototype.map.call(binary, c => {
    return `%${(`00${c.charCodeAt(0).toString(16)}`).slice(-2)}`
  }).join(''))
}

function readRawQueryParams() {
  const result = {}
  try {
    if (typeof window === 'undefined') return result
    const search = String(window.location.search || '').replace(/^\?/, '')
    const hash = String(window.location.hash || '')
    const hashQuery = hash.indexOf('?') >= 0 ? hash.slice(hash.indexOf('?') + 1) : ''
    ;[search, hashQuery].forEach(raw => {
      if (!raw) return
      const params = new URLSearchParams(raw)
      params.forEach((value, key) => {
        if (result[key] === undefined) {
          result[key] = value
        }
      })
    })
  } catch (e) {}
  return result
}

export default {
  name: 'OAuthCallbackPage',
  onLoad(query) {
    this.handleCallback({ ...readRawQueryParams(), ...(query || {}) })
  },
  methods: {
    async handleCallback(query) {
      try {
        if (query.status !== 'success') {
          const message = query.payload ? decodePayload(query.payload) : '第三方登录失败'
          uni.showToast({ title: message || '第三方登录失败', icon: 'none' })
          setTimeout(() => uni.redirectTo({ url: '/pages/auth/login' }), 1200)
          return
        }
        const loginData = JSON.parse(decodePayload(query.payload))
        const store = useUserStore()
        store.applyOAuthLogin(loginData)
        const wsStore = useWebSocketStore()
        wsStore.connect()
        useChatStore().initWsListeners()
        useContactStore().initWsListeners()
        const notifyStore = useNotifyStore()
        notifyStore.initWsListeners()
        notifyStore.fetchUnreadCount().catch(() => {})
        uni.showToast({ title: '登录成功', icon: 'success' })
        setTimeout(() => uni.reLaunch({ url: '/pages/index/index' }), 600)
      } catch (e) {
        console.error('OAuth 回调处理失败:', e)
        uni.showToast({ title: '登录失败', icon: 'none' })
        setTimeout(() => uni.redirectTo({ url: '/pages/auth/login' }), 1200)
      }
    }
  }
}
</script>

<style scoped>
.callback-page {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #F8FAFC;
  padding: 48rpx;
}

.callback-card {
  width: 100%;
  max-width: 640rpx;
  padding: 64rpx 40rpx;
  border-radius: 24rpx;
  background-color: #FFFFFF;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.06);
  display: flex;
  flex-direction: column;
  align-items: center;
}

.loading-dot {
  width: 56rpx;
  height: 56rpx;
  border-radius: 50%;
  border: 6rpx solid #DBEAFE;
  border-top-color: #2563EB;
  animation: spin 800ms linear infinite;
}

.callback-title {
  margin-top: 32rpx;
  font-size: 34rpx;
  font-weight: 600;
  color: #1E293B;
}

.callback-desc {
  margin-top: 12rpx;
  font-size: 26rpx;
  color: #64748B;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}
</style>
