import { defineStore } from "pinia";
import { fetchHomeInfo } from "../api/home.js";
import md from "../md.js";
import { useUserStore } from "./user.js";

export const useHomeStore = defineStore("homeInfo", {
  state: () => {
    return {
      homeInfo: null,
      isLogin: false,
      babyExistence: false,
      hasShownPopup: false, // 记录是否已经显示过弹窗（全局状态）
    };
  },
  actions: {
    /**
     * 更新首页信息
     * @param {Object} homeInfo
     */
    setHomeInfo(homeInfo) {
      if (homeInfo?.memberId === "not_login") {
        this.isLogin = false;
      } else {
        this.isLogin = true;
      }
      this.homeInfo = homeInfo;
    },

    setBabyExistence(babyExistence) {
      console.log("setBabyExistence", babyExistence);
      this.babyExistence = !babyExistence;
    },

    /**
     * 标记弹窗已显示
     */
    markPopupAsShown() {
      this.hasShownPopup = true;
    },

    /**
     * 重置弹窗状态（用于测试或特殊需求）
     */
    resetPopupState() {
      this.hasShownPopup = false;
    },

    /**
     * 获取首页信息
     */
    async loadHomeInfo() {
      const { data } = await fetchHomeInfo();
      console.log("loadHomeInfo", data);
      if (data) {
        this.setHomeInfo(data);

        // 通过参数传入的方式使用 $sensors
this.hasShownPopup = false
		const userStore = useUserStore();

        const mdData = {
          programLogin: this.isLogin ? "登录" : "未注册",
		  miniopenid: data?.unionId,
		  memberType: data?.gradeName,
		  memberid: data?.memberId,
		  wxNickName: userStore.userInfo?.memberName,
        };

        md.login(mdData);
      }
    },
  },
});
