yyb
9 天以前 1c8c18285e5676df8b5eaabff33bfac9d1f33b13
src/store/modules/user.ts
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,129 @@
import { logout, getInfo, loginCheckFactory } from "@/api/login";
import { getRouters as getRoutersApi } from "@/api/menu";
import { getToken, setToken, removeToken } from "@/utils/auth";
import defAva from "@/static/images/profile.jpg";
import { defineStore } from "pinia";
import config from "@/config.js";
export interface LoginForm {
  userName: string;
  password: string;
}
const useUserStore = defineStore("user", {
  state: () => ({
    token: getToken(),
    id: "",
    name: "",
    avatar: "",
    currentFactoryName: "",
    nickName: "",
    roleName: "",
    currentDeptId: "",
    currentLoginTime: "",
    roles: Array(),
    permissions: [],
    routers: [], // è·¯ç”±æƒé™æ•°æ®
  }),
  actions: {
    // éƒ¨é—¨ç™»å½•
    loginCheckFactory(userInfo: any) {
      const userName = userInfo.userName.trim();
      const password = userInfo.password;
      const factoryId = userInfo.factoryId;
      return new Promise((resolve, reject) => {
        loginCheckFactory(userName, password, factoryId)
          .then((res: any) => {
            const token = res.token || res.data?.token;
            if (token) {
              setToken(token);
              this.token = token;
              resolve(null);
            } else {
              reject("未获取到登录令牌");
            }
          })
          .catch((error: any) => {
            reject(error);
          });
      });
    },
    // èŽ·å–ç”¨æˆ·ä¿¡æ¯
    getInfo() {
      return new Promise((resolve, reject) => {
        getInfo()
          .then((res: any) => {
            // å…¼å®¹ res.data ç»“æž„
            const data = res.data || res;
            const user = data.user || {};
            let avatar = user.avatar || "";
            avatar = config.baseUrl + "/profile/" + avatar;
            if (data.roles && data.roles.length > 0) {
              // éªŒè¯è¿”回的roles是否是一个非空数组
              this.roles = data.roles;
              this.permissions = data.permissions;
            } else {
              this.roles = ["ROLE_DEFAULT"];
            }
            this.id = user.userId || "";
            this.name = user.userName || "";
            this.avatar = avatar;
            this.currentFactoryName = user.currentFactoryName || "";
            this.nickName = user.nickName || "";
            this.roleName = Array.isArray(user.roles) && user.roles.length > 0 ? user.roles[0].roleName || "" : "";
            this.currentDeptId = user.tenantId || "";
            this.currentLoginTime = this.getCurrentTime();
            resolve(data);
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    // é€€å‡ºç³»ç»Ÿ
    logOut() {
      return new Promise<null>((resolve, reject) => {
        logout()
          .then(() => {
            this.token = "";
            this.roles = [];
            this.permissions = [];
            this.routers = [];
            this.name = "";
            this.avatar = "";
            removeToken();
            resolve(null);
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    getCurrentTime() {
      const now = new Date();
      const year = now.getFullYear(); // èŽ·å–å¹´ä»½
      const month = String(now.getMonth() + 1).padStart(2, "0"); // æœˆä»½ä»Ž0开始,要+1,并补零
      const day = String(now.getDate()).padStart(2, "0"); // æ—¥æœŸè¡¥é›¶
      const hours = String(now.getHours()).padStart(2, "0"); // å°æ—¶è¡¥é›¶
      const minutes = String(now.getMinutes()).padStart(2, "0"); // åˆ†é’Ÿè¡¥é›¶
      const seconds = String(now.getSeconds()).padStart(2, "0"); // ç§’数补零
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    // èŽ·å–è·¯ç”±æƒé™
    getRouters() {
      return new Promise((resolve, reject) => {
        getRoutersApi()
          .then((res: any) => {
            // å­˜å‚¨è·¯ç”±æƒé™æ•°æ®
            this.routers = res.data || [];
            resolve(res);
          })
          .catch(error => {
            reject(error);
          });
      });
    },
  },
});
export default useUserStore;