

// import { message } from 'ant-design-vue';
import { defineStore } from 'pinia';
import { authorizationService } from './authorization-service';
import { cloneDeep } from 'lodash-es';
// import { router } from '/nerv-lib/paas/router';
// import { http } from '/nerv-lib/util/http';

export interface Catalog {
  label: string;
  name?: string;
  items: CatalogItem[];
}

export interface CatalogItem {
  label: string;
  name: string;
  icon: string;
  url: string;
  dock?: boolean;
  queryParams?: QueryParams;
  isRedirect?: boolean;
  app?: string;
  authModuleNames?: any[]; //权限控制所需的所有模块名
  splitMenuModule?: string; //某个菜单单独拆分出去放在一个app中，权限照旧
  splitModule?: boolean; //被拆分的模块
}
// QueryParams修改声明view和region都为非必选
export interface QueryParams {
  view?: string;
  region?: string;
}

export const CatalogConfigService = defineStore({
  id: 'CatalogConfigService',
  /**
   * sideMenu   侧边栏菜单
   * @returns
   */
  state(): { region: any; data: any[] } {
    return { region: '', data: [] };
  },
  getters: {},
  actions: {
    getCatalogs() {
      if (this.data.length != 0) {
        return this.data;
      }

      // @ts-ignore
      const { ModulesRes } = authorizationService();
      const modules = cloneDeep(ModulesRes);
      this.data = this.convert2Catalog(modules);
      return this.data;
    },

    convert2Catalog(modules: any): any {
      const authService = authorizationService();
      let catalogs: Array<Catalog> = [];
      let sort: any[] = [];
      const storage = JSON.parse((window.localStorage.docks as string) || '[]');
      // console.log('storage', storage);

      modules.forEach((module: any) => {
        if (module.hasOwnProperty('sort')) {
          sort = module.sort;
        } else {
          const catalogName = module.catalog;
          let catalog: Catalog;
          catalogs.forEach((cl) => {
            if (cl.name == catalogName) {
              catalog = cl;
            }
          });
          if (!catalog) {
            catalog = {
              label: catalogName,
              name: catalogName,
              items: [],
            };
            catalogs.push(catalog);
          }

          const catalogItem: CatalogItem = {
            label: module.label,
            name: module.name,
            icon: module.icon,
            url: module.url,
            app: module.app,
            dock: storage.includes(module.name),
          };
          let catalogItemName = module.name;
          if (module['authModuleNames']) {
            catalogItem['authModuleNames'] = module.authModuleNames;
          }
          if (module['splitMenuModule']) {
            catalogItemName = catalogItem['splitMenuModule'] = module['splitMenuModule'];
          }
          if (module['splitModule']) {
            catalogItem['splitModule'] = module['splitModule'];
          }
          if (module.queryParams) {
            catalogItem['queryParams'] = {
              view: module.queryParams.view,
            };
          }

          const isCurrentApp = authService.isCurrentApp(module.app);
          catalogItem['isRedirect'] = !isCurrentApp;

          let firstMenuName;

          /**
           * 如果module.json最外层没有指定url 并且 当前登录是admin账号, 则取module.json中menus的第0个
           */
          if (!catalogItem.url && authService.isAdmin()) {
            if (module['menus'] && module['menus'].length > 0) {
              firstMenuName = module['menus'][0]['name'];
            }
          }

          /**
           * 如果module.json中的最外层没有指定url 且 当前登陆非admin, 则取menus中有权限的第0个
           */
          const menusForAppMap: any = {};
          if (!catalogItem.url && !authService.isAdmin()) {
            /**
             * 将独立模块的子菜单menu['submenus']加进一级菜单里 module['menus']
             * 将文件夹模块的菜单处理和独立模块处理成同一种逻辑
             */
            const globalMenus: Array<any> = []; //保留独立模块的子菜单
            if (module['menus'] && module['menus'].length > 0) {
              module['menus'].forEach((menu: { [x: string]: any[] }) => {
                if ((menu['isGlobal'] || menu['isDir']) && menu['submenus'].length > 0) {
                  menu['submenus'].forEach((subMenu) => {
                    module['menus'].push({
                      name: subMenu['operation']['resource'],
                      url: subMenu['url'],
                      label: subMenu['label'],
                    });
                  });
                  globalMenus.push(menu);
                }
              });
            }
            /**
             * 独立模块下的资源与菜单顺序不一致时候，需要重新对菜单按照menusSort排序
             */
            if (module['menusSort'] && module['menusSort'] instanceof Array) {
              if (module['menus'] && module['menus'].length > 0) {
                let sortMenus: any[] = [];
                module['menusSort'].forEach((sortMenuName) => {
                  module['menus'].forEach((menu: { [x: string]: any }) => {
                    //独立模块下的菜单
                    if (menu['isGlobal'] && menu['submenus'].length > 0) {
                      menu['submenus'].forEach((subMenu: { [x: string]: any }) => {
                        if (!subMenu['operation']['resource']) return;
                        const menuName = subMenu['operation']['resource'];
                        if (menuName == sortMenuName) {
                          sortMenus.push({
                            name: subMenu['operation']['resource'],
                            url: subMenu['url'],
                            label: subMenu['label'],
                          });
                        }
                      });
                      //普通菜单
                    } else if (menu['name'] == sortMenuName) {
                      sortMenus.push(menu);
                    }
                  });
                });
                sortMenus = [...sortMenus, ...globalMenus];
                module['menus'] = sortMenus;
              }
            }
            /***如果app下一级菜单属于不同后端注册模块：authModuleNames存放所有的模块**/
            let authMenus: any[] = [];
            if (catalogItem['authModuleNames'] && catalogItem['authModuleNames'].length > 0) {
              const authModuleNames: any[] = catalogItem['authModuleNames'];
              authModuleNames.forEach((moduleName) => {
                const tempAuthMenus = authService.getValidFirstMenuName(moduleName); //每个模块有权限的菜单
                if (tempAuthMenus && tempAuthMenus.length > 0) {
                  tempAuthMenus.forEach((menu) => {
                    menusForAppMap[menu] = moduleName;
                  });
                }
                // authMenus = [...authMenus, ...tempAuthMenus];
                if (tempAuthMenus) {
                  authMenus = [...authMenus, ...tempAuthMenus];
                } else {
                  authMenus = [...authMenus];
                }
              });
            } else {
              /***如果app下所有资源属于同一个后端注册模块：没有authModuleNames字段**/
              authMenus = authService.getValidFirstMenuName(catalogItemName);
              if (authMenus && authMenus.length > 0) {
                authMenus.forEach((menu) => {
                  menusForAppMap[menu] = catalogItemName;
                });
              }
            }
            if (module['menus'] && module['menus'].length > 0) {
              if (authMenus && authMenus.length > 0) {
                let count = 0;
                module['menus'].forEach((menusItem: { [x: string]: any }) => {
                  if (authMenus.indexOf(menusItem['name']) != -1) {
                    count++;
                    if (count == 1) {
                      firstMenuName = menusItem['name'];
                    }
                  }
                });
              }
            }
          }

          /**
           * 获取第0个子菜单的url以及queryParams
           */
          if (firstMenuName) {
            let moduleName = catalogItemName;
            if (menusForAppMap && menusForAppMap[firstMenuName]) {
              moduleName = menusForAppMap[firstMenuName];
            }
            let urlObj = {};
            let isSubModule = false;
            if (moduleName == catalogItemName) {
              urlObj = this.getUrlObj(firstMenuName, module['menus']);
            } else {
              isSubModule = true;
              let globalModule: any = {};
              if (module['menus'] && module['menus'].length > 0) {
                module['menus'].forEach((subMenusModule: { [x: string]: any }) => {
                  if (subMenusModule['name'] == moduleName) {
                    globalModule = subMenusModule;
                  }
                });
              }
              urlObj = this.getUrlObj(firstMenuName, globalModule['submenus'], isSubModule);
            }
            const url: any = urlObj['url'];
            const queryParams = urlObj['queryParams'];

            if (url) {
              catalogItem['url'] = url;
            }

            if (queryParams) {
              catalogItem['queryParams'] = queryParams;
            }
          }

          /**
           * 如果不是当前应用的url 并且 不是http开头的url, 则加上应用名
           */
          if (catalogItem.url && catalogItem.url.toLowerCase().indexOf('http') != 0) {
            catalogItem.url = '/' + module.app + catalogItem.url;

            /* 如果存在queryParams, 则在url中追加 */
            const queryParams = catalogItem['queryParams'];
            if (queryParams) {
              const paramStringArr = [];
              for (const k in queryParams) {
                const paramString = k + '=' + queryParams[k];
                paramStringArr.push(paramString);
              }
              if (catalogItem.url.indexOf('http') == 0 || catalogItem['isRedirect']) {
                catalogItem.url = catalogItem.url + '?' + paramStringArr.join('&');
              }
            }
          }

          if (!catalogItem.url) {
            catalogItem.url = '';
          }

          catalog.items.push(catalogItem);
        }
      });
      // console.log(catalogs);
      if (sort) {
        catalogs = this.sortcatalogs(catalogs, sort);
      }
      // console.log(catalogs);
      return catalogs;
    },
    getUrlObj(menuName: any, menus: any[], isSubModule?: boolean) {
      let url = null;
      let queryParams = null;
      if (menus && menus instanceof Array) {
        menus.forEach((mu) => {
          if (isSubModule) {
            if (mu['operation']['resource'] != menuName) {
              return;
            }
          } else {
            if (mu['name'] != menuName) {
              return;
            }
          }
          if (this.region) {
            if (mu['queryParams']) {
              mu['queryParams']['region'] = this.region.value;
            } else {
              mu['queryParams'] = { region: this.region.value };
            }
          } else {
            if (mu['queryParams']) {
              delete mu['queryParams']['region'];
            }
          }
          url = mu['url'];
          queryParams = mu['queryParams'];
        });
      }
      return {
        url: url,
        queryParams: queryParams,
      };
    },

    sortcatalogs(orginCatalogs: any[], sort: string | any[]) {
      let destCatalogs = [];
      for (let index = 0; index < sort.length; index++) {
        for (let idx = 0; idx < orginCatalogs.length; idx++) {
          if (orginCatalogs[idx].label == sort[index]) {
            destCatalogs.push(orginCatalogs[idx]);
            orginCatalogs.splice(idx, 1);
          }
        }
      }
      if (orginCatalogs) {
        destCatalogs = destCatalogs.concat(orginCatalogs);
      }
      // console.log(destCatalogs);
      return destCatalogs;
    },
  },
});
