/**
 * 登录状态管理
 */
import { formatMenus, toTreeData, formatTreeData } from 'ele-admin';
import { USER_MENUS } from '@/config/setting';
import { getResourcesTree } from '@/api/layout';
import { getCurrentUserAuthorityDeptAPI } from '@/api/system/organization';
import { getCurrentUser } from '@/utils/token-util';

const formatRouter = (list) => {
  let menuList = []; // menuType
  let authorities = [];

  const fn = (list, pPath = '') => {
    let arr = [];
    for (const p of list) {
      // if (p.name == '外链测试') {
      //   console.log(p, 777778);
      // }
      let curPath = pPath;
      p.path = curPath ? `${curPath}${p.path}` : p.path;
      if (p.parentId === '0') {
        curPath = p.path;
      }
      p.link = p.component;
      p.component = '';
      if (p.menuType === 2) {
        // p.children = [];
        authorities.push(p);
        p.hide = true;
      }
      //报表菜单
      if (p.source === 2 && p.extend) {
        p.path = p.path + '/' + p.extend;
      }
      // else {
      if (p.children?.length) {
        p.children = fn(p.children, curPath);
      } else {
        p.children = [];
      }
      p.meta = {
        secretLevel: p.secretLevel,
        source: p.source,
        path: p.link
      };
      p.link = null;
      arr.push(p);
    }

    return arr;
  };

  menuList = fn(list);

  return { menuList, authorities };
};

export default {
  namespaced: true,
  state: {
    // 当前登录用户信息
    info: null,
    // 当前登录用户的菜单
    menus: null,
    // 当前登录用户的权限
    authorities: [],
    // 当前登录用户的权限路由
    authoritiesRouter: [],
    // 当前登录用户的角色
    roles: [],
    // 当前登录用户的数据权限部门数据
    authorityDept: {}
  },
  mutations: {
    // 设置登录用户的信息
    setUserInfo(state, info) {
      localStorage.setItem('info', JSON.stringify(info));
      state.info = info;
    },
    // 设置登录用户的菜单
    setMenus(state, menus) {
      state.menus = menus;
    },
    // 设置登录用户的权限
    setAuthorities(state, authorities) {
      // console.log(authorities,'authorities')
      state.authorities = authorities;
      // sessionStorage['authorities']=JSON.stringify(authorities.map(item=>item.permissionCode))
    },
    // 设置登录用户的权限路由
    setAuthoritiesRouter(state, authoritiesRouter) {
      state.authoritiesRouter = authoritiesRouter;
    },
    // 设置登录用户的角色
    setRoles(state, roles) {
      state.roles = roles;
    },
    // 当前登录用户的数据权限部门数据
    setAuthorityDept(state, info) {
      state.authorityDept = info;
    }
  },
  actions: {
    async getCurrentUserAuthorityDept({ commit }) {
      const info = await getCurrentUserAuthorityDeptAPI();
      commit('setAuthorityDept', info);
    },
    /**
     * 请求用户信息、权限、角色、菜单
     */
    // async fetchUserInfo({ commit }) {
    //   const result = await getResourcesTree().catch(() => {});
    //   if (!result) {
    //     return {};
    //   }
    //   // 用户信息
    //   commit('setUserInfo', result);
    //   // 用户权限
    //   const authorities =
    //     result.authorities
    //       ?.filter((d) => !!d.authority)
    //       ?.map((d) => d.authority) ?? [];
    //   commit('setAuthorities', authorities);
    //   // 用户角色
    //   const roles = result.roles?.map((d) => d.roleCode) ?? [];
    //   commit('setRoles', roles);
    //   // 用户菜单, 过滤掉按钮类型并转为 children 形式
    //   const { menus, homePath } = formatMenus(
    //     USER_MENUS ??
    //       toTreeData({
    //         data: result.authorities?.filter((d) => d.menuType !== 1),
    //         idField: 'menuId',
    //         parentIdField: 'parentId'
    //       })
    //   );
    //   commit('setMenus', menus);
    //   console.log('menus',menus, 'homePath',homePath)
    //   return { menus, homePath };
    // },
    //动态路由
    async fetchUserInfo({ commit, state }) {
      let currentUser = getCurrentUser()

      const result = await getResourcesTree({
        groupId: currentUser.currentGroupId,
        roleId: currentUser.currentRoleId
      }).catch(() => {});
      if (!result) {
        return {};
      }

      const { menuList, authorities } = formatRouter(result);

      // 用户权限
      // const authorities =
      //   result.authorities
      //     ?.filter((d) => !!d.authority)
      //     ?.map((d) => d.authority) ?? [];

      commit('setAuthorities', authorities);
      // 用户角色
      // const roles = result.roles?.map((d) => d.roleCode) ?? [];
      // commit('setRoles', roles);
      // 用户菜单, 过滤掉按钮类型并转为 children 形式
      const { menus, homePath } = formatMenus(
        USER_MENUS ??
          toTreeData({
            data: menuList,
            idField: 'id',
            parentIdField: 'parentId'
          })
      );
      // 用户路由按钮
      const { menus: authoritiesRouter } = formatMenus(
        USER_MENUS ??
          toTreeData({
            data: authorities.filter((i) => i.path),
            idField: 'id',
            parentIdField: 'parentId'
          })
      );
      console.log('menus--', menus);
      commit('setMenus', menus);
      commit('setAuthoritiesRouter', authoritiesRouter);
      // const menus = result;
      // const homePath = '/dashboard/workplace';
      return {
        menus,
        homePath,
        authoritiesRouter
      };
    },

    /**
     * 更新用户信息
     */
    setInfo({ commit }, value) {
      commit('setUserInfo', value);
    },
    /**
     * 更新菜单数据
     */
    setMenus({ commit }, value) {
      commit('setMenus', value);
    },
    /**
     * 更新菜单的badge
     */
    setMenuBadge({ commit, state }, { path, value, color }) {
      const menus = formatTreeData(state.menus, (m) => {
        if (path === m.path) {
          return {
            ...m,
            meta: {
              ...m.meta,
              badge: value,
              badgeColor: color
            }
          };
        }
        return m;
      });
      commit('setMenus', menus);
    }
  }
};
