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: [],
      childPath: '/test/sh0001',
      err: null
    });

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

    const setChildPath= (v: string) => {
      profile.value.childPath = v
    }

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


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

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