<template>
  <div class="login-open">正在登录……</div>
</template>

<script>
/**
 * returnUrl
 * 所有需要重新登录的地方都要使用returnUrl。包括：
 * axios
 * router
 * home:logout
 */

import { openLogin, getSchoolInfo } from "../api";

export default {
  name: "login-open",
  data() {
    return {};
  },
  created() {
    this.autoLogin();
  },
  methods: {
    async autoLogin() {
      this.$ls.clear();
      const query = this.$route.query;
      this.$ls.set("returnUrl", decodeURIComponent(query["returnUrl"]));

      const data = await openLogin({
        ...query,
        path: "/login-open",
      }).catch(() => {});

      if (!data) {
        window.history.go(-1);
        return;
      }
      // 不同系统登录成功之后的处理逻辑可能会有差异
      if (data.orgInfo)
        this.$ls.set("orgId", data.orgInfo.id, this.GLOBAL.authTimeout);
      if (data.schoolInfo && data.schoolInfo.length) {
        const curSchool = data.schoolInfo[0];
        this.$ls.set("schoolId", curSchool.id, this.GLOBAL.authTimeout);
        this.$ls.set("schoolName", curSchool.name, this.GLOBAL.authTimeout);
        const res = await getSchoolInfo(curSchool.code);
        res.cardSize = res.cardSize ? res.cardSize[0] : "A3";
        this.$ls.set("schoolLogo", res.logo);
        this.$ls.set("schoolInfo", res);
      }
      this.$ls.set("user", data, this.GLOBAL.authTimeout);

      this.$ls.set("token", data.accessToken, this.GLOBAL.authTimeout);

      if (data.roleList && data.roleList.includes("ADMIN")) {
        this.$router.push({
          name: "SelectSchool",
        });
      } else {
        this.$router.push({
          name: "Home",
        });
      }
    },
  },
};
</script>
