import { defineStore } from "pinia";
import { ref, onMounted } from "vue";

export const useUserStore = defineStore("user", () => {
  const token = ref("");
  const isLoggedIn = ref(false);

  const setToken = (newToken: string) => {
    token.value = newToken;
    isLoggedIn.value = true;
    const expiryTime = Date.now() + 31536000 * 1000; // 当前时间 + 1 年
    localStorage.setItem("token", newToken);
    localStorage.setItem("tokenExpiry", expiryTime.toString()); // 保存过期时间
  };
  const setMobilePhone = (phone: string) => {
    localStorage.setItem("mobilePhone", phone);
  };
  const removeMobilePhone=()=>{
    localStorage.removeItem("mobilePhone");
  }
  // const setMerchStatus=(merchStatus:string)=>{
  //   localStorage.setItem("merchStatus",merchStatus)
  // }
  const clearToken = () => {
    try {
      token.value = "";
      isLoggedIn.value = false;
      localStorage.removeItem("token");
      localStorage.removeItem("tokenExpiry"); // 删除过期时间
    } catch (error) {
      console.error("Error clearing token from localStorage:", error);
    }
  };

  const isTokenExpired = () => {
    try {
      const expiryTime = localStorage.getItem("tokenExpiry");
      if (!expiryTime) return true; // 如果没有过期时间，认为已过期
      return Date.now() > parseInt(expiryTime, 10); // 当前时间是否超过过期时间
    } catch (error) {
      console.error("Error checking token expiry:", error);
      return true; // 默认认为已过期
    }
  };
  const setIdentity=(Identity:string)=>{
    localStorage.setItem("Identity", Identity);
  }
  const removeIdentity=()=>{
    localStorage.removeItem('Identity')
  }
  onMounted(() => {
    try {
      const storedToken = localStorage.getItem("token");
      if (storedToken && !isTokenExpired()) {
        token.value = storedToken;
        isLoggedIn.value = true;
      } else {
        clearToken(); // 如果 token 过期，清除 token
      }
    } catch (error) {
      console.error("Error retrieving token from localStorage:", error);
    }
  });

  return {
    token,
    isLoggedIn,
    setToken,
    clearToken,
    setMobilePhone,
    removeMobilePhone,
    setIdentity,
    removeIdentity
  };
});