<template>
  <el-dialog
    :visible.sync="modalIsShow"
    title="同步成绩"
    top="10vh"
    width="500px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    @open="visibleChange"
  >
    <el-form ref="modalFormComp" :model="modalForm" label-width="60px">
      <el-form-item
        prop="paperNumber"
        label="试卷："
        :rules="{
          required: true,
          message: '请选择试卷',
          trigger: 'change',
        }"
      >
        <el-select
          v-model="modalForm.paperNumber"
          placeholder="选择试卷"
          clearable
          class="width-full"
        >
          <el-option
            v-for="paper in papers"
            :key="paper.paperNumber"
            :value="paper.paperNumber"
            :label="paper.paperNumber"
          ></el-option>
        </el-select>
      </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 { endScoreSyncPaperList, endScoreSync } from "../../api";

export default {
  name: "SyncPaperDialog",
  props: {
    course: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      modalIsShow: false,
      isSubmit: false,
      modalForm: { paperNumber: "" },
      papers: [],
    };
  },
  methods: {
    async getPapers() {
      if (this.papers.length) return;
      const res = await endScoreSyncPaperList(this.course);
      this.papers = res || [];
    },
    visibleChange() {
      this.getPapers();
      this.modalForm = { paperNumber: "" };
    },
    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 = {
        cultureProgramId: this.course.cultureProgramId,
        courseId: this.course.courseId,
        paperNumber: this.modalForm.paperNumber,
      };
      const res = await endScoreSync(datas).catch(() => {});
      this.isSubmit = false;

      if (!res) return;

      this.$message.success(`${res.success}，错误：${res.error}`);
      this.$emit("modified");
      this.cancel();
    },
  },
};
</script>
