import { login, fsLogin, getInfo } from '@/api'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { isHttp, isEmpty } from "@/utils/validate"
import defAva from '@/assets/images/profile.jpg'

export default defineStore(
  'user',
  {
    state: () => ({
      token: getToken(),
      id: '',
      name: '',
      avatar: '',
      roles: [],
      permissions: []
    }),
    actions: {
      /**
       * 登录
       * @param {*} param { type: 登录方式 data: 登录数据，code / 工号密码 }
       * @returns {Promise}
       */
      login({ type, data }) {
        const { username, password, code } = data
        return new Promise((resolve, reject) => {
          if (type === 'upass') {
            login({ username, password }).then(res => {
              setToken(res.data.access_token)
              this.token = res.data.access_token
              resolve()
            }).catch(error => {
              reject(error)
            })
          } else if (type === 'fs') {
            fsLogin({ code }).then(res => {
              setToken(res.access_token)
              this.token = res.access_token
              resolve()
            }).catch(error => {
              reject(error)
            })
          }
        })
      },
      // 获取用户信息
      getInfo() {
        return new Promise((resolve, reject) => {
          getInfo().then(res => {
            const user = res.user
            let avatar = user.avatar || ""
            if (!isHttp(avatar)) {
              avatar = (isEmpty(avatar)) ? defAva : import.meta.env.VITE_APP_BASE_API + avatar
            }
            if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
              this.roles = res.roles
              this.permissions = res.permissions
            } else {
              this.roles = ['ROLE_DEFAULT']
            }
            this.id = user.userId
            this.name = user.nickName
            this.avatar = avatar
            resolve(res)
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 退出系统
      logOut() {
        return new Promise((resolve, reject) => {
          // logout(this.token).then(() => {
          this.token = ''
          this.roles = []
          this.permissions = []
          removeToken()
          resolve()
          // }).catch(error => {
          //   reject(error)
          // })
        })
      }
    }
  })

