<script setup>
import { onLaunch, onShow, onHide } from "@dcloudio/uni-app";
import { getEvnUrl } from "@/request/base/config";
import { refreshToken } from "@/hooks/useGoLogin";

let wasOffline = false;
let isRecoveringNetwork = false;

const initAppNetworkData = async () => {
  try {
    /// 获取环境配置
    await getEvnUrl();

    /// 刷新token
    await refreshToken();
    return true;
  } catch (error) {
    console.warn("初始化网络数据失败:", error);
    return false;
  }
};

const getCurrentPageUrl = () => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];

  if (!currentPage) return "/pages/index/index";

  const route = currentPage.route || "pages/index/index";
  const options = currentPage.options || {};
  const query = Object.keys(options)
    .map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(options[key])}`)
    .join("&");

  return `/${route}${query ? `?${query}` : ""}`;
};

const reloadCurrentPage = () => {
  const url = getCurrentPageUrl();
  uni.reLaunch({
    url,
    fail: (error) => {
      console.warn("网络恢复后重载当前页面失败:", error);
    },
  });
};

const recoverAfterNetworkReady = async () => {
  if (!wasOffline || isRecoveringNetwork) return;

  isRecoveringNetwork = true;
  let recovered = false;
  try {
    recovered = await initAppNetworkData();
    if (recovered) {
      reloadCurrentPage();
    }
  } finally {
    if (recovered) {
      wasOffline = false;
    }
    isRecoveringNetwork = false;
  }
};

const checkNetworkStatus = () => {
  uni.getNetworkType({
    success: (res) => {
      if (res.networkType === "none") {
        wasOffline = true;
        return;
      }

      recoverAfterNetworkReady();
    },
  });
};

onLaunch(() => {
  uni.onNetworkStatusChange((res) => {
    if (!res.isConnected || res.networkType === "none") {
      wasOffline = true;
      return;
    }

    recoverAfterNetworkReady();
  });

  checkNetworkStatus();
  initAppNetworkData();
});

onShow(() => {
  console.log("App Show");
  if (wasOffline) {
    checkNetworkStatus();
  }
});

onHide(() => {
  console.log("App Hide");
});

</script>

<style lang="scss">
@import "@/static/fonts/iconfont.css";
@import "@/static/scss/index.scss";

/* 添加全局样式 */
page,
body,
#app {
  font-family: PingFang SC, PingFang SC;
  background-color: #f5f7fa;
  height: 100vh;
  width: 100vw;
}

/*每个页面公共css */
::-webkit-scrollbar {
  display: none;
}

@font-face {
  font-family: znicons;
  src: url("https://oss.nianxx.cn/mp/static/fonts/znicons.ttf");
}
</style>
