/*
 * @Author: your name
 * @Date: 2021-11-09 13:56:33
 * @LastEditTime: 2022-07-08 16:35:31
 * @LastEditors: code4eat awesomedema@gmail.com
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: /KC-MiddlePlatform/src/layouts/index.tsx
 */

import { IRouteComponentProps, useModel, history } from 'umi';
import ProLayout from '@ant-design/pro-layout';

import TopBar from '@/components/topBar';
import { useEffect, useState } from 'react';
import { getPlatformMenu, getUserPlatformNav } from '@/service/menu';
import { NavSelecterData } from '@/components/NavSelecter';

const TopHoc = ({ currentSelectedSys, openedSysLists, navData }: { currentSelectedSys: TopBar.Tab | undefined, openedSysLists: TopBar.Tab[], navData: TopBar.PanelData[] }) => {
  const { initialState, setInitialState } = useModel('@@initialState');


  const onTabChangeHandle = async (data: TopBar.Tab[]) => {
    // await setInitialState((s) => ({ ...s, openedSysLists: [...data] }));
    // localStorage.setItem('initialState', JSON.stringify(initialState)); //缓存tab状态，防止刷新丢失
  };

  const onTabClickHandle = async (data: TopBar.Tab) => {
 
    await setInitialState((s) => ({ ...s, currentSelectedSys: data }));
    console.log({data});
    if(data.type == 4){
        //空白页面
        history.push(`${data.path}?isEmpty=true&menuId=${data.menuId}`);
    }else{
      if(data.isSetupMenu){
        //体系菜单掩藏子应用的menu
        localStorage.setItem('isChildShowMenu','false');
      }else{
        localStorage.setItem('isChildShowMenu','true');
      }

      history.push(data.path);
    }
   
  };

  const userPannelTabClickhandle = (tag: string) => {
    if (tag == 'LOGOUT') {
      if (initialState) {
        const { logout } = initialState;
        logout && logout();
      }
    }
    if (tag == 'SETTING') {
      if (initialState) {
        setInitialState((s) => ({
          ...s,
          currentSelectedSys: {
            menuId: -1,
            name: '个人中心',
            icon: '',
            url: '',
            systemId: '-1',
            type:1,
            path: '/personalCenter',
          },
        }));
      }
    }
  };

  return (
    <TopBar
      navData={navData}
      userData={initialState?.userData}
      openedTabs={openedSysLists}
      onTabChange={onTabChangeHandle}
      onTabClick={onTabClickHandle}
      currentTab={currentSelectedSys}
      userPannelTabClick={userPannelTabClickhandle}
    />

  );
};

export default function Layout({ children, location, route, history, match }: IRouteComponentProps) {
  const { initialState, setInitialState } = useModel('@@initialState');
  const [navData, set_navData] = useState<TopBar.PanelData[]>([]);
  const [emptyPageContent, set_emptyPageContent] = useState('');
  const [isEmpty,set_isEmpty] = useState(false);

  const getNavData = async () => {
    const nav = await getUserPlatformNav();
    if (nav) {
      set_navData(nav);

    }
  }

  useEffect(() => {
    if (location.pathname != '/login') {
      getNavData();
    }
  }, [])

  useEffect(()=>{
    set_isEmpty(location.query.isEmpty == 'true');
  })

  if (location.pathname == '/login') {
    return <div>{children}</div>;
  }

  return (
    <ProLayout
      layout="top"
      contentStyle={{
        margin: 0,
      }}
      menuItemRender={(item, dom) => {
        return (
          <a
            onClick={() => {
              set_emptyPageContent(item.description);
              history.push(`${item.path}${item.contentType == 4 ? `?isEmpty=true&menuId=${item.key}` : ''}` || '/');
            }}
          >
            {dom}
          </a>
        )
      }}
      menu={{

        request: async () => {
          return [
            {
              path: '/index',
              name: '欢迎进入医管平台'
            }
          ]
        },
      }}
      pageTitleRender={false}
      headerRender={() =>
        initialState && (
          <TopHoc
            navData={navData}
            currentSelectedSys={initialState.currentSelectedSys}
            openedSysLists={initialState.openedSysLists ? initialState.openedSysLists : []}
          />
        )
      }
    >
      {
        isEmpty&& (
          <div style={{ textAlign: 'center', paddingTop: 100,height:'93vh' }}>
            <h1>{emptyPageContent}</h1>
          </div>
        )
      }
      {!isEmpty&&(<div style={{ height: `calc(100vh - 48px)`, overflowY: 'scroll' }}>{children}</div>)}
    </ProLayout>
  );
}
