import { defineStore } from 'pinia'
import storage from 'store'
import expirePlugin from 'store/plugins/expire'
import { bindSocial, GetPermissions, login, unbindSocial, uniLogin } from '@/api/login'
import { ChangeUsername, GetUserInfo } from '@/api/user'

storage.addPlugin(expirePlugin)

export const useUserStore = defineStore('user', {
  state: () => ({
    session: '',
    uuid: '',
    username: '',
    avatar: '',
    email: '',
    roles: [],
    permissionCodes: [],
    permissionPoints: [],
    socialBindings: [],
    boundTypes: []
  }),

  actions: { 
    // 登录  
    async login(userInfo) {
      try {
        const res = await login(userInfo)
        if (!res || res.code !== 0) throw new Error(res?.msg ?? '登录失败！请稍后再试')
        storage.set('user', res.data, new Date().getTime() + 7 * 24 * 60 * 60 * 1000)
        this.setUser(res.data)
        await this.refreshPermissions()
        return res.data
      } catch (error) {
        throw error
      }
    },

    async uniLogin(type, code) {
      try {
        const res = await uniLogin({type, code})
        if (!res || res.code !== 0) throw new Error(res?.msg ?? '登录失败！请稍后再试')
        storage.set('user', res.data, new Date().getTime() + 7 * 24 * 60 * 60 * 1000)
        this.setUser(res.data)
        await this.refreshPermissions()
        return res.data
      } catch (error) {
        throw error
      }
    },

    async bindSocial(type, code) {
      try {
        const res = await bindSocial({ type, code })
        if (!res || res.code !== 0) throw new Error(res?.msg ?? '绑定失败！请稍后再试')
        const user = await this.getInfoFromServer()
        return res.data || user
      } catch (error) {
        throw error
      }
    },

    async unbindSocial(type) {
      try {
        const res = await unbindSocial({ type })
        if (!res || res.code !== 0) throw new Error(res?.msg ?? '解绑失败！请稍后再试')
        const user = await this.getInfoFromServer()
        return res.data || user
      } catch (error) {
        throw error
      }
    },

    // 更新用户名
    async changeName(username) {
      try {
        const res = await ChangeUsername({ username })
        if (!res || res.code !== 0) throw new Error(res?.msg ?? '更新失败！请稍后再试')
        this.username = username
        storage.set('user', this.$state, new Date().getTime() + 7 * 24 * 60 * 60 * 1000)
      } catch (error) {
        throw error
      }
    },

    // 获取用户信息
    async getInfo() {
      const user = storage.get('user')
      if (user) {
        this.setUser(user)
        return user
      }
      return this.$state
    },

    async refreshPermissions() {
      if (!this.uuid || !this.session) return
      try {
        const res = await GetPermissions()
        if (!res || res.code !== 0) return
        const payload = res.data || {}
        this.roles = payload.roles || res.roles || this.roles || []
        this.permissionCodes = payload.permissionCodes || []
        this.permissionPoints = payload.permissionPoints || []
        storage.set('user', this.$state, new Date().getTime() + 7 * 24 * 60 * 60 * 1000)
      } catch (_) { }
    },

    async getInfoFromServer() {
      try {
        const res = await GetUserInfo()
        if (!res || res.code !== 0) throw new Error(res?.msg ?? '获取用户信息失败！请稍后再试')
        storage.set('user', res.data, new Date().getTime() + 7 * 24 * 60 * 60 * 1000)
        this.setUser(res.data)
        return res.data
      } catch (error) {
        throw error
      }
    },

    // 登出
    logout() {
      this.setUser({})
      storage.remove('user')
    },

    // 设置用户信息
    setUser(user = {}) {
      this.session = user.session || ''
      this.uuid = user.uuid || ''
      this.avatar = user.avatar || ''
      this.username = user.username || ''
      this.email = user.email || ''
      this.roles = user.roles || []
      this.permissionCodes = user.permissionCodes || []
      this.permissionPoints = user.permissionPoints || []
      this.socialBindings = user.socialBindings || []
      this.boundTypes = user.boundTypes || []
    }
  }
})
