import Taro, { useDidHide, useReady, useUnload } from "@tarojs/taro";
import { reporter } from "@/utils";
import { SWRConfig } from "swr";
import React, { useEffect, useState } from "react";
import { userStore } from "@/store/user-store";
import { Dialog, Toast } from "@nutui/nutui-react-taro";
import { CustomTheme, ShareActionSheet } from "@/components";
import { getCurrentInstance } from "@tarojs/runtime";
import { View } from "@tarojs/components";

let startTime: number; // 记录开始时间
let endTime: number; // 记录结束时间
let map = new Map();

function getCallback() {
  return () => {
    endTime = new Date().getTime();
    const stayDuration = (endTime - startTime) / 1000; // 转换为秒数
    console.log("页面停留时间：", stayDuration);
    reporter("stay", {
      incoming: startTime,
      leaving: endTime,
      duration: stayDuration,
    }).then();

    console.log("卸载map", map);
    const appCache = JSON.stringify(Array.from(map.entries()));
    console.log("appCache", appCache);
    Taro.setStorageSync("app-cache", appCache);
  };
}

const base = (Component: React.FC) => (props: any) => {
  const router = getCurrentInstance().router;
  const currentPath = router?.path;
  const options = Taro.getLaunchOptionsSync();

  const setUser = userStore((state) => state.setUser);

  const [shareOptions, setShareOptions] = useState<any>(); // 小程序分享
  const [shareVisible, setShareVisible] = useState<boolean>(false);

  const login = async () => {
    // const { code } = await Taro.login();
    // await wxMaLogin(code);
    // await setUser();

    if (router?.path.indexOf("/pages/public/login/index") === -1) {
      // 跳转到登录页面
      Taro.reLaunch({
        url: "/pages/public/login/index",
      });
    }
  };

  useReady(() => {
    if (Taro.getStorageSync("user")) {
      setUser().then();
    } else {
      login().then();
    }

    map = new Map(JSON.parse(Taro.getStorageSync("app-cache") || "[]"));
    console.log(map);
    startTime = new Date().getTime();
    reporter("exposure", {
      incoming: startTime,
    }).then();
  });

  useUnload(getCallback());

  useDidHide(getCallback());

  useEffect(() => {
    const handler = (res) => {
      console.log(
        "设置分享类型",
        res.type,
        "设置分享页面",
        res.pagePath,
        "设置分享内容",
        res.result,
      );
      if (!res.pagePath || res.pagePath === currentPath) {
        setShareOptions(res.result);
        setShareVisible(true);
      }
    };

    Taro.eventCenter.on("setShareOptions", handler);

    return () => {
      Taro.eventCenter.off("setShareOptions", handler);
    };
  }, []);

  return (
    <SWRConfig value={{ provider: () => map, revalidateOnFocus: false }}>
      <CustomTheme>
        <View className={"flex min-h-screen w-screen flex-col bg-neutral-100"}>
          <Component
            {...props}
            shareOptions={shareOptions}
            router={router}
            options={options}
          />
          <Toast id="toast" />
          <Dialog id="dialog" />
          <ShareActionSheet
            visible={shareVisible}
            setVisible={setShareVisible}
            onCancel={() => setShareVisible(false)}
            callback={shareOptions?.callback}
          />
        </View>
      </CustomTheme>
    </SWRConfig>
  );
};

export default base;
