import { defineStore } from 'pinia';
import http from '@/jtools/request/index';
import constants from '@/jtools/constants';
import storage from '@/jtools/storage';

const user = defineStore({
  id: 'user',
  state: () => ({
    token: storage.get('token'),
    isLogin: storage.get('isLogin'), // 是否登陆
    userInfo: storage.get('userInfo'), // 用户信息
  }),

  actions: {
		// 登录
		showAuth() {
		  // router.replaceAll('/pages/login/login');
		},

    // 获取个人信息
    async getInfo() {
      const { error, data } = await userApi.profile();
      if (error !== 0) return;
      this.userInfo = data;
      return Promise.resolve(data);
    },


    // 设置token
    setToken(token = '') {
      if (token === '') {
        this.isLogin = false;
		this.token = ''
		this.userInfo = {}
        storage.set('token', '');
		storage.set('isLogin', false);
		storage.set('userInfo', {});
      } else {
        this.isLogin = true;
				this.token = token
        storage.set('token', token);
				storage.set('isLogin', true);
      }
      return this.isLogin;
    },

    // 重置用户默认数据
    resetUserData() {
      this.setToken();
    },
    // 登出
    async logout(force = false) {
      if (!force) {
        const { error } = await userApi.logout();
        if (error === 0) {
          this.resetUserData();
        }
      }
      if (force) {
        this.resetUserData();
      }

      return !this.isLogin;
    },
  },
});

export default user;
