import { defineStore } from 'pinia'
import { ss } from '@/utils/storage'
import { type UserState, type UserInfo, UserStoreStorageKeyEnum, type EquityInfo } from '../types/user'
import { fetchUserDetailInfo } from '@/apis/user'
import { fetchUserEquityInfo } from '@/apis/equity'
import { useI18n } from 'vue-i18n'

export function createDefaultUserInfoFactory(): UserInfo {
  return {
    memberId: null,
    avatarUrl: '',
    nickName: '',
    mobilePhone: '',
    remark: '',
    email: '',
  }
}

export const useUserStore = defineStore('user-store', {
  state: (): UserState => ({
    isLogin: ss.get(UserStoreStorageKeyEnum.isLogin),
    token: ss.get(UserStoreStorageKeyEnum.token) || '',
    userInfo: ss.get(UserStoreStorageKeyEnum.userInfo) || createDefaultUserInfoFactory(),
    equityInfo: {
      usedAgentCount: 0,
      maxAgentCount: 0,
      usedKnowledgeCount: 0,
      maxKnowledgeCount: 0,
      points: 0,
      equityLevel: 'normal',
      expireTime: '',
    },
  }),
  getters: {
    equityLevelName(): string {
      const { t } = useI18n()

      switch (this.equityInfo.equityLevel) {
        case 'normal':
          return t('equity_module.basic_version')
        case 'professional':
          return t('equity_module.professional_version')
        case 'ultimate':
          return t('equity_module.flagship_version')
        default:
          return '-'
      }
    },
  },
  actions: {
    async logout() {
      this.isLogin = false
      this.token = ''
      this.userInfo = createDefaultUserInfoFactory()

      if (window.google) {
        window.google.accounts.id.disableAutoSelect()
      }

      ss.remove(UserStoreStorageKeyEnum.isLogin)
      ss.remove(UserStoreStorageKeyEnum.token)
      ss.remove(UserStoreStorageKeyEnum.userInfo)
    },
    updateToken(token: string) {
      this.token = token
      ss.set(UserStoreStorageKeyEnum.token, token)

      if (token) {
        this.isLogin = true
        ss.set(UserStoreStorageKeyEnum.isLogin, true)
      } else {
        this.isLogin = false
        ss.set(UserStoreStorageKeyEnum.isLogin, false)
      }
    },
    updateUserInfo(userInfo: UserInfo) {
      this.userInfo = userInfo
      ss.set(UserStoreStorageKeyEnum.userInfo, userInfo)
    },
    fetchUpdateUserInfo() {
      return fetchUserDetailInfo<UserInfo>().then((res) => {
        this.userInfo = res.data
      })
    },
    fetchUpdateEquityInfo() {
      return fetchUserEquityInfo<EquityInfo>().then((res) => {
        this.equityInfo = res.data
      })
    },
  },
})
