<template>
  <div class="modify-task-paper">
    <el-dialog
      class="task-detail"
      :visible.sync="modalIsShow"
      :title="title"
      top="10vh"
      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" label-width="100px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="试卷编号：">
                <span>{{ instance.paperNumber }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="课程（代码）：">
                <span>
                  {{ instance.courseName }}（{{ instance.courseCode }}）
                </span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="卷型：">
                <span>{{ instance.paperType }}</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>
            <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>

      <div>
        <div v-if="IS_EDIT" class="mb-2 text-right">
          <el-button
            type="info"
            icon="el-icon-circle-plus-outline"
            @click="addAtachment"
            >增加卷型</el-button
          >
        </div>
        <table class="table">
          <colgroup>
            <col width="100" />
            <col width="280" />
            <col />
            <col v-if="IS_EDIT" width="60" />
          </colgroup>
          <tr>
            <th>试卷类型</th>
            <th>试卷文件</th>
            <th>答题卡</th>
            <th v-if="IS_EDIT">操作</th>
          </tr>
          <tr v-for="(attachment, index) in paperAttachments" :key="index">
            <td>
              <span>{{ attachment.name }}卷</span>
              <span class="color-gray-2" v-if="attachment.isExposed"
                >(已曝光)</span
              >
            </td>
            <td>
              <el-button
                v-if="!attachment.isExposed && IS_EDIT"
                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>
              <el-button
                v-else
                type="text"
                class="btn-primary"
                @click="downloadPaper(attachment)"
              >
                <i
                  class="icon icon-download mr-1"
                  v-if="attachment.attachmentId"
                ></i>
                {{ attachment.filename }}
              </el-button>
            </td>
            <td>
              <template v-if="CAN_EDIT_CARD">
                <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
                >
                <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) ||
                    !(
                      attachment.used &&
                      attachment.savedCardId &&
                      attachment.savedCardId === attachment.cardId
                    )
                  "
                  @click="toEditCard(attachment)"
                  >编辑</el-button
                >
                <el-button
                  class="btn-primary"
                  type="text"
                  :disabled="!canCreateCard"
                  @click="toCreateCard(attachment)"
                  >新建</el-button
                >
              </template>
              <el-button
                v-else
                type="text"
                class="btn-primary"
                @click="toViewCard(attachment)"
              >
                {{ attachment.cardTitle || "预览" }}
              </el-button>
            </td>
            <td v-if="IS_EDIT">
              <el-button
                v-if="attachment.canDelete"
                class="btn-danger btn-icon"
                type="text"
                icon="el-icon-remove"
                @click="deleteAttachment(index)"
              ></el-button>
            </td>
          </tr>
        </table>

        <el-form>
          <el-form-item label="单次抽卷卷型数量：" label-width="150">
            <el-input-number
              v-model="curTaskApply.drawCount"
              :min="1"
              :max="maxFetchCount"
              :step="1"
              step-strictly
              :controls="false"
              :disabled="!IS_EDIT || exposedMode"
            ></el-input-number>
          </el-form-item>
        </el-form>
      </div>

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

    <!-- upload-paper-dialog -->
    <upload-paper-dialog
      :paper-attachment="curAttachment"
      :upload-type="curUploadType"
      @confirm="uploadConfirm"
      ref="UploadPaperDialog"
    ></upload-paper-dialog>
    <!-- ModifyCard -->
    <modify-card ref="ModifyCard" @modified="cardModified"></modify-card>
    <!-- card-preview-dialog -->
    <card-preview-dialog
      ref="CardPreviewDialog"
      :card-id="curAttachment.cardId"
    ></card-preview-dialog>
  </div>
</template>

<script>
import UploadPaperDialog from "./UploadPaperDialog";
import ModifyCard from "../../card/components/ModifyCard";
import CardPreviewDialog from "../../card/components/CardPreviewDialog.vue";
import { taskApplyDetail, taskPaperApplyEdit, cardForSelectList } from "../api";
import { attachmentPreview } from "../../login/api";
import { COMMON_CARD_RULE_ID } from "@/constants/enumerate";
import { copyCard } from "../../card/api";

const initTaskApply = {
  examId: "",
  examTaskId: "",
  paperType: "A",
  paperAttachmentIds: "",
  cardId: "",
  cardRuleId: "",
  makeMethod: "",
  courseCode: "",
  courseName: "",
  drawCount: 1,
  exposedPaperType: "",
  // 题卡状态
  status: "",
  // 考务规则
  includePaper: false,
  customCard: false,
};

export default {
  name: "modify-task-paper",
  components: { UploadPaperDialog, ModifyCard, CardPreviewDialog },
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      },
    },
    editType: {
      type: String,
      default: "PREVIEW",
      validator: (val) => ["EDIT", "PREVIEW"].includes(val),
    },
  },
  computed: {
    title() {
      const names = {
        EDIT: "申请编辑卷库",
        PREVIEW: "卷库详情",
      };
      return names[this.editType];
    },
    IS_PREVIEW() {
      return this.editType === "PREVIEW";
    },
    IS_EDIT() {
      return this.editType === "EDIT";
    },
    CAN_EDIT_CARD() {
      return this.editType === "EDIT" && !this.instance.exposedPaperType;
    },
    maxFetchCount() {
      return this.paperAttachments.length < 1
        ? 1
        : this.paperAttachments.length;
    },
    canCreateCard() {
      return (
        this.curTaskApply.courseCode &&
        this.curTaskApply.examId &&
        this.curTaskApply.cardRuleId !== COMMON_CARD_RULE_ID
      );
    },
    exposedMode() {
      return !!this.curTaskApply.exposedPaperType;
    },
  },
  data() {
    return {
      isSubmit: false,
      modalIsShow: false,
      curTaskApply: { ...initTaskApply },
      paperAttachments: [],
      curAttachment: {},
      curUploadType: "paper",
      abc: "abcdefghijklmnopqrstuvwxyz".toUpperCase(),
      cards: [],
      user: this.$ls.get("user", {}),
    };
  },
  methods: {
    async getCardList() {
      if (!this.curTaskApply.courseCode || !this.curTaskApply.examId) return;
      const data = await cardForSelectList({
        courseCode: this.curTaskApply.courseCode,
        examId: this.curTaskApply.examId,
        paperNumber: this.instance.paperNumber,
      });
      this.cards = data || [];
    },
    async visibleChange() {
      const data = await taskApplyDetail(this.instance.id);
      this.curTaskApply = this.$objAssign(initTaskApply, data || {});
      this.curTaskApply.courseCode = this.instance.courseCode;
      this.curTaskApply.courseName = this.instance.courseName;
      this.curTaskApply.cardRuleId = this.instance.cardRuleId;
      this.curTaskApply.includePaper =
        data.printContent.indexOf("PAPER") !== -1;
      this.paperAttachments = data.paperAttachmentIds
        ? JSON.parse(data.paperAttachmentIds)
        : [];

      const exposedPaperType = data.exposedPaperType || "";
      let exposedPaperTypes = exposedPaperType.split(",");
      exposedPaperTypes.sort((a, b) => (a > b ? -1 : 1));
      const maxExposedPaperType = exposedPaperTypes[0];
      this.paperAttachments.forEach((paper) => {
        paper.canDelete = maxExposedPaperType
          ? paper.name > maxExposedPaperType
          : true;
        paper.isExposed = exposedPaperTypes.includes(paper.name);
        paper.savedCardId = paper.cardId;
      });

      this.$nextTick(() => {
        if (this.CAN_EDIT_CARD) {
          this.getCardList();
        }
      });
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    addAtachment() {
      if (this.paperAttachments.length >= this.abc.length) return;

      const name = this.abc[this.paperAttachments.length];
      const newAttachment = {
        name,
        attachmentId: "",
        filename: "",
        savedCardId: null,
        cardId: "",
        cardType: "",
        createMethod: "",
        cardTitle: "",
        pages: 0,
        canDelete: true,
        isExposed: false,
        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.curTaskApply.drawCount &&
        this.curTaskApply.drawCount > this.paperAttachments.length
      ) {
        this.curTaskApply.drawCount = this.paperAttachments.length;
      }
    },
    toUpload(attachment) {
      this.curUploadType = "paper";
      this.curAttachment = {
        ...attachment,
      };
      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 });
      }
    },
    async downloadPaper(attachment) {
      if (!attachment.attachmentId) return;
      const data = await attachmentPreview(attachment.attachmentId);
      window.open(data.url);
    },
    toViewCard(attachment) {
      this.curAttachment = { ...attachment };
      this.$refs.CardPreviewDialog.open();
    },
    async toCopyCard(attachment) {
      this.curAttachment = { ...attachment };
      const newCardId = await copyCard(
        attachment.cardId,
        this.curTaskApply.courseCode
      );
      this.cardModified({ id: newCardId });
    },
    toEditCard(attachment) {
      this.curAttachment = { ...attachment };
      this.$ls.set("prepareTcPCard", {
        id: attachment.cardId,
        examTaskId: this.curTaskApply.examTaskId,
        courseCode: this.curTaskApply.courseCode,
        courseName: this.curTaskApply.courseName,
        makeMethod: this.curTaskApply.makeMethod,
        cardRuleId: this.curTaskApply.cardRuleId,
        paperType: this.paperAttachments.map((item) => item.name).join(","),
        type: attachment.cardType,
        createMethod: attachment.createMethod,
      });
      this.$refs.ModifyCard.open();
    },
    async cardModified(data) {
      if (!data.id) 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 toCreateCard(attachment) {
      if (!this.curTaskApply.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.curTaskApply.courseCode,
        courseName: this.curTaskApply.courseName,
        schoolName: this.$ls.get("schoolName"),
        makeMethod: "SELF",
        cardName: res.value,
        cardRuleId: this.curTaskApply.cardRuleId,
        type: "CUSTOM",
        createMethod: "STANDARD",
      });
      this.$refs.ModifyCard.open();
    },
    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;
      //   });
    },
    checkDataValid() {
      // 设置了入库强制包含试卷时，校验试卷是否上传。
      // 未设置入库强制包含试卷时，若有试卷上传，则需要上传全部。若无试卷上传，则通过。
      if (this.curTaskApply.includePaper) {
        const attachmentValid = !this.paperAttachments.some(
          (item) => !item.attachmentId
        );
        if (!attachmentValid) {
          this.$message.error("请完成试卷文件上传！");
          return;
        }
      } else {
        const hasUploadPaperAttachments = this.paperAttachments.filter(
          (item) => item.attachmentId
        );
        if (
          hasUploadPaperAttachments.length > 0 &&
          hasUploadPaperAttachments.length !== this.paperAttachments.length
        ) {
          this.$message.error("有试卷文件未完成上传！");
          return;
        }
      }

      let cardValid = !this.paperAttachments.some((item) => !item.cardId);
      if (!cardValid) {
        this.$message.error("有试卷类型未选择题卡！");
        return;
      }

      //   const usedCards = this.paperAttachments
      //     .filter((item) => item.cardId && item.used)
      //     .map((item) => item.name);
      //   if (usedCards.length) {
      //     this.$message.error(`${usedCards.join()}卷选择的题卡已经被使用过！`);
      //     return;
      //   }

      return true;
    },
    async submit() {
      if (!this.checkDataValid()) return;

      this.$confirm("确定要提交申请修改当前任务吗？", "提示", {
        type: "warning",
      })
        .then(async () => {
          const datas = {
            examTaskId: this.curTaskApply.examTaskId,
            drawCount: this.curTaskApply.drawCount,
            paperType: this.paperAttachments.map((item) => item.name).join(","),
            paperAttachmentIds: JSON.stringify(this.paperAttachments),
          };
          const data = await taskPaperApplyEdit(datas).catch(() => {});
          if (!data) return;
          this.$message.success("提交成功！");
          this.$emit("modified");
          this.cancel();
        })
        .catch(() => {});
    },
  },
};
</script>
