import { useEffect, useState } from "react";
import { BrowserRouter, Route, Routes, Outlet } from "react-router-dom";
import Layout from "./container";
import { basicReducer, apiRequest } from "@u";
import { createStore, createSlice } from "@peace/react_client";
import { Provider } from "react-redux";

export default function index (props) {
   const [outerRoutes, setOuterRoutes] = useState([]);
   const [innerRoutes, setInnerRoutes] = useState([]);
   const [routerNav, setRouterNav] = useState([]); //存储内部路由，生成面包屑
   const [store, setStore] = useState(null);

   const flatRoute = route => {
      return route.map(item => {
         return (
            <Route
               key={item.key}
               path={item?.path}
               element={item.component ? <item.component /> : <Outlet />}
            >
               {item.children && flatRoute(item.children)}
            </Route>
         );
      });
   };

   useEffect(() => {
      const reduxEle = basicReducer(props.sections, apiRequest);

      const global = createSlice({
         name: "global",
         initialState: {
            actions: reduxEle.requestMap, // 所有 section 定义的接口请求方法
            contentWidth: -1,
            contentHeight: -1,
         },
         reducers: {
            setContentSize: (state, { payload }) => {
               state.contentWidth = payload.width
               state.contentHeight = payload.height
            },
            setActions: (state, { payload }) => {
               state.actions = payload;
            },
         },
      });
      reduxEle.reducerMap["global"] = global.reducer;

      const store = createStore(reduxEle.reducerMap)

      setStore(store);
      store.dispatch(
         global.actions.setActions(
            Object.assign({}, reduxEle.requestMap, global.actions)
         )
      )
   }, [props.sections]);

   useEffect(() => {
      let outerRoutes = [];
      let innerRoutes = [];
      props.sections.forEach(item => {
         if (item.route.type === "outer") {
            outerRoutes.push(item.route.route);
         } else {
            innerRoutes.push(item.route.route);
         }
      });
      setOuterRoutes(flatRoute(outerRoutes));
      setInnerRoutes(flatRoute(innerRoutes));
      setRouterNav(innerRoutes);
   }, [props.sections]);

   return store ? (
      <Provider store={store}>
         <BrowserRouter>
            <Routes>
               {outerRoutes}
               <Route
                  path="/"
                  element={
                     <Layout routerNav={routerNav} />
                  }
               >
                  {innerRoutes}
               </Route>
            </Routes>
         </BrowserRouter>
      </Provider>
   ) : null;
}
