// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2023 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------

import { asyncRoutes, constantRoutes } from '@/router';
import * as roleApi from '@/api/roleApi.js';
import * as Auth from '@/libs/wechat';
import { formatRoutes } from '@/utils/parsing';

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes (routes, roles) {
  const res = [];

  routes.forEach((route) => {
    const tmp = { ...route };
    if (tmp.child) {
      tmp.child = filterAsyncRoutes(tmp.child, roles);
    }
    res.push(tmp);
  });

  return res;
}

const state = {
  routes: [],
  addRoutes: [],
  topbarRouters: [],
  sidebarRouters: JSON.parse(localStorage.getItem('sidebarRouters')) || [],
};

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes;
    state.routes = routes;
  },
  SET_TOPBAR_ROUTES: (state, routes) => {
    state.topbarRouters = routes;
  },
  SET_SIDEBAR_ROUTERS: (state, routes) => {
    state.sidebarRouters = routes;
    localStorage.setItem('sidebarRouters', JSON.stringify(routes));
    if (!routes.length) localStorage.removeItem('sidebarRouters');
  },
};

const actions = {
  generateRoutes ({ commit }) {
    return new Promise(async (resolve) => {
      let accessedRoutes = [];
      let menus = [];
      let menusAll = [
        {
          "id": 89,
          "pid": 0,
          "name": "分销",
          "icon": "s-check",
          "perms": "",
          "component": "/distribution",
          "menuType": "M",
          "sort": 9993,
          "childList": [
            {
              "id": 3763,
              "pid": 89,
              "name": "业绩报表",
              "icon": "goods",
              "perms": "",
              "component": "/distribution/earningReport",
              "menuType": "C",
              "sort": 3,
              "childList": [
                {
                  "id": 3764,
                  "pid": 3763,
                  "name": "分销员",
                  "icon": "",
                  "perms": "platform:bcx:performance:report:fxy:list",
                  "component": "/distribution/earningReport/distributionPeople",
                  "menuType": "C",
                  "sort": 0,
                  "childList": []
                },

                {
                  "id": 3765,
                  "pid": 3763,
                  "name": "分销商",
                  "icon": "",
                  "perms": "platform:bcx:performance:report:fxs:list",
                  "component": "/distribution/earningReport/distributionCompany",
                  "menuType": "C",
                  "sort": 0,
                  "childList": []
                },

                {
                  "id": 3766,
                  "pid": 3763,
                  "name": "渠道佣金",
                  "icon": "",
                  "perms": "platform:bcx:performance:report:channel:list",
                  "component": "/distribution/earningReport/channelCommission",
                  "menuType": "C",
                  "sort": 0,
                  "childList": []
                }
              ]
            },

            {
              "id": 3769,
              "pid": 89,
              "name": "业绩账单",
              "icon": "tickets",
              "perms": "",
              "component": "/distribution/performanceBill",
              "menuType": "C",
              "sort": 2,
              "childList": [
                {
                  "id": 3770,
                  "pid": 3769,
                  "name": "分销员账单",
                  "icon": "",
                  "perms": "",
                  "component": "/distribution/performanceBill/distributor",
                  "menuType": "C",
                  "sort": 0,
                  "childList": []
                },

                {
                  "id": 3771,
                  "pid": 3769,
                  "name": "分销商账单",
                  "icon": "",
                  "perms": "",
                  "component": "/distribution/performanceBill/companyBill",
                  "menuType": "C",
                  "sort": 0,
                  "childList": []
                },

                {
                  "id": 3772,
                  "pid": 3769,
                  "name": "渠道商账单",
                  "icon": "",
                  "perms": "",
                  "component": "/distribution/performanceBill/channelBill",
                  "menuType": "C",
                  "sort": 0,
                  "childList": []
                }
              ]
            },
          ]
        }
      ]
      menusAll = formatRoutes(menusAll);

      !Auth.isPhone()
        ? (menus = menusAll.filter((item) => item.url !== '/javaMobile'))
        : (menus = menusAll.filter((item) => item.url === '/javaMobile'));
      const _routerResult = comRouter(menus, asyncRoutes);
      accessedRoutes = filterAsyncRoutes(_routerResult);
      // todo 这里控制是否过滤路由，经测试有些菜单不能予以设置，比如系统设置等等
      this.state.settings.showSettings = false;
      commit('SET_ROUTES', menus);
      commit('SET_TOPBAR_ROUTES', menus);

      if (this.state.settings.topNav) {
        if (menus[0].child.length > 0) {
          commit('SET_SIDEBAR_ROUTERS', menus[0].child);
        } else {
          commit('SET_SIDEBAR_ROUTERS', [menus[0]]);
        }
      } else {
        commit('SET_SIDEBAR_ROUTERS', menus);
      }
      resolve(accessedRoutes);

      // commit('SET_ROUTES', asyncRoutes)
      // resolve(asyncRoutes)
    });
  },
};

function comRouter (menus, asyncRouter, hasLeft) {
  const res = [];
  asyncRouter.forEach((router) => {
    const _leftUrl = hasLeft ? hasLeft + '/' + router.path : router.path;
    const _hasPromise = menus.filter((item) => item.url.startsWith(_leftUrl));
    if (_hasPromise.length > 0) {
      res.push(router);
    }
    if (router.children) {
      comRouter(menus, router.children, router.path);
    }
  });
  return res;
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
