<!--
 * @Author: qinzhenpen qzp1807@126.com
 * @Date: 2024-07-15 15:44:46
 * @LastEditors: qinzhenpen qzp1807@126.com
 * @LastEditTime: 2025-05-21 18:07:48
 * @FilePath: \vue3\src\layout\components\AppMain.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <section :class="[role == 4 ? 'app-main' : 'app-main2']">
    <router-view v-slot="{ Component, route }">
      <transition name="fade-transform" mode="out-in" :key="route.path">
        <keep-alive :include="tagsViewStore.cachedViews">
          <component v-if="!route.meta.link" :is="Component" :key="route.path" />
        </keep-alive>
      </transition>
    </router-view>
    <iframe-toggle />
  </section>
</template>
<script setup>
import * as indexApi from "@/api/index";
const { proxy } = getCurrentInstance();
import { dynamicRoutes } from "@/router";
import iframeToggle from "./IframeToggle/index";
import useTagsViewStore from "@/store/modules/tagsView";
import { getUserInfo } from "@/utils/auth";
import useUserStore from "@/store/modules/user";
const userStore = useUserStore();
const tagsViewStore = useTagsViewStore();
const route = useRoute();
const router = useRouter();
const role = ref(JSON.parse(getUserInfo()).roleId);
const module = ["市场需求挖掘", "产品规划", "产品投放测试", "供应渠道管理", "产品评估与考核"];
// 全局监听路由进入和离开
onBeforeRouteUpdate((to, from) => {
  tagsViewStore.addVisitedView(to);
  tagsViewStore.addCachedView(to);
});
function findParentByTitle(routes, targetTitle) {
  for (const route of routes) {
    if (route.children && route.children.length) {
      for (const child of route.children) {
        // 如果 child 还有 children，则递归查找
        if (child.children && child.children.length) {
          const found = findParentByTitle([child], targetTitle);
          if (found) return found;
        } else if (child.meta && child.meta.title === targetTitle) {
          // 找到了目标 title，返回它的父级 route
          return route;
        }
      }
    }
  }
  return null;
}
function useTimeRecorder() {
  const startTime = ref(null);
  const start = () => {
    startTime.value = new Date();
    console.log("计时开始");
  };
  const end = () => {
    if (!startTime.value) {
      console.warn("请先调用 start() 方法！");
      return null;
    }
    const durationMs = new Date() - startTime.value; // 毫秒差值
    const durationMinutes = (durationMs / (1000 * 60)).toFixed(2); // 转为分钟，保留2位小数
    console.log(`计时结束，耗时: ${durationMinutes} 秒`);
    return parseFloat(durationMinutes); // 返回字符串（如 "3.14"）
  };
  const reset = () => {
    startTime.value = null;
    console.log("计时器已重置");
  };
  return { start, end, reset };
}
const { start, end, reset } = useTimeRecorder();
router.beforeEach((to, from, next) => {
  let routess = proxy.$cache.session.getJSON("disabledTitles");
  // 获取当前和上一个模块
  const toModule = findParentByTitle(dynamicRoutes, to.meta.title)?.meta?.title;
  const fromModule = findParentByTitle(dynamicRoutes, from.meta.title)?.meta?.title;
  // 离开模块时结束计时
  if (module.includes(fromModule)) {
    const timeData = end();
    if (timeData) {
      // 发送学习时间到后端
      indexApi
        .updateStudyTime({
          time: Number(timeData),
          projectName: fromModule,
          userId: userStore.userInfo.userId,
        })
        .then((res) => {});
    }
  }
  // 进入新模块时开始计时
  if (module.includes(toModule)) {
    //  判断是否有禁用的模块
    if (routess.includes(to.meta.title)) {
      proxy.$modal.msgError("该模块示暂未开放");
      return;
    }
    start(toModule);
    if (module.includes(fromModule)) {
      // 更新访问次数
      indexApi
        .updateVisitCount({
          classId: userStore.userInfo.classId,
          projectName: fromModule,
          schoolId: userStore.userInfo.schoolId,
          userId: userStore.userInfo.userId,
        })
        .then((res) => {});
    }
  }
  next();
});
</script>
<style lang="scss" scoped>
.app-main {
  /* 50= navbar  50  */
  min-height: calc(100vh - 50px);
  width: 100%;
  position: relative;
  overflow: hidden;
  background: url("@/assets/images/背景.webp") no-repeat;
  background-size: 100% 100%;
}
.app-main2 {
  min-height: calc(100vh - 50px);
  width: 100%;
  position: relative;
  overflow: hidden;
  background: url("@/assets/images/背景f6.png") no-repeat;
  background-size: 100% 100%;
}
.fixed-header + .app-main {
  padding-top: 50px;
}
.hasTagsView {
  .app-main {
    /* 84 = navbar + tags-view = 50 + 34 */
    min-height: calc(100vh - 50px);
  }
  .fixed-header + .app-main {
    padding-top: 84px;
  }
}
</style>
<style lang="scss">
// fix css style bug in open el-dialog
.el-popup-parent--hidden {
  .fixed-header {
    padding-right: 6px;
  }
}

::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-track {
  background-color: #f1f1f1;
}

::-webkit-scrollbar-thumb {
  background-color: #c0c0c0;
  border-radius: 3px;
}
</style>
