import {
  loginCas,
  getUserInfo,
} from '@centit/api-auth'

const loginRoutes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import(/* webpackChunkName: "login" */ '../views/Login.vue'),
    meta: {
      fullscreen: true,
    },
  }
]
export default loginRoutes

export function setLoginTheme (component, login = loginRoutes) {
  login[0].component = () => component
}

export async function checkLogin ({
  router,
  store,
  to,
  from,
}, useCas) {
  if (to.name === 'Login') return true

  if (store.state.core.isLogin) return true

  return getUserInfo()
    .then(info => {
      store.commit('core/setLoginInfo', info)
      return true
    })
    .catch(({ code, message }) => {
      if (code === 302) {
        // 登录页面不需要记录
        if (from.name !== 'Login') {
          router.$lastRoute = from
        }

        if (useCas) {
          loginCas()
        } else {
          from.name !== 'Login' && router.replace({
            name: 'Login'
          })
        }
      }

      console.error({ message })
      return false
    })
}
