import { defineStore } from 'pinia'
import { userLogin, loginOut } from '@/api/login'
import { getUser } from '@/api/login/index.js'
import { setToken, removeToken } from '@/utils/token.js'
import { removeQuestion } from '@/utils/question.js'

import { useTagsMenuStore } from './tagsMenu.js'
import { usePermissionStore } from './permission.js'

export const useUserStore = defineStore('user', {
  persist: {
    enabled: true
  },
  state() {
    return {
      userInfo: {}
    }
  },
  getters: {
    userInfoMsg() {
      return this.userInfo
    }
  },
  actions: {
    /* 登录 */
    async getLoginToken(form) {
      try {
        const res = await userLogin(form)
        if (res.code === 0) {
          /* 设置token */
          setToken(res.data.access_token)
          this.getUserInfo()
          return Promise.resolve(res)
        } else {
          return Promise.reject(res)
        }
      } catch (error) {
        return Promise.reject(error)
      }
    },
    /* 获取用户信息 */
    async getUserInfo() {
      const res = await getUser()
      if (res.code === 0) {
        this.setUserInfo(res.data)
      }
    },
    async userLogout() {
      try {
        const res = await loginOut()
        if (res.code === 0) {
          this.reset()
          return Promise.resolve(res)
        } else {
          return Promise.reject(res)
        }
      } catch (error) {
        return Promise.reject(error)
      }
    },

    reset() {
      removeToken()
      removeQuestion()
      this.$reset()
      const tagsMenuStore = useTagsMenuStore()
      const permissionStore = usePermissionStore()
      tagsMenuStore.$reset()
      permissionStore.$reset()
    },

    setUserInfo(userInfo = {}) {
      this.userInfo = { ...this.userInfo, ...userInfo }
    }
  }
})
