<template>
  <el-dialog
    class="modify-plan-paper"
    :visible.sync="modalIsShow"
    title="关联试卷"
    top="10px"
    width="900px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    @open="visibleChange"
  >
    <div class="part-box part-box-pad part-box-border">
      <el-form
        class="form-info"
        ref="modalFormComp"
        label-width="130px"
        :rules="rules"
        :model="modalForm"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="课程（代码）：">
              <span
                >{{ instance.courseName }}（{{ instance.courseCode }}）</span
              >
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- <el-form-item label="适用专业（方向）：">
              <span>{{ instance.specialty | defaultFieldFilter }}</span>
            </el-form-item> -->
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="题卡规则：">
              <span>{{ instance.cardRuleName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="命题老师：">
              <span>{{ instance.userName }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="mb-2">
          <el-col :span="12">
            <el-form-item prop="paperNumber" label="试卷编号：">
              <el-select
                v-model="modalForm.paperNumber"
                placeholder="请选择"
                filterable
                @change="paperChange"
              >
                <el-option
                  v-for="item in papers"
                  :key="item.id"
                  :value="item.paperNumber"
                  :label="item.paperNumber"
                ></el-option>
              </el-select>
              <!-- <span>{{ instance.paperNumber }}</span> -->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="relatePaperType" label="关联类型：">
              <el-select
                v-model="modalForm.relatePaperType"
                placeholder="请选择"
                multiple
                :multiple-limit="drawCount"
              >
                <el-option
                  v-for="item in paperTypes"
                  :key="item"
                  :value="item"
                  :label="item"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="已曝光类型：">
              <span>{{ instance.exposedPaperType | defaultFieldFilter }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="未曝光类型：">
              <span>{{
                instance.unexposedPaperType | defaultFieldFilter
              }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <h4 class="part-box-tips">试卷内容：</h4>
    <p class="tips-info tips-dark mb-2">
      提示：多卷型试卷由于会绑定一个答题卡模板，因此试卷结构必须相同。多卷型试卷之间客观题要求试题内容相同，可允许大题内的小题题序不同。
    </p>
    <table class="table">
      <tr>
        <th>卷型</th>
        <th>试卷</th>
        <th>答题卡</th>
      </tr>
      <tr v-for="(attachment, index) in paperAttachments" :key="index">
        <td>{{ attachment.name }}卷</td>
        <td>
          <el-button
            type="text"
            class="btn-primary"
            @click="downloadPaper(attachment)"
            title="点击查看试卷"
          >
            <i
              class="icon icon-download mr-1"
              v-if="attachment.attachmentId"
            ></i
            >{{ attachment.filename }}
          </el-button>
        </td>
        <td>
          <el-button
            type="text"
            class="btn-primary"
            @click="toViewCard(attachment)"
            >查看答题卡</el-button
          >
        </td>
      </tr>
    </table>

    <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 { updatePlanLinkPaper, linkPaperNumberList } from "../api";
import { taskApplyDetail } from "../../exam/api";
import { attachmentPreview } from "../../login/api";

const initModalForm = {
  id: null,
  examId: null,
  paperNumber: "",
  relatePaperType: [],
};

export default {
  name: "modify-plan-paper",
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      modalIsShow: false,
      isSubmit: false,
      modalForm: { ...initModalForm },
      papers: [],
      paperTypes: [],
      paperAttachments: [],
      drawCount: 0,
      cardId: "",
      rules: {
        paperNumber: [
          {
            required: true,
            message: "请选择试卷编号",
            trigger: "change",
          },
        ],
        relatePaperType: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (
                value.length < this.drawCount ||
                value.length > this.drawCount
              ) {
                return callback(
                  new Error(`需要选择${this.drawCount}套关联试卷`)
                );
              }
              callback();
            },
            trigger: "change",
          },
        ],
      },
    };
  },
  methods: {
    async getAttachments() {
      const data = await taskApplyDetail(this.instance.id);
      this.paperAttachments = data.paperAttachmentIds
        ? JSON.parse(data.paperAttachmentIds)
        : [];
      this.cardId = data.cardId;
      this.drawCount = data.drawCount;
    },
    // async getPaperTypes() {
    //   const papers = await linkPaperNumberList({
    //     examTaskId: this.instance.id,
    //     printPlanId: this.instance.printPlanId
    //   });

    //   if (papers && papers[0]) this.paperTypes = papers[0].paperTypes;
    // },
    async getPapers() {
      this.papers = await linkPaperNumberList({
        examTaskId: this.instance.id,
        printPlanId: this.instance.printPlanId,
        courseCode: this.instance.courseCode,
      });

      const paper = this.papers.find(
        (item) => item.paperNumber === this.modalForm.paperNumber
      );
      if (paper) this.paperTypes = paper.paperTypes;
    },
    visibleChange() {
      this.modalForm = this.$objAssign(initModalForm, this.instance);
      this.modalForm.relatePaperType = this.instance.relatePaperType
        ? this.instance.relatePaperType.split(",")
        : [];

      this.getPapers();
      // this.getPaperTypes();
      this.getAttachments();

      this.$nextTick(() => {
        this.$refs.modalFormComp.clearValidate();
      });
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    paperChange() {
      this.modalForm.relatePaperType = [];
      this.paperTypes = [];
      const paper = this.papers.find(
        (item) => item.paperNumber === this.modalForm.paperNumber
      );
      if (paper) this.paperTypes = paper.paperTypes;
    },
    async downloadPaper(attachment) {
      const data = await attachmentPreview(attachment.attachmentId);
      window.open(data.url);
    },
    toViewCard(attachment) {
      window.open(
        this.getRouterPath({
          name: "CardPreview",
          params: {
            cardId: attachment.cardId,
            viewType: "view",
          },
        })
      );
    },
    async submit() {
      const valid = await this.$refs.modalFormComp.validate().catch(() => {});
      if (!valid) return;

      if (this.isSubmit) return;
      this.isSubmit = true;
      const datas = {
        examTaskId: this.modalForm.id,
        examId: this.modalForm.examId,
        relatePaperType: this.modalForm.relatePaperType.join(),
        paperNumber: this.modalForm.paperNumber,
        printPlanId: this.instance.printPlanId,
        examDetailCourseIds: this.instance.examDetailCourseIds,
      };
      const data = await updatePlanLinkPaper(datas).catch(() => {});
      this.isSubmit = false;
      if (!data) return;

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