// store/index.js (Vue 3)
import { createStore } from 'vuex'
import storage from '@/utils/storage'

const store = createStore({
  state: {
    isShowToast: false, // 是否在展示Toast中
    remark: [], // 填写订单备注
    shareLink: "", // 分享链接
    verificationKey: "", // 获取key表示验证通过
    distributionId: "", // 分销员Id
    hasLogin: false,
    userInfo: {},
    uuid: "",
    token: "",
    userName: "",
  },

  mutations: {
    // 初始化状态（从存储中恢复）
    initState(state) {
      state.hasLogin = storage.getHasLogin() || false;
      state.userInfo = storage.getUserInfo() || {};
      state.uuid = storage.getUuid() || "";
      if (state.hasLogin && state.userInfo) {
        state.userName = state.userInfo.Name || state.userInfo.Nickname || state.userInfo.Username || "匿名用户";
      }
    },
    login(state, userInfo) {
      state.userInfo = userInfo || {};
      state.userName =
      userInfo.Name || userInfo.Nickname || userInfo.Username || "匿名用户";
      state.hasLogin = true;
    },
    logout(state) {
      state.userName = "";
      state.hasLogin = false;
      state.userInfo = {};
    },
    // 设置填写订单中备注
    setRemark(state, remark) {
      state.remark = remark;
    },
  },

  actions: {
    // 初始化 store（在应用启动后调用）
    init({ commit }) {
      commit('initState');
    },
  },
})

export default store
