import { defineStore } from 'pinia'
import router, { getP } from '@/router'

export const useUserStore = defineStore('user', {
	state: (): auth.AuthUser => ({
		mobile: '',
		email: '',
		fullName: '',
		password: '',
		permissions: [],
		roles: [],
		sex: 'FEMALE',
		token: '',
		refreshToken: '',
		userName: '',
	}),
	getters: {
		isAdmin(state) {
			return state.roles.includes('admin')
		},
		isLogin(state) {
			return state.token && state.refreshToken
		},
		getPermission(state) {
			return state.permissions
		},
	},
	actions: {
		refreshUserInfo(user: auth.AuthUser) {
			Object.assign(this, user)
		},
		userLogin(user: auth.AuthUser) {
			Object.assign(this, user)
			// 根据权限动态添加地址
			if (!this.isAdmin) {
				const path = getP(this.permissions)
				router.addRoute(path)
				// router.replace(router.currentRoute.value.fullPath)
			}
			router.push({ path: '/admin/dashboard' })
		},
		logout() {
			this.mobile = ''
			this.email = ''
			this.userName = ''
			this.fullName = ''
			this.password = ''
			this.permissions = []
			this.roles = []
			this.sex = 'FEMALE'
			this.token = ''
			this.refreshToken = ''
			router.push({ path: '/login/user' })
		},
		hasPermission(permission?: string) {
			if (this.isAdmin) return true
			return permission !== undefined && this.permissions.includes(permission)
		},
	},
	persist: {
		key: 'user',
		storage: localStorage,
	},
})
