import { createWebHistory, createRouter } from "vue-router";
import store from "@/store";
import _ from "lodash";
import cryptoJs from "crypto-js";

import {
  whitelistJoinMeeting,
  registerJoinUser,
  visitorJoinUser,
  panelistJoinMeeting,
  superviseJoinMeeting,
} from "@/api/meeting";
import dayjs from "dayjs";
const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: "/appointment/:meetingId",
      name: "Appointment",
      component: () => import("@/views/appointment.vue"),
    },
    {
      path: "/verify/:meetingId",
      name: "Verify",
      component: () => import("@/views/verify.vue"),
    },
    {
      path: "/panelist-verify/:meetingId",
      name: "PanelistVerify",
      component: () => import("@/views/panelist-verify.vue"),
    },
    {
      path: "/meeting/:meetingId",
      name: "Meeting",
      component: () => import("@/views/meeting.vue"),
    },
    {
      path: "/panelist/:meetingId",
      name: "Panelist",
      component: () => import("@/views/meeting.vue"),
    },
    {
      path: "/host/:meetingId/:createEmail/:pwd/:username/:nickname",
      name: "Host",
      component: () => import("@/views/meeting.vue"),
    },
    {
      path: "/supervisor/:meetingId/:username",
      name: "Supervisor",
      component: () => import("@/views/meeting.vue"),
    },
    {
      path: "/error",
      name: "Error",
      component: () => import("@/views/error.vue"),
    },
    {
      path: "/:pathMatch(.*)*",
      name: "NotFound",
      component: () => import("@/views/error.vue"),
      // redirect: "/error?errorType=notfound",
    },
    // {
    //   path: "/:pathMatch(.*)*",
    //   name: "NotFound",
    //   // component: () => import("@/views/error.vue"),
    //   redirect: "/error?errorType=notfound",
    // },
  ],
});

router.beforeEach(async (to) => {
  await store.dispatch("getMeetingSettings");
  // 判断会议信息是否存在，不存在则请求数据
  if (!store.state.meeting.id && to.params.meetingId) {
    await store.dispatch("getMeetingInfo", to.params.meetingId);
  }
  // 判断会议是否结束
  if (
    dayjs().isAfter(
      dayjs(store.state.meeting.startTime).add(
        store.state.meeting.duration,
        "minute"
      )
    ) &&
    to.name !== "Error"
  ) {
    return `/error?errorType=ended`;
  }
  if (["Meeting", "Host", "Panelist", "Supervisor"].includes(to.name)) {
    // 当参会角色（host,panelist,meeting,supervisor）改变时,清空用户信息、消息列表
    if (store.state.joinRole && store.state.joinRole !== to.name) {
      store.commit("setJoinUser", {});
      store.commit("setLiked", false);
      store.commit("setMessagesList", []);
    }
    store.commit("setJoinRole", to.name);
  }
  // 如果前往页面的会议id于之前的不同，就清除用户信息、消息列表
  if (to.params.meetingId !== store.state.joinUser.meetingId) {
    store.commit("setJoinUser", {});
    store.commit("setMessagesList", []);
    store.commit("setLiked", false);
  }
  // 前往主持人页面
  if (to.name === "Host") {
    // console.log("host");
    // if (to.params.meetingId !== store.state.joinUser.meetingId) {
    //   store.commit("setMessagesList", []);
    // }
    store.commit("setJoinUser", {
      meetingId: to.params.meetingId,
      nickname: to.params.nickname,
      username: to.params.username,
      email: to.params.createEmail,
    });
    store.commit("setPassword", to.params.pwd);
    return true;
  }
  // 如果要前往参会页面
  else if (to.name === "Meeting") {
    // 如果要去的页面会议号于 vuex中的不一样，则清除数据
    // if (to.params.meetingId !== store.state.joinUser.meetingId) {
    //   store.commit("setJoinUser", {});
    //   store.commit("setMessagesList", []);
    // }
    // 如果参会方式发生更改，则清除数据
    if (
      store.state.joinType &&
      store.state.meeting.joinType !== store.state.joinType
    ) {
      store.commit("setJoinUser", {});
      store.commit("setLiked", false);
      store.commit("setMessagesList", []);
      store.commit("setJoinType", store.state.meeting.joinType);
      return `/verify/${to.params.meetingId}`;
    }
    if (store.state.meeting.joinType === "1") {
      // 如果是白名单模式
      if (store.state.joinUser.icCard) {
        // 检测输入的IC卡号是否在白名单范围内，是则放行，否则返回原地址
        try {
          const { meetingPassword, email } = await whitelistJoinMeeting({
            meetingId: to.params.meetingId,
            icCard: store.state.joinUser.icCard,
          });
          store.commit("setJoinUser", {
            ...store.state.joinUser,
            email: email.email,
            token: email.token,
          });
          store.commit("setPassword", meetingPassword);
          return true;
        } catch (error) {
          store.commit("setJoinUser", {});
          store.commit("setLiked", false);
          store.commit("setMessagesList", []);
          return `/verify/${to.params.meetingId}`;
        }
      } else {
        store.commit("setJoinUser", {});
        store.commit("setLiked", false);
        store.commit("setMessagesList", []);
        return `/verify/${to.params.meetingId}`;
      }
    } else {
      if (_.isEmpty(store.state.joinUser)) {
        store.commit("setJoinUser", {});
        store.commit("setLiked", false);
        store.commit("setMessagesList", []);
        return `/verify/${to.params.meetingId}`;
      } else {
        if (store.state.meeting.joinType === "2") {
          const { meetingPassword, email } = await registerJoinUser(
            store.state.joinUser
          );
          store.commit("setJoinUser", {
            ...store.state.joinUser,
            email: email.email,
            token: email.token,
          });
          store.commit("setPassword", meetingPassword);
        } else {
          const { meetingPassword, email } = await visitorJoinUser(
            store.state.joinUser
          );
          store.commit("setJoinUser", {
            ...store.state.joinUser,
            email: email.email,
            token: email.token,
          });
          store.commit("setPassword", meetingPassword);
        }
        return true;
      }
    }
  } else if (to.name === "Panelist") {
    // 如果要去的页面会议号于 vuex中的不一样，则清除数据
    // if (to.params.meetingId !== store.state.joinUser.meetingId) {
    //   store.commit("setJoinUser", {});
    //   store.commit("setMessagesList", []);
    // }
    if (store.state.joinUser.icCard) {
      try {
        const { meetingPassword, email } = await panelistJoinMeeting({
          meetingId: to.params.meetingId,
          icCard: store.state.joinUser.icCard,
        });
        store.commit("setJoinUser", {
          ...store.state.joinUser,
          email: email.email,
          token: email.token,
        });
        store.commit("setPassword", meetingPassword);
        return true;
      } catch (error) {
        store.commit("setJoinUser", {});
        store.commit("setLiked", false);
        store.commit("setMessagesList", []);
        return `/panelist-verify/${to.params.meetingId}`;
      }
    } else {
      store.commit("setJoinUser", {});
      store.commit("setLiked", false);
      store.commit("setMessagesList", []);
      return `/panelist-verify/${to.params.meetingId}`;
    }
  } else if (to.name === "Supervisor") {
    // 监管参会
    if (to.params.meetingId !== store.state.joinUser.meetingId) {
      store.commit("setMessagesList", []);
    }
    const { email, meetingPassword } = await superviseJoinMeeting({
      icCard: to.params.username,
      meetingId: to.params.meetingId,
    });
    store.commit("setJoinUser", {
      meetingId: to.params.meetingId,
      icCard: to.params.username,
      email: email.email,
      token: email.token,
    });
    store.commit("setPassword", meetingPassword);
    return true;
  }
});

export default router;
