import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getStore, setStore } from '@/utils/storage'
import { loginByPwd } from '@/api/login'
import { logout, refreshToken } from '@/api/user'
import { resetRouter } from '@/router'
import { usePermissionStore } from './permission'

export const useUserStore = defineStore('user', () => {
  const accessToken = ref<string>(getStore('accessToken') || '')
  const userInfo = ref<any>(getStore('userInfo') || {})
  const curTheme = ref<string>(getStore('curTheme') || 'dark')
  const expireTime = ref<number>(getStore('expireTime') || 0)
  const urlPrefix = ref<string>(getStore('urlPrefix') || '')

  function setCurTheme(theme: string) {
    curTheme.value = theme
    setStore('curTheme', theme)
  }

  function setUserInfo(info: any) {
    userInfo.value = info
    setStore('userInfo', info)
  }

  function setAccessToken(token: string) {
    accessToken.value = token
    setStore('accessToken', token)
  }

  function setExpireTime(ttl: number) {
    const time = new Date().getTime() + ttl * 1000
    expireTime.value = time
    setStore('expireTime', time)
  }

  function setUrlPrefix(prefix: string) {
    urlPrefix.value = prefix
    setStore('urlPrefix', prefix)
  }

  function switchRoleFn(data: any) {
    setAccessToken(data.token)
    const permStore = usePermissionStore()
    permStore.setAuthBtnCodes(data.permissionCodes || [])
    setExpireTime(data.ttl)
  }

  async function loginByUsername(user: any) {
    const res = await loginByPwd(user)
    setAccessToken(res.data.token)
    setUrlPrefix(res.data.urlPrefix)
    const permStore = usePermissionStore()
    permStore.setAuthBtnCodes(res.data.permissionCodes || [])
    setExpireTime(res.data.ttl)
    return res
  }

  async function logoutAction() {
    const res = await logout()
    if (res.code === 200) {
      setAccessToken('')
      const permStore = usePermissionStore()
      permStore.SET_MULTIPLE_TAG([])
      permStore.setAuthBtnCodes([])
      resetRouter()
    }
    return res
  }

  async function refreshTokenAction() {
    const res = await refreshToken()
    setAccessToken(res.data.token)
    setUrlPrefix(res.data.urlPrefix)
    setExpireTime(res.data.ttl)
  }

  async function removeStorage() {
    setAccessToken('')
    setUrlPrefix('')
    const permStore = usePermissionStore()
    permStore.SET_MULTIPLE_TAG([])
    permStore.setAuthBtnCodes([])
  }

  return {
    accessToken,
    userInfo,
    curTheme,
    expireTime,
    urlPrefix,
    setCurTheme,
    setUserInfo,
    switchRoleFn,
    loginByUsername,
    logoutAction,
    refreshTokenAction,
    removeStorage
  }
})
