import { defineStore } from "pinia";
import ls from "@/utils/store2";
import { ref } from "vue";
import { userToken } from "../composables/config";
import crypt from "../composables/crypt";

export interface UserInfo {
  id?: string;
  name: string;
  email: string;
  phone: string;
  approveStatus?: number;
}
export interface AccountInfo {
  loginName: string;
  password: string;
  rememberPassword: boolean;
}
const STORAGE_KEY = "user";
const ACCOUNT_INFO_KEY = "accountInfo";
const useUserStore = defineStore("userStore", () => {
  const userInfo = ref<UserInfo | null>(null);
  const accountInfo = ref<AccountInfo | null>(null);
  const isLoggedIn = ref(false);
  const initUserInfo = () => {
    const encryptedInfo = ls.get(STORAGE_KEY);
    if (encryptedInfo) {
      const decryptedInfo = crypt.decrypt(encryptedInfo);
      if (decryptedInfo) {
        userInfo.value = JSON.parse(decryptedInfo);
        isLoggedIn.value = true;
      }
    }
  };
  const initAccountInfo = () => {
    const encryptedInfo = ls.get(ACCOUNT_INFO_KEY);
    if (encryptedInfo) {
      const decryptedInfo = crypt.decrypt(encryptedInfo);
      if (decryptedInfo) {
        accountInfo.value = JSON.parse(decryptedInfo);
      }
    }
  };
  const saveUserInfo = (info: UserInfo) => {
    userInfo.value = info;
    isLoggedIn.value = true;
    const encryptedInfo = crypt.encrypt(JSON.stringify(info));
    ls.set(STORAGE_KEY, encryptedInfo);
  };
  const saveAccountInfo = (info: AccountInfo) => {
    accountInfo.value = info;
    const encryptedInfo = crypt.encrypt(JSON.stringify(info));
    ls.set(ACCOUNT_INFO_KEY, encryptedInfo);
  };
  const clearUserInfo = () => {
    userInfo.value = null;
    isLoggedIn.value = false;
    userToken.value = "";
    ls.remove(STORAGE_KEY);
  };
  initUserInfo();
  initAccountInfo();
  return {
    userInfo,
    accountInfo,
    isLoggedIn,
    saveUserInfo,
    saveAccountInfo,
    clearUserInfo,
  };
});

export default useUserStore;
