<template>
  <div class="info-exam-task">
    <div class="part-box part-box-pad part-box-border part-box-gray">
      <el-form
        ref="examTaskComp"
        :model="examTask"
        :rules="rules"
        label-width="120px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item prop="semesterId" label="使用学期：">
              <semester-select
                v-model="examTask.semesterId"
                class="width-full"
                default-select-in-used
                @change="semesterChange"
              ></semester-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="examId" label="考试：">
              <exam-select
                v-model="examTask.examId"
                :semester-id="examTask.semesterId"
                :clearable="false"
                class="width-full"
                @change="examChange"
              ></exam-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="部门：">
              {{ teachingRoomName }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="courseCode" label="课程（代码）：">
              <el-select
                v-model="examTask.courseCode"
                placeholder="请选择"
                filterable
                class="width-full"
                :disabled="!examTask.examId"
                @change="courseChange"
              >
                <el-option
                  v-for="item in courses"
                  :key="item.code"
                  :value="item.code"
                  :label="`${item.name}（${item.code}）`"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item prop="paperNumber" label="试卷编号：">
              <el-input
                v-model.trim="examTask.paperNumber"
                placeholder="试卷编号不填写时会自动生成"
                :maxlength="50"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="teacherName" label="拟卷教师：">
              <el-input
                v-model.trim="examTask.teacherName"
                placeholder="请输入拟卷教师"
                :maxlength="50"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <div class="apply-content task-detail">
      <div class="task-body">
        <div class="mb-4 tab-btns">
          <el-button
            v-for="tab in tabs"
            :key="tab.val"
            size="medium"
            :type="curTab == tab.val ? 'primary' : 'default'"
            @click="selectMenu(tab.val)"
            >{{ tab.name }}
          </el-button>
        </div>
        <table class="table mb-2">
          <colgroup>
            <col width="90" />
            <col width="280" />
            <col />
            <col v-if="!IS_REBUILD" width="80" />
          </colgroup>
          <tr>
            <th>试卷类型</th>
            <th>试卷文件</th>
            <th>答题卡</th>
            <th v-if="!IS_REBUILD">操作</th>
          </tr>
          <tr v-for="(attachment, index) in paperAttachments" :key="index">
            <td>{{ attachment.name }}卷</td>

            <td v-if="IS_TIKU_TAB">
              <el-button
                type="text"
                class="btn-primary"
                @click="toSelect(attachment)"
              >
                <i
                  :class="[
                    'icon',
                    attachment.attachmentId ? 'icon-files-act' : 'icon-files',
                  ]"
                ></i
                >{{ attachment.filename || "选择试卷" }}
              </el-button>
            </td>
            <td v-else>
              <el-button
                type="text"
                class="btn-primary"
                @click="toUpload(attachment)"
              >
                <i
                  :class="[
                    'icon',
                    attachment.attachmentId ? 'icon-files-act' : 'icon-files',
                  ]"
                ></i
                >{{
                  attachment.attachmentId
                    ? attachment.filename
                    : "点击上传试卷文件"
                }}
              </el-button>
            </td>
            <td v-if="IS_TIKU_TAB">
              <el-select
                v-model="attachment.cardId"
                placeholder="请选择"
                style="width: 260px; margin-right: 10px"
              >
                <el-option
                  v-if="attachment.cardId"
                  :value="attachment.cardId"
                  :label="attachment.cardTitle"
                >
                </el-option>
              </el-select>
              <el-button
                class="btn-primary"
                type="text"
                :disabled="!attachment.cardId"
                @click="toViewCard(attachment)"
                >预览</el-button
              >
              <el-button
                v-if="!IS_REBUILD"
                class="btn-primary"
                type="text"
                :disabled="!attachment.cardId"
                @click="toEditCard(attachment)"
                >编辑</el-button
              >
            </td>
            <td v-else>
              <el-select
                class="mr-2"
                v-model="attachment.cardId"
                placeholder="请选择"
                style="width: 200px"
                filterable
                @visible-change="
                  (visible) => cardOptionOpened(visible, attachment)
                "
                @change="cardChange(attachment)"
              >
                <el-option
                  v-for="item in cards"
                  :key="item.id"
                  :value="item.id"
                  :label="item.title"
                  :disabled="item.disabled"
                >
                  <span
                    :class="[
                      item.type === 'GENERIC'
                        ? 'color-success'
                        : 'color-primary',
                      'mr-1',
                      {
                        'color-danger': item.used,
                      },
                    ]"
                    >[{{ item.type === "GENERIC" ? "通" : "专" }}]</span
                  >
                  {{ item.title }}
                </el-option>
              </el-select>
              <span
                v-if="attachment.cardId"
                :class="[
                  attachment.cardType === 'GENERIC'
                    ? 'color-success'
                    : 'color-primary',
                  'mr-1',
                  {
                    'color-danger': attachment.used,
                  },
                ]"
                >[{{ attachment.cardType === "GENERIC" ? "通" : "专" }}]</span
              >
              <el-button
                class="btn-primary"
                type="text"
                :disabled="!attachment.cardId"
                @click="toViewCard(attachment)"
                >预览</el-button
              >
              <template v-if="!IS_REBUILD">
                <el-button
                  class="btn-primary"
                  type="text"
                  :disabled="
                    !attachment.cardId ||
                    (attachment.cardType === 'GENERIC' &&
                      attachment.createMethod !== 'STANDARD')
                  "
                  @click="toCopyCard(attachment)"
                  >复制</el-button
                >
                <el-button
                  class="btn-primary"
                  type="text"
                  :disabled="
                    !attachment.cardId ||
                    attachment.cardType === 'GENERIC' ||
                    !(!attachment.used && attachment.createId === user.id)
                  "
                  @click="toEditCard(attachment)"
                  >编辑</el-button
                >
                <el-button
                  class="btn-primary"
                  type="text"
                  :disabled="!canCreateCard"
                  @click="toCreateCard(attachment)"
                  >新建</el-button
                >
              </template>
            </td>
            <td v-if="!IS_REBUILD" class="text-right">
              <el-button
                v-if="index === paperAttachments.length - 1"
                class="btn-primary btn-icon"
                type="text"
                icon="el-icon-circle-plus"
                @click="addAtachment"
              ></el-button>
              <el-button
                class="btn-danger btn-icon"
                type="text"
                icon="el-icon-remove"
                @click="deleteAttachment(index)"
              ></el-button>
            </td>
          </tr>
          <tr v-if="!paperAttachments.length">
            <td colspan="5">
              <p class="tips-info text-center">暂无数据</p>
            </td>
          </tr>
        </table>

        <el-form v-if="!IS_REBUILD">
          <el-form-item label="单次抽卷卷型数量：" label-width="150">
            <el-input-number
              v-model="examTaskDetail.drawCount"
              :min="1"
              :max="1"
              :step="1"
              step-strictly
              :controls="false"
            ></el-input-number>
          </el-form-item>
        </el-form>

        <h4 class="mb-2">附件<span>（最多4张）</span>：</h4>
        <div class="image-list">
          <div
            class="image-item"
            v-for="(img, index) in paperConfirmAttachments"
            :key="index"
          >
            <img
              :src="img.url"
              :alt="img.filename"
              title="点击查看大图"
              @click="toPreview(index)"
            />
            <div class="image-delete">
              <i
                class="el-icon-delete-solid"
                @click="deletePaperConfirmAttachment(index)"
              ></i>
            </div>
          </div>
          <div
            v-if="paperConfirmAttachments.length < 4"
            class="image-item image-add"
            title="上传入库审核表"
            @click="toUploadPaperConfirm"
          >
            <i class="el-icon-plus"></i>
          </div>
        </div>

        <h4 class="mb-2">附件说明：</h4>
        <el-input
          class="mb-2"
          v-model="examTaskDetail.remark"
          type="textarea"
          resize="none"
          :rows="2"
          :maxlength="100"
          clearable
          show-word-limit
          placeholder="建议不超过100个字"
        ></el-input>
      </div>
    </div>

    <!-- upload-paper-dialog -->
    <upload-paper-dialog
      :paper-attachment="curAttachment"
      :upload-type="curUploadType"
      @confirm="uploadConfirm"
      ref="UploadPaperDialog"
    ></upload-paper-dialog>
    <!-- image-preview -->
    <simple-image-preview
      :cur-image="curImage"
      @on-prev="toPrevImage"
      @on-next="toNextImage"
      ref="SimpleImagePreview"
    ></simple-image-preview>
    <!-- ModifyCard -->
    <modify-card ref="ModifyCard" @modified="cardModified"></modify-card>
    <!-- SelectTikuPaperDialog -->
    <select-tiku-paper-dialog
      ref="SelectTikuPaperDialog"
      :row="curAttachment"
      @confirm="tikuPaperSelected"
    ></select-tiku-paper-dialog>
    <!-- CardBuildDialog -->
    <card-build-dialog
      ref="CardBuildDialog"
      :presetData="cardBuildPresetData"
      @confirm="cardBuildConfirm"
    ></card-build-dialog>
  </div>
</template>

<script>
import { mapState, mapMutations } from "vuex";
import UploadPaperDialog from "../UploadPaperDialog.vue";
import SimpleImagePreview from "@/components/SimpleImagePreview";
import ModifyCard from "../../../card/components/ModifyCard.vue";
import SelectTikuPaperDialog from "./SelectTikuPaperDialog.vue";
import { COMMON_CARD_RULE_ID } from "../../../../constants/enumerate";
import { cardForSelectList } from "../../api";
import { courseQuery, examConfigByExamIdOrgId } from "../../../base/api";
import { copyCard } from "../../../card/api";

import CardBuildDialog from "../../../card/components/CardBuildDialog.vue";

// type=GENERIC时， 为通卡，不可复制，不可编辑，可预览。
// type=CUSTOM时，可复制，不可编辑，如果是当前自己任务的题卡，才可编辑。
export default {
  name: "info-exam-task",
  components: {
    UploadPaperDialog,
    SimpleImagePreview,
    ModifyCard,
    SelectTikuPaperDialog,
    CardBuildDialog,
  },
  data() {
    return {
      tabs: [
        {
          name: "上传本地试卷",
          val: "upload",
        },
        {
          name: "从题库选择试卷",
          val: "tiku",
        },
      ],
      curTab: "upload",
      user: {},
      task: {},
      rules: {
        semesterId: [
          {
            required: true,
            message: "请选择使用学期",
            trigger: "change",
          },
        ],
        examId: [
          {
            required: true,
            message: "请选择考试",
            trigger: "change",
          },
        ],
        teachingRoomId: [
          {
            required: true,
            message: "请选择机构",
            trigger: "change",
          },
        ],
        courseCode: [
          {
            required: true,
            message: "请选择课程",
            trigger: "change",
          },
        ],
        paperNumber: [
          {
            message: "试卷编号不能超过50个字符",
            max: 50,
            trigger: "change",
          },
        ],
        teacherName: [
          {
            message: "拟卷教师不能超过50个字符",
            max: 50,
            trigger: "change",
          },
        ],
      },
      examTask: {},
      cards: [],
      courses: [],
      semesters: [],
      teachingRoomName: "",
      cardRuleName: "全部通卡",
      // card-build
      cardBuildPresetData: {},
      // exam-task-detail
      examTaskDetail: { makeMethod: "" },
      paperConfirmAttachmentId: { attachmentId: "", filename: "", url: "" },
      paperAttachments: [],
      paperConfirmAttachments: [],
      curAttachment: {},
      curUploadType: "paper",
      attachmentLimitCount: 26,
      abc: "abcdefghijklmnopqrstuvwxyz".toUpperCase(),
      // image-preview
      curImage: {},
      curImageIndex: 0,
    };
  },
  computed: {
    ...mapState("exam", [
      "infoExamTask",
      "infoExamTaskDetail",
      "infoExamPrintPlan",
    ]),
    maxFetchCount() {
      return this.paperAttachments.length < 1
        ? 1
        : this.paperAttachments.length;
    },
    canCreateCard() {
      return (
        this.examTask.courseCode &&
        this.examTask.examId &&
        this.examTask.cardRuleId !== COMMON_CARD_RULE_ID
      );
    },
    IS_TIKU_TAB() {
      return this.curTab === "tiku";
    },
    IS_REBUILD() {
      return this.examTask.category === "REBUILD";
    },
  },
  watch: {
    "examTask.examId": function (val, oldval) {
      if (val !== oldval) this.examAndRoomChange();
    },
    "examTask.teachingRoomId": function (val, oldval) {
      if (val !== oldval) this.examAndRoomChange();
    },
  },
  mounted() {
    this.initData();
  },
  methods: {
    ...mapMutations("exam", ["updateTaskInfo"]),
    initData() {
      this.user = this.$ls.get("user", {});
      const userOrg = this.user.orgInfo;
      this.teachingRoomName = userOrg.name;
      this.examTask = { ...this.infoExamTask, teachingRoomId: userOrg.id };
      this.examTaskDetail = { ...this.infoExamTaskDetail };
      this.paperAttachments = this.examTaskDetail.paperAttachmentIds
        ? JSON.parse(this.examTaskDetail.paperAttachmentIds)
        : [];

      if (!this.paperAttachments.length) {
        this.addAtachment();
      }

      this.paperConfirmAttachments = this.examTaskDetail
        .paperConfirmAttachmentIds
        ? JSON.parse(this.examTaskDetail.paperConfirmAttachmentIds)
        : [];

      this.getCourses();
      this.getCardList();

      this.$nextTick(() => {
        this.$refs.examTaskComp.clearValidate();
      });
    },
    async selectMenu(tab) {
      const attachment = this.paperAttachments[0];
      if (attachment.cardId || attachment.attachmentId) {
        const result = await this.$confirm(
          "更改类型会清空已设置数据，确定要更改类型？",
          "提示",
          {
            type: "warning",
          }
        ).catch(() => {});
        if (result !== "confirm") return;

        this.paperAttachments = [];
        this.addAtachment();
      }

      this.curTab = tab;
    },
    async getCardList() {
      if (!this.examTask.courseCode || !this.examTask.examId) return;
      const data = await cardForSelectList({
        courseCode: this.examTask.courseCode,
        examId: this.examTask.examId,
      });
      this.cards = data || [];
      if (this.IS_REBUILD) {
        this.cards = this.cards.filter((item) => item.type === "GENERIC");
      }
    },
    async getCourses() {
      if (!this.examTask.teachingRoomId) return;
      const res = await courseQuery({
        teachingRoomId: this.examTask.teachingRoomId,
      });
      this.courses = res || [];
    },
    semesterChange(val) {
      this.examTask.paperName = val.name;
    },
    examChange(val) {
      if (!val.id) return;
      this.examTask.examModel = val.examModel;
      this.examTask.category = val.category;
      this.clearTaskData();
    },
    courseChange(val) {
      if (val) {
        const course = this.courses.find((item) => item.code === val);
        this.examTask.courseName = course.name;
      } else {
        this.examTask.courseName = "";
      }
      this.clearTaskData();
      this.updateTaskInfo({ infoExamTask: this.examTask });
    },
    clearTaskData() {
      this.paperAttachments = [];
      this.addAtachment();

      this.cards = [];
      this.getCardList();
    },
    async examAndRoomChange() {
      this.updateTaskInfo({ infoExamTask: this.examTask });

      const { examId, teachingRoomId } = this.examTask;
      if (examId && teachingRoomId) {
        const examPrintPlan = await examConfigByExamIdOrgId({
          examId,
          orgId: teachingRoomId,
        });
        this.examTask.cardRuleId = examPrintPlan.cardRuleId;
        this.examTaskDetail.review = examPrintPlan.review;
        this.examTaskDetail.includePaper =
          examPrintPlan.printContent.indexOf("PAPER") !== -1;
        this.updateTaskInfo({
          infoExamPrintPlan: Object.assign(
            {},
            this.infoExamPrintPlan,
            examPrintPlan
          ),
          infoExamTask: this.examTask,
          infoExamTaskDetail: this.examTaskDetail,
        });
      }
    },
    cardChange(attachment) {
      const card = this.cards.find((item) => item.id === attachment.cardId);
      if (card) {
        attachment.cardType = card.type;
        attachment.createMethod = card.createMethod;
        attachment.cardTitle = card.title;
        attachment.used = card.used;
        attachment.createId = card.createId;
      }
    },
    cardOptionOpened(visible, attachment) {
      if (!visible) return;

      //   const selectedCardIds = this.paperAttachments.map((item) => item.cardId);
      //   this.cards = this.cards.map((card) => {
      //     card.disabled =
      //       card.id !== attachment.cardId &&
      //       selectedCardIds.includes(card.id) &&
      //       card.type !== "GENERIC";
      //     return card;
      //   });
    },
    async toCreateCard(attachment) {
      if (!this.examTask.cardRuleId) {
        this.$message.error("题卡规则缺失！");
        return;
      }
      const res = await this.$prompt("请输入题卡名称?", "提示", {
        type: "warning",
        showInput: true,
        inputPlaceholder: "请输入题卡名称",
        inputValidator: (val) => {
          if (!val) return "请输入题卡名称！";
          if (val.length > 50) return "题卡名称不得超过50个字符！";
          return true;
        },
      }).catch(() => {});
      if (!res || res.action !== "confirm") return;
      this.curAttachment = { ...attachment };
      this.$ls.set("prepareTcPCard", {
        courseCode: this.examTask.courseCode,
        courseName: this.examTask.courseName,
        schoolName: this.$ls.get("schoolName"),
        makeMethod: "SELF",
        cardName: res.value,
        cardRuleId: this.examTask.cardRuleId,
        type: "CUSTOM",
        createMethod: "STANDARD",
      });
      this.$refs.ModifyCard.open();
    },
    toEditCard(attachment) {
      this.curAttachment = { ...attachment };
      // 这里只允许新建标准专卡
      this.$ls.set("prepareTcPCard", {
        id: attachment.cardId,
        courseCode: this.examTask.courseCode,
        courseName: this.examTask.courseName,
        schoolName: this.$ls.get("schoolName"),
        makeMethod: "SELF",
        cardRuleId: this.examTask.cardRuleId,
        type: "CUSTOM",
        createMethod: "STANDARD",
      });
      this.$refs.ModifyCard.open();
    },
    toViewCard(attachment) {
      window.open(
        this.getRouterPath({
          name: "CardPreview",
          params: {
            cardId: attachment.cardId,
            viewType: "view",
          },
        })
      );
    },
    async toCopyCard(attachment) {
      this.curAttachment = { ...attachment };
      const newCardId = await copyCard(
        attachment.cardId,
        this.examTask.courseCode
      );
      this.cardModified({ id: newCardId });
    },
    async cardModified(data) {
      // data: {id,title}
      if (!data.id) return;

      if (this.IS_TIKU_TAB) {
        const aind = this.paperAttachments.findIndex(
          (item) => item.name === this.curAttachment.name
        );
        this.paperAttachments[aind].cardTitle = data.title;
        return;
      }

      await this.getCardList();
      let card = this.cards.find((item) => item.id === data.id);

      const aind = this.paperAttachments.findIndex(
        (item) => item.name === this.curAttachment.name
      );
      if (aind !== -1 && card) {
        this.paperAttachments[aind].cardId = card.id;
        this.paperAttachments[aind].cardType = card.type;
        this.paperAttachments[aind].createMethod = card.createMethod;
        this.paperAttachments[aind].cardTitle = card.title;
        this.paperAttachments[aind].used = card.used;
        this.paperAttachments[aind].createId = card.createId;
      }
    },
    async checkData() {
      const valid = await this.$refs.examTaskComp.validate().catch(() => {});
      if (!valid) return Promise.reject();

      if (this.IS_TIKU_TAB) {
        const attachmentValid = !this.paperAttachments.some(
          (item) => !item.cardId
        );
        if (!attachmentValid) {
          this.$message.error("请完成试卷选择！");
          return Promise.reject();
        }
        return Promise.resolve(true);
      }

      // 设置了入库强制包含试卷时，校验试卷是否上传。
      // 未设置入库强制包含试卷时，若有试卷上传，则需要上传全部。若无试卷上传，则通过。
      if (this.examTaskDetail.includePaper) {
        const attachmentValid = !this.paperAttachments.some(
          (item) => !item.attachmentId
        );
        if (!attachmentValid) {
          this.$message.error("请完成试卷文件上传！");
          return Promise.reject();
        }
      } else {
        const hasUploadPaperAttachments = this.paperAttachments.filter(
          (item) => item.attachmentId
        );
        if (
          hasUploadPaperAttachments.length > 0 &&
          hasUploadPaperAttachments.length !== this.paperAttachments.length
        ) {
          this.$message.error("有试卷文件未完成上传！");
          return Promise.reject();
        }
      }

      // if (!this.paperConfirmAttachments.length) {
      //   this.$message.error("请上传附件！");
      //   return;
      // }

      let cardValid = !this.paperAttachments.some((item) => !item.cardId);
      if (!cardValid) {
        this.$message.error("有试卷类型未选择题卡！");
        return Promise.reject();
      }
      //   const usedCards = this.paperAttachments
      //     .filter((item) => item.cardId && item.used)
      //     .map((item) => item.name);
      //   if (usedCards.length) {
      //     this.$message.error(`${usedCards.join()}卷选择的题卡已经被使用过！`);
      //     return Promise.reject();
      //   }

      return Promise.resolve(true);
    },
    updateData() {
      let data = {
        infoExamTask: this.examTask,
        infoExamTaskDetail: this.getTaskDetailData(),
      };
      this.updateTaskInfo(data);
    },
    emitRelateInfo(type) {
      this.$emit("relate-info-change", this.getData(), type);
    },
    // select-paper
    toSelect(attachment) {
      this.curAttachment = {
        ...attachment,
        courseCode: this.examTask.courseCode,
      };
      this.$refs.SelectTikuPaperDialog.open();
      // this.tikuPaperSelected({ id: "1", name: "paper-name" });
    },
    async tikuPaperSelected(data) {
      this.cardBuildPresetData = {
        examId: this.examTask.examId,
        courseCode: this.examTask.courseCode,
        courseName: this.examTask.courseName,
        schoolName: this.$ls.get("schoolName"),
        makeMethod: "SELF",
        cardName: "",
        cardRuleId: this.examTask.cardRuleId,
        type: "CUSTOM",
        createMethod: "STANDARD",
        paperId: data.id,
        paperName: data.name,
        uuid: this.examTask.uuid,
      };
      this.$refs.CardBuildDialog.open();
    },
    cardBuildConfirm(data) {
      if (!data.success) {
        this.$message.error(data.message);
        return;
      }
      const ind = this.paperAttachments.findIndex(
        (item) => item.name === this.curAttachment.name
      );
      if (ind === -1) return;

      const info = data.data;
      this.curAttachment = { ...this.paperAttachments[ind] };
      this.paperAttachments[ind] = Object.assign(this.paperAttachments[ind], {
        paperId: this.cardBuildPresetData.paperId,
        cardType: this.cardBuildPresetData.type,
        createMethod: this.cardBuildPresetData.createMethod,
        filename: this.cardBuildPresetData.paperName,
        cardId: info.id,
        cardTitle: info.title,
        uuid: info.uuid,
        attachmentId: info.attachmentId,
      });
    },
    // exam-task-detail edit
    addAtachment() {
      if (this.paperAttachments.length >= this.attachmentLimitCount) return;

      const newAttachment = {
        name: this.abc[this.paperAttachments.length],
        attachmentId: "",
        filename: "",
        paperId: null,
        uuid: null,
        cardId: "",
        cardType: "",
        createMethod: "",
        cardTitle: "",
        pages: 0,
        used: false,
        createId: null,
      };
      this.paperAttachments.push(newAttachment);
    },
    deleteAttachment(index) {
      if (this.paperAttachments.length <= 1) {
        this.$message.error("试卷类型数量不得少于1");
        return;
      }
      this.paperAttachments.splice(index, 1);
      this.paperAttachments.forEach((item, itemIndex) => {
        item.name = this.abc[itemIndex];
      });
      if (
        this.examTaskDetail.drawCount &&
        this.examTaskDetail.drawCount > this.paperAttachments.length
      ) {
        this.examTaskDetail.drawCount = this.paperAttachments.length;
      }
    },
    toUpload(attachment) {
      this.curUploadType = "paper";
      this.curAttachment = {
        ...attachment,
      };
      this.$refs.UploadPaperDialog.open();
    },
    toUploadPaperConfirm() {
      if (this.paperConfirmAttachments.length >= 4) return;
      this.curUploadType = "paperConfirm";
      this.curAttachment = {
        ...this.paperConfirmAttachmentId,
      };
      this.$refs.UploadPaperDialog.open();
    },
    uploadConfirm(attachment, uploadType) {
      if (uploadType === "paper") {
        const index = this.paperAttachments.findIndex(
          (item) => item.name === attachment.name
        );
        this.paperAttachments.splice(index, 1, { ...attachment });
      } else {
        this.paperConfirmAttachments.push(attachment);
      }
    },
    deletePaperConfirmAttachment(index) {
      this.paperConfirmAttachments.splice(index, 1);
    },
    // cardConfirm(data) {
    //   this.examTaskDetail = this.$objAssign(this.examTaskDetail, data);
    // },
    getTaskDetailData() {
      let data = { ...this.examTaskDetail };
      data.paperType = this.paperAttachments.map((item) => item.name).join(",");
      data.paperAttachmentIds = JSON.stringify(this.paperAttachments, (k, v) =>
        k === "url" ? undefined : v
      );
      data.paperConfirmAttachmentIds = JSON.stringify(
        this.paperConfirmAttachments
      );
      return data;
    },
    // image-preview
    toPreview(index) {
      this.curImageIndex = index;
      this.selectImage(index);
      this.$refs.SimpleImagePreview.open();
    },
    selectImage(index) {
      this.curImage = this.paperConfirmAttachments[index];
    },
    toPrevImage() {
      if (this.curImageIndex === 0) {
        this.curImageIndex = this.paperConfirmAttachments.length - 1;
      } else {
        this.curImageIndex--;
      }

      this.selectImage(this.curImageIndex);
    },
    toNextImage() {
      if (this.curImageIndex === this.paperConfirmAttachments.length - 1) {
        this.curImageIndex = 0;
      } else {
        this.curImageIndex++;
      }

      this.selectImage(this.curImageIndex);
    },
  },
};
</script>
