import { defineAsyncComponent, shallowRef, Ref } from 'vue'
import { OperationTabMenu, OperationTabMenuAuth } from '@/services/go/commonService/interface'
import { initData } from '@/common/methods'
import { useRoute } from 'vue-router'
import { DynamicComponent } from './interface'
import { BtnListType } from '@/common/components/btnList/interface';
import { getClassName } from '@/common/setup/table/button'
import APP from '@/services'

/**
 * 路由菜单
 */
export function useMenu() {
    const route = useRoute();
    const menus: Ref<OperationTabMenu[]> = APP.getRef('menus');

    const auth = (() => {
        const result: BtnListType[] = [];
        if (route.meta.auth) {
            const routeAuth = route.meta.auth as OperationTabMenuAuth[];
            routeAuth.forEach((e) => {
                const { label, code } = e;
                result.push({
                    lable: label,
                    code: code,
                    className: getClassName(code),
                })
            })
        }
        return result;
    })()

    /**
     * 过滤操作权限
     * @param filtered 过滤的数据项
     * @param reverse 是否反向过滤
     * @returns 
     */
    const authFilter = (filtered: string[] = [], reverse = false) => {
        if (filtered.length) {
            if (reverse) {
                // 返回除指定的权限代码
                return auth.filter((e) => !filtered.includes(e.code));
            } else {
                // 返回指定的权限代码
                return auth.filter((e) => filtered.includes(e.code));
            }
        }
        return auth;
    }

    /**
     * 通过code获取对应的子菜单
     * @param menucode 
     * @returns 
     */
    const getChildrenMenu = (menucode?: string) => {
        const filter = (items: OperationTabMenu[], name?: string): OperationTabMenu | undefined => {
            if (name) {
                for (let i = 0; i < items.length; i++) {
                    const { code, children } = items[i];
                    if (code === name) return items[i];
                    if (children) {
                        const res = filter(children, name);
                        if (res) return res;
                    }
                }
            }
            return undefined;
        }
        return filter(menus.value, menucode ?? route.name?.toString());
    }

    return {
        route,
        menus,
        auth,
        getChildrenMenu,
        authFilter
    }
}

/**
 * 底部动态组件
 */
export function useDynamicComponent(menucode?: string) {
    const { getChildrenMenu } = useMenu();
    const dynamicComponents: DynamicComponent[] = [];
    const currentAuth: BtnListType[] = []; // 当前操作权限
    const currentTabComponent = shallowRef<DynamicComponent>(); // 当前选中的子组件

    // 处理动态组件
    const parseComponent = (items: OperationTabMenu[]) => {
        let result: DynamicComponent[] = [];

        items.forEach((menu) => {
            const { title, code, component, children, auth } = menu;
            if (component) {
                let asyncComponent;

                if (component === 'Main') {
                    asyncComponent = defineAsyncComponent(() => import('@/@next/components/layout/footer-main/index.vue'));
                } else {
                    const componentString = component.replace(/^\/+/, ''); // 过滤字符串前面所有 '/' 字符
                    const componentPath = componentString.replace(/\.\w+$/, ''); // 过滤后缀名，为了让 import 加入 .vue ，不然会有警告提示...
                    asyncComponent = defineAsyncComponent(() => import('@/' + componentPath + '.vue'));
                }

                const dynamicComponent: DynamicComponent = {
                    title: title,
                    code: code,
                    auth: auth?.map((e) => ({
                        lable: e.label,
                        code: e.code,
                        className: getClassName(e.code)
                    })) ?? [],
                    component: asyncComponent
                }

                if (children?.length) {
                    dynamicComponent.children = parseComponent(children);
                }

                result = [...result, dynamicComponent];
            }
        })

        return result;
    }

    // 切换组件
    const componentChange = (component: DynamicComponent) => {
        currentTabComponent.value = component;
    }

    initData(() => {
        const childrenMenu = getChildrenMenu(menucode);
        if (childrenMenu) {
            const { auth, children } = childrenMenu;
            if (auth) {
                auth.forEach((e) => {
                    const { label, code } = e;
                    currentAuth.push({
                        lable: label,
                        code: code,
                        className: getClassName(code),
                    })
                })
            }
            if (children) {
                const components = parseComponent(children);
                dynamicComponents.push(...components);
                if (components.length) {
                    currentTabComponent.value = components[0];
                }
            }
        }
    })

    return {
        dynamicComponents,
        currentAuth,
        currentTabComponent,
        componentChange,
    }
}