import Vue from "vue";
import Router from "vue-router";
import store from '../store'
Vue.use(Router);

const originalPush = Router.prototype.push;
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => err);
};
// 其他路由
let constantRoutes = [
  {
    path: "/index",
    component: () => import("@/views/login/login"),
    meta: {
      title: "otherLogin",
    },
  },
  {
    path: "/",
    redirect: "/index"//redirect: "/studentAnalysisReport"
  },
];
// 学生端分析报告
let studentAnalysisReport = {
  path: "/studentAnalysisReport",
  redirect: "/studentAnalysisReport/list",
  component: () => import("@/views/analysisReport/index"),
  children: [
    {
      path: "/studentAnalysisReport/list", // 报告列表
      meta: {
        title: "分析报告",
      },
      component: () => import("@/views/analysisReport/studentPage/list/mainPage"),
    },
    {
      name: "reportDetails",
      path: "/studentAnalysisReport/reportDetails",
      component: () => import("@/views/analysisReport/studentPage/mainPage"),
      children: [
        {
          path: "scrolReport",
          component: () =>
            import("@/views/analysisReport/studentPage/scrolReport/transcript"),
          meta: {
            title: "学生分析",
          },
        }
      ],
    },
  ],
};
const createRouter = () =>
  new Router({
    mode: "hash",
    routes: [
      ...constantRoutes,
      studentAnalysisReport
    ],
    scrollBehavior(to, from, savedPosition) {
      if (savedPosition) {
        return savedPosition;
      } else {
        return {
          x: 0,
          y: 0,
        };//路由切换时，滚动条回到顶部
      }
    },
  });
// 添加统计分析脚本的函数
function addAnalyticsScript() {
  
  // 移除已存在的统计脚本
  let  existingScript = document.getElementById('_bxtj');
  // console.log('移除已存在的统计脚本...',existingScript);
  while  (existingScript) {
    existingScript.remove();
    existingScript = document.getElementById('_bxtj');
  }
   // 移除已存在的统计脚本
  let  existingScriptFrame= document.getElementById('_bxtjiframe');
  // console.log('移除已存在的统计脚本...',existingScriptFrame);
  while (existingScriptFrame) {
    existingScriptFrame.remove();
    existingScriptFrame = document.getElementById('_bxtjiframe');
  }
  console.log('添加统计分析脚本...');
  // 等待DOM加载完成
  setTimeout(() => {
    var _s = document.createElement('script');
    _s.setAttribute('type','text/javascript');
    _s.setAttribute('id','_bxtj');
    _s.setAttribute('async',true);
    
    // 获取当前用户信息
    const userInfo = store.state.user.userInfo || {};
    const currentUser = userInfo.loginName || ''; // 当前用户名
    const subSiteName = userInfo.schoolName || '';
    const mySiteId = localStorage.getItem("user_schoolWebSiteId") || ''; // 你的站点ID
    console.log("当前学校站点id",userInfo, mySiteId);
    if(mySiteId !='') {
      // 构建URL（按照原始代码格式）
      let src = `https://bjedures.bjedu.cn/bjjw_logdb/bxlog.js?user=${currentUser}&id=${mySiteId}`;
      if (subSiteName) {
        src += `&subSiteName=${encodeURIComponent(subSiteName)}`;
      }
      _s.setAttribute('src', src);
      var body = document.getElementsByTagName('body');
      body[0].appendChild(_s);
      console.log('统计分析脚本已添加到body中。');
    }
  }, 1000);//1秒后添加
}
let router = createRouter();
router.beforeEach((to, from, next) => {
  if (to.meta.title) {
    document.title = "慧教研-" + to.meta.title;
  }
  next();
});
// 路由后置守卫：添加统计脚本
router.afterEach(() => {
  // 添加统计分析脚本
  addAnalyticsScript()
});

export default router;
