import { create } from "zustand";
import { auth } from "@/services";
import { getStorageSyncTime, setStorageSyncSecond } from "@/utils";
import Taro from "@tarojs/taro";

type State = {
  user?: AuthAPI.UserVO | null;
};

type Action = {
  setUser: () => Promise<void>;
};

export const userStore = create<State & Action>((set) => ({
  user: null,
  setUser: async () => {
    let user = getStorageSyncTime<AuthAPI.UserVO>("user");
    console.log("user", user);

    if (!user) {
      const {
        data: { data: userAuth },
      } = await auth.user.userInfo();

      if (!userAuth) {
        return;
      }
      user = userAuth?.userVO;
      setStorageSyncSecond("user", user);
      let platformId = "1991353387274342401";
      Taro.setStorageSync(
        "userRoleVO",
        userAuth.userRoleVOList?.find((item) => item.platformId === platformId),
      );
    }

    set((state) => ({
      ...state,
      user: user,
    }));
  },
}));
