import React, { useEffect, useState } from 'react';
import {  Menu, Tooltip } from 'antd';
import { Link, useLocation } from 'react-router-dom';
import { useHistory } from 'react-router-dom';
import { SiderProps } from './module.interface';
import { YRouterItem } from '@/default.interface';
import { YIcon } from '../icon';
import { MenuStyle, SideBarStyle } from './styles';
import { useSidebar } from './useSidebar';
import { useModuleStore } from './useStore';


export const Sider: React.FC<SiderProps> = ({ config, onMenuClick }) => {
  const {moduleId, moduleName} = config;
  const { getMenu, isLoading, initMenu, selectMenu } = useSidebar(config);
  const useLocationFn = useLocation();
  const historyRouter = useHistory();
  const [state] = useModuleStore();
  const [selectedKeys, setSelectedKeys] = useState(state.defaultSelectedMenus);
  const [list, setList] = useState<YRouterItem[]>(null as unknown as YRouterItem[]);

  useEffect(() => {
    initMenu();
    console.log('updateSessionData sidebar change', config)
  }, [config.moduleId]);

  useEffect(() => {
    if (typeof window !== 'undefined' && !isLoading) {
      console.log('init_menu location', useLocationFn)
      const { pathname } = useLocationFn;
      getMenu(pathname);
    }
  }, [isLoading]);

  useEffect(() => {
    const newList = state.menus && state.menus.length ? state.menus?.filter((item: YRouterItem) => {
      return item.hidden !== true
    }) : [];
    setList(newList)
  }, [state.menus]);

  const clickMenu = ({key }: any) => {
    const url = `/${moduleName}/${moduleId}/#${key}`;
    onMenuClick && onMenuClick(url);
    selectMenu(key);
  }

  const onSelectMenu = ({ selectedKeys }: any) => {
    setSelectedKeys(selectedKeys);
  };

  useEffect(() => {
    setSelectedKeys(state.defaultSelectedMenus);
  }, [state.defaultSelectedMenus]);

  return (
    <SideBarStyle>
      {list && list.length ? (
        <MenuStyle
          mode="inline"
          selectedKeys={selectedKeys}
          onSelect={onSelectMenu}
          onClick={clickMenu}
        >
          {list.map((item: YRouterItem) => {
            const icon = item.meta.icon && <YIcon name={item.meta.icon} />;
            return (
              <Menu.Item key={item.path} disabled={item.disable}>
                {
                  item.disable ? (
                    <Tooltip title={`暂时您没有权限，请联系${item.productOwner?.name}申请权限！`}>
                      <span>{item.meta?.title}</span>
                    </Tooltip>
                  ) : (
                    <Link to={item.path}>
                      {item.meta?.title}
                    </Link>
                  )
                }
              </Menu.Item>
            )
          })}
        </MenuStyle>
      ) : (
        ''
      )}
    </SideBarStyle>
  );
};
