<template>
  <el-dialog
    class="handle-rollup-dialog"
    :visible.sync="dialogVisible"
    width="640px"
    title="手动收卷"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    append-to-body
    @open="opened"
    @close="closed"
  >
    <div class="tips-info tips-error">
      <i class="el-icon-warning"></i>
      <p>
        系统检测到如下考生正在进行异常处理尚未交卷，请监考老师勾选需要手动收卷的考生！
        注意：被收卷的考生无法继续完成考试，请谨慎操作！
      </p>
    </div>
    <el-form
      ref="modalFormComp"
      :model="modalForm"
      :rules="rules"
      label-width="120px"
    >
      <el-form-item prop="ids" label="证件号/姓名：">
        <multiple-select-student
          data-key="examRecordId"
          :data-list="dataList"
          :seleted-ids="modalForm.ids"
          @selected="idsChange"
          ref="MultipleSelectStudent"
          v-if="dataReady"
        ></multiple-select-student>
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel" plain>取消</el-button>
      <el-button type="primary" @click="confirm" :disabled="isSubmit"
        >确认</el-button
      >
    </div>
  </el-dialog>
</template>

<script>
import MultipleSelectStudent from "../common/MultipleSelectStudent";
import { invigilateFinish } from "@/api/invigilation";

export default {
  name: "handle-rollup-dialog",
  components: { MultipleSelectStudent },
  props: {
    dataList: {
      type: Array,
      default() {
        return [];
      },
    },
  },
  data() {
    const idsValidator = (rule, value, callback) => {
      if (!value || !value.length) {
        callback(new Error("请选择学生"));
      } else {
        callback();
      }
    };
    return {
      dialogVisible: false,
      dataReady: false,
      isSubmit: false,
      modalForm: {
        ids: [],
      },
      rules: {
        ids: [
          {
            required: true,
            validator: idsValidator,
            trigger: "change",
          },
        ],
      },
    };
  },
  methods: {
    opened() {
      this.modalForm.ids = this.dataList.map((item) => item.examRecordId);
      this.dataReady = true;
    },
    closed() {
      this.dataReady = false;
    },
    cancel() {
      this.dialogVisible = false;
    },
    open() {
      this.dialogVisible = true;
    },
    idsChange(ids) {
      this.modalForm.ids = ids;
    },
    async confirm() {
      const valid = await this.$refs.modalFormComp.validate().catch(() => {});
      if (!valid) return;

      if (this.isSubmit) return;
      this.isSubmit = true;
      const result = await invigilateFinish({
        examRecordId: this.modalForm.ids,
        type: "MANUAL",
      }).catch(() => {});

      this.isSubmit = false;
      if (!result) return;

      this.$emit("modified");
      this.cancel();
    },
  },
};
</script>
