<template>
  <div class="login">
    <n-spin>
      <template #description>
        正在进入系统中...
      </template>
    </n-spin>
  </div>
</template>

<script>
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '@/store/modules/user'
import { fetchPermission } from '@/api/auth/index'
import { signinRedirectCallback, signoutRedirectCallback, signoutRedirect, getPath, removePath } from '@/utils/oidc/index.js'

export default {
  name: 'LoginPage',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const userStore = useUserStore()
    if (route.query?.code && route.query?.state) {
      /* 登录后的回调 */
      signinRedirectCallback().then(res => {
        // router.push({ path: getPath() })
        // removePath()
        // userStore.getUserInfos()
        /* 判断返回的授权信息是否能访问该平台 */
        const { authority, clientRoleList } = res.profile

        const { VITE_PLATFORM, VITE_CLIENT_ID } = import.meta.env
        const { roleId } = clientRoleList.find((item) => {
          return item.clientId === VITE_CLIENT_ID
        })
        if (authority && (authority.includes(VITE_PLATFORM) || authority.includes('admin'))) {
          fetchPermission({ roleId, clientId: 'tuoheng-hhz-admin' })
            .then(res => {
              const { opMenusList } = res.data
              const path = opMenusList[0].path
              router.push(path)
            })
          // router.push('/')
        } else {
          $message.error('暂无权限访问，请联系管理员')
          setTimeout(() => {
            signoutRedirect()
          }, 2000)
        }
      }).catch(err => {
        console.log(err)
        /* 失败则退出登录 */
        signoutRedirect()
      })
      // } else if (getPath()) {
      //   signoutRedirectCallback().then(res => {
      //     router.push({ path: getPath() })
      //     userStore.setUserInfo()
      //     removePath()
      //   })
    }
  }
}

</script>
<style scoped lang='scss'>
.login{
  width: 100vw;
  height: 100vh;
  position: relative;
  .n-spin-body{
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
  }
}
</style>
