<template>
  <el-dialog
    ref="dialog"
    custom-class="page-dialog"
    title="编辑绑卷"
    width="800px"
    :visible.sync="visible"
    @close="closeDialog"
  >
    <el-form :model="form" ref="form" :rules="rules" inline>
      <div class="part-box part-box-form">
        <el-form-item label="批次名称">
          <ExamSelect v-model="course.examId" disabled />
        </el-form-item>
        <el-form-item label="科目名称">
          <CourseSelect
            :examId="course.examId"
            v-model="course.courseCode"
            disabled
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="toAddPaper">新增绑卷</el-button>
        </el-form-item>
      </div>
      <el-table :data="papers" stripe style="width: 100%;">
        <el-table-column label="试卷名称">
          <template slot-scope="scope">
            <el-select
              v-if="scope.row.isHandleAdd"
              v-model="scope.row.id"
              placeholder="请选择"
              @change="selectPaperChange(scope)"
            >
              <ol-option
                v-for="paper in paperSources"
                :key="paper.id"
                :value="paper.id"
                :label="paper.name"
              ></ol-option>
            </el-select>
            <span v-else>{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column width="100" label="分值">
          <span slot-scope="scope">{{ scope.row.totalScore }}</span>
        </el-table-column>
        <el-table-column width="170" label="抽卷几率">
          <span slot-scope="scope">
            <el-input-number
              v-model.trim="scope.row.weight"
              :min="0"
              :step="1"
              step-strictly
              :max="100"
              style="width: 50px;"
              :controls="false"
            >
            </el-input-number>
            %
          </span>
        </el-table-column>
        <el-table-column width="170" label="音频播放次数">
          <span slot-scope="scope">
            <el-input-number
              v-model.trim="scope.row.audioPlayCount"
              :min="1"
              :max="1000"
              :step="1"
              step-strictly
            ></el-input-number>
          </span>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <div slot-scope="scope">
            <el-button size="mini" type="danger" plain @click="toDelete(scope)">
              删除
            </el-button>
          </div>
        </el-table-column>
      </el-table>

      <el-row>
        <el-col :span="12">
          <el-form-item label="客观题小题乱序" prop="objectiveShuffle">
            <el-radio-group v-model="refreshCourse.objectiveShuffle">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客观题选项乱序" prop="optionShuffle">
            <el-radio-group v-model="refreshCourse.optionShuffle">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div slot="footer" class="d-flex justify-content-center">
      <el-button type="primary" @click="submitForm" :loading="loading">
        保 存
      </el-button>
      <el-button @click="closeDialog">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {
  searchCourses,
  searchPapers,
  saveCourse,
  savePapers,
  searchUnionPapers,
} from "@/api/examwork-course";

export default {
  name: "CoursePaperDialog",
  props: {
    course: Object,
  },
  data() {
    return {
      visible: false,
      form: {},
      rules: {},
      refreshCourse: {},
      papers: [],
      loading: false,
      paperSources: [],
    };
  },
  watch: {
    course: {
      immediate: true,
      handler() {
        this.refreshCourse = {};
        this.papers = [];
        this.getPaperSources();
        this.initData();
      },
    },
  },
  methods: {
    async getPaperSources() {
      const res = await searchUnionPapers(this.course.courseCode);
      this.paperSources = res.data || [];
    },
    async initData() {
      if (!this.course?.examId) return;
      const courseRes = await searchCourses({
        id: this.course.id,
        examId: this.course.examId,
        pageNumber: 1,
        pageSize: 1,
      });
      this.refreshCourse = courseRes?.data.data.records[0];

      const res = await searchPapers({
        examId: this.refreshCourse.examId,
        courseCode: this.refreshCourse.courseCode,
        pageNumber: this.currentPage,
        pageSize: this.pageSize,
      });
      this.papers = res?.data.data;
    },
    openDialog() {
      this.visible = true;
    },
    closeDialog() {
      this.visible = false;
    },
    toAddPaper() {
      this.papers.push({
        id: null,
        name: "",
        totalScore: null,
        weight: 100,
        audioPlayCount: 2,
        isHandleAdd: true,
      });
    },
    toDelete({ $index }) {
      this.papers.splice($index, 1);
    },
    selectPaperChange({ row, $index }) {
      const sPapers = this.papers
        .filter((item, index) => index !== $index)
        .map((item) => item.id);
      if (sPapers.includes(row.id)) {
        row.id = null;
        this.$message.error("当前试卷已经被选择！");
        return;
      }
    },
    async submitForm() {
      try {
        const totalWieght = this.papers
          .map((v) => v.weight)
          .reduce((p, c) => p + c);
        if (totalWieght !== 100) {
          this.$notify({
            type: "warning",
            title: `抽卷几率之和必须等于100，当前之和为${totalWieght}`,
          });
          return;
        }
        this.loading = true;
        await saveCourse({
          examId: this.refreshCourse.examId,
          courseCode: this.refreshCourse.courseCode,
          objectiveShuffle: this.refreshCourse.objectiveShuffle,
          optionShuffle: this.refreshCourse.optionShuffle,
        });
        const ps = [];
        for (const paper of this.papers) {
          ps.push({
            id: paper.id,
            weight: paper.weight,
            audioPlayCount: paper.audioPlayCount,
          });
        }
        await savePapers(ps);
        this.$emit("reload");
        this.$notify({ title: "保存成功", type: "success" });
        this.closeDialog();
      } catch (error) {
        console.log(error);
        this.initData();
        this.$notify({ title: "保存失败", type: "warning" });
      } finally {
        this.loading = false;
      }
    },
  },
};
</script>

<style></style>
