//获取用户信息与权限
import { defineStore } from 'pinia'
import { getUserAuthority } from '@/apis/authority'
import { getFrameConfig } from '@/apis/frame'
import {
  type Result,
  type FrameUserInfo,
  type FrameConfigInfo,
  type FrameThemeInfo,
  type DelegateInfo,
  type UserAuthorityInfo,
  SuccessResultCode,
  setTheme
} from '@cacp/ui'
import config from '@/config'

interface CoreState {
  isInited: boolean
  isAuthInited: boolean
  currentUser: FrameUserInfo | undefined
  userAuthority: UserAuthorityInfo | undefined
  theme: FrameThemeInfo | undefined
  delegates: Array<DelegateInfo> | undefined
  extraAttrs: Record<string, string> | undefined
}

export const useCoreStore = defineStore('core', {
  state: (): CoreState => ({
    isInited: false,
    isAuthInited: false,
    currentUser: undefined,
    userAuthority: undefined,
    theme: undefined,
    delegates: [],
    extraAttrs: undefined
  }),
  actions: {
    async init() {
      if (config.NEED_USER_AUTHORITY && !this.isAuthInited) {
        const res: Result<UserAuthorityInfo> = await getUserAuthority()
        if (res.code === SuccessResultCode) {
          this.$patch({
            isAuthInited: true,
            userAuthority: res.data
          })
        }
      }
      if (!this.isInited) {
        const res: Result<FrameConfigInfo> = await getFrameConfig()
        if (res.code === SuccessResultCode) {
          this.$patch({
            isInited: true,
            currentUser: res.data.user,
            theme: res.data.theme,
            delegates: res.data.delegates,
            extraAttrs: res.data.extraAttrs
          })
          setTheme(res.data.theme)
        }
      }
    },
    clear() {
      this.$patch({
        isInited: false,
        isAuthInited: false,
        currentUser: undefined,
        userAuthority: undefined,
        theme: undefined,
        delegates: [],
        extraAttrs: undefined
      })
    }
  },
  persist: false
})
