import React from 'react';
import Taro from '@tarojs/taro';
import { View, Image } from '@tarojs/components';
import { useModel } from '@/store';
import { Loading, Notify, Dialog } from '@antmjs/vantui';
import NavLoading from '@/components/NavLoading';
import Auth from '@/components/Auth';
import TabBar from './TabBar';
import laySty from './layout.module.less';

export default (props) => {
  const { className, style, roles, tabBar = false, loading } = props;

  const { person, user, duty } = useModel('user');
  const { setPageCtx } = useModel('page');
  const [pageShow, setPageShow] = React.useState(false);
  const PageContext = React.useMemo(() => {
    const ctx = React.createContext({show: false});
    setPageCtx(ctx);

    return ctx;
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const containerClass = `${laySty['page-conatiner']} ${tabBar ? laySty['with-tabbar'] : ''} ${className}`;

  React.useEffect(() => {
    if (person && !user) {
      const currentPage = Taro.getCurrentPages().slice().pop();
      if ('pages/login/index' !== currentPage.route) {
        Taro.navigateTo({
          url: '/pages/login/index',
        })
      }
    }
  }, [person, user]);

  Taro.useShareAppMessage(() => {
    return {
      title: '文明霍山'
    };
  });

  Taro.useDidShow(() => {
    // useDidShow 比 React Hook 要早
    // 所以使用 nextTick
    Taro.nextTick(() => {
      setPageShow(true);
    });
  });

  Taro.useDidHide(() => {
    Taro.nextTick(() => {
      setPageShow(false);
    });
  })

  return (
    <PageContext.Provider value={{ show: pageShow }}>
      <View className={laySty['page-wrapper']}>
        <Notify id="vanNotify" />
        <Dialog id="vanDialog" />
        <NavLoading loading={loading} />
        <View className={containerClass} style={style}>
          {
            !person && (
              <View className={laySty.loading}>
                <Loading size="32px" vertical>
                  加载中...
                </Loading>
              </View>
            )
          }
          <Auth roles={roles}>
            {props.children}
          </Auth>

          {
            !tabBar && (
              <View className={laySty['pdm-space']}></View>
            )
          }
        </View>
        {
          tabBar && <TabBar className={laySty['page-tabbar']} active={tabBar} duty={duty} />
        }
      </View>
    </PageContext.Provider>
  )
}
