/*
 * @Description  :
 * @Autor        : cl
 * @Date         : 2025-03-21 19:37:14
 */

import { defineStore } from 'pinia'
import { login, logout } from '@/api/auth/auth'
import { menuPermissionsList } from '@/api/rbac/menu-permission'
import { shopUserInfo } from '@/api/platform/sys-user'
import { listMenuIds } from '@/api/rbac/menu'
import { getToken, removeToken, setToken } from '@/utils/auth'
import { resetRouter } from '@/router'

export const useUserStore = defineStore('user', {
  state: () => {
    return {
      token: getToken(),
      name: '',
      userName: '',
      avatar: '',
      introduction: '',
      isAdmin: 0,
      userId: '',
      tenantId: '',
      roles: [],
      menuIds: [],
      isPassShop: 0
    }
  },
  actions: {
    // 登录
    login (loginData) {
      return new Promise((resolve, reject) => {
        login(loginData).then(response => {
          this.token = response.accessToken
          setToken(response.accessToken)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // get userInfo
    getUserInfo () {
      return new Promise((resolve, reject) => {
        shopUserInfo().then(shopUser => {
          this.name = shopUser.nickName
          this.avatar = shopUser.avatar
          this.isAdmin = shopUser.isAdmin
          this.userId = shopUser.userId
          this.userName = shopUser.userName
          resolve(shopUser)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取权限列表
    listPermissions () {
      return new Promise((resolve, reject) => {
        if (this.isAdmin) {
          this.roles = ['']
          resolve([''])
          return
        }
        menuPermissionsList().then(permissions => {
          if (!permissions) {
            reject(new Error('Verification failed, please Login again.'))
          }
          // roles must be a non-empty array
          if (!permissions || permissions.length <= 0) {
            permissions = ['']
          }
          this.roles = permissions
          resolve(permissions)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 获取拥有的菜单id
    listMenuIds () {
      return new Promise((resolve, reject) => {
        listMenuIds().then(menuIds => {
          this.menuIds = menuIds
          resolve(menuIds)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    logout () {
      return new Promise((resolve, reject) => {
        logout().then(() => {
          this.resetToken()
          resetRouter()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 重置token
    resetToken () {
      this.token = ''
      removeToken()
      this.name = ''
      this.userName = ''
      this.avatar = ''
      this.isAdmin = 0
      this.userId = ''
      this.tenantId = ''
      this.roles = []
      this.menuIds = []
      this.isPassShop = 0
    }
  }
})
