<template>
  <div id="home-screen" class="main-bg flex flex-col scrollbar-hide h-screen overflow-y-auto">
    <header class="relative flex items-center">
      <SvgComponent :content="headerSvg" class="w-full h-[98px]" />
      <SvgComponent :content="titleSvg" class="w-[50%] h-[69px] absolute top-0 left-50% translate-x-[-50%]" />
      <div class="absolute top-[25%] right-[24px] translate-y-[-25%] z-1 flex items-center justify-center w-max">
        <DigitalWatch class="" />
        <div class="text-[#45A2FF] flex items-center ml-[10px]">
          <SvgIcon name="avatar" class="w-[16px] h-[16px]" />
          <div class="mx-[5px]">{{ username }}</div>
          <SvgIcon name="logout" class="w-[16px] h-[16px] cursor-pointer" @click="handleLogout" />
        </div>
      </div>
    </header>
    <div class="flex items-center justify-end pr-[24px] cursor-pointer mb-[13px]" @click="updateAllData">
      <SvgIcon name="circle" class="text-[14px] text-[#C0EEFF] transition-all duration-300" />
      <div class="text-[#C0EEFF] text-[12px] ml-[5px]">数据更新时间:{{ formatDatetime(updateTime) }}</div>
    </div>

    <div class="grid grid-rows-[210px_358px_320px] gap-y-5 w-full min-h-[928px] gap-[20px] flex-1 overflow-auto md:overflow-hidden mb-[27px]">
      <div class="flex items-center px-[24px] justify-start">
        <PaymentTotal class="flex-1" />
        <TodayPayment class="ml-[20px] flex-1" />
        <GainTotal class="ml-[20px] flex-1" />
        <GainToday class="ml-[20px] flex-1" />
        <LossStatic class="ml-[20px] flex-1" />
      </div>
      <div class="grid grid-cols-2 items-center px-[24px] gap-x-[20px]">
        <OperatingTrends class="flex-1" />
        <AskSection class="flex-1" />
      </div>
      <div class="grid grid-cols-6 gap-[20px] items-center px-[24px]">
        <StudentSource class="" />
        <OnLineStatus class="" />
        <OfflineStatus class="" />
        <SixStatistics class="" />
        <ChargingRanking class="" />
        <WinCustomer class="" />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import SvgComponent from "@/components/SvgComponent.vue";
  import SvgIcon from "@/components/svg-icon/SvgIcon.vue";

  import DigitalWatch from "@/components/watch/DigitalWatch.vue";

  import { defineAsyncComponent } from "vue";
  import autofit from "autofit.js";
  import { useFetchAllData } from "./composables/useFetchData";
  import { runImmediatelyAll, updateTime } from "@/composables/usePolling";
  import { formatDatetime } from "@/utils/date";
  import { getUserInfoUrl, getLogoutUrl } from "@/api/fetchUrl";
  import { getRequest, postRequest } from "@/api/customFetch";
  import { useUserStore } from "@/store/user";
  import { asyncComponentConfig } from "@/composables/useLazyLoad";
  import { usePlatformType } from "@/utils/device";

  const PaymentTotal = defineAsyncComponent({
    ...asyncComponentConfig,
    loader: () => import("@/views/components/PaymentTotal.vue"),
  });
  const TodayPayment = defineAsyncComponent({
    ...asyncComponentConfig,
    loader: () => import("@/views/components/TodayPayment.vue"),
  });
  const GainTotal = defineAsyncComponent({
    ...asyncComponentConfig,
    loader: () => import("@/views/components/GainTotal.vue"),
  });
  const GainToday = defineAsyncComponent({
    ...asyncComponentConfig,
    loader: () => import("@/views/components/GainToday.vue"),
  });
  const LossStatic = defineAsyncComponent({
    ...asyncComponentConfig,
    loader: () => import("@/views/components/LossStatic.vue"),
  });
  const OperatingTrends = defineAsyncComponent({
    ...asyncComponentConfig,
    loader: () => import("@/views/components/OperatingTrends.vue"),
  });
  const AskSection = defineAsyncComponent({
    ...asyncComponentConfig,
    loader: () => import("@/views/components/AskSection.vue"),
  });
  const StudentSource = defineAsyncComponent({
    ...asyncComponentConfig,
    loader: () => import("@/views/components/StudentSource.vue"),
  });
  const OnLineStatus = defineAsyncComponent({
    ...asyncComponentConfig,
    loader: () => import("@/views/components/OnlineStatus.vue"),
  });
  const OfflineStatus = defineAsyncComponent({
    ...asyncComponentConfig,
    loader: () => import("@/views/components/OfflineStatus.vue"),
  });
  const SixStatistics = defineAsyncComponent({
    ...asyncComponentConfig,
    loader: () => import("@/views/components/SixStatistics.vue"),
  });
  const ChargingRanking = defineAsyncComponent({
    ...asyncComponentConfig,
    loader: () => import("./components/ChargingRanking.vue"),
  });
  const WinCustomer = defineAsyncComponent({
    ...asyncComponentConfig,
    loader: () => import("./components/WinCustomer.vue"),
  });

  const router = useRouter();
  const { isMobile } = usePlatformType();
  let hasAutofitInit = false;

  const headerSvg = ref("");
  const headerBackgroundSvg = async () => {
    const { default: svg } = await import("/src/assets/svg-img/header-background.svg?raw");
    headerSvg.value = svg;
  };

  const titleSvg = ref("");
  const headerTitleSvg = async () => {
    const { default: svg } = await import("/src/assets/svg-img/header-title.svg?raw");
    titleSvg.value = svg;
  };

  useFetchAllData();
  const updateAllData = () => {
    runImmediatelyAll();
  };

  const username = ref("");

  const userStore = useUserStore();
  const getUserInfo = () => {
    const accessToken = userStore.getAccessToken;
    getRequest(getUserInfoUrl(), {}, { headers: { Authorization: `Bearer ${accessToken}` } }).then((resp) => {
      if (resp.code === 200) {
        username.value = (resp.result as { account: string }).account;
      } else if (resp.code === 401) {
        router.push("/login");
      }
    });
  };

  const handleLogout = () => {
    const accessToken = userStore.getAccessToken;
    postRequest(getLogoutUrl(), {}, { headers: { "content-type": "application/json; charset=utf-8", Authorization: `Bearer ${accessToken}` } }).then((resp) => {
      if (resp.code === 200) {
        userStore.setAccessToken("");
        userStore.setRefreshToken("");
      }
      router.push("/login");
    });
  };

  onBeforeMount(() => {
    headerBackgroundSvg();
    headerTitleSvg();
    getUserInfo();
    // 跳转到首页
    if (isMobile) {
      router.push("/app");
    }
  });

  onMounted(() => {
    if (isMobile) {
      return;
    }
    autofit.init({
      el: "#home-screen",
      dw: 1920,
      dh: 1080,
      resize: true,
      allowScroll: false,
    });
    hasAutofitInit = true;
  });

  onBeforeUnmount(() => {
    if (hasAutofitInit && autofit.isAutofitRunning) {
      autofit.off("#home-screen");
    }
  });
</script>

<style scoped lang="scss">
  .main-bg {
    background-image: url("/images/main-bg.png");
    background-size: 100% 100%;
    background-position: center;
    background-repeat: no-repeat;
  }
</style>
