/*
 * @Author: guanxiaoyan guanxiaoyan@pb-station.com
 * @Deion:
 * @Date: 2024-01-28 16:14:31
 * @LastEditors: guanxiaoyan guanxiaoyan@pb-station.com
 * @LastEditTime: 2024-01-30 20:08:05
 * @FilePath: /followUp-admin/src/store/modules/user.js
 */
import { getUserPermissions } from "@/api/common/login";
import Cookies from "js-cookie";

const user = {
  state: {
    avatar: "",
    permissions: [],
    userInfo: localStorage.getItem("userInfo") ? JSON.parse(localStorage.getItem("userInfo")) : {},
  },

  mutations: {
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions;
    },
  },

  actions: {
    // 获取用户权限
    GetPermissions({ commit, state }) {
      return new Promise((resolve, reject) => {
        getUserPermissions()
          .then((res) => {
            const rolePermissionList = res.data.find(
              (item) => item.code === "8"
            ).rolePermissionList;
            commit(
              "SET_PERMISSIONS",
              getAllPermsCodes(rolePermissionList, {
                key: "code",
                children: "rolePermissionList",
              })
            );

            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    LogOut({ commit, state }) {
      commit(
        "SET_PERMISSIONS",
        []
      )
      Cookies.set('JSESSIONID', '')
    }
  },
};

// 获取所有资源code
function getAllPermsCodes(list, props = {}) {
  const { children, key } = props;
  let codes = [];
  list.forEach((item) => {
    codes.push(item[key]);
    if (item[children] && item[children].length > 0) {
      codes = codes.concat(getAllPermsCodes(item[children], props));
    }
  });

  return codes;
}

export default user;
