import { defineStore } from 'pinia'
import { ElMessage } from 'element-plus'

import { LoginReq, SysUser } from '@/types/api/auth'
import { loginApi } from '@/api/auth'
import { setToken } from '@/api/axios'
import useMenuTreeStore from '@/store/menuTree'
import { buildDynamicRoutes } from '@/router/dynamicRoutes'
import { registerDynamicRoutes } from '@/router'
import router from '@/router'

export interface AppStoreState {
  user?: SysUser
  token?: string
}
const useUserStore = defineStore('user', {
  state: () => {
    let user: SysUser | undefined
    const userJson = localStorage.getItem('user')
    if (userJson) {
      try {
        user = JSON.parse(userJson)
      } catch {
        // ignore
      }
    }
    return { user } as AppStoreState
  },
  actions: {
    setUser(user?: SysUser) {
      this.user = user
      localStorage.setItem('user', JSON.stringify(user))
    },
    async login(data: LoginReq) {
      try {
        const resp = await loginApi(data)
        const { sysMenus } = resp.data
        if (!sysMenus || sysMenus.length === 0) {
          ElMessage.error('未分配菜单权限，请联系管理员')
          this.logout()
          return
        }
        // 菜单树
        useMenuTreeStore().setMenuTreeNoBtn(sysMenus)
        // 根据 sysMenus 动态注册路由到 / (Home) 下
        registerDynamicRoutes(buildDynamicRoutes(sysMenus))

        this.setUser(resp.data.sysUser)
        setToken(resp.data.token)
        localStorage.setItem(
          'baseExternalAccountTypes',
          JSON.stringify(resp.data.sysUser.baseExternalAccountTypes),
        )

        router.push({ path: '/dashboard' })
      } catch (error) {
        // showError(error)
      }
    },
    async logout() {
      this.setUser(undefined)
      setToken('')
      // 清空动态菜单和路由
      useMenuTreeStore().clearMenuTree()
      // 清掉登录时写入的其他鉴权相关缓存
      localStorage.removeItem('baseExternalAccountTypes')
      // localStorage.removeItem('factory_code')
    },
  },
})

export default useUserStore
