import { UserInfo } from '@/model/user'
import { http } from '@/utils/http'
import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
  persist: true,
  state: () => {
    const user = {} as UserInfo
    return {
      user,
    }
  },
  actions: {
    logout() {
      uni.switchTab({ url: '/pages/user/login' })
    },
    async login(mobileNo: string, code: string) {
      const { data } = await http<UserInfo>({
        url: '/api/v1/login', // 用户登录地址
        method: 'POST',
        data: { mobileNo, code },
        header: {
          Authorization: this.token,
        },
      })
      this.user = data
    },
  },
  getters: {
    token: ({ user }) => user.token,
    isLogin: ({ user }) => user && !!user.token,
    userInfo: ({ user }) => user,
  },
})
