<template>
  <div>
    <h2>{{ "新增" + "场次" }}</h2>

    <el-row>
      <el-col :span="3"> 考试名称: </el-col>
      <el-col :span="21">
        {{ exam.name }}
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="3"> 考试时间段: </el-col>
      <el-col :span="21">
        {{ exam.startTime | datetimeFilter }} ~
        {{ exam.endTime | datetimeFilter }}
      </el-col>
    </el-row>
    <el-row>
      <el-form
        :model="item"
        :ref="'form' + index"
        :rules="rules"
        label-position="right"
        inline
        v-for="(item, index) in form"
        :key="index"
      >
        <div class="d-flex">
          <el-form-item label="考试时间" prop="startTime">
            <el-date-picker
              v-model="item.startTime"
              type="datetime"
              placeholder="选择日期时间"
              style="width: 188px;"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="交卷时间" prop="finishTime">
            <el-date-picker
              v-model="item.finishTime"
              type="datetime"
              placeholder="选择日期时间"
              style="width: 188px;"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="考试时长" prop="prepareSeconds">
            <MinuteInput
              v-model="item.maxDurationSeconds"
              style="width: 125px;"
            />
          </el-form-item>
          <el-form-item label="候考时间" prop="prepareSeconds">
            <MinuteInput v-model="item.prepareSeconds" style="width: 125px;" />
          </el-form-item>
          <el-form-item label="迟到时长" prop="prepareSeconds">
            <MinuteInput v-model="item.openingSeconds" style="width: 125px;" />
          </el-form-item>
        </div>
      </el-form>
    </el-row>
    <el-row class="d-flex justify-content-center">
      <el-button type="primary" @click="submitForm">保 存</el-button>
      <el-button type="primary" @click="addActivity">新 增</el-button>
      <el-button @click="() => this.$router.back()">取 消</el-button>
    </el-row>
  </div>
</template>

<script>
import { saveActivities } from "@/api/examwork-activity";
import { getExamDetail } from "@/api/examwork-exam";
import moment from "moment";

export default {
  name: "ActivityEdit",
  computed: {
    examId() {
      return this.$route.params.examId;
    },
    activityId() {
      return this.$route.params.activityId;
    },
    isEdit() {
      return !!this.$route.params.activityId;
    },
  },
  data() {
    const that = this;
    return {
      form: [
        {
          id: "",
          startTime: null,
          finishTime: null,
          prepareSeconds: 0,
          openingSeconds: 0,
          maxDurationSeconds: 0,
        },
      ],
      rules: {
        startTime: [
          { required: true, message: "开始时间必填" },
          {
            validator(rule, value) {
              return new Promise((resolve, reject) => {
                if (
                  moment(value).isBetween(
                    moment(that.exam.startTime),
                    moment(that.exam.endTime)
                  )
                ) {
                  resolve(); // reject with error message
                } else {
                  reject("reject");
                }
              });
            },
            // type: "date",
            // asyncValidator: (rule, value) => {
            //   console.log(value);
            //   return new Promise((resolve, reject) => {
            //     if (
            //       moment(value).isBetween(
            //         moment(that.exam.startTime),
            //         moment(that.exam.endTime)
            //       )
            //     ) {
            //       resolve(); // reject with error message
            //     } else {
            //       reject();
            //     }
            //   });
            // },
            message: "场次的开始时间不在考试的时间范围",
          },
        ],
        finishTime: [
          { required: true, message: "交卷时间必填" },
          {
            validator(rule, value) {
              return new Promise((resolve, reject) => {
                if (
                  moment(value).isBetween(
                    moment(that.exam.startTime),
                    moment(that.exam.endTime)
                  )
                ) {
                  resolve(); // reject with error message
                } else {
                  reject("reject");
                }
              });
            },
            message: "场次的交卷时间不在考试的时间范围",
          },
        ],
        maxDurationSeconds: [{ required: true, message: "考试时长必填" }],
        prepareSeconds: [{ required: true, message: "候考时间必填" }],
        openingSeconds: [{ required: true, message: "迟到时长必填" }],
      },
      exam: {},
      activity: {},
    };
  },
  async created() {
    try {
      this.exam = (await getExamDetail({ id: this.examId }))?.data.data;
      this.form[0].prepareSeconds = this.exam.prepareSeconds;
      this.form[0].openingSeconds = this.exam.openingSeconds;
      this.form[0].maxDurationSeconds = this.exam.maxDurationSeconds;
    } catch (error) {
      console.log(error);
      this.$notify({ type: "error", title: "获取考试详情失败" });
    }

    // if (this.isEdit) {
    //   try {
    //     this.activity = (
    //       await getActivityDetail({ id: this.activityId })
    //     )?.data.data.records[0];
    //     this.form = this.activity;
    //   } catch (error) {
    //     console.log(error);
    //     this.$notify({ type: "error", title: "获取场次详情失败" });
    //   }
    // } else {
    // this.form = {
    //   id: "",
    //   startTime: null,
    //   finishTime: null,
    //   prepareSeconds: 0,
    //   openingSeconds: 0,
    //   maxDurationSeconds: 0,
    //   enable: 0,
    // };
    // }
  },
  methods: {
    addActivity() {
      this.form.push({
        id: "",
        startTime: null,
        finishTime: null,
        prepareSeconds: this.exam.prepareSeconds,
        openingSeconds: this.exam.openingSeconds,
        maxDurationSeconds: this.exam.maxDurationSeconds,
      });
    },
    async submitForm() {
      let data = [];
      for (let i = 0; i < this.form.length; i++) {
        try {
          const valid = await this.$refs["form" + i][0].validate();
          data.push({
            examId: this.examId,
            startTime: new Date(this.form[i].startTime).valueOf(),
            finishTime: new Date(this.form[i].finishTime).valueOf(),
            prepareSeconds: this.form[i].prepareSeconds,
            openingSeconds: this.form[i].openingSeconds,
            maxDurationSeconds: this.form[i].maxDurationSeconds,
            enable: 1,
          });
          console.log(data);
          if (!valid) return;
        } catch (error) {
          console.log(error);
          return;
        }
      }

      await saveActivities(data);
      this.$emit("reload");
    },
  },
};
</script>

<style></style>
