import { defineStore } from 'pinia'
import { UserState } from '@/types'
import { ls } from '@/utils'
import { login, logout } from '@/api/login'
import { userGetApi } from '@/api/system/user.ts'
import router, { resetRouter } from '@/router'
import md5 from 'js-md5'

const useUserStore = defineStore({
	id: 'user',
	state: (): UserState => ({
		token: ls.get('token') || '',
		userInfo: ls.get('userInfo') || {},
		// 当前用户详情
		cur_userInfo: {},
		// nickname: '',
		// avatar: '',
		roles: [],
		perms: [],
		loginQuery: {},
		isLogin: false
	}),
	actions: {
		async RESET_STATE() {
			this.$reset()
		},
		/**
		 * 用户登录请求
		 * @param params 登录用户信息
		 *  username: 用户名
		 *  password: 密码 -> md5加密
		 */
		login(params: { username: string; password: string }) {
			const _params = {
				...params,
				password: md5(params.password)
			}
			return login(_params).then((data: any) => {
				const { token, userInfo } = data || {}
				ls.set('token', token)
				this.token = token
				// 用户信息
				ls.set('userInfo', userInfo)
				this.userInfo = userInfo
				const { redirect, ...query } = (this.loginQuery || {}) as any
				// debugger
				const path = redirect || '/'
				router.push({ path, query })
				return data
			})
		},
		/**
		 *  获取用户信息（昵称、头像、角色集合、权限集合）
		 */
		getUserInfo() {
			return userGetApi(this.userInfo.userId).then(res => {
				console.error(res, '用户信息 res.......')
				this.cur_userInfo = res
				this.isLogin = true // user/get
			})
			/*return new Promise(resolve => {
				console.log('fetch 获取用户信息')
				this.isLogin = true // user/get
				resolve(true)
			})*/
			// return getUserInfo()
			//   .then(({ data }) => {
			//     if (!data) {
			//       return console.error('Verification failed, please Login again.')
			//     }
			//     const { nickname, avatar, roles, perms } = data
			//     if (!roles || roles.length <= 0) {
			//       console.error('getUserInfo: roles must be a non-null array!')
			//     }
			//     this.nickname = nickname
			//     this.avatar = avatar
			//     this.roles = roles
			//     this.perms = perms
			//   })
		},

		/**
		 *  注销
		 */
		logout() {
			return new Promise(resolve => {
				ls.remove('token')
				this.RESET_STATE()
				resetRouter()
				return resolve(true)
			})
			// return logout()
			//   .then(() => {
			//     ls.remove('token')
			//     this.RESET_STATE()
			//     resetRouter()
			//   })
		},

		/**
		 * 清除 Token
		 */
		resetToken() {
			return new Promise(resolve => {
				ls.remove('token')
				this.RESET_STATE()
				resolve(null)
			})
		}
	}
})

export default useUserStore
