import router from '@/router'
import config from '@/config/defaultSetting'
import { useRouterStore } from '@/stores/router'
import { getMenuList, login, getUserInfo } from '@/api/user'

export const useUserStore = defineStore({
  id: 'user',
  state: () => ({
    user: {
      orgName: '山西方是科技股份有限公司 '
    },
    flag: false,
    token: useStorage('token', ''),
    permission: [] as string[]
  }),
  actions: {
    async getUserInfo() {
      try {
        const userRes: any = await getUserInfo()
        this.user = userRes.data.user
        this.permission = userRes.data.permissions
        this.permission && useStorage('permissionList', this.permission)
      } catch (error) {
        console.log(error)
      }

      if (config.isDynamicRouter) {
        const res: any = await getMenuList()
        useRouterStore().setDynamicRouter(res.data)
      }
      this.flag = true
    },
    async login(data: any) {
      const res: any = await login(data)
      this.token = res.token
      this.user = res.user

      router.replace({ path: (router.currentRoute.value.query.redirect as string) || '/' })
    },
    logout() {
      this.$reset()
      this.token = ''
      sessionStorage.removeItem('globalTabs')
      router.push({ path: '/login', query: { redirect: router.currentRoute.value.fullPath } })
    },
    hasPermission(permission: string | string[]) {
      if (!Array.isArray(permission)) {
        permission = permission?.split(',') || []
      }
      return this.permission.some(item => permission.includes(item))
    }
  }
})
