import React, { useRef } 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 { user, duty, current: currentUser } = useModel("user");
  const containerClass = `${laySty["page-conatiner"]} ${
    tabBar ? laySty["with-tabbar"] : ""
  } ${className}`;

  const userRef = useRef();
  // const personRef = useRef();

  // React.useEffect(() => {
  //   if (!userRef.current && !personRef.current) {
  //     userRef.current = person;
  //     personRef.current = user;
  //   }
  //   if (!user) {
  //     userRef.current = null;
  //   }
  //   console.log("personRef******************");
  //   console.log(personRef.current);
  //   console.log("userRef******************");
  //   console.log(userRef.current);
  //   console.log(personRef.current && !userRef.current);

  //   if (personRef.current && !userRef.current) {
  //     const currentPage = Taro.getCurrentPages().slice().pop();
  //     console.log(currentPage.route);
  //     if ("pages/login/index" !== currentPage.route) {
  //       Taro.navigateTo({
  //         url: "/pages/login/index",
  //       });
  //     }
  //   }
  // }, [person, user]);

  React.useEffect(() => {
    console.log("personRef******************");
    // console.log(person);
    console.log("userRef******************");
    console.log(user);
    console.log(!user);
    // if (!userRef.current&&user) {
    //   userRef.current = user;
    // }

    if (!user) {
      currentUser().catch(() => {
        const currentPage = Taro.getCurrentPages().slice().pop();
        if (!currentPage.route.includes("pages/login/index")) {
          Taro.navigateTo({
            url: "/pages/login/index",
          });
        }
      })
    }
  }, [user]);

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

  return (
    <View className={laySty["page-wrapper"]}>
      <Notify id="vanNotify" />
      <Dialog id="vanDialog" />
      <NavLoading loading={loading} />
      <View className={containerClass} style={style}>
        {/* {!user && (
          <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>
  );
};
