/**
 * 登录状态管理
 */
import { formatMenus, toTreeData, formatTreeData } from 'ele-admin';
import { USER_MENUS } from '@/config/setting';
import { getResourcesTree } from '@/api/layout';
import { SYSTEM_NAME } from '@/config/setting';
import Vue from 'vue';
import { getCurrentUserAuthorityDeptAPI } from '@/api/login';
const formatRouter = (list) => {
  let menuList = []; // menuType
  let authorities = [];

  const fn = (list) => {
    let arr = [];
    for (const p of list) {
      if (p.menuType === 2) {
        // p.children = [];
        authorities.push(p);
        p.hide = true;
      }
      //  else {
      if (p.children?.length) {
        p.children = fn(p.children);
      } else {
        p.children = [];
      }
      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) {
      state.info = info;
    },
    // 设置登录用户的菜单
    setMenus(state, menus) {
      state.menus = menus;
    },
    // 设置登录用户的权限
    setAuthorities(state, authorities) {
      state.authorities = 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 }) {
      const result = await getResourcesTree().catch(() => {});
      const list = result.filter((i) => i.path === `/page-${SYSTEM_NAME}`);
      if (!list.length) {
        return {};
      }

      const { menuList, authorities } = formatRouter(list[0].children);

      // 用户权限
      // 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'
          })
      );

      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 }) {
      if (window.__POWERED_BY_QIANKUN__) {
        Vue.prototype.$portalStore?.dispatch('user/setMenuBadge', {
          path: `/page-${SYSTEM_NAME}${path}`,
          value,
          color
        });
      } else {
        const menus = formatTreeData(state.menus, (m) => {
          if (path === m.path) {
            return {
              ...m,
              meta: {
                ...m.meta,
                badge: value,
                badgeColor: color
              }
            };
          }
          return m;
        });
        commit('setMenus', menus);
      }
    }
  }
};
