import { defineStore } from 'pinia'
import {
  computed,
  ref,
} from 'vue'
import Strings from '@/common/utils/strings.ts'
import Evt from '@/common/utils/evt.ts'

export const useAppUserStore = defineStore('AppUser', () => {
  const userId = ref<string | null>(null)
  const roles = ref<string[]>([])
  const nickname = ref<string | null>(null)
  const avatar = ref<string | null>(null)
  const token = ref<string | null>(null)
  const tenantId = ref<string | null>(null)
  const tenantName = ref<string | null>(null)
  const currentCustomerId = ref<string | null>(null)
  const identities = ref<LoginTypes.IdentityInfo[]>([])
  const currentIdentity = ref<LoginTypes.IdentityInfo | null>(null)
  const isAuthenticated = computed(() => !Strings.isEmpty(token.value))
  const hasCaiGou = ref<boolean>(false)
  const isCaiGou = ref<boolean>(false)
  const hasChanFei = ref<boolean>(false)
  const isChanFei = ref<boolean>(false)
  const hasSiJi = ref<boolean>(false)
  const isSiJi = ref<boolean>(false)
  const hasXiaoNa = ref<boolean>(false)
  const isXiaoNa = ref<boolean>(false)
  const hasYunShu = ref<boolean>(false)
  const isYunShu = ref<boolean>(false)
  const isAdmin = ref<boolean>(false)

  function $reset() {
    userId.value = null
    avatar.value = null
    nickname.value = null
    token.value = null
    tenantId.value = null
    tenantName.value = null
    roles.value = []
    currentCustomerId.value = null
    currentIdentity.value = null
    identities.value = []
    tenantId.value = null
    tenantName.value = null
    hasCaiGou.value = false
    isCaiGou.value = false
    hasChanFei.value = false
    isChanFei.value = false
    hasSiJi.value = false
    isSiJi.value = false
    hasXiaoNa.value = false
    isXiaoNa.value = false
    hasYunShu.value = false
    isYunShu.value = false
    isAdmin.value = false
  }

  Evt.on('logout', $reset)

  return {
    userId,
    avatar,
    nickname,
    token,
    tenantId,
    tenantName,
    isAuthenticated,
    roles,
    hasCaiGou,
    isCaiGou,
    hasChanFei,
    isChanFei,
    hasSiJi,
    isSiJi,
    hasXiaoNa,
    isXiaoNa,
    hasYunShu,
    isYunShu,
    isAdmin,
    identities,
    currentIdentity,
    currentCustomerId,
    $reset,
  }
}, {
  persist: {
    pick: [ 'userId', 'avatar', 'nickname', 'token', 'tenantId', 'tenantName' ],
  },
})

