import {
  createRouter,
  createWebHistory,
  RouteRecordRaw,
  createWebHashHistory,
} from "vue-router";
import store from "@/store";
import { Https } from "@/tool/https";
import { getCookie, setCookie } from "@/tool/cookie";

const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    // redirect重定向
    meta: { enter: "all" },
    redirect: "/Square",
    // redirect: "/upgrade"
  },
  {
    path: "/login",
    name: "login",
    meta: { enter: "all" },
    component: () => import("@/views/Login.vue"),
  },
  {
    path: "/canvasExample",
    name: "canvasExample",
    meta: { enter: "all" },
    component: () => import("@/component/Canvas/canvasExample.vue"),
  },

  {
    path: "/schoolLogin",
    name: "schoolLogin",
    meta: { enter: "all" },
    component: () => import("@/views/Login.vue"), // 使用通用登录组件
  },
  {
    path: "/enterpriseLogin",
    name: "enterpriseLogin",
    meta: { enter: "all" },
    component: () => import("@/views/Login.vue"), // 使用通用登录组件
  },
  {
    path: "/test",
    name: "test1",
    meta: { enter: "all" },
    component: () => import("@/views/test.vue"),
  },
  {
    path: "/register",
    name: "register",
    meta: { enter: "all" },
    component: () => import("@/views/Register.vue"),
  },
  {
    path: "/upgrade",
    name: "upgrade",
    meta: { enter: "all" },
    component: () => import("@/views/Upgrade.vue"),
  },
  {
    path: "/home",
    name: "home",
    meta: { enter: "all" },
    component: () => import("@/views/HomeMain.vue"),
    children: [
      {
        path: "tools",
        name: "tools",
        meta: { enter: "all",cache:true },
        component: () => import("@/views/HomeView/Tools.vue"),
      },
    //   {
    //     path: "homePage",
    //     name: "homePage",
    //     meta: { enter: "all" },
    //     component: () => import("@/views/HomeView/HomeView.vue"),
    //   },
      {
        path: "library",
        name: "library",
        meta: { enter: "all" },
        component: () => import("@/views/HomeView/library.vue"),
      },
      {
        path: "history",
        name: "history",
        meta: { enter: "all" },
        component: () => import("@/views/HomeView/history.vue"),
      },
	//   {
    //     path: "history/:type/:id",
    //     name: "toolsPage",
    //     meta: { enter: "all",cache:true },
    //     component: () => import("@/views/HomeView/Tools.vue"),
    //   },
	  {
        path: "history/:id",
        name: "designPage",
        meta: { enter: "all",cache:true },
        component: () => import("@/component/home/design/index.vue"),
      },
      {
        path: "works",
        name: "works",
        meta: { enter: "all" },
        component: () => import("@/views/HomeView/Works.vue"),
      },
      {
        path: "events",
        name: "events",
        meta: { enter: "all" },
        component: () => import("@/views/HomeView/Events.vue"),
      },
      {
        path: "cloud",
        name: "cloud",
        meta: { enter: "all" },
        component: () => import("@/views/HomeView/cloudGeneration.vue"),
      },
      {
        path: "eventsDetail",
        name: "eventsDetail",
        meta: { enter: "all" },
        component: () => import("@/component/Events/eventsDetail.vue"),
      },
      {
        path: "account",
        name: "account",
        meta: { enter: "all" },
        component: () => import("@/component/Account/account.vue"),
        children: [
          {
            path: "",
            name: "accountChil",
            meta: { enter: "all" },
            redirect: "/home/account/frontPage",
          },
          {
            path: "frontPage",
            name: "frontPage",
            meta: { enter: "all" },
            component: () => import("@/component/Account/frontPage.vue"),
          },
          {
            path: "accountMessage",
            name: "accountMessage",
            meta: { enter: "all" },
            component: () => import("@/component/Account/accountMessage.vue"),
          },
          {
            path: "accountFollowFans",
            name: "accountFollowFans",
            meta: { enter: "all" },
            component: () =>
              import("@/component/Account/accountFollowFans.vue"),
          },
        ],
      },
      {
        path: "otherUsers",
        name: "otherUsers",
        meta: { enter: "all" },
        component: () => import("@/component/Account/otherUsers.vue"),
      },
    ],
  },
  {
    path: "/Square",
    name: "HomeRecommend",
    meta: { enter: "all" },
    component: () => import("@/views/HomeRecommend.vue"),
  },
  {
    path: "/administrator",
    name: "administrator",
    meta: { enter: 3 },
    component: () => import("@/views/Administrator.vue"),
    children: [
      {
        path: "allUser",
        name: "allUser",
        meta: { enter: 3 },
        component: () => import("@/component/Administrator/allUser.vue"),
      },
      {
        path: "coupons",
        name: "coupons",
        meta: { enter: 3 },
        component: () => import("@/component/Administrator/coupons/index.vue"),
      },
      {
        path: "testClickData",
        name: "testClickData",
        meta: { enter: 3 },
        component: () => import("@/component/Administrator/TestClickData.vue"),
      },
      {
        path: "trialApproval",
        name: "trialApproval",
        meta: { enter: 3 },
        component: () => import("@/component/Administrator/trialApproval.vue"),
      },
      {
        path: "questionnaire",
        name: "questionnaire",
        meta: { enter: 3 },
        component: () => import("@/component/Administrator/questionnaire.vue"),
      },
      {
        path: "recentActiveChart",
        name: "recentActiveChart",
        meta: { enter: 3 },
        component: () =>
          import("@/component/Administrator/recentActiveChart.vue"),
      },
      {
        path: "recentActiveUser",
        name: "recentActiveUser",
        meta: { enter: 3 },
        component: () =>
          import("@/component/Administrator/recentActiveUser.vue"),
      },
      {
        path: "recentActiveUserChart",
        name: "recentActiveUserChart",
        meta: { enter: 3 },
        component: () =>
          import("@/component/Administrator/recentActiveUserChart.vue"),
      },
      {
        path: "recentNewUser",
        name: "recentNewUser",
        meta: { enter: 3 },
        component: () => import("@/component/Administrator/recentNewUser.vue"),
      },
      {
        path: "recentNewUserChart",
        name: "recentNewUserChart",
        meta: { enter: 3 },
        component: () =>
          import("@/component/Administrator/recentNewUserChart.vue"),
      },
      {
        path: "trialUserCountry",
        name: "trialUserCountry",
        meta: { enter: 3 },
        component: () =>
          import("@/component/Administrator/trialUserCountry.vue"),
      },
      {
        path: "trialUserConversionRateChart",
        name: "trialUserConversionRateChart",
        meta: { enter: 3 },
        component: () =>
          import("@/component/Administrator/trialUserConversionRateChart.vue"),
      },
      {
        path: "trialAllUser",
        name: "trialAllUser",
        meta: { enter: 3 },
        component: () => import("@/component/Administrator/trialAllUser.vue"),
      },
      {
        path: "affiliateAudit",
        name: "affiliateAudit",
        meta: { enter: 3 },
		component: () =>import("@/component/Administrator/affiliate/affiliateAudit/affiliateAudit.vue"),
      },
	  {
		path: "affiliateReferral",
		name: "affiliateReferral",
		meta: {
			enter: 3,
		},
		component: () =>import("@/component/Administrator/affiliate/affiliateReferral/index.vue"),
		},
      {
        path: "TransactionTable",
        name: "TransactionTable",
        meta: { enter: 3 },
        component: () =>
          import("@/component/Administrator/Transaction/TransactionTable.vue"),
      },
      {
        path: "organization",
        name: "organization",
        meta: { enter: 3 },
        component: () =>
          import("@/component/Administrator/organization/organization.vue"),
      },
      {
        path: "subscriptionPlan",
        name: "subscriptionPlan",
        meta: { enter: 3 },
        component: () =>
          import("@/component/Administrator/subscriptionPlan.vue"),
      },
      //企业版教育管理员页面
      {
        path: "allUserSE",
        name: "allUserSE",
        meta: { enter: 3 },
        component: () =>
          import("@/component/Administrator/SE/allUser/index.vue"),
      },
      {
        path: "testClickDataSE",
        name: "testClickDataSE",
        meta: { enter: 3 },
        component: () =>
          import("@/component/Administrator/SE/designDetailList/index.vue"),
      },
	  {
        path: "recentActiveChartSE",
        name: "recentActiveChartSE",
        meta: { enter: 3 },
        component: () =>
          import("@/component/Administrator/SE/recentActiveChart.vue"),
      },
      {
        path: "generateFrequencySE",
        name: "generateFrequencySE",
        meta: { enter: 3 },
        component: () =>
          import("@/component/Administrator/SE/getGenerateFrequency/index.vue"),
      },
    ],
  },
  {
    path: "/paySucceed",
    name: "paySucceed",
    meta: {
      enter: "all",
    },
    component: () => import("@/views/paySucceed.vue"),
  },
  {
    path: "/affiliate",
    name: "affiliate",
    meta: {
      enter: 2,
    },
    component: () => import("@/views/affiliate/affiliatePage.vue"),
    children: [
		{
		path: "",
		name: "defaultAffiliateHome",
		 meta: {
          enter: 2,
        },
        component: () => import("@/component/affiliate/home.vue"),
		},
      {
        path: "/affiliateHome",
        name: "affiliateHome",
        meta: {
          enter: 2,
        },
        component: () => import("@/component/affiliate/home.vue"),
      },
    ],
  },
  {
    path: "/affiliateRegister",
    name: "affiliateRegister",
    meta: {
      enter: "all",
    },
    component: () => import("@/views/affiliate/affiliateRegister.vue"),
  },
  {
    path: "/feedbackSurvey",
    name: "feedbackSurvey",
    meta: {
      enter: "all",
    },
    component: () => import("@/views/feedbackSurvey.vue"),
  },
  {
    path: "/feedbackSurveyCN",
    name: "feedbackSurveyCN",
    meta: {
      enter: "all",
    },
    component: () => import("@/views/feedbackSurveyCN.vue"),
  },
  {
    path: "/email3-1EN",
    name: "email3-1EN",
    meta: {
      enter: "all",
    },
    component: () => import("@/views/emailPage/email3-1EN.vue"),
  },
  {
    path: "/email3-1CN",
    name: "email3-1CN",
    meta: {
      enter: "all",
    },
    component: () => import("@/views/emailPage/email3-1CN.vue"),
  },
  {
    path: "/404",
    name: "404",
    meta: {
      enter: "all",
    },
    component: () => import("@/views/404.vue"),
  },
  {
    path: "/userManual",
    name: "userManual",
    meta: {
      enter: "all",
    },
    component: () => import("@/views/userManual.vue"),
  },
  {
    path: "/:catchAll(.*)",
    redirect: "/404",
  },
];

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  //   history: createWebHashHistory(),
  routes,
});
// 刷新保存数据-
let state: any = store.state;
// window.addEventListener("beforeunload", (e) => {
//   localStorage.setItem(
//     "vuex_setUserDetail",
//     JSON.stringify(state.UserHabit.userDetail)
//   );
// });
// var vuex_userDetail: any = localStorage.getItem("vuex_userDetail");
// if (vuex_userDetail) {
// 	console.log(vuex_userDetail)
//   if (JSON.parse(vuex_userDetail).email != "-------------") {
//     store.commit("setUserStatus", JSON.parse(vuex_userDetail));
//   }
// }

let setMurmur = (id: any) => {
  let murmurStr: any = localStorage.getItem("murmurStr");
  // let isSxis = false
  let data = {
    browserIdentifiers: murmurStr,
    id: id,
  };
  if (data.id) {
    Https.axiosPost(Https.httpUrls.noLoginRequired, data)
      .then((rv) => {
        let isTest = rv.systemUser == 3 ? true : false;
        let isBeginner = rv?.isBeginner == 1 ? true : false;
        setCookie("isMurmur", true);
        setCookie("token", rv.token);
        setCookie("isTest", isTest);
        setCookie("isBeginner", isBeginner);
        setCookie("isBeginnerNum", 0); //从第一步开始，机器人开始的话就是从第二部开始
        setCookie("userInfo", JSON.stringify(rv));
        let userid = {
          ueserId: rv.userId,
          systemUser: rv.systemUser,
        };
        store.commit("upUserDetail", userid);
        sessionStorage.setItem("isTimeOne", JSON.stringify(false)); //是否需要公告 提示 弹窗
        let randomNum: any =
          Math.floor(Math.random() * 9000000000000000) + 1000000000000000;
        sessionStorage.setItem("sessionId", randomNum);
        router.push("/home");
      })
      .catch((res) => {
        // router.push('/Square')
      });
  }
};
const setViewsIncrease = (value: any) => {
  sessionStorage.setItem("affiliateRef", value);
  let data = {
    id: value,
  };
  Https.axiosGet(Https.httpUrls.viewsIncrease, { params: data }).then(
    (rv) => {}
  );
};
let upgradeList = ["/feedbackSurvey", "/feedbackSurveyCN", "emailVerify"]; //指定页面系统维护也可以访问
function isTimeRangePassed(timeRange) {
    const [startStr, endStr] = timeRange.split(' - ');
    const startTime = new Date(startStr).getTime();
    const endTime = new Date(endStr).getTime();
    const currentTime = new Date().getTime();
    
    if (currentTime < startTime) {
        return 'not_started'; // 未开始
    } else if (currentTime >= startTime && currentTime <= endTime) {
        return 'in_progress'; // 进行中
    } else {
        return 'ended'; // 已结束
    }
}

router.beforeEach((to: any, from, next) => {
	store.commit("set_view_loading", true);
  //系统维护时间
	const time = '2025-12-19T21:00:00 - 2025-12-19T22:00:00';
	if (isTimeRangePassed(time) == 'in_progress') {
	  // 	系统维护
		const toName = to.name === 'upgrade';
		if(to.query.status == 'admin'){
			localStorage.setItem('isAdminVisit', 'true')
		}
		const isAdminVisit = localStorage.getItem('isAdminVisit') == 'true'
		if(upgradeList.indexOf(to.path) > -1 || isAdminVisit){
			next();
		}else{
			if (toName) {
				next();
			} else {
				next({ name: 'upgrade' });
			}
		}
	} else {
		localStorage.setItem('isAdminVisit', 'false')
		
		// 机房用户
		let herfData = window.location.search.substring(1);
		if (herfData.split("=")[0] == "noLogin" && to.name != "homePage") {
			setMurmur(herfData.split("=")[1]);
			return;
		}
		let affiliateRef = sessionStorage.getItem("affiliateRef");
		if (to.query.order) sessionStorage.setItem("orderId", to.query.order); //记录是否点击跳转订单链接
		if (to.query.ref && affiliateRef != to.query.ref)
			setViewsIncrease(to.query.ref);

			var vuex_systemList: any = sessionStorage.getItem("vuex_systemList");
		if (to.meta.enter == "all") {
			next();
		} else if (
			(state.UserHabit?.userDetail?.systemList?.indexOf(to.meta.enter) > -1) || (vuex_systemList?.indexOf(to.meta.enter))
		) {
			next();
		} else {
			next("/404");
		}
	}
	
  
  // if(systemUser == 0){//游客用户只能进入这两个页面
});
router.afterEach((to, from) => {
	store.commit("set_view_loading", false);
});
export default router;
