<template>
  <el-dialog
    :visible.sync="modalIsShow"
    title="平时成绩编辑"
    top="10vh"
    width="550px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    @open="visibleChange"
  >
    <el-form
      ref="modalFormComp"
      :model="modalForm"
      :key="modalForm.id"
      label-width="100px"
    >
      <el-form-item
        prop="name"
        label="考生姓名："
        :rules="{
          required: true,
          message: '考生姓名不能为空，最多30字符',
          max: 30,
          trigger: 'change',
        }"
      >
        <el-input
          v-model.trim="modalForm.name"
          placeholder="考生姓名"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item label="考生学号：">
        {{ modalForm.studentCode }}
      </el-form-item>
      <el-form-item
        v-for="(item, index) in modalForm.normalScore"
        :key="index"
        :label="`${item.name}：`"
        :prop="`normalScore.${index}.score`"
        :rules="{
          required: true,
          message: '分数不能为空',
          trigger: 'change',
        }"
      >
        <el-input-number
          v-model="item.score"
          class="width-80"
          size="small"
          :min="0"
          :max="1000"
          :step="0.01"
          step-strictly
          :controls="false"
        >
        </el-input-number>
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button type="primary" :disabled="isSubmit" @click="submit"
        >确认</el-button
      >
      <el-button @click="cancel">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { deepCopy } from "@/plugins/utils";
import { normalScoreSave } from "../api";

const initModalForm = {
  id: null,
  name: "",
  studentCode: "",
  normalScore: [],
};

export default {
  name: "ModifyNormalScore",
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      modalIsShow: false,
      isSubmit: false,
      modalForm: { ...initModalForm },
    };
  },
  methods: {
    visibleChange() {
      this.modalForm = this.$objAssign(initModalForm, this.instance);
      this.modalForm.normalScore = deepCopy(this.instance.normalScore);
    },
    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 = {
        id: this.modalForm.id,
        name: this.modalForm.name,
        score: JSON.stringify(this.modalForm.normalScore),
      };
      const data = await normalScoreSave(datas).catch(() => {});
      this.isSubmit = false;

      if (!data) return;

      this.$message.success("修改成功！");
      this.$emit("modified");
      this.cancel();
    },
  },
};
</script>
