import { userStore } from "@/store/user-store";
import { useShallow } from "zustand/react/shallow";
import base from "@/hocs/base";
import { Loading, Overlay } from "@nutui/nutui-react-taro";
import { View } from "@tarojs/components";
import React, { useEffect, useState } from "react";
import Taro from "@tarojs/taro";
import { buildParams } from "@/utils";
import { globalStore } from "@/store/global-store";

const hocAuth = (
  Component: any,
  skeleton?: React.ReactNode,
  location?: boolean,
) =>
  base((props: any) => {
    const { options, router } = props;
    const user = userStore(useShallow((state) => state.user));
    const { userRoleVO, setUserRoleVO, loading, setLoading } = globalStore(
      (state: any) => state,
    );

    const [longitude, setLongitude] = useState<number>();
    const [latitude, setLatitude] = useState<number>();

    // 控制是否已初始化
    const [isInitialized, setIsInitialized] = useState(false);

    useEffect(() => {
      setUserRoleVO(Taro.getStorageSync("userRoleVO"));
    }, []);

    useEffect(() => {
      if (location) {
        Taro.getLocation({
          success: (res) => {
            console.log("res", res);
            setLongitude(res.longitude);
            setLatitude(res.latitude);
          },
        });
      }
    }, [location]);

    useEffect(() => {
      const screen = options?.query?.screen;

      if (screen === "homepage" && router.path !== "/pages/main/index/index") {
        let shareToPath =
          options?.query?.shareToPath || "/pages/main/index/index";
        Taro.reLaunch({
          url: decodeURIComponent(shareToPath),
        });
      }
    }, []);

    if (process.env.TARO_ENV === "weapp") {
      useEffect(() => {
        if (!user) {
          return;
        }

        Taro.onUserCaptureScreen(function () {
          const query = buildParams({
            ...router?.params,
            from: "screenshot",
            userId: user.userId,
          });

          return {
            query: query, // 通过截屏图片打开小程序的query参数
            // promise: new Promise((resolve) => {
            //   // 通过promise延时传递小程序的query参数
            //   setTimeout(() => {
            //     resolve({
            //       query: query,
            //     });
            //   }, 1000); // 在1秒内对query进行解析
            // }),
          };
        });

        return () => {
          Taro.offUserCaptureScreen(function (res) {
            console.log("取消截屏事件", res);
          });
        };
      }, [user]);
    }

    if (!user || !userRoleVO) {
      if (skeleton) {
        return skeleton;
      }

      return (
        <View className={"flex h-screen w-full items-center justify-center"}>
          <Loading />
        </View>
      );
    }

    return (
      <>
        <Overlay visible={loading}>
          <View
            className="wrapper"
            style={{
              display: "flex",
              height: "100%",
              alignItems: "center",
              justifyContent: "center",
            }}
          >
            <Loading direction="vertical">加载中</Loading>
          </View>
        </Overlay>
        <Component
          {...props}
          longitude={longitude}
          latitude={latitude}
          user={user}
          userRoleVO={userRoleVO}
          isInitialized={isInitialized}
          setIsInitialized={setIsInitialized}
          setLoading={setLoading}
        />
      </>
    );
  });

export default hocAuth;
