import { defineStore } from 'pinia'
import type { RouteRecordRaw } from 'vue-router'
import { getUserInfo, login, logout } from '@/api/user'
import router, { filterAsyncRoutes, resetRouter } from '@/router'
import cache from '@/utils/cache'

export const useUserStore = defineStore('user', () => {
  // 状态定义
  const token = ref<string>(cache.get('token') || '')
  const userInfo = ref<Record<string, any>>({})
  const routes = ref<RouteRecordRaw[]>([])
  const permissions = ref<string[]>([])

  // 重置授权信息
  const resetAuthInfo = () => {
    token.value = ''
    userInfo.value = {}
    routes.value = []
    permissions.value = []
    cache.remove('token')
    resetRouter()
  }
  // 登录
  const loginAction = (params: any) => {
    return new Promise((resolve, reject) => {
      login({
        account: params.account.trim(),
        password: params.password,
        ...(params.captcha_key && { captcha_key: params.captcha_key, captcha: params.captcha })
      })
        .then((data) => {
          if (params.remember) {
            cache.set('remember_account', params.account.trim())
          } else {
            if (cache.get('remember_account')) cache.remove('remember_account')
          }
          token.value = data.token
          cache.set('token', data.token)
          resolve(data)
        })
        .catch((error) => {
          reject(error)
        })
    })
  }
  // 退出登录
  const logoutAction = async () => {
    return new Promise((resolve, reject) => {
      logout()
        .then(async (data) => {
          token.value = ''
          await router.push('/login')
          resetAuthInfo()
          resolve(data)
        })
        .catch((error) => {
          reject(error)
        })
    })
  }
  // 获取用户信息
  const getUserInfoAction = async () => {
    return new Promise((resolve, reject) => {
      getUserInfo()
        .then((data) => {
          userInfo.value = data.admin || {}
          routes.value = filterAsyncRoutes(data.menu || [])
          permissions.value = data.permissions || []
          resolve(data)
        })
        .catch((error) => {
          reject(error)
        })
    })
  }
  return {
    token,
    userInfo,
    routes,
    permissions,
    resetAuthInfo,
    login: loginAction,
    logout: logoutAction,
    getUserInfo: getUserInfoAction
  }
})
