import apiAuth from '@/api/modules/auth'
import router from '@/router'

export const useAppAccountStore = defineStore('appAccount', () => {
  const appSettingsStore = useAppSettingsStore()
  const appTabbarStore = useAppTabbarStore()
  const appRouteStore = useAppRouteStore()
  const appMenuStore = useAppMenuStore()

  // 账号信息
  const token = ref(localStorage.getItem('token') ?? '')
  const account = ref(localStorage.getItem('account') ?? '')
  const avatar = ref(localStorage.getItem('avatar') ?? '')
  const userInfo = ref<any>(null)

  // 权限信息
  const permissions = ref<string[]>([])
  const roles = ref<string[]>([])

  // 登录状态
  const isLogin = computed(() => {
    if (token.value) {
      return true
    }
    return false
  })

  // 登录
  async function login(data: {
    user_name: string
    password: string
  }) {
    const res = await apiAuth.login(data)
    const { token: tk, user, roles: r } = res.data
    localStorage.setItem('account', user.nick_name)
    localStorage.setItem('token', tk)
    localStorage.setItem('avatar', user.avatar || '')
    account.value = user.nick_name
    token.value = tk
    avatar.value = user.avatar || ''
    userInfo.value = user
    roles.value = r || []
  }

  // 手动登出
  function logout(redirect = router.currentRoute.value.fullPath) {
    localStorage.removeItem('token')
    token.value = ''
    router.push({
      name: 'login',
      query: {
        ...(redirect !== appSettingsStore.settings.app.home.fullPath && router.currentRoute.value.name !== 'login' && { redirect }),
      },
    }).then(logoutCleanStatus)
  }

  // 请求登出
  function requestLogout() {
    localStorage.removeItem('token')
    token.value = ''
    router.push({
      name: 'login',
      query: {
        ...(
          router.currentRoute.value.fullPath !== appSettingsStore.settings.app.home.fullPath
          && router.currentRoute.value.name !== 'login'
          && {
            redirect: router.currentRoute.value.fullPath,
          }
        ),
      },
    }).then(logoutCleanStatus)
  }

  // 登出后清除状态
  function logoutCleanStatus() {
    localStorage.removeItem('account')
    localStorage.removeItem('avatar')
    account.value = ''
    avatar.value = ''
    userInfo.value = null
    permissions.value = []
    roles.value = []
    appSettingsStore.updateSettings({}, true)
    appTabbarStore.clean()
    appRouteStore.removeRoutes()
    appMenuStore.setActived(0)
  }

  // 获取权限
  async function getPermissions() {
    const res = await apiAuth.userInfo()
    if (res.data) {
      userInfo.value = res.data.user
      permissions.value = res.data.permissions || []
      roles.value = res.data.roles || []
    }
  }

  // 修改密码
  async function editPassword(data: {
    password: string
    newPassword: string
  }) {
    // 通过 sysUser resetPassword 接口修改密码
    const apiSysUser = (await import('@/api/modules/sysUser')).default
    await apiSysUser.resetPassword({
      id: (userInfo.value as any)?.id,
      new_password: data.newPassword,
    })
  }

  // 锁屏
  function lock() {
    localStorage.removeItem('token')
  }

  // 解锁
  function unlock() {
    localStorage.setItem('token', token.value)
  }

  return {
    token,
    account,
    avatar,
    userInfo,
    permissions,
    roles,
    isLogin,
    login,
    logout,
    requestLogout,
    getPermissions,
    editPassword,
    lock,
    unlock,
  }
})
