import { defineStore } from "pinia";
import { ref, computed, watchEffect,onUnmounted } from "vue";
import { ElMessage } from 'element-plus';

export const useUserStore = defineStore("user", () => {
  const token = ref(localStorage.getItem("token") || "");
  const mobilePhone = ref(localStorage.getItem("mobilePhone") || "");

  const handleStorageChange = (e:StorageEvent)=>{
     if (e.key === "token") {
      // 当 localStorage 的 token 变化时，更新 Pinia 的 token
      token.value = e.newValue || "";
      // console.log("localStorage token 变化，同步到 Pinia:", token.value);
    }
  }
    // 定时检查 localStorage，同步 token（每 1 秒一次，可调整）
  const syncTokenInterval = setInterval(() => {
    const latestToken = localStorage.getItem("token");
    if (latestToken !== token.value) {
      token.value = latestToken || "";
    }
  }, 1000); // 1秒检查一次

  window.addEventListener("storage", handleStorageChange);
    onUnmounted(() => {
    window.removeEventListener("storage", handleStorageChange);
    clearInterval(syncTokenInterval);
  });
  
  // 改为 computed 属性，实时计算登录状态
  const isLoggedIn = computed(() => {
    return !!token.value && !isTokenExpired();
  });

  // 设置合理的 Token 有效期（示例：2小时）
  const setToken = (data: string) => {
    token.value = data;
    const expiryTime = Date.now() + 30 * 1000; // 
    localStorage.setItem("token", data);
    localStorage.setItem("tokenExpiry", expiryTime.toString());
  };

  const setMobilePhone = (phone: string) => {
    mobilePhone.value = phone;
    localStorage.setItem("mobilePhone", phone);
  };

  const removeMobilePhone = () => {
    mobilePhone.value = "";
    localStorage.removeItem("mobilePhone");
  };

  const clearToken = () => {
    try {
      token.value = "";
      mobilePhone.value = ""; // 清空手机号
      localStorage.removeItem("userInfo");
      localStorage.removeItem("token");
      localStorage.removeItem("tokenExpiry");
      localStorage.removeItem("mobilePhone"); // 确保从本地存储删除
    } catch (error) {
       console.error("清除 Token 失败:", error);
    }
  };

  const isTokenExpired = () => {
    try {
      const expiryTime = localStorage.getItem("tokenExpiry");
      if (!expiryTime) return true;
      
      const isExpired = Date.now() > parseInt(expiryTime, 10);
      return isExpired;
    } catch (error) {
      return true;
    }
  };

  const setIdentity = (identity: string) => {
    localStorage.setItem("Identity", identity);
  };

  const removeIdentity = () => {
    localStorage.removeItem("Identity");
  };

  // 自动监听 Token 变化并检查过期状态
  watchEffect(() => {
    if (token.value && isTokenExpired()) {
      ElMessage.error('登录已过期，请重新登录'); // 提示用户
      clearToken();
      window["$router"]?.push("/");
    }
  });

  // 初始化时检查 Token 状态
  watchEffect(() => {
    if (!localStorage.getItem("token")) {
      // 本地存储没有 Token，确保状态一致
      token.value = "";
    }
  });

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