import { type UserState } from '@/stores/interface'
import { type LoginData } from '@/api/interface/login'
import UserApi from '@/api/module/system/user'
import { type UserInfo } from '@/api/interface/system/user'
import LoginApi from '@/api/module/login'
import { pinia } from '../index'
export const useUserStore = defineStore('eco-user', {
  state: (): UserState => ({
    token: '',
    expireIn: 0,
    user: {
      userId: undefined,
      account: '',
      userName: '',
      orgId: '',
      nickname: '',
      userType: ''
    },
    permissionCodes: [],
    roleCodes: []
  }),
  getters: {},
  actions: {
    userLogin(loginData: LoginData) {
      return new Promise<Result>((resolve, reject) => {
        LoginApi.login(loginData)
          .then(({ code, data, msg }) => {
            if (code === 200) {
              const { accessToken, user, roleCodes, permissionCodes, expireIn } = data
              this.setToken(accessToken)
              this.token = accessToken
              this.user = user
              this.roleCodes = roleCodes
              this.permissionCodes = permissionCodes
              this.expireIn = expireIn
              resolve({ code, msg })
            }
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    userLogout() {
      return new Promise<Result>((resolve, reject) => {
        LoginApi.logout()
          .then(({ code, msg }) => {
            if (code === 200) {
              this.token = ''
              this.roleCodes = []
              this.permissionCodes = []
              resolve({ code, msg })
            }
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    getUserInfo() {
      return new Promise<UserInfo>((resolve, reject) => {
        UserApi.getInfo()
          .then(({ code, data }) => {
            if (code === 200) {
              const { user, roleCodes, permissionCodes } = data
              this.user = user
              this.roleCodes = roleCodes
              this.permissionCodes = permissionCodes
              resolve(data)
            } else {
              this.roleCodes = []
            }
          })
          .catch(error => {
            this.roleCodes = []
            reject(error)
          })
      })
    },
    setToken(tokenStr: string) {
      this.token = tokenStr
    }
  },
  persist: true
})
export const useUserStoreWithOut = () => {
  return useUserStore(pinia)
}
