import { createApp, computed } from 'vue'
import './style.css'
import './global.scss'
import App from './App.vue'
import { getAssetsFile } from '@/utils/imgResolve'
import router from './router'
import store, { useStore } from './store/index'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import 'vant/lib/index.css'
import '@vant/touch-emulator'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'

const setHtmlFontSize = () => {
  //   store.commit('screenChange');
  const htmlDom = document.getElementsByTagName('html')[0]
  let htmlWidth = document.documentElement.clientWidth || document.body.clientWidth
  console.log(htmlWidth)
  if (htmlWidth >= 750) {
    htmlWidth = 750
  }
  if (htmlWidth <= 450) {
    htmlWidth = 450 // 12px
  }
  htmlDom.style.fontSize = `${htmlWidth / 37.5}px`
}

window.onresize = setHtmlFontSize
setHtmlFontSize()
const whteList = ['/home', '/login', '/my_game', '/cate', '/']
const platform = computed(() => {
  const u = navigator.userAgent
  return {
    mobile: !!u.match(/AppleWebKit.*Mobile.*/), // 是否为移动终端
    ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), // ios终端
    android: u.indexOf('Android') > -1 || u.indexOf('Adr') > -1, // android终端
    iPhone: u.indexOf('iPhone') > -1, // 是否为iPhone或者QQHD浏览器
    iPad: u.indexOf('iPad') > -1, // 是否iPad
    webApp: u.indexOf('Safari') === -1, // 是否web应该程序，没有头部与底部
    weixin: u.indexOf('MicroMessenger') > -1 // 是否微信
  }
})

const app = createApp(App)

app.provide('img', getAssetsFile)
app.use(store)
app.use(router)
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}
app.use(ElementPlus, {
  locale: zhCn,
  size: 'large', zIndex: 3000
})

app.mount('#app')
const { user } = useStore()
router.beforeEach((to, _from, next) => {
  // ...
  // 返回 false 以取消导航
  // return false
  console.log(platform.value.mobile)
  console.log('store', user.loginFormVisible)

  document.title = to.meta.title as string
  const token = sessionStorage.getItem('token')
  if (whteList.includes(to.path)) {
    next()
  } else {
    if (!token) {
      if (platform.value.mobile) {
        next('/login')
      } else {
        user.loginFormVisible = true
        next(false)
      }
    } else {
      next()
    }
  }
})
