import { getUser } from '~/api'

export const useStore = () => {
  const visibleAppDownloadPopup = useState<boolean>('visibleAppDownloadPopup', () => false)
  const user = useState<any>('user', () => null)
  const isFetchingUser = useState<boolean>('isFetchingUser', () => false)

  const isLogin = computed(() => !!user.value)

  const fetchUser = async () => {
    // 如果已经有用户数据，或者正在抓取中，则直接返回
    if (user.value || isFetchingUser.value) return

    isFetchingUser.value = true
    try {
      const res = await getUser()
      user.value = res.data
    } catch (error) {
      user.value = null
    } finally {
      isFetchingUser.value = false
    }
  }

  const tenantMap: Record<string, string> = {
    sofia: 'https://sofia-learning.ezijing.com/',
    kelley: 'https://kelley-learning.ezijing.com/',
    gm: 'https://gm-learning.ezijing.com/',
    seg: 'https://seg-learning.ezijing.com/',
    campbellsville: 'https://campbellsville-learning.ezijing.com/',
    ciis: 'https://ciis-learning.ezijing.com/',
    marywood: 'https://marywood-learning.ezijing.com/',
    cuw: 'https://cuw-learning.ezijing.com/',
  }

  const learningLink = computed(() => {
    if (!user.value) return 'javascript:;'
    const tenant = user.value?.learning_info[0]?.tenant || 'ezijing'
    return tenantMap[tenant] || 'javascript:;'
  })

  return { visibleAppDownloadPopup, user, isLogin, fetchUser, learningLink }
}
