<!--
  外部系统 SSO 桥接页（cloud_law -> EchoChat）

  入参（query）：
    - payload: URI 编码的 JSON 字符串 { token, refresh_token, expires_in, user }
    - redirect: URI 编码的目标 hash 路径，例如 /pages/meeting/join?code=XXX-XXX-XXX

  逻辑：
    1. 读取 payload，写入 storage（saveToken + saveUserInfo）
    2. 同步 user store
    3. 跳转 redirect（默认 /pages/meeting/index）
-->
<template>
  <view class="sso">
    <text class="sso-title">{{ statusText }}</text>
  </view>
</template>

<script setup>
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { saveToken, saveUserInfo } from '@/utils/storage'
import { useUserStore } from '@/store/user'

const statusText = ref('正在登录…')

onLoad((query) => {
  try {
    if (!query?.payload) {
      statusText.value = '缺少 payload 参数'
      return
    }
    const payload = JSON.parse(decodeURIComponent(query.payload))
    if (!payload.token || !payload.user) {
      statusText.value = 'payload 字段不完整'
      return
    }
    // 写入持久化存储
    saveToken(payload.token, payload.refresh_token || '', payload.expires_in || 0)
    saveUserInfo(payload.user)
    // 同步 pinia store
    const userStore = useUserStore()
    userStore.token = payload.token
    userStore.userInfo = payload.user

    const redirect = query.redirect ? decodeURIComponent(query.redirect) : '/pages/meeting/index'
    statusText.value = '登录成功，跳转中…'
    // redirectTo 不保留历史，避免返回到 sso 页造成循环
    setTimeout(() => {
      uni.redirectTo({ url: redirect })
    }, 200)
  } catch (e) {
    console.error('[SSO] 解析失败', e)
    statusText.value = `SSO 失败：${e.message || e}`
  }
})
</script>

<style scoped>
.sso {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #F8FAFC;
}
.sso-title {
  font-size: 30rpx;
  color: #475569;
}
</style>
