import * as React from 'react';
import { useMatches, useLocation, Outlet, useNavigate } from 'react-router-dom';
import { observer } from 'mobx-react';
import { Layout, Divider,Tour } from 'antd';
import type { TourProps } from 'antd';
import Header from './components/Header';
import Nav from './components/Nav';
import Breadcrumb from './components/Breadcrumb';
import EntryModal from './components/EntryModal';
import store from './store';
import LocalStorage from '@/LocalStorage';
import './style.less';
import { trackDerivedFunction } from 'mobx/dist/internal';
import loginStore from '../login/store';
const { Content } = Layout;

const LayoutApp: React.FC = () => {
  const ref1 = React.useRef(null);
  const ref2 = React.useRef(null);
  const ref3 = React.useRef(null);
  const ref4 = React.useRef(null);
  const ref5 = React.useRef(null);
  const navigate = useNavigate(); // 添加useNavigate hook
  const {
    state,
    onClickLogout,
    onChangeSelectedKey,
    onOpenChange,
    onClickCollapsed,
    init,
    reset,
    onSetRouterMatchList,
  } = store;
  const {
    routerMatchList,
    userName,
    collapsed,
    selectedKey,
    openKeys,
  } = state;
  const matches = useMatches();
  // console.log('matches',matches)
  const location = useLocation();
  const onList = () => {
    if(matches.length===1){
        const item:any = matches[0];
        return [{
          path: item.handle?.key || item.pathname,
          breadcrumbName: item.pathname==='/overview' ? '概览' : item.pathname,
          hidden: item.handle?.hidden || false
        }];
    }else{
      const list = matches.filter((item: any) => item.handle?.breadcrumbName).map((item: any) => {
        return {
          path: item.handle?.key || item.pathname,
          breadcrumbName: item.handle.breadcrumbName,
          hidden: item.handle?.hidden || false
        }
      });
      return list;
    }
  }
  React.useEffect(() => {
    const list = onList();
    init(list);
  }, [matches]);

  const currentMenuType = LocalStorage.getMenuType();
  const [entryModalOpen, setEntryModalOpen] = React.useState(false);




  React.useEffect(() => {
    LocalStorage.setMenuType(1);
    return () => reset();
  }, []);

  // 统一管理菜单类型状态
  const [menuType, setMenuType] = React.useState(1);
  // 处理菜单类型变化
  const handleSelectChange = (value: string) => {
    navigate(value);
  };

  // 添加路由变化监听
  React.useEffect(() => {
    const path = location.pathname;
    const type = 1;
    setMenuType(type);
    // console.log('路由变化了，当前路由：', path);
    // 确保selectedKey与当前路由同步
    if (path !== selectedKey) {
      // onChangeSelectedKey({
      //   key: path,
      // });
    }
    // 知识库导览
    if(path === '/knowledge/knowledgeLib'&& !localStorage.getItem('knowledgeTour')){
        setTimeout(()=>{
          setOpenTour(true);
        },800)
    }
    // 应用导览
    if(path === '/appCenter/questionAnswer'&& !localStorage.getItem('appTour')){
        setTimeout(()=>{
          setOpenTour(true);
        },800)
    }
  }, [location.pathname]);
  const [openTour, setOpenTour] = React.useState(false);

  // 根据当前路由动态生成步骤
  const steps: TourProps['steps'] = React.useMemo(() => {
    const path = location.pathname;

    // 知识库页面导览步骤
    if (path === '/knowledge/knowledgeLib') {
      return [
        {
          title: '步骤 1.1 导航到知识库',
          description: '点击侧边栏的"知识库管理"菜单，进入"知识库"页面。',
          target: () => {
            const el = ref1.current;
            return el ? el : document.body;
          },
        },
        {
          title: '步骤 1.2 创建知识库',
          description: '点击右上角的"创建知识库"按钮，开始创建您的第一个知识库并上传知识文档。',
          target: () => {
            const el = ref2.current;
            return el? el : document.body;
          },
        },
        {
          title: '步骤 1.3 接下来还需要创建应用',
          description: '点击侧边栏的"应用中心"菜单，寻找"我创建的应用"页面，选择知识库，创建您的第一个RAG应用。',
          target: () => {
            const el = ref3.current;
            return el? el : document.body;
          },
        },
      ];
    }

    // 应用列表页面导览步骤
    if (path === '/appCenter/questionAnswer') {
      return [
        {
          title: '步骤 2.1 导航到我创建的应用',
          description: '点击侧边栏的"应用中心"菜单，将会自动展开"我创建的应用"页面。',
          target: () => {
            const el = ref5.current;
            return el? el : document.body;
          },
        },
        {
          title: '步骤 2.2 创建RAG应用',
          description: '点击右上角的"创建RAG应用"按钮，开始创建您的第一个应用，发布后即可在下方菜单中找到。',
          target: () => {
            const el = ref4.current;
            return el? el : document.body;
          },
        },
      ];
    }

    return [];
  }, [location.pathname]);
  const tourClose = () => {
    // 关闭引导后的一些操作
    const path = location.pathname;
    if (path === '/knowledge/knowledgeLib') {
      localStorage.setItem('knowledgeTour', 'true');
    } else if (path === '/appCenter/questionAnswer') {
      localStorage.setItem('appTour', 'true');
    }
    setOpenTour(false);
  }
  return (
    <Layout style={{
      minHeight: '100vh',
      overflow: 'auto',
      display: 'flex',
      flexDirection: 'column',
      backgroundColor: '#fff'
    }}>
      <Header
        userName={userName}
        onClickLogout={onClickLogout}
        onSelectChange={handleSelectChange} // 传递回调函数
        currentMenuType={selectedKey}
      />
      <div style={{ display: 'flex', marginTop: '64px', backgroundColor: '#fff' }}>
        {location.pathname !== '/appCenter' && <Nav
          selectedKey={selectedKey}
          ref1={ref1}
          ref3={ref3}
          ref5={ref5}
          onChangeSelectedKey={onChangeSelectedKey}
          openKeys={openKeys}
          onOpenChange={onOpenChange}
          collapsed={collapsed}
          onClickCollapsed={onClickCollapsed}
          menuType={menuType}
        />}
        <Layout style={{
          marginLeft: location.pathname !== '/appCenter' ? (collapsed ? '80px' : '200px') : 0,
          width: location.pathname !== '/appCenter' ? (collapsed ? 'calc(100% - 80px)' : 'calc(100% - 200px)') : '100%',
          backgroundColor: '#fff',
          minHeight: 'calc(100vh - 64px)',
          transition: 'all 0.2s ease'
        }}>

          <Content className='main-content'>
            {
              location.pathname === '/404' &&
              <div style={{ width: '100%', height: 20 }}></div>
            }
            {location.pathname !== '/appCenter' && <Breadcrumb ref2={ref2} ref4={ref4} routerMatchList={routerMatchList} />}
            <div className='content-scroll-area'>
              <Outlet />
            </div>
          </Content>
        </Layout>
      </div>
      <Tour open={openTour} onClose={() => { tourClose();}} steps={steps} />
      {
        entryModalOpen &&
        <EntryModal
          open={entryModalOpen}
          onClickConfirm={(type) => {
            // handleSelectChange(type);
            setEntryModalOpen(false);
            LocalStorage.setMenuType(type);
          }}
        />
      }
    </Layout>
  );
};

export default observer(LayoutApp);
