import { create } from 'zustand';
import { message } from 'antd';
import { apis } from '@/apis';
import LocalStorage from '@/LocalStorage';

export interface RouterMatchItem {
    breadcrumbName: string;
    path: string;
    hidden?: boolean;
}

interface LayoutState {
    routerMatchList: RouterMatchItem[];
    userName: string;
    collapsed: boolean;
    selectedKey: string;
    openKeys: string[];
    appThemeMode: string;
}

interface LayoutActions {
    setRouterMatchList: (list: RouterMatchItem[]) => void;
    setUserName: (userName: string) => void;
    setCollapsed: (collapsed: boolean) => void;
    setSelectedKey: (key: string) => void;
    setOpenKeys: (openKeys: string[]) => void;
    setRoouterName: (name: string) => void;
    reset: () => void;
}

export type LayoutStore = LayoutState & LayoutActions & {
    // Actions
    logout: (navigate: any) => Promise<void>;
    onClickLogout: (navigate: any) => Promise<void>;
    onChangeSelectedKey: (item: { key: string; keyPath?: string[] }) => void;
    onOpenChange: (openKeys: string[]) => void;
    onClickCollapsed: () => void;
    init: (list: RouterMatchItem[]) => void;
    onSetRouterMatchList: (list: RouterMatchItem[]) => void;
    handleSelectChange: (menuLevel: number) => void;
    onSetRoouterName: (name: string) => void;
};

const initialState: LayoutState = {
    routerMatchList: [],
    userName: '',
    collapsed: false,
    selectedKey: '',
    openKeys: [],
    appThemeMode: '',
};

export const useLayoutStore = create<LayoutStore>((set, get) => ({
    ...initialState,
    
    setRouterMatchList: (list) => set({ routerMatchList: list }),
    
    setUserName: (userName) => set({ userName }),
    
    setCollapsed: (collapsed) => set({ collapsed }),
    
    setSelectedKey: (key) => set({ selectedKey: key }),
    
    setOpenKeys: (openKeys) => set({ openKeys }),
    
    setRoouterName: (name) => set((state) => ({
        routerMatchList: state.routerMatchList.map((val) => {
            if (val && val.breadcrumbName === '知识库详情') {
                return { ...val, breadcrumbName: name };
            }
            return val;
        }),
    })),
    
    reset: () => set(initialState),
    
    logout: async (navigate) => {
        try {
            await apis.logout();
            await apis.getSseclose();
            LocalStorage.clear();
            navigate({ pathname: '/login' }, { replace: true });
            message.success('退出成功');
        } catch (e) {
            console.error('退出登录失败:', e);
        }
    },
    
    onClickLogout: async (navigate) => {
        await get().logout(navigate);
    },
    
    onChangeSelectedKey: (item) => {
        set({ selectedKey: item.key });
        if (item.keyPath) {
            get().onOpenChange(item.keyPath);
        }
    },
    
    onOpenChange: (openKeys) => {
        // 点击菜单，收起其他展开的所有菜单
        const latestOpenKey = openKeys.find((key) => get().openKeys.indexOf(key) === -1);
        set({ openKeys: latestOpenKey ? [latestOpenKey] : [] });
    },
    
    onClickCollapsed: () => {
        set((state) => ({ collapsed: !state.collapsed }));
    },
    
    init: (list) => {
        const userInfo = LocalStorage.getUserInfo();
        if (userInfo) {
            set({ userName: userInfo.name });
        }
        set({ routerMatchList: list });
        
        const routerInfo = list.length > 1 ? list[list.length - 1] : list[0];
        const flagkeyPath = list.map(item => item.path);
        const visibleItems = list.filter(item => item?.hidden === false);
        const lastVisibleItem = visibleItems.at(-1);
        
        if (routerInfo && lastVisibleItem) {
            get().onChangeSelectedKey({
                key: lastVisibleItem.path,
                keyPath: flagkeyPath,
            });
        }
    },
    
    onSetRouterMatchList: (list) => {
        set({ routerMatchList: list });
    },
    
    handleSelectChange: () => {
        // 预留功能
    },
    
    onSetRoouterName: (name) => {
        get().setRoouterName(name);
    },
}));
