<template>
  <div class="activity-edit">
    <div class="part-box-head">
      <div class="part-box-head-left">
        <h1>新增场次</h1>
      </div>
    </div>

    <div class="part-filter">
      <div class="part-filter-form">
        <el-form inline>
          <el-form-item label="考试名称：">
            <span> {{ exam.name }}</span>
          </el-form-item>
          <el-form-item label="考试时间段：" label-width="140px">
            <span>
              {{ exam.startTime | datetimeFilter }} ~
              {{ exam.endTime | datetimeFilter }}</span
            >
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="part-box">
      <el-form
        :model="item"
        :ref="'form' + index"
        :rules="rules(index)"
        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;"
              value-format="timestamp"
            >
            </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;"
              value-format="timestamp"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="考试时长" prop="maxDurationSeconds">
            <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="openingSeconds">
            <MinuteInput v-model="item.openingSeconds" style="width: 125px;" />
          </el-form-item>
          <el-form-item label="操作">
            <el-button type="primary" @click="removeActivity(index)" size="mini"
              >删 除</el-button
            >
          </el-form-item>
        </div>
      </el-form>
      <div class="d-flex justify-content-center">
        <el-button type="primary" @click="submitForm" :loading="loading"
          >保 存</el-button
        >
        <el-button type="primary" @click="addActivity">新 增</el-button>
        <el-button type="danger" @click="() => this.$router.back()"
          >取 消</el-button
        >
      </div>
    </div>
  </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() {
    return {
      form: [
        {
          id: "",
          startTime: null,
          finishTime: null,
          prepareSeconds: 0,
          openingSeconds: 0,
          maxDurationSeconds: 0,
        },
      ],

      exam: {},
      activity: {},
      loading: false,
    };
  },
  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: {
    rules(index) {
      return {
        startTime: [
          { required: true, message: "开始时间必填" },
          {
            validator: (rule, value) => {
              return new Promise((resolve, reject) => {
                if (
                  moment(value).isBetween(
                    moment(this.exam.startTime),
                    moment(this.exam.endTime),
                    undefined,
                    "[]"
                  )
                ) {
                  resolve(); // reject with error message
                } else {
                  reject("reject");
                }
              });
            },
            message: "场次的开始时间不在考试的时间范围",
          },
        ],
        finishTime: [
          { required: true, message: "交卷时间必填" },
          {
            validator: (rule, value) => {
              return new Promise((resolve, reject) => {
                if (
                  moment(this.form[index].finishTime) -
                    moment(this.form[index].startTime) <=
                  0
                ) {
                  reject("考试结束时间要大于考试开始时间");
                  return;
                }
                if (
                  moment(value).isBetween(
                    moment(this.exam.startTime),
                    moment(this.exam.endTime),
                    undefined,
                    "[]"
                  )
                ) {
                  resolve(); // reject with error message
                } else {
                  reject("场次的交卷时间不在考试的时间范围");
                }
              });
            },
          },
        ],
        maxDurationSeconds: [
          { required: true, message: "考试时长必填" },
          {
            validator: (rule, value) => {
              return new Promise((resolve, reject) => {
                if (
                  moment(this.form[index].finishTime) -
                    moment(this.form[index].startTime) >=
                  value * 1000
                ) {
                  resolve();
                } else {
                  reject("reject");
                }
              });
            },
            message: "考试时长超出范围",
          },
        ],
        prepareSeconds: [{ required: true, message: "候考时间必填" }],
        openingSeconds: [{ required: true, message: "迟到时长必填" }],
      };
    },
    addActivity() {
      this.form.push({
        id: "",
        startTime: null,
        finishTime: null,
        prepareSeconds: this.exam.prepareSeconds,
        openingSeconds: this.exam.openingSeconds,
        maxDurationSeconds: this.exam.maxDurationSeconds,
      });
    },
    removeActivity(index) {
      this.form.splice(index, 1);
    },
    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;
        }
      }

      try {
        this.loading = true;
        await saveActivities(data);
        this.$notify({ title: "保存成功", type: "success" });
        this.$router.back();
      } finally {
        this.loading = false;
      }
    },
  },
};
</script>

<style></style>
