import { defineStore } from "pinia";
import { ref } from "vue";
import _ from "underscore";
import type { LoginResult } from "@/types/user";
// 定义 Store
export const useMemberStore = defineStore(
  "member",
  () => {
    // 会员信息
    const profile = ref<LoginResult>({
      token: "",
      userInfo: {
        userName: "",
        factoryName: "",
      },
      menusList: [],
      menusNameList: [],
      err: null,
    });
	
	const mechanism = ref<any>({
	  mechanismCode: "",
	  mechanismName: "",
	});

    // 保存会员信息，登录时使用
    const setProfile = (val: any) => {
      profile.value = { ...profile.value, ...val };
      profile.value.menusNameList = _.pluck(val.menusList, "name");
    };

    const setErr = (v: any) => {
      profile.value.err = v;
    };

    // 清理会员信息，退出时使用
    const clearProfile = () => {
      profile.value = {
        token: "",
        userInfo: {
          userName: "",
          factoryName: "",
        },
        menusList: [],
        menusNameList: [],
      };
	  
	  mechanism.value.mechanismCode = ""
	  mechanism.value.mechanismName = ""
    };

    
    const setMechanism = (v: { mechanismCode: ""; mechanismName: "" }) => {
      mechanism.value = v;
    };

    // 记得 return
    return {
      profile,
      setProfile,
      setErr,
      clearProfile,
      mechanism,
      setMechanism,
    };
  },
  {
    // 配置持久化
    persist: {
      // 调整为兼容多端的API
      storage: {
        setItem(key, value) {
          uni.setStorageSync(key, value);
        },
        getItem(key) {
          return uni.getStorageSync(key);
        },
      },
    },
  }
);
