import { defineStore } from 'pinia';
import { GenKey } from '@/config';
import { isEmpty, encode, decode } from '@/utils';

export const useUserStore = defineStore({
  id: GenKey('userStore'),
  state: () => ({
    token: null,
    userInfo: {},
    currentOrg: null,
    orgList: [],
    menus: [],
  }),
  getters: {},
  actions: {
    setToken(token) {
      this.token = token;
    },
    hasToken() {
      return !isEmpty(this.token);
    },
    setUserInfo(userInfo) {
      this.userInfo = encode(JSON.stringify(userInfo), true);
    },
    getUserInfo() {
      return !isEmpty(this.userInfo) ? JSON.parse(decode(this.userInfo, true)) : {};
    },
    setOrgList(orgList) {
      this.orgList = encode(JSON.stringify(orgList), true);
    },
    getOrgList() {
      return !isEmpty(this.orgList) ? JSON.parse(decode(this.orgList, true)) : [];
    },
    setCurrentOrg(org) {
      this.currentOrg = org;
    },
    getCurrentOrg() {
      const list = this.getOrgList().filter((item) => {
        return item.id === this.currentOrg;
      });
      return !isEmpty(list) ? list[0] : {};
    },
    setMenus(menus) {
      this.menus = encode(JSON.stringify(menus), true);
    },
    getMenus() {
      return !isEmpty(this.menus) ? JSON.parse(decode(this.menus, true)) : [];
    },
    logout() {
      this.token = null;
      this.userInfo = {};
      this.currentOrg = null;
      this.orgList = [];
      this.menus = [];
      localStorage.removeItem(GenKey('userStore'));
    },
    clear() {
      localStorage.removeItem(GenKey('userStore'));
    },
  },
  persist: {
    key: GenKey('userStore'),
    storage: window.localStorage,
  },
});
