<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">
          <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>
                <i>{{ attachment.filename }}</i>
              </el-button>
            </td>
            <td>
              <template v-if="CAN_EDIT_CARD">
                <el-select
                  class="mr-2"
                  v-model="attachment.cardId"
                  placeholder="请选择"
                  style="width: 200px"
                  filterable
                  @change="cardChange(attachment)"
                >
                  <el-option
                    v-for="item in cards"
                    :key="item.id"
                    :value="item.id"
                    :label="item.title"
                  >
                  </el-option>
                </el-select>
                <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.createMethod === 'UPLOAD'
                  "
                  @click="toCopyCard(attachment)"
                  >复制</el-button
                >
                <el-button
                  class="btn-primary"
                  type="text"
                  :disabled="
                    !attachment.cardId || attachment.createMethod === 'UPLOAD'
                  "
                  @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"
                type="text"
                @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>
  </div>
</template>

<script>
import UploadPaperDialog from "./UploadPaperDialog";
import ModifyCard from "../../card/components/ModifyCard";
import { taskApplyDetail, taskPaperApplyEdit, cardForSelectList } from "../api";
import { attachmentPreview } from "../../login/api";
import { examRuleDetail } from "../../base/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 },
  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(),
      includePaper: false,
      cards: []
    };
  },
  created() {
    this.getExamRule();
  },
  methods: {
    async getExamRule() {
      const examRule = await examRuleDetail();
      this.includePaper = examRule && examRule.includePaper;
    },
    async getCardList() {
      if (!this.curTaskApply.courseCode || !this.curTaskApply.examId) return;
      const data = await cardForSelectList({
        courseCode: this.curTaskApply.courseCode,
        examId: this.curTaskApply.examId
      });
      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 = this.includePaper;
      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);
      });

      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: "",
        cardId: "",
        cardType: "",
        createMethod: "",
        cardTitle: "",
        pages: 0,
        canDelete: true,
        isExposed: false
      };
      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) {
      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.cardModified(newCardId);
    },
    toEditCard(attachment) {
      this.curAttachment = { ...attachment };
      this.$ls.set("prepareTcPCard", {
        cardId: 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: "CUSTOM",
        createMethod: "STANDARD"
      });
      this.$refs.ModifyCard.open();
    },
    async cardModified(cardId) {
      if (!cardId) return;
      await this.getCardList();
      let card = this.cards.find(item => item.id === cardId);

      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;
      }
    },
    toCreateCard(attachment) {
      if (!this.curTaskApply.cardRuleId) {
        this.$message.error("题卡规则缺失！");
        return;
      }
      this.curAttachment = { ...attachment };
      this.$ls.set("prepareTcPCard", {
        courseCode: this.curTaskApply.courseCode,
        courseName: this.curTaskApply.courseName,
        schoolName: this.$ls.get("schoolName"),
        makeMethod: "SELF",
        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;
      }
    },
    checkDataValid() {
      const attachmentValid = !this.paperAttachments.some(
        item => !item.attachmentId
      );
      // 设置了入库强制包含试卷时，校验试卷是否上传。
      if (this.curTaskApply.includePaper && !attachmentValid) {
        this.$message.error("请完成试卷文件上传！");
        return;
      }

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

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

      this.$confirm("确定要提交申请修改当前任务吗？", "提示", {
        type: "warning"
      })
        .then(async () => {
          const datas = {
            examTaskId: this.curTaskApply.examTaskId,
            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>
