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,
    };
  },
  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;
    },

    /**
     * 获取首页信息
     */
    async loadHomeInfo() {
      const { data } = await fetchHomeInfo();
      console.log("loadHomeInfo", data);
      if (data) {
        this.setHomeInfo(data);
        // 通过参数传入的方式使用 $sensors

		const userStore = useUserStore();

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

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