import { defineStore } from "pinia"
import { removeToken, setToken, setCODE401 } from "@/libs/auth"
import router from "@/router"
import { httpAjax } from "@/plugins/httpAjax"
import { store } from "./index"
import { getUserInfoApi } from "@/api/user"
interface userType {
  userInfo: {
    nickname?: string
    phone?: string
  }
  roles: ""
}

const useStore = defineStore("user", {
  state: (): userType => {
    return {
      userInfo: {}, //用户信息
      roles: "" //用户角色
    }
  },
  actions: {
    /** 登录 */
    async login() {
      function getAuthorizationFromUrl() {
        const fullUrl = window.location.href
        const queryIndex = fullUrl.indexOf("?")
        if (queryIndex === -1) return undefined
        const queryString = fullUrl.slice(queryIndex + 1)
        const params = new URLSearchParams(queryString)
        return params.get("Authorization") || undefined
      }
      const token = getAuthorizationFromUrl()
      token && setToken(token)
    },
    /** 获取用户信息 */
    async getUserInfo() {
      const userInfoRes = await httpAjax(getUserInfoApi)
      if (userInfoRes.code !== 200) {
        return Promise.reject(userInfoRes)
      }
      const userInfo = userInfoRes.data || {}
      if (!userInfo.id) {
        return Promise.reject({
          code: "500",
          data: null,
          message: "获取用户信息出错，请联系管理员!"
        })
      }
      this.userInfo = userInfo
      this.roles = userInfo.id
      return Promise.resolve()
    },
    /** 退出登录 */
    async loginOut() {
      this.resetUser()
      return Promise.resolve()
    },
    /** 清空所有登录信息，退出 */
    resetUser() {
      this.userInfo = {}
      this.roles = ""
      removeToken()
      router.push({
        path: "/login"
      })
    }
  }
})
export default () => {
  return useStore(store)
}
