<template>
  <div class="question-library-manage marker-login">
    <div class="part-box part-box-pad">
      <el-button
        v-for="item in roles"
        :key="item.roleCode"
        type="primary"
        class="auth-item"
        :disabled="loading"
        @click="toAuth(item)"
        >{{ item.roleName }}</el-button
      >
    </div>
  </div>
</template>

<script>
import { tikuAuth } from "../api";

export default {
  name: "question-library-manage",
  data() {
    return {
      roleNames: {
        SUBJECT_TEACHER: "学科老师",
        ASSIGN_TEACHER: "命题老师",
      },
      roles: [],
      user: {},
      loading: false,
    };
  },
  mounted() {
    this.user = this.$ls.get("user");
    this.getRoles();
    if (this.$route.query.trigger) {
      this.toAuth({ roleCode: this.$route.query.trigger });
    }
  },
  methods: {
    getRoles() {
      const userRoles = this.user.roleSource.filter(
        (item) => item.roleSource === "QUESTION_LIBRARY"
      );
      if (!userRoles.length) {
        this.$message.error("当前用户无对应角色！");
        return;
      }
      const stRole = userRoles.find(
        (item) => item.roleCode === "SUBJECT_TEACHER"
      );
      if (stRole) {
        this.roles = [stRole];
      } else {
        this.roles = [userRoles[0]];
      }
    },
    async toAuth(item) {
      if (this.loading) return;
      this.loading = true;
      const data = await tikuAuth({
        loginName: this.user.loginName,
        realName: this.user.realName,
        role: item.roleCode,
        returnUrl: encodeURIComponent(window.location.href),
      }).catch(() => {});
      this.loading = false;

      if (!data) return;
      window.location.href = data.redirectUrl;
    },
  },
};
</script>
