import { defineStore } from 'pinia';
import { ref, computed } from 'vue';

interface Token {
  access_token: any;
  userid: string | null;
  name: string;
  loginType?: string; // 添加此行
}

export const useTokenStore = defineStore('mytoken', () => {
  const tokenJson = ref<string>(window.localStorage.getItem("TokenInfo") || "{}");

  const token = computed<Token>(() => {
    try {
      return JSON.parse(tokenJson.value) as Token;
    } catch (e) {
      console.error("Failed to parse token JSON", e);
      return { access_token: null, userid: null, name: '' };
    }
  });

  function setToken(newToken: string) {
    tokenJson.value = newToken;
    window.localStorage.setItem("TokenInfo", newToken);
  }

  function saveToken(userInfo: { userId: number | null, name: string, loginType?: string }) {
    const userIdString = userInfo.userId !== null && userInfo.userId !== undefined ? userInfo.userId.toString() : null;
    const tokenInfo = JSON.stringify({ userid: userIdString, name: userInfo.name, loginType: userInfo.loginType });
    setToken(tokenInfo);
  }

  function clearToken() {
    setToken("{}"); // 设置为空对象以清除 token
  }

  return { token, setToken, saveToken, clearToken };
});