import React, { useEffect, useState } from 'react';
import { inject, observer } from 'mobx-react';
import { RouteComponentProps, useParams } from 'react-router-dom';
import { IMainStore } from '../stores/index';
import AMisRenderer from '../components/AMisRenderer';
import loadPageByPath from '../utils/loadPageByPath';

export default inject('store')(
    observer(function ({
        store,
    }: { store: IMainStore } & RouteComponentProps<{
        id: string;
    }>) {
        let { centre_id, id } = useParams<any>();
        const [schema, setSchema] = useState({
            type: 'page',
            body: {
                type: 'spinner',
            },
        });

        useEffect(() => {
            setSchema({
                type: 'page',
                body: {
                    type: 'spinner',
                },
            });
            let nav: any = store.flat_navigations
                .filter((x: any) => x.path !== null)
                .find((x: any) => x.id.toString() === id);
            let pagePath = nav ? nav.schema_path : '';
            loadPageByPath(pagePath).then((page: any) => {
                setSchema(page.schema);
            });
        }, [id]);

        // TODO: schema中的api有时没自动加载
        return <AMisRenderer schema={schema} centre_id={centre_id} />;
    })
);
