<template>
  <div>
    <el-dialog
      class="modify-plan-paper task-detail"
      :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="请选择"
                >
                  <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 v-if="instance.exposedPaperType">
                  卷{{ instance.exposedPaperType }}
                </span>
                <span v-else>--</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="未曝光类型：">
                <span v-if="instance.unexposedPaperType">
                  卷{{ instance.unexposedPaperType }}
                </span>
                <span v-else>--</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">
        <colgroup>
          <col width="80" />
          <col width="60" />
          <col width="300" />
          <col />
        </colgroup>
        <tr>
          <th>备用卷</th>
          <th>卷型</th>
          <th>试卷</th>
          <th>答题卡</th>
        </tr>
        <template v-for="(paperAttachment, pindex) in paperAttachments">
          <tr
            v-for="(attachment, index) in paperAttachment.paperAttachmentIds"
            :key="`${pindex}-${index}`"
          >
            <td
              v-if="index === 0"
              :rowspan="paperAttachment.paperAttachmentIds.length"
            >
              卷{{ paperAttachment.serialNumber }}
            </td>
            <td>
              <span>{{ attachment.name }}</span>
            </td>
            <td>
              <el-button
                type="text"
                class="btn-primary"
                @click="toViewAttachment(attachment)"
                title="点击查看试卷"
              >
                <i
                  class="icon icon-download mr-1"
                  v-if="attachment.attachmentId"
                ></i
                >{{ attachment.filename }}
              </el-button>
            </td>
            <td
              v-if="index === 0"
              :rowspan="paperAttachment.paperAttachmentIds.length"
            >
              <el-button
                type="text"
                class="btn-primary"
                @click="toViewCard(attachment)"
                >查看答题卡</el-button
              >
            </td>
          </tr>
        </template>
      </table>

      <div slot="footer">
        <el-button type="primary" :disabled="isSubmit" @click="submit"
          >确认</el-button
        >
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-dialog>

    <!-- card-preview-dialog -->
    <card-preview-dialog
      ref="CardPreviewDialog"
      :card-id="curAttachment.cardId"
      show-watermark
    ></card-preview-dialog>

    <!-- PreviewAttachment -->
    <preview-attachment
      ref="PreviewAttachment"
      :attachment-ids="attachmentIds"
    ></preview-attachment>
    <!-- PreviewFile -->
    <preview-file ref="PreviewFile" :data="curFile"></preview-file>
  </div>
</template>

<script>
import { updatePlanLinkPaper, linkPaperNumberList } from "../api";
import { taskApplyDetail } from "../../exam/api";
import { attachmentPreview } from "../../login/api";
import PreviewAttachment from "@/components/PreviewAttachment.vue";
import PreviewFile from "@/components/PreviewFile.vue";
import CardPreviewDialog from "../../card/components/CardPreviewDialog.vue";

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

export default {
  name: "modify-plan-paper",
  components: { PreviewAttachment, PreviewFile, CardPreviewDialog },
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      modalIsShow: false,
      isSubmit: false,
      modalForm: { ...initModalForm },
      papers: [],
      paperTypes: [],
      paperAttachments: [],
      cardId: "",
      rules: {
        paperNumber: [
          {
            required: true,
            message: "请选择试卷编号",
            trigger: "change",
          },
        ],
        relatePaperType: [
          {
            required: true,
            message: "请选择关联类型",
            trigger: "change",
          },
        ],
      },
      curAttachment: {},
      // attachmentId preview
      attachmentIds: [],
      // preview file
      curFile: {
        url: "",
        type: "",
      },
    };
  },
  methods: {
    async getAttachments() {
      const data = await taskApplyDetail(this.instance.id);
      this.paperAttachments = (data.examTaskDetailList || []).map((item) => {
        const paperAttachmentIds = item.paperAttachmentIds
          ? JSON.parse(item.paperAttachmentIds)
          : [];
        paperAttachmentIds.forEach((aitem) => {
          aitem.serialNumber = item.serialNumber;
        });
        return {
          ...item,
          paperAttachmentIds,
        };
      });
      this.cardId = data.cardId;
    },
    // 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,
        courseId: this.instance.courseId,
      });

      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 toViewAttachment(attachment) {
      if (!attachment.jpgAttachmentId) {
        if (!attachment.attachmentId) {
          this.$message.error("附件丢失！");
          return;
        }
        const data = await attachmentPreview(attachment.attachmentId);
        if (!data[0].url) {
          this.$message.error("附件丢失！");
          return;
        }
        this.curFile = {
          url: data[0].url,
          type: "application/pdf",
        };
        this.$refs.PreviewFile.open();
        return;
      }

      const datas = JSON.parse(attachment.jpgAttachmentId);
      this.attachmentIds = datas.map((item) => item.attachmentId);
      this.$refs.PreviewAttachment.open();
    },
    toViewCard(attachment) {
      this.curAttachment = { ...attachment };
      this.$refs.CardPreviewDialog.open();
    },
    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,
        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>
