import { createRouter, createWebHashHistory } from 'vue-router'
import routes from 'virtual:generated-pages'
import { user, webInfo } from '~/store/index'

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes,
})

function getUrlParams(url) {
  // 通过 ? 分割获取后面的参数字符串
  const urlStr = decodeURIComponent(url).split('?')[1]
  if (urlStr != undefined) {
    // 创建空对象存储参数
    const obj = {}
    // 再通过 & 将每一个参数单独分割出来
    const paramsArr = urlStr.split('&')
    for (let i = 0, len = paramsArr.length; i < len; i++) {
      // 再通过 = 将每一个参数分割为 key:value 的形式
      const arr = paramsArr[i].split('=')
      obj[arr[0]] = arr[1]
    }
    return obj
  }
  else {
    return {}
  }
}
const token = getUrlParams(window.location.href).token// 免登录
const js_code = getUrlParams(window.location.href).js_code
const appname = getUrlParams(window.location.href).appname
const appicon = getUrlParams(window.location.href).appicon

if (appname) {
  localStorage.setItem('appname', appname)
} else {
  localStorage.setItem('appname', '数字教师')
}

if (appicon) {
  localStorage.setItem('appicon', appicon)
} else {
  localStorage.setItem('appicon', 'https://ossdownload.bozedu.net/template/default/static/img/appico/AI慕课.png')
}

if (js_code) {
  request({
    baseURL: window.GLOBAL_CONFIG.openapi,
    url: '/jlt/set/detail',
    data: {
      js_code: js_code,
    },
  }).then((res) => {
    webInfo.value = res.data.one_info
    if (window.location.href.indexOf('/#/login?') != -1) {
      document.title = webInfo.value.default.js_title
      var currentIcon = `${window.GLOBAL_CONFIG.oss}/${webInfo.value.default.js_logo}`
      var link = document.querySelector('link[rel*="icon"]')
      if (webInfo.value.default.js_logo)
        link.href = currentIcon

      else
        link.href = `${window.GLOBAL_CONFIG.oss}/null`
    } else {
      document.title = webInfo.value.js_title
      var currentIcon = `${window.GLOBAL_CONFIG.oss}/${webInfo.value.js_logo}`
      var link = document.querySelector('link[rel*="icon"]')
      if (webInfo.value.js_logo)
        link.href = currentIcon
      else
        link.href = `${window.GLOBAL_CONFIG.oss}/null`
    }
  })
}

if (token) {
  const { code, data } = await request({
    baseURL: window.GLOBAL_CONFIG.openapi,
    url: '/user/main/detail',
    data: {
      token,
    },
  })
  if (code == 1) {
    user.value = data
  }
}

router.beforeEach((to, from) => {
  if (user.value?.token)
    return true
  if (!user.value?.token && to.name !== 'login' && to.name !== 'weixin-auth')
    window.location.href = "https://jltweb.bozedu.net/#/login?t=" + webInfo?.value?.js_code
  // return { name: 'login' }
})

export default router
