import { defineStore } from 'pinia'
import type { UserState } from './types'
import { resetRouter } from '@/router'
import api from '@/api'
const { apiGetUserRoleInfo, apiLogout } = api.login

const useUserStore = defineStore('user', {
  state: (): UserState => {
    return {
      tokenName: '',
      tokenValue: '',
      userPhone: '',
      userNickName: '',
      userId: NaN,
      perms: [],
      tenantId: NaN
    }
  },
  actions: {
    async RESET_STATE() {
      this.$reset()
    },
    // 登录
    onLogin(data: { tokenValue: string; tokenName: string }) {
      this.tokenValue = data.tokenValue
      this.tokenName = data.tokenName
    },
    // 获取用户信息（昵称、头像、角色集合、权限集合）
    getUserRoleInfo() {
      return new Promise((resolve) => {
        apiGetUserRoleInfo.get!({ tenantCode: 'loan_system' }).then((res: any) => {
          const {
            userInfo: { userPhone, userNickName, tenantId, id },
            menuResourceList,
            buttonResourceList
          } = res.data
          this.userPhone = userPhone
          this.userNickName = userNickName
          this.userId = id
          this.tenantId = tenantId
          this.perms.splice(
            0,
            this.perms.length,
            ...(buttonResourceList ? buttonResourceList.map((item: any) => item.resourceCode) : [])
          )
          resolve(menuResourceList)
        })
      })
    },
    // 退出登录
    onLogout() {
      return new Promise((resolve) => {
        apiLogout.get!().then(() => {
          this.RESET_STATE()
          resetRouter()
          resolve(null)
        })
      })
    },
    // 清除 Token
    onResetToken() {
      return new Promise((resolve) => {
        this.RESET_STATE()
        resolve(null)
      })
    }
  },
  persist: {
    key: 'login',
    storage: localStorage
  }
})

export default useUserStore
