import React, { createContext, useCallback, useState, useEffect } from 'react';
import { IRouteComponentProps } from 'umi';
import pathToRegexp from 'path-to-regexp'
import {history as router} from 'umi';
import {Provider} from 'mobx-react'
import stores from '../../../store'
import lodash from 'lodash';

export type dooringContextType = 'h5' | 'pc';

export interface IdooringContextType {
  theme: dooringContextType;
  setTheme: Function;
  addImageLoadingNum: Function;
  removeImageLoadingNum: Function;
  getImageLoadingNum: Function;
}

export const dooringContext = createContext<IdooringContextType>({
  theme: 'h5',
  setTheme: (e) => {},
  addImageLoadingNum: () => {},
  removeImageLoadingNum: () => {},
  getImageLoadingNum: () => {}
});
export default function Layout({ children }: IRouteComponentProps) {
  const [state, setState] = useState<dooringContextType>('h5');
  let [imageLoadingNum, setImageLoadingNum] = useState<Array<string>>([]);
  useEffect(() => {
    let match = pathToRegexp('/editorPc/:id').exec(router.location.pathname);
    let match3 = pathToRegexp('/editorTemplatePc/:id').exec(router.location.pathname);
    if (match || match3) {
      setState('pc');
    }
    let match2 = pathToRegexp('/editorWap/:id').exec(router.location.pathname);
    let match4 = pathToRegexp('/editorTemplateWap/:id').exec(router.location.pathname);
    if (match2 || match4) {
      setState('h5');
    }
  }, [window.location.pathname])

  return (
    <dooringContext.Provider
      value={{
        theme: state,
        setTheme: setState,
        addImageLoadingNum: (id) => {
          if (imageLoadingNum.indexOf(id) === -1) {
            imageLoadingNum.push(id)
            setImageLoadingNum(imageLoadingNum)
          }
        },
        removeImageLoadingNum: (id) => {
          const index = imageLoadingNum.indexOf(id)
          if (index !== -1) {
            imageLoadingNum.splice(index, 1)
            setImageLoadingNum(imageLoadingNum)
          }
        },
        getImageLoadingNum: () => {
          return imageLoadingNum.length
        },
      }}
    >
      <div style={{ height: '100%', width: '100%', overflow: 'hidden' }}>
        <Provider {...stores}>
         {children}
       </Provider>
      </div>
    </dooringContext.Provider>
  );
}
