import { defineStore } from 'pinia'
import { getStore, removeStore, setStore } from '@/utils/storage'
import { UserState } from './types'
import { User } from '@/entity/upms/user'
import axios from '@/utils/axios'

const defaultUser: User = {
  id: '',
  token: '',
  claims: {
    status: '',
    isSystem: false,
    tenantShortName: '-',
    platformType: 'sys',
    tenantLogo: ''
  },
  phone: '',
  fullName: '',
  tenantName: '-',
  permissions: []
}

// eslint-disable-next-line import/prefer-default-export
export const useUserStore = defineStore('user', {
  state: (): UserState => ({
    user: getStore('userInfo') || defaultUser,
    tenantId: getStore('tenantId')
  }),

  getters: {
    userInfo(state: UserState): UserState {
      return { ...state }
    },
    permissions(state: UserState): any {
      const obj = {}
      state.user.permissions.forEach((item) => {
        // @ts-ignore
        obj[item] = true
      })
      return obj
    }
  },

  actions: {
    // Get user's information
    async info() {
      // this.name,this.avatar
      // const res = await getUserInfo()
      // this.setInfo(res.data)
    },
    /**
     * 加载菜单
     */
    loadPermissions() {
      // 延迟设为加载中避免骨架屏一闪而过
      axios.post('/sys/user/get/permissions').then((res) => {
        this.login({
          ...this.user,
          permissions: res
        })
      })
    },
    // Login
    async login(info: User) {
      this.user = info
      setStore('userInfo', info)
      // const res = await userLogin(loginForm)
      // setToken(res.data.token)
    },

    logout() {
      this.user = defaultUser
      removeStore('userInfo')
      removeStore('token')
    }
  }
})
