import React, { useEffect, useState, useRef, useContext } from "react";
import { Breadcrumb, Layout, theme } from "antd";
import { Outlet, useLocation } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import { ErrorBoundary } from '@comps'

const { Content } = Layout;

export default function content (props) {
   const { token: { colorBgContainer, borderRadiusLG }, } = theme.useToken();
   const actions = useSelector(state => state.global.actions);
   const dispatch = useDispatch();
   const location = useLocation();
   const [breadcrumbItems, setBreadcrumbItems] = useState([]);
   const contentRef = useRef();

   useEffect(() => {
      /* 监听 content 容器大小变化 */
      const resizeObserver = new ResizeObserver(entries => {
         for (const entry of entries) { // 因为只监听一个元素(contentRef)，所以不做判断
            const { width, height } = entry.contentRect;
            dispatch(actions?.setContentSize({ width, height }))
         }
      });
      resizeObserver.observe(contentRef.current);
   }, [])

   useEffect(() => {
      /** 组织面包屑 */
      let { pathname = '' } = location
      if (pathname.startsWith('/')) {
         pathname = pathname.substring(1)
      }
      let breadcrumbList = []
      if (pathname) {
         let pathnamArr = pathname.split('/')
         let nav_ = props.routerNav;

         for (let kp of pathnamArr) {
            for (let nv of nav_) {
               if (kp == nv?.path) {
                  breadcrumbList.push({ title: nv.label, patch: nv.path });
                  nav_ = nv.children || [];
                  break
               }
            }
         }
      }
      setBreadcrumbItems(breadcrumbList ?? []);
   }, [location.pathname]);

   return (
      <>
         <Content
            ref={contentRef}
            style={{ margin: "0 12px 0 0", position: 'relative' }}
         >
            <Breadcrumb
               style={{ margin: "8px 0", minHeight: 22 }}
               items={breadcrumbItems}
               onClick={e => { }}
            />
            <div style={{
               paddingRight: 6,
               height: 'calc(100% - 50px)',
               background: colorBgContainer,
               borderRadius: borderRadiusLG,
               overflow: 'hidden',
            }}>
               <div
                  style={{
                     padding: '12px 4px 12px 12px',
                     minHeight: 360,
                     height: '100%',
                     overflow: 'auto',
                  }}
               >
                  <ErrorBoundary>
                     <Outlet />
                  </ErrorBoundary>
               </div>
            </div>
         </Content>
         {/* <Footer
				style={{
					textAlign: "center",
				}}
			>
				江西飞尚科技 ©{new Date().getFullYear()}
			</Footer> */}
      </>
   );
}
