/*
 * @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 { login, logout, getUserPermissions } from "@/api/common";
import {
  getToken,
  setToken,
  // setLoginName,
  setName,
  getLoginName,
  removeToken,
  removeClientId,
} from "@/utils/auth";

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

  mutations: {
    SET_USERINFO: (state, user) => {
      state.userInfo = user;
      localStorage.setItem("userInfo", JSON.stringify(user));
    },
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_NAME: (state, name) => {
      state.name = name;
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar;
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions;
    },
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      console.log("userInfo", userInfo);
      const username = userInfo.username.trim();
      const password = userInfo.password;
      const clientId = userInfo.clientId;
      const code = userInfo.code;
      const uuid = userInfo.uuid;
      return new Promise((resolve, reject) => {
        login(username, password, clientId, code, uuid)
          .then((res) => {
            setToken(res.data.token);
            commit("SET_TOKEN", res.data.token);
            commit("SET_NAME", res.data.username);
            commit("SET_USERINFO", res.data?.user);
            setName(res.data.username);
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 获取用户权限
    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 }) {
      return new Promise((resolve, reject) => {
        logout()
          .then(() => {
            commit("SET_TOKEN", "");
            commit("SET_PERMISSIONS", []);
            removeToken();
            removeClientId();
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise((resolve) => {
        commit("SET_TOKEN", "");
        removeToken();
        removeClientId();
        resolve();
      });
    },
  },
};

// 获取所有资源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;
