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: [],
    appThemeMode:'', // 主题模式
});

// 修改状态
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;
        },
        // 如果是知识库就替换掉路由
        setRoouterName:(name)=>{
            const newList = state.routerMatchList.map((val:any) => {
                if (val && val.breadcrumbName === '知识库详情') {
                    return {
                        ...val,
                        breadcrumbName: name,
                    };
                }
                return val;
            });
            state.routerMatchList = newList;
            // console.log('state.routerMatchList', state.routerMatchList);
        }
    };
};

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

    const api = {
        // 退出登录
        logout: async (navigate:any) => {
            try {
                await apis.logout();
                await apis.getSseclose();
                LocalStorage.clear();
                // LocalStorage.removeToken('token');
                // LocalStorage.removeToken('menuType');
                // LocalStorage.removeToken('permissions');
                // LocalStorage.removeToken('userInfo');
                // LocalStorage.removeToken('jk_constant_routes_v1');

                navigate({ pathname: '/login' }, { replace: true });
                message.success('退出成功');
            } catch (e) {
                console.error(e);
            }
        },
    }

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

    // 改变选中菜单
    interface IItem {
        key: string;
        item?: Object,
        keyPath?: string[],
        selectedKeys?: string[],
    }
    const onChangeSelectedKey = (item:IItem) => {
        actions.setSelectedKey(item.key);
        if(item.keyPath){
            onOpenChange(item.keyPath);
        }
    }

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

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

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

    const onSetRouterMatchList = (list: any[]) => {
        actions.setRouterMatchList(list);
    }

    // 初始渲染
    const init: LayoutStore['init'] = (list) => {
        const userInfo = LocalStorage.getUserInfo();
        if (userInfo) {
            actions.setUserName(userInfo.name);
        }
        actions.setRouterMatchList(list);
        const routerInfo = list.length>1?list[list.length - 1]:list[0];
        const flagkeyPath = list.map(item=> {
            return item.path;
        });
        // console.log('flagkeyPath',flagkeyPath,routerInfo)
        // console.log('list---list',list)
        const visibleItems = list.filter(item => item?.hidden === false);
        let lastVisibleItem:any = visibleItems.at(-1)!;
        if (routerInfo) {
            onChangeSelectedKey({
                key: lastVisibleItem.path,
                keyPath: flagkeyPath,
            });
        }
    }

    // 状态重置
    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);
    }

    const onSetRoouterName = (name:string)=>{
        actions.setRoouterName(name)
    }

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

export default useLayoutStore();