<script setup lang="ts">
import { getPlatformUser, getUserInfo } from '@af-mobile-client-vue3/api/user'
import { getUserPermissions } from '@af-mobile-client-vue3/services/api/search'
import { useSettingStore } from '@af-mobile-client-vue3/stores/modules/setting'
import { useUserStore } from '@af-mobile-client-vue3/stores/modules/user'
import { UserType } from '@af-mobile-client-vue3/types/auth'
import { PlatformType } from '@af-mobile-client-vue3/types/platform'
import { isWechat } from '@af-mobile-client-vue3/utils/platform-auth'
import { funcToRouter, loadRoutes } from '@af-mobile-client-vue3/utils/routerUtil'
import { secureStorageBatchWrite } from '@af-mobile-client-vue3/utils/secureStorage'
import { Loading as VanLoading } from 'vant'
import { onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const setting = useSettingStore()
// 响应式状态
const isLoading = ref(true)
const errorMessage = ref('')
const errorDetail = ref('')
const hasError = ref(false)

// 主要认证处理逻辑
async function handleAuth() {
  try {
    const authParam = route.query as Record<string, string>
    if (authParam.platformType) {
      // 先清理缓存 token 以及配置
      await userStore.registerClean()
      switch (authParam.platformType) {
        case PlatformType.WECHAT_OFFICIAL:
        case PlatformType.WECHAT_MINI:
          // 微信公众号,微信小程序授权登录参数
          await handleExternalLogin(authParam)
          break
        default:
          // 其他环境使用原生扫码（需要页面跳转或调用原生API）
          throw new Error('当前环境不支持授权登录')
      }
    }
    else {
      // 无授权参数，检查是否已登录或等待授权
      await handleWaitingForAuth()
    }
  }
  catch (error) {
    console.error('[AuthLoading] 认证处理失败:', error)

    isLoading.value = false
    hasError.value = true

    if (error instanceof Error) {
      errorMessage.value = '授权失败，请尝试重新进入此页面'
      errorDetail.value = error.message
    }
    else {
      errorMessage.value = '认证失败'
      errorDetail.value = String(error)
    }
  }
}

// 处理外部用户登录
async function handleExternalLogin(loginParams: any) {
  let data: any
  if (loginParams.platformType === PlatformType.WECHAT_OFFICIAL) {
    data = await userStore.loginExternal(Object.assign(loginParams, {
      isMobile: true,
      resourceName: setting.getSetting()?.routerName || '智慧手机',
    }))
  }
  else {
    data = await userStore.loginExternalMini(Object.assign(JSON.parse(loginParams.appData), {
      isMobile: true,
      resourceName: setting.getSetting()?.routerName || '智慧手机',
    }))
  }

  const loginInfo = {
    f: data,
    jwt: data.id,
    r: data.r,
  }
  userStore.setLogin(loginInfo)
  // 设置用户信息
  userStore.setUserType(data.resources.userType || UserType.SYSTEM)
  userStore.setPlatformType(loginParams.platformType || PlatformType.WECHAT_OFFICIAL)
  await afterGeneral(data.resources, data.access_token, userStore.getUserType())

  // 获取重定向地址并跳转
  const targetPath = route.query.redirect as string
  // 方法1: 使用解构和删除属性
  await router.replace({
    path: targetPath,
    query: (() => {
      const query = { ...route.query }
      // 删除不需要的参数
      delete query.redirect
      delete query.state
      delete query.tenantName
      delete query.platformUserId
      delete query.token
      delete query.code
      delete query.platformType
      delete query.appData
      // 可以继续删除其他不需要的参数
      return query
    })(),
  })
}

function closeWindows() {
  if (isWechat()) {
    (window as any).WeixinJSBridge.call('closeWindow')
  }
  else {
    // 关闭页面
    if (navigator.userAgent.includes('Firefox') || navigator.userAgent.includes('Chrome')) {
      window.open('about:blank', '_self')
      window.close()
    }
    else {
      window.opener = null
      window.open('', '_self')
      window.close()
    }
  }
}

async function afterGeneral(result, token = '', userType = UserType.SYSTEM) {
  if (userType === UserType.SYSTEM && result.platformType && result.functions && result.functions.length === 0 && result.ename) {
    const res = await getUserInfo({
      username: result.ename,
      resourceName: setting.getSetting()?.routerName || '智慧手机',
    })
    console.log('获取用户信息', res)
    if (res.resources.functions && res.resources.functions.length > 0) {
      result.functions = res.resources.functions
    }
    if (res.resources.permissions && res.resources.permissions.length > 0) {
      result.permissions = res.resources.permissions
    }
  }
  if (result?.platformUserId && result?.platformType && result?.dir && setting.getSetting()?.getPlatformUser) {
    const wxRes = await getPlatformUser({
      platformUserId: result?.platformUserId,
      tenantName: result.dir,
    })
    if (wxRes?.nickname) {
      result.nickname = wxRes.nickname
    }
  }
  // 排序 functions 及其嵌套的 children
  if (result.functions && Array.isArray(result.functions)) {
    // 对顶层菜单进行排序
    result.functions.sort((a, b) => (a.position || 0) - (b.position || 0))

    // 对每个菜单的子项进行排序
    for (const item of result.functions) {
      if (item.children && Array.isArray(item.children)) {
        item.children.sort((a, b) => (a.position || 0) - (b.position || 0))
      }
    }
  }

  const user: any = {
    ...result,
    username: result.ename,
    avatar: result.avatar,
    nickname: result.nickname,
  }
  userStore.setUserInfo(user)
  // 如果result中没有返回 权限 需要主动获取权限列表
  if (!result.permissions && userType !== UserType.EXTERNAL) {
    result.permissions = await getUserPermissions(result.id)
  }
  userStore.setPermissions(result.permissions)
  userStore.setRoles([{ id: userType, operation: ['add', 'edit', 'delete'] }])
  // 加载路由
  if (user.functions) {
    loadRoutes(funcToRouter(user.functions))
  }

  // 存储登录数据到本地缓存
  secureStorageBatchWrite([
    {
      key: 'loginData',
      value: {
        token,
      },
    },
    {
      key: 'userData',
      value: result,
    },
  ])

  // 每次重新登录时，清除indexedDB缓存
  // indexedDB.clear()
}

// TODO 处理等待授权的情况 暂未实现目前不确定三方对接方式
async function handleWaitingForAuth() {
  console.log('[AuthLoading] 处理等待授权情况')

  // 检查是否已登录
  const token = userStore.getToken()
  const userType = userStore.getUserType()

  if (token) {
    const targetPath = userType === 'EXTERNAL' ? '/ex' : '/'
    await router.replace(targetPath)
  }
  else {
    // 根据来源决定处理方式
    const source = route.query.source as string
    closeWindows()

    if (source === 'external') {
      // 外部用户需要重新获取授权
      throw new Error('第三方授权已过期，请重新尝试')
    }
    else {
      // 其他情况
      throw new Error('需要重新获取授权')
    }
  }
}

onMounted(() => {
  handleAuth()
})
</script>

<template>
  <div class="auth-loading">
    <!-- Logo区域 -->
    <div class="logo-section">
      <div class="company-logo">
        <div class="logo-text">
          智慧燃气
        </div>
      </div>
    </div>

    <!-- Loading区域 -->
    <div v-if="isLoading && !hasError" class="loading-section">
      <div class="loading-spinner">
        <VanLoading type="spinner" size="48px" color="#007BFF" />
      </div>
      <div class="loading-text">
        稍等，这就好
      </div>
    </div>

    <!-- 错误处理区域 -->
    <div v-if="hasError" class="error-section">
      <div class="error-icon">
        ⚠️
      </div>
      <div class="error-message">
        {{ errorMessage }}
      </div>
      <div v-if="errorDetail" class="error-detail">
        {{ errorDetail }}
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 主容器 */
.auth-loading {
  min-height: 100vh;
  background: #ffffff;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 32px 20px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

/* Logo区域 */
.logo-section {
  margin-bottom: 64px;
}

.company-logo {
  display: flex;
  align-items: center;
  justify-content: center;
}

.logo-text {
  font-size: 28px;
  font-weight: 600;
  color: #007bff;
  letter-spacing: 2px;
}

/* Loading区域 */
.loading-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.loading-spinner {
  margin-bottom: 24px;
}

.loading-text {
  font-size: 18px;
  font-weight: 500;
  color: #2c3e50;
  margin-bottom: 12px;
  line-height: 1.4;
}

.platform-text {
  font-size: 14px;
  color: #6c757d;
  line-height: 1.4;
}

/* 错误处理区域 */
.error-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  max-width: 300px;
}

.error-icon {
  font-size: 48px;
  margin-bottom: 20px;
  opacity: 0.8;
}

.error-message {
  font-size: 16px;
  color: #dc3545;
  margin-bottom: 24px;
  line-height: 1.5;
}

.error-detail {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
  padding: 12px;
  background: #f5f5f5;
  border-radius: 8px;
  word-break: break-all;
  text-align: left;
  max-width: 100%;
  overflow-x: auto;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .auth-loading {
    padding: 24px 16px;
  }

  .logo-text {
    font-size: 24px;
  }

  .loading-text {
    font-size: 16px;
  }

  .platform-text {
    font-size: 13px;
  }

  .error-message {
    font-size: 15px;
  }
}

/* 大屏适配 */
@media (min-width: 768px) {
  .auth-loading {
    max-width: 400px;
    margin: 0 auto;
  }
}

/* 兼容性优化 - 避免使用可能有问题的CSS特性 */
.loading-spinner :deep(.van-loading__spinner) {
  animation-duration: 1s;
  animation-timing-function: linear;
  animation-iteration-count: infinite;
}

/* 禁用选择，提升用户体验 */
.auth-loading {
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

/* 确保文字在各种设备上清晰显示 */
.logo-text,
.loading-text,
.platform-text,
.error-message {
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}
</style>
