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

interface CoreState {
  isInited: boolean
  isAuthInited: boolean
  currentUser: FrameUserInfo | undefined
  userAuthority: UserAuthorityInfo | undefined
}

export const useCoreStore = defineStore('core', {
  state: (): CoreState => ({
    isInited: false,
    isAuthInited: false,
    currentUser: undefined,
    userAuthority: 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<FrameUserInfo> = await getFrameUser()
        console.log('res', res)
        if (res.code === SuccessResultCode) {
          this.$patch({
            isInited: true,
            currentUser: res.data
          })
          setTheme(res.data.theme)
        }
      }
    },
    clear() {
      this.$patch({
        isInited: false,
        isAuthInited: false,
        currentUser: undefined,
        userAuthority: undefined
      })
    }
  }
})
