/*
 * @Author: cclu
 * @Date: 2021-12-13 11:01:23
 * @LastEditors: cclu 1106109051@qq.com
 * @LastEditTime: 2025-03-28 17:54:43
 * @FilePath: \cloud-platform\src\utils\menuformatter.ts
 * @Description:
 *
 * Copyright (c) 2022 by cclu/杭州驿商科技, All Rights Reserved.
 */
import type { SystemMenuModel, ModuleItem } from '@/pages/Setting/Module/data';
import type { MenuDataItem } from '@ant-design/pro-layout';

type ResponseModel = {
    node: SystemMenuModel;
    children: ResponseModel[];
};

const childrenMenu = (children: ModuleItem[]) => {
    if (!children.length) return [];
    const ch = children.map((n) => {
        return {
            SYSTEMMENU_ICO: n.SYSTEMMODULE_ICO,
            name: n.SYSTEMMODULE_NAME,
            hideInMenu: n.SYSTEMMODULE_STATUS !== 1,
            SYSTEMMODULE_DESC: n.SYSTEMMODULE_DESC,
            path: n.SYSTEMMODULE_URL,
            guid: n.SYSTEMMODULE_GUID || '',
        };
    });
    return ch;
};
// 用户左侧菜单权限格式化
export const menuFormatter = (menudata: ResponseModel[]) => {
    if (!menudata.length) return [];
    const reg = /<(.*) \/>/;
    const list: MenuDataItem[] = menudata.map((item: ResponseModel) => {

        if (item.node) {

            const n = item.node;
            const [iconName] = reg.exec(n?.SYSTEMMENU_ICO)?.reverse() || ['']
            const defaultMenuChild = n?.SystemModuleList?.[0]
            const defaultMenuPath = defaultMenuChild ? defaultMenuChild.SYSTEMMODULE_URL.match(/\/(\S*)\//) : null

            const result: { children: MenuDataItem[], name: string, SYSTEMMODULE_DESC: string, icon: string, path?: string, hideInMenu: boolean } = {
                children: [],
                name: n.SYSTEMMENU_NAME,
                SYSTEMMODULE_DESC: n.SYSTEMMODULE_DESC,
                icon: iconName,
                hideInMenu: n.SYSTEMMENU_STATUS !== 1,
                guid: n.SYSTEMMODULE_GUID || '',
                path: n.SYSTEMMENU_ID.toString() // defaultMenuPath ? defaultMenuPath[1]  :''
                // path: !business.BusinessSystem_Desc ? '/' : business.BusinessSystem_Desc,
            };
            // 是否有子菜单
            if (item.children.length > 0) {
                const childrenEles = menuFormatter(item.children)
                result.children = [...result.children, ...childrenEles];

            }
            // 是否有子模块
            if (n.SystemModuleList) {
                result.children = result.children.concat(childrenMenu(n.SystemModuleList));
            }
            return result
        }
        return {}
    });

    return list;
};
