import {PageContainer, ProLayout} from '@ant-design/pro-components';
import {useCallback, useEffect, useRef} from 'react';
import {Route, Routes, Link, Navigate, useNavigate} from 'react-router-dom';
import useI18NPrefix from '../../hooks/useI18NPrefix.js';
import {styled} from 'styled-components';
import {defaultProps, ICON_MAPPING, router} from "./constants";
import {PATH, MAIN_PATH, STORE_PATH} from '../../constants';
import {SettingPanel} from '../../components/SettingPanel.jsx';
import {LazyHomePage} from '../HomePage/Loadable';
import {AvatarPanel} from '../../components/AvatarPanel.jsx';
import {DataSetPage} from '../DataSetPage/index';
import {ChatPanel} from './components/ChatPanel.jsx';
import {Tour} from 'antd';
import {selectTouring, selectTourName, selectPathname, selectTabs, selectCurrentUser} from '../../slice/selectors.js';
import {useAppDispatch, useAppSelector} from '../../../redux/configureStore.js';
import {getCurrentUser, logout} from '../../slice/thunks.js';
import {LazyUserManagePage} from '../UserManage/Loadable.jsx'
import {LazyRoleManagePage} from '../RoleManage/Loadable'
import {LazyConditionManage} from '../ConditionPage/Loadable'
import {LazyTimeCycleManage} from '../TimeCycle/Loadable.jsx'
import {LazyModalManage} from '../ModalManage/Loadable.jsx'
import {LazyIndexLibraryPage} from "../IndexLibraryPage/Loadable";
import {LazyIndexDefine} from "../IndexDefine/Loadable";
import {useMainSlice} from "./slice";
import {LazyIndexDataSet} from "../IndexDataSet/Loadable";
import {appActions} from "../../slice";
import {DimensionManage} from "../DimensionManage";
import {DatabaseSourcePage} from "../DatabaseSourcePage";
import {getToken} from "../../../utils/auth";
import {ThemeDesigner} from "../../components/ThemeDesigner";

export const MainPage = () => {
  useMainSlice();
  const logged = !!getToken();
  /** 全局i18n */
  const t = useI18NPrefix('global');
  const l = useI18NPrefix('login');
  /** 推送状态函数 */
  const dispatch = useAppDispatch();

  /** 当前用户信息 */
  const currentUser = useAppSelector(selectCurrentUser);
  /** 导游名称*/
  const tourName = useAppSelector(selectTourName);
  /** 插入的标签页 */
  const tabs = useAppSelector(selectTabs);
  /** 当前路由路径 */
  const pathname = useAppSelector(selectPathname);
  /** 路由 */
  const navigate = useNavigate();

  /** 状态检测 */
  useEffect(() => {
    if (!logged) {
      navigate('/');
    }
    if (!currentUser){
      dispatch(getCurrentUser());
    }
  }, [dispatch,logged,currentUser]);

  /** 导游权限、步骤、名称、状态 */
  const ref1 = useRef(null);
  const ref2 = useRef(null);
  const steps = [
    {
      title: '主页设置',
      description: '点击这里设置页面的主题、语言等主页配置。',
      cover: (
        <img
          alt="tour.png"
          src="https://user-images.githubusercontent.com/5378891/197385811-55df8480-7ff4-44bd-9d43-a7dade598d70.png"
        />
      ),
      target: () => ref1.current,
    },
    {
      title: 'AI智能向导',
      description: '项目中内嵌的AI智能体，可以更方便的帮助我们了解项目。',
      target: () => ref2.current,
    },
  ];

  /** 插入Tab页 */
  const addTab = useCallback((router) => {
    const index = tabs.findIndex(item => item.key === router.path)
    if (index === -1) {
      dispatch(appActions.updateTabs(
        tabs.concat({
          tab: router.name,
          key: router.path,
        })
      ))
    }
  }, [tabs]);

  /** 删除Tab页 */
  const actionTab = useCallback((key, action) => {
    if (key!=='/welcome' && action === 'remove') {
      dispatch(appActions.updateTabs(
        tabs.filter(item => item.key !== key),
      ))
      navigate(PATH.MAIN+ '/welcome');
      dispatch(appActions.updatePathname('/welcome'));
    }
  }, [tabs])

  /** 切换Tab */
  const changeTab = useCallback((key) => {
    dispatch(appActions.updatePathname(key));
    // dispatch(mainActions.reset());
    navigate(PATH.MAIN + key);
  }, [])

  /** 头像选择下来菜单选项回调 */
  const onAvaSelect = (e) => {
    if (e.key === 'logout') {
      dispatch(
        logout(() => {
          navigate("/")
        })
      )
    }
  }
  /** 菜单切换回调 */
  const switchPathname = useCallback((item)=>{
    addTab(item)
    dispatch(appActions.updatePathname(item.path || MAIN_PATH.WELCOME))
    //dispatch(mainActions.reset());
  },[tabs,pathname])

  /** 导游步骤 */
  const closeTouring = useCallback(()=>{
    dispatch(appActions.startTour(false));
  },[])

  const touring = useAppSelector(selectTouring);

  return (
    <LayoutContainer>
      <Tour open={tourName === "/main/welcome" && touring} onClose={closeTouring} steps={steps}/>
      <ThemeDesigner />
      <ProLayout
        {...defaultProps}
        title={l("title")}
        menu={{type: 'sub'}}
        route={router}
        location={{pathname}}
        avatarProps={{
          src: 'https://gw.alipayobjects.com/zos/antfincdn/efFD%24IOql2/weixintupian_20170331104822.jpg',
          title: <AvatarPanel onSelect={onAvaSelect}>{currentUser?.userName||'游客'}</AvatarPanel>,
          size: 'small',
        }}
        actionsRender={(props) => {
          if (props.isMobile) return [];
          return [
            <SettingPanel ref={ref1}>{ICON_MAPPING.SETTING}</SettingPanel>,
            <ChatPanel ref={ref2}>{ICON_MAPPING.CHAT}</ChatPanel>,
          ];
        }}
        menuItemRender={(item, dom) =>
          <Link
            children={dom}
            onClick={() => switchPathname(item)}
            to={PATH.MAIN + item.path}
          />
        }
        waterMarkProps={{
          content:currentUser?.userName
        }}
      >
        <PageContainer
          tabList={tabs}
          tabProps={{
            hideAdd: true,
            type: 'editable-card',
            activeKey: pathname,
            onEdit: actionTab,
            onChange: changeTab
          }}
        >
          {
            logged &&
            <Routes>
              <Route exact path={PATH.ROOT} element={<Navigate replace to={PATH.MAIN + MAIN_PATH.WELCOME}/>}/>
              <Route path={MAIN_PATH.WELCOME} Component={LazyHomePage}/>
              <Route path={MAIN_PATH.MANAGE + "/basic/user"} Component={LazyUserManagePage}/>
              <Route path={MAIN_PATH.MANAGE + "/basic/role"} Component={LazyRoleManagePage}/>
              <Route path={MAIN_PATH.MANAGE + "/index/business"} Component={LazyConditionManage}/>
              <Route path={MAIN_PATH.MANAGE + "/index/time_cycle"} Component={LazyTimeCycleManage}/>
              <Route path={MAIN_PATH.MANAGE + "/index/db_source"} Component={DatabaseSourcePage}/>
              <Route path={MAIN_PATH.INDEX + "/index_df"} Component={LazyIndexDefine}/>
              <Route path={MAIN_PATH.INDEX + "/index_set"} Component={LazyIndexDataSet}/>
              <Route path={MAIN_PATH.INDEX + "/dimension"} Component={DimensionManage}/>
              <Route path={MAIN_PATH.MODAL} Component={LazyModalManage}/>
              <Route path={MAIN_PATH.STORE + STORE_PATH.DATA_SET} element={<DataSetPage/>}/>
              <Route path={MAIN_PATH.STORE + STORE_PATH.LIB} Component={LazyIndexLibraryPage}/>
            </Routes>
          }
        </PageContainer>
      </ProLayout>
    </LayoutContainer>
  );
};

const LayoutContainer = styled.div`
  height: 100vh
`
