<template>
  <el-dialog
    class="exam-batch-dialog"
    :visible.sync="dialogVisible"
    width="600px"
    title="请选择考试批次"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    append-to-body
  >
    <el-radio-group size="medium" v-model="examBatchId">
      <el-radio v-for="item in examBatchs" :key="item.id" :label="item.id">{{
        item.label
      }}</el-radio>
    </el-radio-group>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel" plain>取消</el-button>
      <el-button type="primary" @click="confirm">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { examMonitorBatchList } from "@/api/invigilation";
import { dateFormatForAPI } from "@/utils/utils";

export default {
  name: "exam-batch-dialog",
  props: {
    initExamid: String,
  },
  data() {
    return {
      dialogVisible: false,
      examBatchId: null,
      examBatchs: [],
      userId: this.$store.state.user.id,
    };
  },
  mounted() {
    this.getExamList();
  },
  methods: {
    async getExamList() {
      const res = await examMonitorBatchList({
        userId: this.userId,
        pageNumber: 1,
        pageSize: 100,
      });
      this.examBatchs = res.data.data.records.map((item) => {
        return {
          ...item,
          label: `${item.name}【${dateFormatForAPI(
            item.startTime
          )} - ${dateFormatForAPI(item.endTime)}】`,
        };
      });

      let selectedExam = null;
      if (this.initExamid) {
        selectedExam = this.examBatchs.find(
          (item) => item.id === this.initExamid
        );
      } else {
        selectedExam = this.examBatchs[0];
      }

      this.examBatchId = selectedExam && selectedExam.id;

      this.$emit("confirm", selectedExam);
    },
    cancel() {
      this.dialogVisible = false;
    },
    open() {
      this.dialogVisible = true;
    },
    confirm() {
      if (!this.examBatchId) {
        this.$message.error("请选择考试批次！");
        return;
      }
      const exam = this.examBatchs.find((item) => item.id === this.examBatchId);
      this.$emit("confirm", exam);
      this.cancel();
    },
  },
};
</script>
