import type { RouteRecordRaw } from "vue-router"
import type { IUserInfo } from "@/api/login/types/login"
import { defineStore } from "pinia"
import { ref } from "vue"
import { getUserInfoApi } from "@/api/login"
import router, { resetRouter } from "@/router"
import store from "@/store"
import { redirectToLogin } from "@/utils/auth-redirect"
import { getToken, removeToken, setToken } from "@/utils/cache/cookies"
import { usePermissionStore } from "./permission"
import { useTagsViewStore } from "./tags-view"

export const useUserStore = defineStore("user", () => {
  const token = ref<string>(getToken() || "")
  const roles = ref<string[]>([])
  const username = ref<string>("")
  const userInfo = ref<IUserInfo | null>(null)

  const permissionStore = usePermissionStore()
  const tagsViewStore = useTagsViewStore()

  /** 设置角色数组 */
  const setRoles = (value: string[]) => {
    roles.value = value
  }
  /** 获取用户详情 */
  const getInfo = () => {
    return new Promise((resolve, reject) => {
      getUserInfoApi()
        .then((res) => {
          const data = { ...res.data, roles: ["admin"] }
          if (!data) {
            reject(new Error("Verification failed, please Login again."))
            return
          }
          setRoles(data.roles)
          userInfo.value = data
          resolve({ ...data })
        })
        .catch((error) => {
          reject(error)
        })
    })
  }
  /** 切换角色 */
  const changeRoles = async (role: string) => {
    const newToken = `token-${role}`
    token.value = newToken
    setToken(newToken)
    await getInfo()
    permissionStore.setRoutes(roles.value)
    resetRouter()
    permissionStore.dynamicRoutes.forEach((item: RouteRecordRaw) => {
      router.addRoute(item)
    })
    _resetTagsView()
  }
  /** 登出 */
  const logout = () => {
    removeToken()
    userInfo.value = null
    token.value = ""
    roles.value = []
    resetRouter()
    _resetTagsView()
    // 主动退出走 SSO 的 logout 路由
    redirectToLogin({
      authPath: "/logout",
      redirect_uri: `${window.location.origin}${import.meta.env.VITE_PUBLIC_PATH}`,
      scene: "logout"
    })
  }
  /** 重置 Token */
  const resetToken = () => {
    removeToken()
    token.value = ""
    roles.value = []
  }
  /** 重置 visited views 和 cached views */
  const _resetTagsView = () => {
    tagsViewStore.delAllVisitedViews()
    tagsViewStore.delAllCachedViews()
  }

  return { token, userInfo, roles, username, setRoles, getInfo, changeRoles, logout, resetToken }
})

/** 在 setup 外使用 */
export function useUserStoreHook() {
  return useUserStore(store)
}
