<template>
  <main-layout>
    <Breadcrumb
      style="
        text-align: left;
        padding-left: 20px;
        height: 40px;
        line-height: 40px;
        background-color: #fafafa;
      "
    >
      当前所在位置：
      <BreadcrumbItem>{{ locationTitle }}</BreadcrumbItem>
    </Breadcrumb>

    <div class="home">
      <div style="text-align: left; margin-bottom: 20px;">
        选择考试批次：
        <Select
          v-model="examId"
          style="width: 200px;"
          filterable
          @on-change="fetchList"
        >
          <Option
            v-for="item in examList"
            :key="item.id"
            :value="item.id"
            :label="item.name"
          >
          </Option>
        </Select>
      </div>

      <OnlinePracticeList
        :courses="courses"
        :exam-list="examList"
      ></OnlinePracticeList>
    </div>
  </main-layout>
</template>

<script>
import OnlinePracticeList from "./OnlinePracticeList.vue";
import { mapState as globalMapState } from "vuex";

export default {
  name: "OnlinePracticeHome",
  components: {
    OnlinePracticeList,
  },
  data() {
    return {
      examId: null,
      examList: [],
      courses: [],
    };
  },
  computed: {
    ...globalMapState(["user", "menus"]),
    locationTitle() {
      return (
        this.menus.find(
          (v) => v.link.toUpperCase() === this.$route.path.toUpperCase()
        ) || {}
      ).name;
    },
  },
  async mounted() {
    window._hmt.push(["_trackEvent", "在线练习列表页面", "进入页面"]);
    this.logger({ page: "在线练习列表页面", action: "进入页面" });
    if (this.$route.query.examId) {
      this.examId = this.$route.query.examId - 0;
      try {
        await this.fetchList(this.examId);
      } catch (error) {
        return;
      }
    }

    try {
      const res = await this.$http.get(
        "/api/ecs_exam_work/exam/queryByNameLike?name=&examTypes=PRACTICE&studentId=" +
          this.user.id
      );
      this.examList = (res.data || []).filter((e) => e.enable);
      if (this.$route.query.examId === undefined && this.examList[0]) {
        const examId = this.examList[0].id;
        // this.$router.replace({ query: { examId } });
        this.examId = examId;
        try {
          await this.fetchList(this.examId);
        } catch (error) {
          return;
        }
      }
    } catch (error) {
      this.$Message.error({
        content: "查询练习列表失败！",
        duration: 15,
        closable: true,
      });
    }
  },
  methods: {
    async fetchList(examId) {
      this.$router.replace({ query: { examId } });

      try {
        const res = await this.$http.get(
          "/api/branch_ecs_oe_admin/practice/queryPracticeCourseList?examId=" +
            examId
        );

        this.courses = res.data;
      } catch (error) {
        this.$Message.error({
          content: "获取课程列表失败",
          duration: 15,
          closable: true,
        });
      }
    },
  },
};
</script>

<style scoped>
.home {
  margin: 20px;
}
</style>
