import { defineStore, acceptHMRUpdate } from "pinia"
import { store } from '@/stores'
import { ACCESS_TOKEN, ACCESS_EXPIRES, USER_INFO } from '@/stores/modules/mutation-types'
// import { loginApi } from '@/apis/auths/index'
import { notification } from 'ant-design-vue';
import { useRouterStoreWithOut } from './async-router'

interface LoginForm {
  email: string;
  password: string;
}

interface UserState {
  token: string | null
  role: string | null
  permissions: {
    [key: string]: ExtraObj
  },
  userInfo?: ExtraObj,
}

export const useUserStore = defineStore('user', {
  state: (): UserState => ({
    token: '',
    role: null,
    permissions: {},
    userInfo: {},
  }),
  getters: {
    ROLE(state) {
      return state.role
    },
    TOKEN(): string {
      return this.getToken()
    },
    USERINFO(state) {
      return state.userInfo
    },

  },
  actions: {
    // 获取token
    getToken() {
      const raw = localStorage.getItem(ACCESS_TOKEN) || ''
      return raw
    },
    // 设置token
    setToken(token: string) {
      console.log('ACCESS_TOKEN', ACCESS_TOKEN)
      localStorage.setItem(ACCESS_TOKEN, token || '')
    },
    // 设置用户数据
    setUserInfo(data: ExtraObj | null) {
      this.$patch((state) => {
        if (data) {
          state.userInfo = data
          state.permissions = data.permissions
          state.role = data.role
        } else {
          state.userInfo = {}
          state.permissions = {}
          state.role = null
          state.userInfo = {}
        }

      })
    },
    // 登录
    async login(data: LoginForm) {
      // let res: ExtraObj
      // res = await loginApi(data)
      // .catch((err) => {
      //   notification.error({
      //     message: '登录失败',
      //     description: err.message,
      //   })
      //   return err
      // })
      // if (res.code == 200) {
      //   this.setToken(res.data.token)
      //   this.setUserInfo(res.data)
      //   this.getUserInfo()
      // }
      // return res
    },
    // 获取用户信息
    async getUserInfo() {

    },
    // 退出
    logout() {

    },
  },
})

if (import.meta.hot) {
  import.meta.hot.accept(acceptHMRUpdate(useUserStore, import.meta.hot))
}

export const useUserStoreWithOut = () => {
  return useUserStore(store)
}
