<template>
  <el-dialog
    class="modify-analysis-batch"
    :visible.sync="modalIsShow"
    :title="title"
    top="10vh"
    width="540px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    @opened="visibleChange"
  >
    <el-form
      ref="modalFormComp"
      :model="modalForm"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item prop="batchName" label="批次名称：">
        <el-input
          class="width-full"
          v-model.trim="modalForm.batchName"
          placeholder="请输入批次名称"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item prop="semesterId" label="学期：">
        <semester-select
          class="width-full"
          v-model="modalForm.semesterId"
          placeholder="学期"
        ></semester-select>
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button type="primary" :disabled="isSubmit" @click="submit"
        >确认</el-button
      >
      <el-button type="danger" @click="cancel" plain>取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { updateAnalysisBatch } from "../api";

const initModalForm = {
  id: null,
  semesterId: null,
  batchName: ""
};

export default {
  name: "modify-analysis-batch",
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  computed: {
    isEdit() {
      return !!this.instance.id;
    },
    title() {
      return (this.isEdit ? "编辑" : "新增") + "分析批次";
    }
  },
  data() {
    return {
      modalIsShow: false,
      isSubmit: false,
      modalForm: {},
      rules: {
        batchName: [
          {
            required: true,
            message: "请输入批次名称",
            trigger: "change"
          },
          {
            max: 50,
            message: "批次名称不能超过50",
            trigger: "change"
          }
        ],
        semesterId: [
          {
            required: true,
            message: "请选择学期",
            trigger: "change"
          }
        ]
      }
    };
  },
  methods: {
    async visibleChange() {
      if (this.instance.id) {
        this.modalForm = this.$objAssign(initModalForm, this.instance);
      } else {
        this.modalForm = { ...initModalForm };
      }
      this.$nextTick(() => {
        this.$refs.modalFormComp.clearValidate();
      });
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    async submit() {
      const valid = await this.$refs.modalFormComp.validate().catch(() => {});
      if (!valid) return;

      if (this.isSubmit) return;
      this.isSubmit = true;
      const datas = { ...this.modalForm };
      const data = await updateAnalysisBatch(datas).catch(() => {});
      this.isSubmit = false;
      if (!data) return;

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