import { defineStore } from 'pinia'
import { getUserInfo,logout } from '@/api/auth.js'



export const useAppStore = defineStore('app', {
  state: () => ({
    // 当前语言
    userInfo: localStorage.getItem('userInfo') ? JSON.parse(localStorage.getItem('userInfo')) : null,
    token: localStorage.getItem('token') || null,
    avatarDefault: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
    showLoginDialog: false,
    isScroll: false,
  }),
  getters: {
    avatar() {
      return this.userInfo?.avatar || this.avatarDefault;
    },
  },
  actions: {
   UPDATE_TOKEN(token = '') {
      if (!token) {
        return;
      }
      this.token = token;
      localStorage.setItem('token', token);
      this.USERINFO();
    },
    LOGOUT() {
      this.token = undefined;
      this.userInfo = undefined;
      localStorage.removeItem('token');
      localStorage.removeItem('userInfo');
    },
    UPDATE_USERINFO(userInfo) {
      this.userInfo = userInfo;
      localStorage.setItem('userInfo', JSON.stringify(userInfo));
      // uniLogin();
    },
    async USERINFO(force) {
      try {
        if (!this.token) {
          return;
        }
        const res = await getUserInfo();
        if (res.code === 200 && res.user) {
          this.UPDATE_USERINFO(res.user);
        }else {
          this.LOGOUT();
        }
      } catch (e) {
        // 可以处理异常
      }
    },

  }
})