import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { LanguageEnum } from '@/enums/appEnum'
import { router } from '@/router'
import { UserInfo } from '@/types/store'
import { useSettingStore } from './setting'
import { useWorktabStore } from './worktab'
import { AppRouteRecord } from '@/types/router'
import { setPageTitle } from '@/router/utils/utils'
import { resetRouterState } from '@/router/guards/beforeEach'
import { RoutesAlias } from '@/router/routesAlias'
import { AuthService } from '@/api/modules/auth'

// 用户
export const useUserStore = defineStore(
  'userStore',
  () => {
    const language = ref(LanguageEnum.ZH)
    const isLogin = ref(false)
    const isLock = ref(false)
    const lockPassword = ref('')
    const info = ref<Partial<UserInfo>>({})
    const searchHistory = ref<AppRouteRecord[]>([])
    const accessToken = ref('')
    const refreshToken = ref('')
    const permissions = ref<string[]>([])
    const menus = ref<any[]>([])
    const buttons = ref<string[]>([])

    const getUserInfo = computed(() => info.value)
    const getSettingState = computed(() => useSettingStore().$state)
    const getWorktabState = computed(() => useWorktabStore().$state)
    const getPermissions = computed(() => permissions.value)
    const getMenus = computed(() => menus.value)
    const getButtons = computed(() => buttons.value)

    const setUserInfo = (newInfo: UserInfo) => {
      info.value = newInfo
    }

    const setPermissions = (perms: string[]) => {
      permissions.value = perms
    }

    const setMenus = (menuList: any[]) => {
      menus.value = menuList
    }

    const setButtons = (buttonList: string[]) => {
      buttons.value = buttonList
    }

    // 检查是否是超级管理员
    const isSuperAdmin = computed(() => info.value.user_type === 1)

    // 检查是否有某个权限
    const hasPermission = (permission: string): boolean => {
      // 超级管理员拥有所有权限
      if (isSuperAdmin.value) return true
      return permissions.value.includes(permission)
    }

    // 检查是否有某些权限中的任意一个
    const hasAnyPermission = (perms: string[]): boolean => {
      // 超级管理员拥有所有权限
      if (isSuperAdmin.value) return true
      return perms.some((perm) => permissions.value.includes(perm))
    }

    // 检查是否有所有指定权限
    const hasAllPermissions = (perms: string[]): boolean => {
      // 超级管理员拥有所有权限
      if (isSuperAdmin.value) return true
      return perms.every((perm) => permissions.value.includes(perm))
    }

    // 检查是否有某个按钮权限
    const hasButton = (buttonCode: string): boolean => {
      // 超级管理员拥有所有权限
      if (isSuperAdmin.value) return true
      return buttons.value.includes(buttonCode)
    }

    const setLoginStatus = (status: boolean) => {
      isLogin.value = status
    }

    const setLanguage = (lang: LanguageEnum) => {
      setPageTitle(router.currentRoute.value)
      language.value = lang
    }

    const setSearchHistory = (list: AppRouteRecord[]) => {
      searchHistory.value = list
    }

    const setLockStatus = (status: boolean) => {
      isLock.value = status
    }

    const setLockPassword = (password: string) => {
      lockPassword.value = password
    }

    const setToken = (newAccessToken: string, newRefreshToken?: string) => {
      accessToken.value = newAccessToken
      if (newRefreshToken) {
        refreshToken.value = newRefreshToken
      }
    }

    // 清理本地状态（不调用退出接口）
    const clearLocalState = () => {
      info.value = {}
      isLogin.value = false
      isLock.value = false
      lockPassword.value = ''
      accessToken.value = ''
      refreshToken.value = ''
      permissions.value = []
      menus.value = []
      buttons.value = []
      useWorktabStore().opened = []
      sessionStorage.removeItem('iframeRoutes')
      resetRouterState(router)
      router.push(RoutesAlias.Login)
    }

    const logOut = async () => {
      try {
        // 调用退出登录接口
        await AuthService.logout()
      } catch (error) {
        console.error('退出登录接口调用失败:', error)
      } finally {
        // 无论接口成功与否，都清理本地状态
        clearLocalState()
      }
    }

    return {
      language,
      isLogin,
      isLock,
      lockPassword,
      info,
      searchHistory,
      accessToken,
      refreshToken,
      permissions,
      menus,
      buttons,
      getUserInfo,
      getSettingState,
      getWorktabState,
      getPermissions,
      getMenus,
      getButtons,
      isSuperAdmin,
      setUserInfo,
      setPermissions,
      setMenus,
      setButtons,
      hasPermission,
      hasAnyPermission,
      hasAllPermissions,
      hasButton,
      setLoginStatus,
      setLanguage,
      setSearchHistory,
      setLockStatus,
      setLockPassword,
      setToken,
      clearLocalState,
      logOut
    }
  },
  {
    persist: {
      key: 'user',
      storage: localStorage,
      pick: [
        'accessToken',
        'refreshToken',
        'isLogin',
        'language',
        'isLock',
        'lockPassword',
        'info',
        'permissions',
        'menus',
        'buttons'
      ]
    }
  }
)
