import { makeAutoObservable } from 'mobx';
import { message } from 'antd';
import { apis } from '@/apis';
import LocalStorage from '@/LocalStorage';
import router from '@/router';
import { State, ReadonlyState, StateAction, LayoutStore } from './types';

// 定义状态
const stateGenerator = (): ReadonlyState => ({
    routerMatchList: [],
    userName: '',
    collapsed: false,
    selectedKey: '',
    openKeys: [],
});

// 修改状态
const stateActionsGenerator = (state: State): StateAction => {
    return {
        setRouterMatchList: (list) => {
            state.routerMatchList = list;
        },
        setUserName: (userName) => {
            state.userName = userName;
        },
        setCollapsed: (status) => {
            state.collapsed = status;
        },
        setSelectedKey: (key) => {
            state.selectedKey = key;
        },
        setOpenKeys: (openKeys) => {
            state.openKeys = openKeys;
        },
    };
};

// 使用仓库
const useLayoutStore = (): LayoutStore => {
    const state = makeAutoObservable(stateGenerator());
    const actions = stateActionsGenerator(state);

    const api = {
        // 退出登录
        logout: async () => {
            try {
                await apis.logout();
                LocalStorage.clear();
                router.navigate({ pathname: '/login' }, { replace: true });
                message.success('退出成功');
            } catch (e) {
                console.error(e);
            }
        },
    }

    // 点击退出登录
    const onClickLogout = async () => {
        // 退出登录
        await api.logout();
    }

    // 改变选中菜单
    const onChangeSelectedKey = (path: string, menuLevel: number) => {
        // 直接使用完整路径作为selectedKey
        actions.setSelectedKey(path);
        
        const pathParts = path.split('/').filter(Boolean);
        
        if (menuLevel === 2 && pathParts.length >= 2) {
            // 选中二级菜单，打开对应的一级菜单
            onOpenChange(['/' + pathParts[0]]);
        } else {
            // 选中一级菜单，关闭所有展开的菜单
            onOpenChange([]);
        }
    }

    // 打开菜单
    const onOpenChange = (openKeys: string[]) => {
        actions.setOpenKeys(openKeys);
    }

    // 收缩释放菜单
    const onClickCollapsed = () => {
        actions.setCollapsed(!state.collapsed);
    }

    const handleSelectChange = ( menuLevel: number) => {
        
    }

    // 初始渲染
    const init: LayoutStore['init'] = (list) => {
        const userInfo = LocalStorage.getUserInfo();
        if (userInfo) {
            actions.setUserName(userInfo.name);
        }
        actions.setRouterMatchList(list);
        const routerInfo = list[list.length - 1];
        if (routerInfo) {
            onChangeSelectedKey(routerInfo.path, routerInfo.menuLevel);
        }
    }

    // 状态重置
    const reset = () => {
        const initialRouterMatchList = stateGenerator().routerMatchList;
        const initialUserName = stateGenerator().userName;
        const initialCollapsed = stateGenerator().collapsed;
        const initialSelectedKey = stateGenerator().selectedKey;
        const initialOpenKeys = stateGenerator().openKeys;

        actions.setRouterMatchList(initialRouterMatchList);
        actions.setUserName(initialUserName);
        actions.setCollapsed(initialCollapsed);
        actions.setSelectedKey(initialSelectedKey);
        actions.setOpenKeys(initialOpenKeys);
    }

    return {
        state,
        onClickLogout,
        onChangeSelectedKey,
        onOpenChange,
        onClickCollapsed,
        init,
        handleSelectChange,
        reset
    };
};

export default useLayoutStore();