// 自动生成的文件，请勿修改
import asyncComponent from '@/common/services/async-component'
import routerService from '@/common/services/router-service'
import axios from '@/common/services/axios-instance'
import routerReady, { router } from '@/common/router-ready'
import { sdLocalStorage, sdSessionStorage } from '@/common/services/storage-service'
import { getUserInfo } from '@/common/store-mixin'
import loginService from './login-service'

routerService.route('/sd-login', {
  component:asyncComponent(
    () => import(/* webpackChunkName: "src-login" */ './sd-login.vue')
  ),
  meta: { anonymouse: true },
})
routerService.route('/sd-thirdparty-login', {
  component:asyncComponent(
    () => import(/* webpackChunkName: "src-login" */ './sd-thirdparty-login.vue')
  ),
  beforeEnter: (routeTo, routeFrom, next) => {
    if (!routeTo.query.code) {
      debugger
      const path =
        'http://iam.spic/idp/oauth2/authorize?redirect_uri=http%3A%2F%2Fszsj.spic%2F%23%2Fsd-thirdparty-login&client_id=dsjsjeq&response_type=code'
      window.open(path, '_self')
    } else {
      next()
    }
  },
  meta: { anonymouse: true },
})
axios.interceptors.request.use((config) => {
  const token = loginService.getTokens().access_token
  if (token) config.headers.Authorization = token
  if (loginService.getRunAs()) {
    config.headers['X-RUN-AS'] = loginService.getRunAs()
  }
  return config
})

axios.interceptors.response.use(
  (response) => response,
  (error) => {
    if (!error.response) {
      return Promise.reject(error)
    }
    let p = Promise.resolve(error.response.data)

    if (error.response.config.responseType === 'blob') {
      p = new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.readAsText(error.response.data)
        reader.onloadend = function() {
          // @ts-ignore
          resolve(JSON.parse(reader.result))
        }
      })
    }
    return p.then((data) => {
      error.response.data = data
      if ([1012, 1011, 2051, 2052].includes(error.response.data?.code)) {
        // token过期的情况 ，无效令牌  重新发请求获取数据
        return loginService.refreshToken(error.response.data?.code).then(() => {
          return axios(error.response.config)
        })
      }
      if ([1002, 1003, 1012].includes(error.response.data?.code)) {
        // 账号锁定，用户名密码错误，用户信息不存在，跳到登陆页
        router.replace({
          path: '/sd-login',
          query: { redirect: router.currentRoute.fullPath },
        })
      }
      if (error.response.data?.code === 2050) {
        // 第一次登陆必须修改密码
        router.replace({ path: '/sd-change-password' })
      }
      return Promise.reject(error)
    })
  }
)

routerReady((router) => {
  router.beforeEach((routeTo, routeFrom, next) => {
    const anonymouse = routeTo.matched.every((route) => route.meta.anonymouse)
    // 匿名或者已登录，直接放行
    if (anonymouse || loginService.getTokens().access_token) return next()
    // 重定向到登录页
    next({
      path: '/sd-thirdparty-login',
      query: { redirect: routeTo.fullPath },
      replace: true,
    })
  })
})

function toWorkbench() {
  let toWorkbench = sdSessionStorage.getItem('WorkbenchFirst') === '1'
  // 三员开关
  const openSecret = JSON.parse(sdLocalStorage.getItem('commonConfig') || '{}').openSecret
  if (openSecret) {
    // 开启了三员开关，系统管理员、安全管理员和安全审计员，直接打开工作台
    const userInfo = getUserInfo()
    if (userInfo && (userInfo.isSysAdmin || userInfo.isSecAdmin || userInfo.isSecAudit)) {
      toWorkbench = true
    }
  }
  return toWorkbench
}

routerService.route('/', {
  component: null,
  beforeEnter: (routeTo, routeFrom, next) => {
    let path = '/sd-home'
    if (toWorkbench()) path = '/sd-frame'
    next({ path, replace: true })
  },
  meta: { anonymouse: true },
})
